Exercises
These exercises will deepen your understanding of interpreted languages. Try them in order.
Exercise 1: Add Print Statement
Add a print builtin that outputs values:
print(42)
print(fib(10))
Hints:
- Add
Printvariant toStmtinast.rs - Parse
print(expr)inparser.rs - In the interpreter, evaluate the expression and use
println!
Checkpoint: print(1 + 2) should output 3
Exercise 2: Add For Loop
Add a for loop with range syntax:
for i in 0..10 {
print(i)
}
Hints:
- Add
For { var, start, end, body }toStmt - Grammar:
For = { "for" ~ Identifier ~ "in" ~ Expr ~ ".." ~ Expr ~ Block } - In interpreter: create a loop that assigns
varfromstarttoend-1
Checkpoint: for i in 0..3 { print(i) } outputs 0, 1, 2
Exercise 3: Add Comparison Operators
Add <, >, <=, >=, ==, !=:
if (x < 10) {
return 1
}
Hints:
- Add new variants to
BinaryOpenum - Return
1for true,0for false (we have no bool type yet) - Update grammar:
CompOp = { "<=" | ">=" | "<" | ">" | "==" | "!=" }
Checkpoint: 5 < 10 returns 1, 5 > 10 returns 0
Exercise 4: Add Logical Operators
Add and and or with short-circuit evaluation:
if (x > 0 and x < 10) {
return 1
}
Hints:
- For
and: if left is0, return0without evaluating right - For
or: if left is non-zero, return it without evaluating right - This is called short-circuit evaluation
Checkpoint: 0 and crash() should not call crash()
Exercise 5: Add String Type
Add string literals and concatenation:
s = "hello"
t = s + " world"
print(t)
Hints:
- Add
Value::String(String)to your value type - Parse string literals:
StringLit = { "\"" ~ (!"\"" ~ ANY)* ~ "\"" } - Implement
+for string concatenation
Checkpoint: "hello" + " world" returns "hello world"
Stretch Goals
If you complete the above:
- Arrays:
arr = [1, 2, 3]; arr[0] - Modulo operator:
10 % 3returns1 - Unary minus:
-5,-(3 + 2) - Comments:
# this is a comment - Multi-line strings:
"""multi\nline"""
What You Practiced
- Extending the grammar incrementally
- Adding new AST node types
- Modifying the interpreter for new constructs
- The pattern: Grammar → AST → Interpreter