Interpreting Programs
Last time, we saw CalcLang, syntax trees, and an interpreter
for a calculator program. In this lecture we will break these ideas down further
and more methodically explore them.
import Lait
#lait
Parsing and Grammars
Recall our CalcLang abstract syntax datastructure from last lecture.
For this class, we’ll add a few other operations: subtraction and multiplication.
type CalcLang := | NumE (val : Int)
| AddE (left : CalcLang) (right : CalcLang)
| MulE (left : CalcLang) (right : CalcLang)
| SubtractE (left : CalcLang) (right : CalcLang)
We can draw a CalcLang data structure as a tree. For instance,
we can draw AddE (AddE (NumE 1) (NumE 2)) (NumE 3) as the
following parse tree:
+
/ \
+ 3
/ \
1 2
Elements of the AST that have children are called non-terminal;
for example, AddE, MulE, and SubtractE are non-terminal.
Conversely, elements of the AST that have no children are called terminal;
NumE is the only terminal. By convention, children of non-terminals
are drawn left-to-right: so, the left child of the tree node for
AddE (AddE (NumE 1) (NumE 2)) (NumE 3)
is the tree node for AddE (NumE 1) (NumE 2).
Grammars
To translate surface syntax into abstract syntax, we parse it using a grammar.
This is what takes the sequence of characters 1 + 2 * 3 into the abstract syntax tree AddE (NumE 1) (MulE (NumE 2) (NumE 3)).
You learn early on that multiplication “happens before” addition; which means that we should parse it as 1 + (2 * 3), and not as (1 + 2) * 3.
The technical term for this is that multiplication binds more tightly than addition, and thus results in this parse tree for 1 + 2 * 3:
+
/ \
1 *
/ \
2 3
If we were to parse it as (1 + 2) * 3, we would get this parse tree:
*
/ \
+ 3
/ \
1 2
As languages get more complicated, there will be lots of rules about how to translate various surface syntax into abstract syntax. These rules are summarized by a grammar.
Before showing the grammar for infix notation, let’s see a simpler grammar for s-expressions.
Recall that using s-expressions, we can write CalcLang programs as follows:
// S-Expression for: 1 + 2 * 3
(+ 1 (* 2 3))
// S-Expression for: (1 + 2) * 3
(* (+ 1 2) 3)
Now, below is the grammar for s-expressions:
<expr> ::= <number>
| (+ <expr> <expr>)
| (* <expr> <expr>)
| (- <expr> <expr>)
<number> ::= 1 | 2 | 3 | ...
This grammar defines the non-terminal <expr>, which is an expression in CalcLang.
Each vertical bar denotes one possible way of forming expression; we call these production rules.
Every character inside a production rule NOT contained in angle brackets is a lexeme; that is,
a string from the surface syntax. (In our language, the lexemes are (, ), +, *, and -, along with the numbers 1, 2, 3, etc.)
Note
The above syntax for a grammar is inspired by BNF, or Backus-Naur Form. BNF specifications of grammars are used pervasively in computer science.
Now we can learn the algorithm for using grammars to parse strings by example. The first thing we need to do is convert syntax strings to a sequence of lexemes. Then, we have each production rule “consume” the lexemes in order to parse the string.
Consider the following surface syntax string: “10”.
This is a single lexeme consisting of a number, so only
matches one production rule: the one for <number>; hence, this parses to NumE 10.
Next, consider the string (+ 1 2).
There are five lexemes here: (, +, 1, 2, and ).
The first lexeme is (, so this cannot be a number; it must be one of the other productions.
The other productions contain ( as the first lexeme, so we then move to the second one, +.
The only production rule that applies here is the one for addition.
Recursively, we then need to parse two sub-expressions. The next lexeme in the sequence is 1 — which only matches the production rule for <number> — so
we consume that 1 and set the first sub-expression to NumE 1.
The next lexeme is 2, and similarly we consume it and set the next sub-expression to NumE 2.
Now that we have built the two sub-expressions and consumed the first four lexemes, the next lexeme we expect to see following the rule for addition is ).
Fortunately, we have that in our sequence, so we consume it. We are now out of lexemes and the top-level production rule has finished, so we output AddE (NumE 1) (NumE 2).
Finally, consider the string (+ (+ 1 2) 3).
This will proceed as before, with nine lexemes: (, +, (, +, 1, 2, ), 3, and ).
The same recursive strategy will apply, except that when we reach the first sub-expression,
we don’t see a number, but instead see the lexemes ( and +. This matches the rule for addition (as we saw above).
Hence, the parser will return AddE (AddE (NumE 1) (NumE 2)) (NumE 3).
Infix Grammar for CalcLang
Now that we’ve seen how to parse s-expressions, let’s see how to parse infix notation. This is similarly given by a grammar:
<expr> ::= <number>
| ( <expr> <expr> )
| <expr> * <expr>
| <expr> + <expr>
| <expr> - <expr>
<number> ::= 1 | 2 | 3 | ...
Above, <expr> now has four production rules: in addition to the rules for numbers and infix operators, we have a production rule for parenthesized expressions.
By convention, we assume rules are applied in the order that they appear in the
grammar; this gives parenthesis and multiplication priority over addition
and subtraction, which we expect from PEMDAS.
This grammar seems reasonable, but it is tricky: what does the surface syntax 1 + 2 + 3 parse to?
This is an example of ambiguity. From the above grammar, there are two
valid parse trees for this expresion:
+
/ \
1 +
/ \
2 3
and
+
/ \
+ 3
/ \
1 2
To resolve this ambiguity, we will specify the binding order of our operations. We say binary operations bind to the left, meaning that we prefer the second tree to the first. Sometimes it makes sense to bind to the right; then, we would prefer the first tree.
In general, there are many tools for generating parsers these days from specifications like the grammars we showed you here. We won’t spend much of this class focusing on the implementation of parsers themselves. Instead, we will focus with manipulating abstract syntax trees directly.
Note
There are a lot of different ways people think about parsing. Examples include Pratt parsing, Earley parsing, Parser combinators, LR/LL parsing, and more. Some projects prefer to implement their own parser, while other projects prefer to use a parsing library.
The Stepper: Simplifying Calculator Programs
We saw last time how to give a semantics to calculator programs using Lait as a metalanguage. Let’s extend our interpreter from last time to handle the new operations:
def interp_calc (c : CalcLang) : Int :=
match c with
| NumE v => v
| AddE e1 e2 => interp_calc e1 + interp_calc e2
| MulE e1 e2 => interp_calc e1 * interp_calc e2
| SubtractE e1 e2 => interp_calc e1 - interp_calc e2
end
#test (interp_calc (AddE (NumE 1) (NumE 2))) === 3
#test (interp_calc (SubtractE (AddE (NumE 1) (NumE 2)) (NumE 3))) === 0
The above interpreter is called a
definitional interpreter for CalcLang: it defines the semantics of CalcLang
via an interpreter that recursively evaluates sub-programs.
One of the themes we’ll see in this class is that there are many
ways to run programs that have uses in different contexts.
Here we’ll see another way to interpret CalcLang programs that
is more like how you learned to calculate in high school: by simplification.
If you are given a big expression like 1 + ((2 * 3) + 7), the way that
you usually approach solving it is by simplifying it in pieces, like:
1 + ((2 * 3) + 7)
--> 1 + (6 + 7)
--> 1 + 13
--> 14
Each line of the above computation is a step of simplification. We can
design an alternative interpreter for CalcLang that works more like this
style of reasoning that progressively simplifies programs until there is no work
left to do.
Let’s start by making a step function that takes one step
of simplification. There are of course many different orders in which
simplification can occur; let’s pick one and see the consequences, focusing
only on addition for now:
def step (e : CalcLang) : CalcLang :=
match e with
| NumE v => NumE v
| AddE e1 e2 =>
match e1 with
| NumE v1 =>
match e2 with
| NumE v2 => NumE (v1 + v2)
| _ => AddE (NumE v1) (step e2)
end
| _ => AddE (step e1) e2
end
| MulE e1 e2 =>
match e1 with
| NumE v1 =>
match e2 with
| NumE v2 => NumE (v1 * v2)
| _ => MulE (NumE v1) (step e2)
end
| _ => MulE (step e1) e2
end
| SubtractE e1 e2 =>
match e1 with
| NumE v1 =>
match e2 with
| NumE v2 => NumE (v1 - v2)
| _ => SubtractE (NumE v1) (step e2)
end
| _ => SubtractE (step e1) e2
end
end
#eval step (AddE (AddE (NumE 1) (NumE 2)) (AddE (NumE 3) (NumE 4)))>> AddE (NumE 3) (AddE (NumE 3) (NumE 4))
#eval step (AddE (NumE 3) (AddE (NumE 3) (NumE 4)))>> AddE (NumE 3) (NumE 7)
Notice how with each step a particular part of the program is simplified. We arbitrarily chose to simplify the left expression first, and then the right expression.
Now we can define a function run that steps a program until it reaches a
fixed point (i.e., it does not change):
def run (e : CalcLang) : CalcLang :=
let stepped_e := step e in
if stepped_e == e then
e
else
run stepped_e
#test (run (AddE (AddE (NumE 1) (NumE 2)) (AddE (NumE 3) (NumE 4))))
=== NumE 10
#test (run (AddE (AddE (NumE 1) (NumE 2)) (NumE 3)))
=== NumE 6
#test (run (AddE (AddE (NumE 1) (NumE 2)) (AddE (NumE 3) (NumE 4))))
=== NumE 10
#test (run (SubtractE (AddE (NumE 1) (NumE 2)) (NumE 3)))
=== NumE 0
We call the above interpreter a small-step interpreter. The key is that the small-step and definitional interpreters always agree on the value that all programs run to. We will see more of the small step interpreter as we progress through the course, but for now, the key takeaway is that there is more than one way of evaluating a program. The small step interpreter makes each step of computation very explicit, and seems to correspond closely to how a computer might execute the above program. The definitional interpreter seems to be the most straightforward implementation strategy.
IfLang: Adding Conditionals
Now, let’s grow our little language by adding conditionals; we will call this
langauge IfLang. We will use the following abstract syntax:
type IfLang := | NumI (value : Int)
| AddI (e1 : IfLang) (e2 : IfLang)
| IfI (guard : IfLang) (thn : IfLang) (els : IfLang)
Notice, IfLang does not have any Booleans. This doesn’t stop
us from giving a semantics for IfI, though. Let’s
choose a meaning: if guard evaluates to a non-zero value,
then evaluate the then branch; otherwise, evaluate the else
branch. We can implement this semantics in a definitional interpreter:
def interp_if (e : IfLang) : Int :=
match e with
| NumI v => v
| AddI e1 e2 => interp_if e1 + interp_if e2
| IfI guard thn els => if interp_if guard != 0 then interp_if thn else interp_if els
end
#test (interp_if (IfI (NumI 0) (NumI 10) (NumI 20))) === 20
Notice here that our object language (IfLang) has a different semantics for
conditionals than our meta language (Lait), even though we make use of Lait’s
if construct to give a semantics to IfLang’s. This is often the case
when making interpreters, and we’ll see more examples of this.