Demystify Variables

Part of "Demystify Programming Languages" series

  1. Demystify Programming Languages
  2. Demystify Errors
  3. Demystify Variables
  4. Demystify Functions
  5. Demystify Closures

For now our simple programming language (PL) have two operations (+, -), two types (number, symbol - at this point everything that is not number, for example a, b, +, -, etc.). The next feature we want to add is “variable”.

What is variable?

There are many sides to this question. So let’s start with the simplest point of view of what variable can be.

The variable is temporary storage. Imagine if you need to calculate some complex formula, you will do this in small portions and you will write down intermediate result or memorize it (if your memory is good enough). Variables allow us to store some intermediate result of the calculation. Generally speaking, it allows to store any information, it can be user input or some predefined constant values, etc.

Variable has a name (or identifier) which we use to distinguish them. In our language, we will use symbols for variables. We already have symbols in our PL, for now, we use them to denote operations. We will extend the usage of symbols to denote variables as well.

What we omit?

As I said this is a simplified version of variables implementation, so we omit some subjects, for example,

  • local scope vs global scope (we will use global one for now)
  • call by value vs call by name
  • reassignment, referential transparency (we don’t allow reassignment for now)
  • references, pointers

How it will work?

We need to implement two operations:

  • write - to save the value
  • read - to get the value

usage of write, read words may confuse you in the future because we will discuss input-output (IO) and writing to IO, reading from IO is a bit different thing. We can call “write” - memory allocation and assignment in one action.

Write will be implemented as an operation which takes two values - name of the variable and value. We will use the word define for this operation. In our case it will look like this:

1(define x 1)

In other languages it can look like this, for example:

1x = 1
2x := 1
3const x = 1

The read will take only one value - the name. For simplicity, we will not use any explicit operators to read, instead of whenever we meat symbol other than some special case we will substitute a value for it (stored previously). This way it will resemble mathematical notation:

1(+ x 1)

Implementation

We said that we store variables in some storage, aka memory. If you would read some book about how to implement compiler you may also meat other names for it: stack (saving in the stack), heap (saving in heap).

In the context of PL, we will call it environment. Every operation (or program) executes is some context, some environment.

We need some data structure capable of storing pairs (name, value). The simplest solution may be storing a list of pairs:

1[["x", 1], ["y", 2] ...]

But it would be not very comfortable to work with - we will need to iterate through the list each time to compare name that we want to find with the name in the pair.

It would be nice if we can use the same principle as they use in the dictionary - you use the word as “address” and get an explanation about the word based on it.

There is such a data structure. It is called a dictionary or hash table. It is subject for a separate post on how to implement it. For now, let’s see how it works in JS:

1const environment = {};
2// define
3environment["x"] = 1;
4// read
5environment["x"];

Let’s add define to evaluate:

 1const environment = {};
 2const evaluate = ast => {
 3  let [name, first, second] = ast;
 4  const numberOfArguments = ast.length - 1;
 5  if (name === "+") {
 6    // ...
 7  } else if (name === "-") {
 8    // ...
 9  } else if (name === "define") {
10    return (environment[first] = second);
11  } else {
12    throw new RuntimeError(`"${name}" is not a function`);
13  }
14};

Let’s add read “operartion”:

 1const environment = {};
 2const evaluate = ast => {
 3  if (typeof ast === "string") {
 4    return environment[ast];
 5  } else if (typeof ast === "number") {
 6    return ast;
 7  }
 8  let [name, first, second] = ast;
 9  const numberOfArguments = ast.length - 1;
10  if (name === "+") {
11    return evaluate(first) + evaluate(second);
12  } else if (name === "-") {
13    // ...
14  } else if (name === "define") {
15    // ...
16  } else {
17    throw new RuntimeError(`"${name}" is not a function`);
18  }
19};

At this point we should be able to do:

1> (define x 1)
21
3> (+ x 1)
42

The basic implementation is in place, but there is more…

Caveats

Eval value

We should be able to do:

1(define x (+ 1 1))

To support this we need to add evaluate to the second argument:

1if (name === "define") {
2  return (environment[first] = evaluate(second));
3}

Note: think about why we evaluate the second argument, but not the first one.

Symbols only

What should happen if we do:

1(define 1 2)

It doesn’t make sense. To prevent this we need to check if the first argument is a symbol and respond with an error in case it is not:

1if (name === "define") {
2  if (typeof first !== "string") {
3    throw new TypeError(
4      `"${name}" expects symbol as the first argument, instead got "${first}"`
5    );
6  }
7  return (environment[first] = evaluate(second));
8}

Reassign

What should happen if we do:

1> (define x 1)
2> (define x 2)

There are two possible ways to respond to this:

  • allow reassignment, so the value, in the end, would be 2
  • make variable produced with define behave as constant e.g. we can’t change the value after it was defined the first time.

I chose the second option:

 1if (name === "define") {
 2  if (typeof first !== "string") {
 3    throw new TypeError(
 4      `"${name}" expects symbol as the first argument, instead got "${first}"`
 5    );
 6  }
 7  if (environment[first] !== undefined) {
 8    throw new RuntimeError(`Can't redefine "${first}" variable`);
 9  }
10  return (environment[first] = evaluate(second));
11}

Special symbols

What should happen if we do:

1(define + 1)

it can get very confusing:

1> (+ + +)
22

We don’t want that, so let’s prohibit this behviour:

 1if (name === "define") {
 2  if (typeof first !== "string") {
 3    throw new TypeError(
 4      `"${name}" expects symbol as the first argument, instead got "${first}"`
 5    );
 6  }
 7  if (
 8    environment[first] !== undefined ||
 9    first === "+" ||
10    first === "-" ||
11    first === "define"
12  ) {
13    throw new RuntimeError(`Can't redefine "${first}" variable`);
14  }
15  return (environment[first] = evaluate(second));
16}

Note: think about why we handle special keywords in the same manner as other environment variables.

Undefined values

What should happen if we do:

1(+ x y)

and we never defined y? As we talked in the previous post there are two ways to handle errors:

  • return some value which indicates an error, for example, undefined or null
  • interrupt current execution

I chose second option:

1if (typeof ast === "string") {
2  if (environment[ast] === undefined) {
3    throw new RuntimeError(
4      `Can't find "${ast}" variable. Use \`(define ${ast} ...)\` to define it`
5    );
6  }
7  return environment[ast];
8}

Undefined defined values

What should happen if we do:

1(+ + +)

At the moment it will result in:

1Can't find "+" variable. Use `(define + ...)` to define it

but when we will do as it says

1(define + 1)

it will result in

1Can't redefine "+" variable

I don’t think there would be a developer who would want to use special symbols as variables, so let’s not worry about that.

We kind of silently introduced 3-rd type (function as value), which is not usable at the moment but shows itself in this weird behavior.

Tests

The current implementation isn’t easy to test, because it uses a global variable (environment). Let’s fix that, by adding a second (optional) argument to evaluate

 1const evaluate = (ast, environment = {}) => {
 2  //...
 3  let [name, first, second] = ast;
 4  const numberOfArguments = ast.length - 1;
 5  if (name === "+") {
 6    return evaluate(first, environment) + evaluate(second, environment);
 7  } else {
 8    // ...
 9  }
10};

Now we can write tests:

 1const assert = require("assert");
 2
 3let testEnv = {};
 4assert.equal(evaluate(parse("(define x 1)"), testEnv), 1);
 5assert.equal(testEnv["x"], 1);
 6
 7assert.equal(evaluate(parse("(+ x x)"), { x: 1 }), 2);
 8
 9try {
10  evaluate(parse("(+ x x)"), {});
11} catch (e) {
12  assert.equal(
13    e.message,
14    'Can\'t find "x" variable. Use `(define x ...)` to define it'
15  );
16}
17
18try {
19  evaluate(parse("(define 1 1)"), {});
20} catch (e) {
21  assert.equal(
22    e.message,
23    `"define" expects symbol as the first argument, instead got "1"`
24  );
25}
26
27try {
28  evaluate(parse("(define x 1)"), { x: 1 });
29} catch (e) {
30  assert.equal(e.message, `Can't redefine "x" variable`);
31}
32
33testEnv = { y: 1 };
34evaluate(parse("(define x y)"), testEnv);
35assert.equal(testEnv["x"], 1);
36
37try {
38  evaluate(parse("(define x x)"));
39} catch (e) {
40  assert.equal(
41    e.message,
42    'Can\'t find "x" variable. Use `(define x ...)` to define it'
43  );
44}
45
46try {
47  testEnv = {};
48  evaluate(parse("(define + 1)"), testEnv);
49  // we don't want this to be valid program
50  evaluate(parse("(+ + +)"), testEnv);
51} catch (e) {
52  assert.equal(e.message, `Can't redefine "+" variable`);
53}

PS

Source code for this post is here.

Guess what. Next subject would be functions, closures, and scopes.

Except where otherwise noted, content on this site is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0