Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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 Print variant to Stmt in ast.rs
  • Parse print(expr) in parser.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 } to Stmt
  • Grammar: For = { "for" ~ Identifier ~ "in" ~ Expr ~ ".." ~ Expr ~ Block }
  • In interpreter: create a loop that assigns var from start to end-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 BinaryOp enum
  • Return 1 for true, 0 for 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 is 0, return 0 without 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:

  1. Arrays: arr = [1, 2, 3]; arr[0]
  2. Modulo operator: 10 % 3 returns 1
  3. Unary minus: -5, -(3 + 2)
  4. Comments: # this is a comment
  5. 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