Making Languages

Part 5: Interpretation

Christopher Pitt
Making Languages
Published in
2 min readOct 13, 2014

--

← Back | Forward →

Edit:

Anthony Ferrara points out that my wording was wrong here. Interpreters aren’t a kind of compiler — they’re a kind of machine. Compilers convert code from one language to another while interpreters do things with code in a specific language.

Let’s step back and think about what a program does. It sometimes accepts input, does some processing and sometimes returns some output. A program that doesn’t accept input or provide output is boring. The question is — how is that input provided and returned?

The answer (at least for our case) is a context. A context is an array we give a program. This array is changed by the processing and we can inspect it after the program has run to see what happened.

Interpreting

This means we should add a construct for writing to the context:

This is from Assignment.php

This class takes an $identity (variable name) parameter and a $value parameter. The apply() method uses these to store some contextual data. We also need to add a couple methods to the existing constructs:

This is from Number.php

This is from Addition.php

These new getValue() methods return the underlying integer values. Addition constructs can be nested but the values of the Number instances are always returned. This is thanks to recursion!

We can use this new Assignment construct to write to a context:

← Back | Forward →

--

--