Build a language implementation by scanning source into tokens, constructing a syntax tree and evaluating programs. Each extension adds another part of the language.

Set up your project

Choose a starter for your language. C · Clojure · C++ · C# · Elixir · Gleam · Go · Haskell · Java · JavaScript · Kotlin · OCaml · Odin · PHP · Python · Ruby · Rust · Scala · Swift · TypeScript · Zig.

Use the examples in each stage to check your implementation locally. CodeCrafters operates its hosted runner separately.

Contents

Core project

1. Scanning: Empty file

An interpreter’s first job is to turn raw source code text into tokens (the smallest meaningful units of code). In this stage, you’ll handle the simplest possible input: an empty .lox file.

The tokenize command

The tokenize command tokenizes a Lox program and prints the tokens to stdout. We’ll use this for testing all stages in the Scanning chapter.

If there’s a file named test.lox with the following contents:

var language = "lox";

The tokenize command will return the following:

$ ./your_program.sh tokenize test.lox
VAR var null
IDENTIFIER language null
EQUAL = null
STRING "lox" lox
SEMICOLON ; null
EOF  null

This output format matches the spec in the book’s repository.

Each line corresponds to a token in the file (Image from Section 4.2: Lexemes & Tokens):

img

This is the format for each line:

<token_type> <lexeme> <literal>
  • <token_type>: The type of the token.
    • Examples: VAR, IDENTIFIER, STRING, EOF etc.
  • <lexeme>: The actual sequence of characters that formed the token.
    • Examples: var, breakfast, "bagels" etc.
    • For an EOF token, the lexeme is an empty string.
  • <literal>: The literal value of the token.
    • For most tokens this is null.
    • For STRING/NUMBER tokens, it holds the value of the string/number.

The EOF token is a special token that represents the end of the file. All calls to tokenize will include an EOF token at the end.

Tests

The tester will write an empty file to test.lox. It’ll then run your program like this:

$ ./your_program.sh tokenize test.lox
EOF  null

Since the file is empty, only one token is expected in the output: EOF. The tester will verify that EOF<space><space>null is printed to stdout.

Notes
  • This output format matches the spec in the book’s repository
  • There are two spaces between EOF and null. This is because the <lexeme> part is an empty string for the EOF token.
  • In this stage, your scanner only needs to handle empty files. You’ll gradually expand its functionality in the upcoming stages.

Original stage ry8

2. Scanning: Parentheses

In this stage, you’ll add support for scanning parentheses.

Book reference

The code for this stage is implemented in Section 4.5: Recognizing Lexemes.

Tests

The tester will run a series of tests with test.lox files that contain parentheses.

For example, if test.lox contains the following:

(()

The tester will run your program like this:

$ ./your_program.sh tokenize test.lox
LEFT_PAREN ( null
LEFT_PAREN ( null
RIGHT_PAREN ) null
EOF  null

The tester will assert that the stdout of your program matches the format above.

Notes
  • This output format matches the spec in the book’s repository
  • When scanning for tokens, it’s valid to have “unbalanced” parentheses. When we get to parsing expressions in later stages, these cases will be highlighted as errors.

Original stage ol4

3. Scanning: Braces

In this stage, you’ll add support for scanning braces.

Book reference

The code for this stage is implemented in Section 4.5: Recognizing Lexemes.

Tests

The tester will run a series of tests with test.lox files that contain braces combined with parentheses.

For example, if test.lox contains the following:

{{}}

The tester will run your program like this:

$ ./your_program.sh tokenize test.lox
LEFT_BRACE { null
LEFT_BRACE { null
RIGHT_BRACE } null
RIGHT_BRACE } null
EOF  null

The tester will assert that the stdout of your program matches the format above.

Notes
  • This output format matches the spec in the book’s repository
  • When scanning for tokens, it’s valid to have “unbalanced” braces. When we get to parsing expressions in later stages, these cases will be highlighted as errors.

Original stage oe8

4. Scanning: Other single-character tokens

In this stage, you’ll add support for scanning other single-character tokens, namely ,, ., -, +, ; and *. / is not covered here, it’s covered in later stages.

Book reference

The code for this stage is implemented in Section 4.5: Recognizing Lexemes.

Tests

The tester will run a series of tests with test.lox files that contain parentheses, braces combined with all the new single-character tokens.

For example, if test.lox contains the following:

({*.,+*})

The tester will run your program like this:

$ ./your_program.sh tokenize test.lox
LEFT_PAREN ( null
LEFT_BRACE { null
STAR * null
DOT . null
COMMA , null
PLUS + null
STAR * null
RIGHT_BRACE } null
RIGHT_PAREN ) null
EOF  null

The tester will assert that the stdout of your program matches the format above.

Here’s a list of all the single-character tokens along with their types:

Token Token Type
, COMMA
. DOT
- MINUS
+ PLUS
; SEMICOLON
/ SLASH
* STAR
( LEFT_PAREN
) RIGHT_PAREN
{ LEFT_BRACE
} RIGHT_BRACE
Notes
  • This output format matches the spec in the book’s repository
  • When scanning for tokens, it’s valid to have “unbalanced” parentheses or braces. When we get to parsing expressions in later stages, these cases will be highlighted as errors.

Original stage xc5

5. Scanning: Lexical errors

In this stage, you’ll add support for reporting errors when scanning invalid tokens like $, #, etc.

Book reference

The code for this stage is implemented in Section 4.5.1: Lexical Errors.

Tests

The tester will run a series of tests with test.lox files that contain unknown tokens mixed with other previously introduced token types.

For example, if test.lox contains the following:

,.$(#

The tester will run your program like this:

$ ./your_program.sh tokenize test.lox
[line 1] Error: Unexpected character: $
[line 1] Error: Unexpected character: #
COMMA , null
DOT . null
LEFT_PAREN ( null
EOF  null

Errors should be printed to the stderr stream, starting with the [line N] prefix. If lexical errors were present, your program must exit with exit code 65.

The tester will assert that:

  • The stderr stream contains one line for each lexical error (if present)
    • Each line must match the format [line N] Error: Unexpected character: <character>
  • The stdout stream contains one line for each valid token (even if other lexical errors are present)
  • Your program exits with exit code 65 if lexical errors are present, and exit code 0 if not

Since we haven’t introduced the newline character yet, all errors will start with [line 1]. We’ll get to multi-line errors in later stages.

Notes
  • This output format matches the spec in the book’s repository
  • Since stdout and stderr are separate streams, the relative order of errors vs. valid tokens doesn’t matter. You’re free to print errors first, errors last, or errors interleaved with valid tokens.
  • Only lines that start with [line N] are considered errors, so you can still print other lines to stderr for debugging purposes.
  • When scanning for tokens, it’s valid to have “unbalanced” parentheses or braces. When we get to parsing expressions in later stages, these cases will be highlighted as errors.

Original stage ea6

6. Scanning: Assignment & equality Operators

In this stage, you’ll add support for scanning assignment & equality operators.

Book reference

The code for this stage is implemented in Section 4.5.2: Operators.

Tests

The tester will run a series of tests with test.lox files that contain equality & assignment operators mixed with previously introduced tokens.

For example, if test.lox contains the following:

={===}

The tester will run your program like this:

$ ./your_program.sh tokenize test.lox
EQUAL = null
LEFT_BRACE { null
EQUAL_EQUAL == null
EQUAL = null
RIGHT_BRACE } null
EOF  null

The tester will assert that the stdout of your program matches the format above.

Notes
  • This output format matches the spec in the book’s repository
  • When scanning for tokens, it’s valid to have “unbalanced” parentheses or braces. When we get to parsing expressions in later stages, these cases will be highlighted as errors.

Original stage mp7

7. Scanning: Negation & inequality operators

In this stage, you’ll add support for scanning negation & inequality operators.

Book reference

The code for this stage is implemented in Section 4.5.2: Operators.

Tests

The tester will run a series of tests with test.lox files that contain inequality & negation operators mixed with previously introduced tokens.

For example, if test.lox contains the following:

!!===

The tester will run your program like this:

$ ./your_program.sh tokenize test.lox
BANG ! null
BANG_EQUAL != null
EQUAL_EQUAL == null
EOF  null

The tester will assert that the stdout of your program matches the format above.

Notes
  • This output format matches the spec in the book’s repository
  • When scanning for tokens, it’s valid to have “unbalanced” parentheses or braces. When we get to parsing expressions in later stages, these cases will be highlighted as errors.

Original stage bu3

8. Scanning: Relational operators

In this stage, you’ll add support for scanning relational operators, which are: <, >, <=, >=.

Book reference

The code for this stage is implemented in Section 4.5.2: Operators.

Tests

The tester will run a series of tests with test.lox files that contain relational operators mixed with previously introduced tokens.

For example, if test.lox contains the following:

<<=>>=

The tester will run your program like this:

$ ./your_program.sh tokenize test.lox
LESS < null
LESS_EQUAL <= null
GREATER > null
GREATER_EQUAL >= null
EOF  null

The tester will assert that the stdout of your program matches the format above.

Notes
  • This output format matches the spec in the book’s repository
  • When scanning for tokens, it’s valid to have “unbalanced” parentheses or braces. When we get to parsing expressions in later stages, these cases will be highlighted as errors.

Original stage et2

9. Scanning: Division operator & comments

In this stage, you’ll add support for scanning the division operator & comments. Comments start with //, and the division operator is /.

Book reference

The code for this stage is implemented in Section 4.6: Longer Lexemes.

Tests

The tester will run a series of tests with test.lox files that contain / & // mixed with previously introduced tokens.

For example, if test.lox contains the following:

()// Comment

The tester will run your program like this:

$ ./your_program.sh tokenize test.lox
LEFT_PAREN ( null
RIGHT_PAREN ) null
EOF  null

Similarly, if test.lox contains the following:

/()

The tester will run your program like this:

$ ./your_program.sh tokenize test.lox
SLASH / null
LEFT_PAREN ( null
RIGHT_PAREN ) null
EOF  null

The tester will assert that the stdout of your program matches the format above.

Notes
  • This output format matches the spec in the book’s repository
  • There’s no token type for comments, your scanner just needs to ignore any characters after //.
  • When scanning for tokens, it’s valid to have “unbalanced” parentheses or braces. When we get to parsing expressions in later stages, these cases will be highlighted as errors.

Original stage ml2

10. Scanning: Whitespace

In this stage, you’ll add support for scanning whitespace characters (tabs, spaces and newlines).

Book reference

The code for this stage is implemented in Section 4.6: Longer Lexemes.

Tests

The tester will run a series of tests with test.lox files that contain whitespaces (tabs, spaces and newlines) mixed with previously introduced tokens.

For example, if test.lox contains the following:

(<|TAB|>
<|SPACE|>)

The tester will run your program like this:

$ ./your_program.sh tokenize test.lox
LEFT_PAREN ( null
RIGHT_PAREN ) null
EOF  null

The tester will assert that the stdout of your program matches the format above.

Note that the tab, space and newline characters are ignored, so they don’t appear as tokens in the output.

Notes
  • This output format matches the spec in the book’s repository
  • In the logs, the spaces will be replaced with <|SPACE|> and tabs will be replaced with <|TAB|> for readability. The test.lox file will contain actual space/tab characters.
  • When scanning for tokens, it’s valid to have “unbalanced” parentheses or braces. When we get to parsing expressions in later stages, these cases will be highlighted as errors.

Original stage er2

11. Scanning: Multi-line errors

In this stage, you’ll add support for scanning lexical errors, which span multiple lines.

Book reference

The code for this stage is implemented in Section 4.5.1: Lexical Errors.

Tests

The tester will run a series of tests with test.lox files that contain lexical errors spanning multiple lines.

For example, if test.lox contains the following:

#<|SPACE|>(
)<|TAB|>@

The tester will run your program like this:

$ ./your_program.sh tokenize test.lox
[line 1] Error: Unexpected character: #
[line 2] Error: Unexpected character: @
LEFT_PAREN ( null
RIGHT_PAREN ) null
EOF  null

Errors should be printed to the stderr stream, starting with the [line N] prefix. If lexical errors were present, your program must exit with exit code 65.

The tester will assert that:

  • The stderr stream contains one line for each lexical error (if present)
    • Each line must match the format [line N] Error: Unexpected character: <character>
  • The stdout stream contains one line for each valid token (even if other lexical errors are present)
  • Your program exits with exit code 65 if lexical errors are present, and exit code 0 if not

Line numbers should start at 1.

Notes
  • This output format matches the spec in the book’s repository
  • Since stdout and stderr are separate streams, the relative order of errors vs. valid tokens doesn’t matter. You’re free to print errors first, errors last, or errors interleaved with valid tokens.
  • Only lines that start with [line N] are considered errors, so you can still print other lines to stderr for debugging purposes.
  • When scanning for tokens, it’s valid to have “unbalanced” parentheses or braces. When we get to parsing expressions in later stages, these cases will be highlighted as errors.

Original stage tz7

12. Scanning: String literals

In this stage, you’ll add support for scanning string literals.

Book reference

The code for this stage is implemented in Section 4.6.1: String literals.

Tests

The tester will run a series of tests with test.lox files that contain string literals inside double quotes, mixed with previously introduced tokens.

For example, if test.lox contains the following:

"foo baz"

The tester will run your program like this:

$ ./your_program.sh tokenize test.lox
STRING "foo baz" foo baz
EOF  null

The tester will assert that the stdout of your program matches the format above.

As mentioned in the book, the format for printing out tokens is <TOKEN_TYPE> <LEXEME> <LITERAL>. Up until now, the <LITERAL> field was always null. For strings, the <LITERAL> field will contain the string’s contents.

If a string is unterminated, a lexical error should be raised.

For example, if test.lox contains the following:

"bar

The tester will run your program like this:

$ ./your_program.sh tokenize test.lox
[line 1] Error: Unterminated string.
EOF  null

The tester will assert that a lexical error is raised, the error message matches the expected format, and the program exits with status code 65.

Notes
  • This output format matches the spec in the book’s repository
  • The <LEXEME> field will contain the string’s contents including quotes, since it represents the actual characters that matched the token. The <LITERAL> field will contain the string’s contents without quotes, since it represents the string’s value.
  • Lox doesn’t support escape sequences within strings, so you can’t include a " inside a string.
  • When scanning for tokens, it’s valid to have “unbalanced” parentheses or braces. When we get to parsing expressions in later stages, these cases will be highlighted as errors.

Original stage ue7

13. Scanning: Number literals

In this stage, you’ll add support for scanning number literals.

Book reference

The code for this stage is implemented in Section 4.6.2: Number literals.

Tests

The tester will run a series of tests with test.lox files that contain number literals mixed with previously introduced tokens.

For example, if test.lox contains the following:

42

The tester will run your program like this:

$ ./your_program.sh tokenize test.lox
NUMBER 42 42.0
EOF  null

Just like strings, number literals have a “literal value” attached. Note that the literal value for an integer is represented as “42.0” (with a decimal point). This matches the book’s format.

You’ll also need to handle numbers with a decimal point, for example if test.lox contains the following:

1234.1234

The tester will run your program like this:

$ ./your_program.sh tokenize test.lox
NUMBER 1234.1234 1234.1234
EOF  null

The tester will run multiple such tests with randomized tokens, for example:

Input Expected output
1 NUMBER 1 1.0
2345.6789 NUMBER 2345.6789 2345.6789
42.0000 NUMBER 42.0000 42.0

The tester will assert that the stdout of your program matches the format above.

Notes
  • This output format matches the spec in the book’s repository
  • Although the <LITERAL> field for an integer is represented as “42.0” (with a decimal point), the <LEXEME> field will contain the integer’s value without the decimal point since it represents the actual characters that matched the token.
  • When scanning for tokens, it’s valid to have “unbalanced” parentheses or braces. When we get to parsing expressions in later stages, these cases will be highlighted as errors.

Original stage kj0

14. Scanning: Identifiers

In this stage, you’ll add support for scanning identifiers.

Book reference

The code for this stage is implemented in Section 4.7: Reserved Words and Identifiers.

Tests

The tester will run a series of tests with test.lox files that contain identifiers mixed with previously introduced tokens.

For example, if test.lox contains the following:

foo bar _hello

The tester will run your program like this:

$ ./your_program.sh tokenize test.lox
IDENTIFIER foo null
IDENTIFIER bar null
IDENTIFIER _hello null
EOF  null

The tester will assert that the stdout of your program matches the format above.

Notes
  • This output format matches the spec in the book’s repository
  • When scanning for tokens, it’s valid to have “unbalanced” parentheses or braces. When we get to parsing expressions in later stages, these cases will be highlighted as errors.

Original stage ey7

15. Scanning: Reserved words

In this stage, you’ll add support for scanning reserved words, which are: and, class, else, false, for, fun, if, nil, or, print, return, super, this, true, var, while.

Book reference

The code for this stage is implemented in Section 4.7: Reserved Words and Identifiers.

Tests

The tester will run a series of tests with test.lox files that contain reserved words mixed with other previously introduced token types.

For example, if test.lox contains the following:

and

The tester will run your program like this:

$ ./your_program.sh tokenize test.lox
AND and null
EOF  null

The tester will assert that the stdout of your program matches the format above.

Notes
  • This output format matches the spec in the book’s repository
  • When scanning for tokens, it’s valid to have “unbalanced” parentheses or braces. When we get to parsing expressions in later stages, these cases will be highlighted as errors.

Original stage pq5

Back to contents

Parsing Expressions

1. Booleans & Nil

In this stage you’ll implement support for the parse command and handle parsing true, false, and nil literals.

Book reference

Before starting this stage, make sure you’ve read the Representing Code chapter (chapter 5). The code covered in that chapter (AstPrinter) will be required to generate the output tested in this stage.

The code for this stage is implemented in Section 6.2: Recursive Descent Parsing.

The parse command

In the previous stages, the tester used the tokenize command to test your scanner implementation. In this extension, the tester will need to test your parser implementation, so it’ll use a different command instead: parse.

The parse command accepts a path to a file (test.lox for example) and prints out the AST representation of the file to stdout.

For example, if test.lox contains the following:

2 + 3

The parse command will return the following:

$ ./your_program.sh parse test.lox
(+ 2.0 3.0)

This output format matches the spec in the book’s repository.

For the same file, here’s what the output from tokenize would’ve been:

$ ./your_program.sh tokenize test.lox
NUMBER 2 2.0
PLUS + null
NUMBER 3 3.0
EOF  null
Tests

The tester will run a series of tests with test.lox files that contain the boolean values true & false, and the nil literal.

For example, if test.lox contains the following:

true

The tester will run your program like this:

$ ./your_program.sh parse test.lox
true

The tester will assert that the stdout of your program matches the format above.

Here’s a list of the tokens you’ll need to parse in this stage:

Input Expected output
true true
false false
nil nil
Notes

Original stage sc2

2. Number literals

In this stage, you’ll add support for parsing number literals.

Book reference

The code for this stage is implemented in Section 6.2: Recursive Descent Parsing.

Tests

The tester will run a series of tests with test.lox files that contain number literals, we include both integers and floats.

For example, if test.lox contains the following:

42.47

The tester will run your program like this:

$ ./your_program.sh parse test.lox
42.47

The tester will run multiple such tests with randomized expressions, for example:

Input Expected output
42 42.0
0.0 0.0
12.34 12.34

The tester will assert that the stdout of your program matches the format above.

Notes

Original stage ra8

3. String literals

In this stage, you’ll add support for parsing string literals.

Book reference

The code for this stage is implemented in Section 6.2: Recursive Descent Parsing.

Tests

The tester will run a series of tests with test.lox files that contain string literals, it can contain whitespaces, and numbers too, but everything is inside double quotes.

For example, if test.lox contains the following:

"hello"

The tester will run your program like this:

$ ./your_program.sh parse test.lox
hello

The tester will assert that the stdout of your program matches the format above.

Notes

Original stage th5

4. Parentheses

In this stage, you’ll add support for parsing parentheses.

Book reference

The code for this stage is implemented in Section 6.2: Recursive Descent Parsing.

Tests

The tester will run a series of tests with test.lox files that contain parentheses, combined with number literals, string literals and booleans.

For example, if test.lox contains the following:

("foo")

The tester will run your program like this:

$ ./your_program.sh parse test.lox
(group foo)

The tester will assert that the stdout of your program matches the format above.

Notes
  • This output format matches the spec in the book’s repository
  • Errors for unclosed parenthese are not checked in this stage, they’ll be checked in later stages.

Original stage xe6

5. Unary Operators

In this stage, you’ll add support for parsing the negation operator (-) & the logical not operator (!).

Book reference

The code for this stage is implemented in Section 6.2: Recursive Descent Parsing.

Tests

The tester will run a series of tests with test.lox files that contain unary operators, combined with previously introduced tokens.

For example, if test.lox contains the following:

!true

The tester will run your program like this:

$ ./your_program.sh parse test.lox
(! true)

The tester will assert that the stdout of your program matches the format above.

Notes

Original stage mq1

6. Arithmetic operators (1/2)

In this stage, you’ll add support for parsing the multiplication operator (*) & the division operator (/).

Book reference

The code for this stage is implemented in Section 6.2: Recursive Descent Parsing.

Tests

The tester will run a series of tests with test.lox files that contain multiplicative algebraic operators, combined with previously introduced tokens.

For example, if test.lox contains the following:

16 * 38 / 58

The tester will run your program like this:

$ ./your_program.sh parse test.lox
(/ (* 16.0 38.0) 58.0)

The tester will assert that the stdout of your program matches the format above.

Notes

Original stage wa9

7. Arithmetic operators (2/2)

In this stage, you’ll add support for parsing the addition operator (+) & the subtraction operator (-).

Book reference

The code for this stage is implemented in Section 6.2: Recursive Descent Parsing.

Tests

The tester will run a series of tests with test.lox files that contain additive algebraic operators, combined with previously introduced tokens.

For example, if test.lox contains the following:

52 + 80 - 94

The tester will run your program like this:

$ ./your_program.sh parse test.lox
(- (+ 52.0 80.0) 94.0)

The tester will assert that the stdout of your program matches the format above.

Notes

Original stage yf2

8. Comparison operators

In this stage, you’ll add support for parsing comparison operators: >, <, >= & <=.

Book reference

The code for this stage is implemented in Section 6.2: Recursive Descent Parsing.

Tests

The tester will run a series of tests with test.lox files that contain comparison operators, combined with previously introduced tokens.

For example, if test.lox contains the following:

83 < 99 < 115

The tester will run your program like this:

$ ./your_program.sh parse test.lox
(< (< 83.0 99.0) 115.0)

The tester will assert that the stdout of your program matches the format above.

Notes

Original stage uh4

9. Equality operators

In this stage, you’ll add support for parsing equality operators: == & !=.

Book reference

The code for this stage is implemented in Section 6.2: Recursive Descent Parsing.

Tests

The tester will run a series of tests with test.lox files that contain comparison operators, combined with previously introduced tokens.

For example, if test.lox contains the following:

"baz" == "baz"

The tester will run your program like this:

$ ./your_program.sh parse test.lox
(== baz baz)

The tester will assert that the stdout of your program matches the format above.

Notes

Original stage ht8

10. Syntactic errors

In this stage, you’ll add support for handling syntax errors in expressions.

Book reference

The code for this stage is implemented in Section 6.3: Syntax Errors.

Tests

The tester will run a series of tests with test.lox files that contain syntax errors.

For example, if test.lox contains the following:

(72 +)

The tester will run your program like this:

$ ./your_program.sh parse test.lox
[line 1] Error at ')': Expect expression.

The tester will assert that the exit code is 65.

Notes
  • This output format matches the spec in the book’s repository
  • Error messages should be printed to stderr, not stdout.
  • The tester won’t check the exact error message in this stage, it will only check that the program exits with code 65.

Original stage wz8

Back to contents

Evaluating Expressions

1. Literals: Booleans & Nil

In this stage you’ll implement support for the evaluate command and handle evaluating the true, false, and nil literals.

Book reference

The code for this stage is implemented in Section 7.2.1: Evaluating Literals.

The evaluate command

In the previous stages, the tester used the parse command to test your parser implementation. In this extension, the tester will need to test your evaluator implementation, so it’ll use a different command instead: evaluate.

The evaluate command accepts a path to a file (test.lox for example) and prints out the result of evaluating the file to stdout.

For example, if test.lox contains the following:

2 + 3

The evaluate command will return the following:

$ ./your_program.sh evaluate test.lox
5

This output format matches the spec in the book’s repository.

For the same file, here’s what the output from parse would’ve been:

$ ./your_program.sh parse test.lox
(+ 2.0 3.0)
Tests

The tester will run a series of tests with test.lox files that contain the boolean values true & false, and the nil literal.

For example, if test.lox contains the following:

true

The tester will run your program like this:

$ ./your_program.sh evaluate test.lox
true

The tester will run multiple such tests with randomized expressions, for example:

Input Expected output
true true
false false
nil nil

The tester will assert that the stdout of your program matches the format above.

Notes
  • This output format matches the spec in the book’s repository
  • For the nil literal, the tester will check that the program prints nil.

Original stage iz6

2. Literals: Strings & Numbers

In this stage, you’ll add support for evaluating number and string literals.

Book reference

The code for this stage is implemented in Section 7.2.1: Evaluating Literals.

Tests

The tester will run a series of tests with test.lox files that contain number literals and string literals.

For example, if test.lox contains the following:

"hello world!"

The tester will run your program like this:

$ ./your_program.sh evaluate test.lox
hello world!

The tester will run multiple such tests with randomized expressions, for example:

Input Expected output
"hello world!" hello world!
10.40 10.4
10 10

The tester will assert that the stdout of your program matches the format above.

Notes
  • For the string literals, the tester will check that the program prints the string without quotes.
  • For the number literals, the tester will check that the program prints the number with the minimum number of decimal places without losing precision. (For example, 10.40 should be printed as 10.4).
  • The formatting for numbers differs slightly from the scanning and parsing stages, but it aligns with the spec in the book’s repository

Original stage lv1

3. Parentheses

In this stage, you’ll add support for evaluating expressions inside parentheses.

Book reference

The code for this stage is implemented in Section 7.2.2: Evaluating parentheses.

Tests

The tester will test your program using a test.lox file that contains an expression with parentheses.

For example, if test.lox contains the following:

("hello world!")

The tester will run your program like this:

$ ./your_program.sh evaluate test.lox
hello world!

The tester will run multiple such tests with randomized expressions, for example:

Input Expected output
("hello world!") hello world!
(true) true
(10.40) 10.4
((false)) false

The tester will assert that the stdout of your program matches the format above.

Notes
  • This output format matches the spec in the book’s repository
  • String literals & number literals must be formatted using the same rules as the previous stage.

Original stage oq9

4. Unary Operators: Negation & Not

In this stage, you’ll add support for evaluating unary operators - and !.

Book reference

The code for this stage is implemented in Section 7.2.3: Evaluating unary expressions.

Tests

The tester will run a series of tests with test.lox files that contain expressions with unary operators.

For example, if test.lox contains the following:

-(73)

The tester will run your program like this:

$ ./your_program.sh evaluate test.lox
-73

The tester will run multiple such tests with randomized expressions, for example:

Input Expected output
-73 -73
!true false
!10.40 false
!((false)) true

The tester will assert that the stdout of your program matches the format above.

Notes
  • This output format matches the spec in the book’s repository
  • For truthyness and falsyness, we will follow the convention introduced in the book, where false and nil are falsy, and everything else is truthy.

Original stage dc1

5. Arithmetic Operators (1/2)

In this stage, you’ll add support for evaluating binary operators * and /.

Book reference

The code for this stage is implemented in Section 7.2.5: Evaluating binary operators.

Tests

The tester will run a series of tests with test.lox files that contain expressions with the arithmetic operators * and /.

For example, if test.lox contains the following:

(18 * 3 / (3 * 6))

The tester will run your program like this:

$ ./your_program.sh evaluate test.lox
3

The tester will run multiple such tests with randomized expressions, for example:

Input Expected output
42 / 5 8.4
18 * 3 / (3 * 6) 3
(10.40 * 2) / 2 10.4

The tester will assert that the stdout of your program matches the format above.

Notes
  • This output format matches the spec in the book’s repository
  • In this stage, you can assume we will not test for error cases. Runtime errors will be introduced in later stages. For now, all arithmetic operations will involve only two numbers.

Original stage bp3

6. Arithmetic Operators (2/2)

In this stage, you’ll add support for evaluating binary operators + and -.

Book reference

The code for this stage is implemented in Section 7.2.5: Evaluating binary operators.

Tests

The tester will run a series of tests with test.lox files that contain expressions with the arithmetic operators + and -.

For example, if test.lox contains the following:

20 + 74 - (-(14 - 33))

The tester will run your program like this:

$ ./your_program.sh evaluate test.lox
75

The tester will run multiple such tests with randomized expressions, for example:

Input Expected output
70 - 65 5
69 - 93 -24
10.40 - 2 8.4
23 + 28 - (-(61 - 99)) 13

The tester will assert that the stdout of your program matches the format above.

Notes
  • This output format matches the spec in the book’s repository
  • In this stage, you can assume we will not test for error cases. Runtime errors will be introduced in later stages. For now, all arithmetic operations will involve only two numbers.

Original stage jy2

7. String Concatenation

In this stage, you’ll add support for overloading the + operator. When the + operator is applied to two strings, it should concatenate them.

Book reference

The code for this stage is implemented in Section 7.2.5: Evaluating binary operators.

Tests

The tester will run a series of tests with test.lox files that contain expressions with the operator +.

For example, if test.lox contains the following:

"hello" + " world!"

The tester will run your program like this:

$ ./your_program.sh evaluate test.lox
hello world!

The tester will run multiple such tests with randomized expressions, for example:

Input Expected output
"hello" + " world!" hello world!
"42" + "24" 4224
"foo" + "bar" foobar

The tester will assert that the stdout of your program matches the format above.

Notes
  • This output format matches the spec in the book’s repository
  • In this stage, you can assume we will not test for error cases. Runtime errors will be introduced in later stages. For now, we will only pass 2 strings to the + operator in this stage.

Original stage jx8

8. Relational Operators

In this stage, you’ll add support for evaluating relational operators >, <, >= & <=.

Book reference

The code for this stage is implemented in Section 7.2.5: Evaluating binary operators.

Tests

The tester will run a series of tests with test.lox files that contain expressions with the relational operators >, <, >= & <=.

For example, if test.lox contains the following:

10 > 5

The tester will run your program like this:

$ ./your_program.sh evaluate test.lox
true

The tester will run multiple such tests with randomized expressions, for example:

Input Expected output
57 > -65 true
11 >= 11 true
(54 - 67) >= -(114 / 57 + 11) true

The tester will assert that the stdout of your program matches the format above.

Notes
  • This output format matches the spec in the book’s repository
  • In this stage, you can assume we will not test for error cases. Runtime errors will be introduced in later stages. For now, all relational operations will involve only two numbers.

Original stage et4

9. Equality Operators

In this stage, you’ll add support for evaluating equality operators == and !=.

Book reference

The code for this stage is implemented in Section 7.2.5: Evaluating binary operators.

Tests

The tester will run a series of tests with test.lox files that contain expressions with the equality operators == and !=.

For example, if test.lox contains the following:

156 == (89 + 67)

The tester will run your program like this:

$ ./your_program.sh evaluate test.lox
true

The tester will run multiple such tests with randomized expressions, for example:

Input Expected output
"hello" == "world" false
"foo" != "bar" true
"foo" == "foo" true
61 == "61" false

The tester will assert that the stdout of your program matches the format above.

Notes
  • This output format matches the spec in the book’s repository
  • In this stage, you can assume we will not test for error cases. Runtime errors will be introduced in later stages. For now, all equality operations will involve only numbers or strings.

Original stage hw7

10. Runtime Errors: Unary Operators

In this stage, you’ll add support for handling runtime errors while evaluating the unary operator -.

Book reference

The code for this stage is implemented in Section 7.3: Runtime Errors.

Tests

The tester will test your program using a test.lox file that contains an expression with the unary operator -. This expression will contain a usage of the - operator that should throw a runtime error.

The unary operator - will throw a runtime error if the operand is not a number.

For example, if test.lox contains the following:

-"hello world!"

The tester will run your program like this:

$ ./your_program.sh evaluate test.lox
Operand must be a number.
[line 1]

The tester will run multiple such tests with randomized expressions, for example:

Input Expected output
-"foo" Operand must be a number.
-true Operand must be a number.
-("foo" + "bar") Operand must be a number.
-false Operand must be a number.

The tester will assert that the exit code is 70, signifying a runtime error. Note that this is different from the expected exit code for a syntax error, which is 65.

Notes
  • This output format matches the spec in the book’s repository
  • Error messages should be printed to stderr, not stdout.
  • The tester won’t check the exact error message in this stage, it will only check that the program exits with code 70.

Original stage gj9

11. Runtime Errors: Binary Operators (1/2)

In this stage, you’ll add support for handling runtime errors while evaluating the binary operators * & /.

Book reference

The code for this stage is implemented in Section 7.3: Runtime Errors.

Tests

The tester will test your program using a test.lox file that contains an expression with the binary operators * or /. This expression will contain a usage of the * or / operator that should throw a runtime error.

The binary operators * & / will throw a runtime error if the operands are not both numbers.

For example, if test.lox contains the following:

"foo" / 42

The tester will run your program like this:

$ ./your_program.sh evaluate test.lox
Operands must be numbers.
[line 1]

The tester will run multiple such tests with randomized expressions, for example:

Input Expected output
"foo" * 42 Operands must be numbers.
true / 2 Operands must be numbers.
("foo" * "bar") Operands must be numbers.
false / true Operands must be numbers.

The tester will assert that the exit code is 70, signifying a runtime error. Note that this is different from the expected exit code for a syntax error, which is 65.

Notes
  • This output format matches the spec in the book’s repository
  • Error messages should be printed to stderr, not stdout.
  • The tester won’t check the exact error message in this stage, it will only check that the program exits with code 70.

Original stage yu6

12. Runtime Errors: Binary Operators (2/2)

In this stage, you’ll add support for handling runtime errors while evaluating the binary operators + & -.

Book reference

The code for this stage is implemented in Section 7.3: Runtime Errors.

Tests

The tester will test your program using a test.lox file that contains an expression with the binary operators + or -. This expression will contain usages of the + or - operator that should throw a runtime error.

The binary operators + & - will throw a runtime error if the operands are not both numbers or both strings.

For example, if test.lox contains the following:

17 + "bar"

The tester will run your program like this:

$ ./your_program.sh evaluate test.lox
Operands must be two numbers or two strings.
[line 1]

The tester will run multiple such tests with randomized expressions, for example:

Input Expected output
"foo" + true Operands must be numbers.
42 - true Operands must be numbers.
true + false Operands must be numbers.
"foo" - "bar" Operands must be numbers.

The tester will assert that the exit code is 70, signifying a runtime error. Note that this is different from the expected exit code for a syntax error, which is 65.

Notes
  • This output format matches the spec in the book’s repository
  • Error messages should be printed to stderr, not stdout.
  • The tester won’t check the exact error message in this stage, it will only check that the program exits with code 70.

Original stage cq1

13. Runtime Errors: Relational Operators

In this stage, you’ll add support for handling runtime errors while evaluating the relational operators >, <, >= & <=.

Book reference

The code for this stage is implemented in Section 7.3: Runtime Errors.

Tests

The tester will test your program using a test.lox file that contains an expression with the relational operator >, <, >= or <=. This expression will contain a usage of the relational operator that should throw a runtime error.

The relational operators >, <, >= & <= will throw a runtime error if the operands are not numbers.

For example, if test.lox contains the following:

17 > "bar"

The tester will run your program like this:

$ ./your_program.sh evaluate test.lox
Operands must be numbers.
[line 1]

The tester will run multiple such tests with randomized expressions, for example:

Input Expected output
"foo" < false Operands must be numbers.
true < 2 Operands must be numbers.
("foo" + "bar") < 42 Operands must be numbers.
false > true Operands must be numbers.

The tester will assert that the exit code is 70, signifying a runtime error. Note that this is different from the expected exit code for a syntax error, which is 65.

Notes
  • This output format matches the spec in the book’s repository
  • Error messages should be printed to stderr, not stdout.
  • The tester won’t check the exact error message in this stage, it will only check that the program exits with code 70.

Original stage ib5

Back to contents

Statements & State

1. Print: Generate output

In this stage, you’ll add support for the run command and handle running the print statement. For this, you’ll need to update your AST generator, parser & interpreter.

Book reference

The code for this stage is implemented in Section 8.1: Statements.

Tests

The tester will run a series of tests with test.lox files that contain the print statement.

For example, if test.lox contains the following

print "Hello, World!";

The tester will run your program like this:

$ ./your_program.sh run test.lox
Hello, World!

The tester will run multiple such tests with randomized expressions, for example:

Input Expected output
print "Hello, World!"; Hello, World!
print 42; 42
print true; true
print 12 + 24; 36

The tester will assert that the stdout of your program matches the format above, and that the exit code is 0.

The tester will also verify that your program correctly handles invalid print statements. For example:

print;

The tester will assert that the exit code is 65, signifying a syntax error.

Notes
  • This output format matches the spec in the book’s repository
  • The run command expects each statement to end with a semicolon. In contrast, the evaluate command is intended for single expressions and does not require a semicolon. Your implementation should support both modes of execution.

Original stage xy1

2. Print: Multiple statements

In this stage, you’ll add support for handling multiple statements in a single program. From here on, we will create test programs that span across multiple statements.

Book reference

The code for this stage is implemented in Section 8.1: Statements.

Tests

The tester will run a series of tests with test.lox files that contain multiple statements.

For example, if test.lox contains the following

print "Hello, World!";
print 42;

The tester will run your program like this:

$ ./your_program.sh run test.lox
Hello, World!
42

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

print "world" + "baz" + "bar";
print 27 - 26;
print "bar" == "quz";

Expected Output:

worldbazbar
1
false

Test Case 2:

Input:

print "hello"; print true;
print false;
print "bar"; print 43;

Expected Output:

hello
true
false
bar
43

Test Case 3:

Input:

print 81;
    print 81 + 46;
        print 81 + 46 + 19;

Expected Output:

81
127
146

Test Case 4:

Input:

print true != true;

print "36
10
78
";

print "There should be an empty line above this.";

Expected Output:

false
36
10
78

There should be an empty line above this.

The tester will assert that the stdout of your program matches the format above, and that the exit code is 0.

Notes

Original stage oe4

3. Expression statements

In this stage, you’ll add support for handling expression statements. An expression statement lets you place an expression where a statement is expected. They exist to evaluate expressions that have side effects.

Book reference

The code for this stage is implemented in Section 8.1: Statements.

Tests

The tester will run a series of tests with test.lox files that contain expressions that have side effects, combined with the print statement.

For example, if test.lox contains the following

"foo" + "bar";
print "baz";

The tester will run your program like this:

$ ./your_program.sh run test.lox
baz

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

(37 + 42 - 21) > (76 - 37) * 2;
print !false;
"baz" + "hello" + "quz" + "bar" == "bazhelloquzbar";
print !false;

Expected Output:

true
true

Test Case 2:

Input:

27 - 60 >= -99 * 2 / 99 + 76;
true == true;
("world" == "bar") == ("baz" != "hello");
print true;

Expected Output:

true

Test Case 3:

Input:

print "the expression below is invalid";
49 + "baz";
print "this should not be printed";

Expected Output:

the expression below is invalid
Operands must be two numbers or two strings.
[line 2]

Test Case 4:

Input:

print "79" + "baz";
print false * (18 + 84);

Expected Output:

79baz
Operands must be numbers.
[line 2]

The tester will assert that the stdout of your program matches the format above, and that the exit code is 70.

Notes

Original stage fi3

4. Variables: Declare variables

In this stage, you’ll add support for declaring variables using the var statement. For this, you’ll need to add support for the var declaration in your AST generator, parser & interpreter.

Book reference

The code for this stage is implemented in Section 8.2: Global Variables.

Tests

The tester will run a series of tests with test.lox files that contain the var statement.

For example, if test.lox contains the following

var a = "foo";
print a;

The tester will run your program like this:

$ ./your_program.sh run test.lox
foo

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

var world = 10;
print world;

Expected Output:

10

Test Case 2:

Input:

var bar = 99;
var foo = 99;
print bar + foo;
var quz = 99;
print bar + foo + quz;

Expected Output:

198
297

Test Case 3:

Input:

var foo = (8 * (62 + 62)) / 4 + 62;
print foo;

Expected Output:

310

Test Case 4:

Input:

var quz = 76;
var baz = quz;
print baz + quz;

Expected Output:

152

The tester will assert that the stdout of your program matches the format above, and that the exit code is 0.

Notes

Original stage yg2

5. Variables: Runtime Errors

In this stage, you’ll add support for handling runtime errors while accessing variables that haven’t been declared yet.

Book reference

The code for this stage is implemented in Section 8.2: Global Variables.

Tests

The tester will run a series of tests with test.lox files that access variables that haven’t been declared yet.

For example, if test.lox contains the following

print a;

The tester will run your program like this:

$ ./your_program.sh run test.lox
Undefined variable 'a'.
[line 1]

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

print 22;
print x;

Expected Output:

22
Undefined variable 'x'.
[line 2]

Test Case 2:

Input:

var baz = 96;
print hello;

Expected Output:

Undefined variable 'hello'.
[line 2]

Test Case 3:

Input:

var hello = 85;
var result = (hello + bar) / world;
print result;

Expected Output:

Undefined variable 'bar'.
[line 2]

Test Case 4:

Input:

var quz = 20;
var world = 51;
var hello = 56;
print quz + world + he

Expected Output:

Undefined variable 'he'.
[line 4]

The tester will assert that the exit code is 70, signifying a runtime error. Note that this is different from the expected exit code for a syntax error, which is 65.

Notes
  • This output format matches the spec in the book’s repository
  • Error messages should be printed to stderr, not stdout.
  • The tester won’t check the exact error message in this stage, it will only check that the program exits with code 70.

Original stage sv7

6. Variables: Initialize variables

In this stage, you’ll add support for initializing variables with the value passed to the var statement, or initializing them with nil if no value is passed.

Book reference

The code for this stage is implemented in Section 8.2: Global Variables.

Tests

The tester will run a series of tests with test.lox files that contain the var statement.

For example, if test.lox contains the following

var a;
print a;

The tester will run your program like this:

$ ./your_program.sh run test.lox
nil

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

var foo;
print foo;

Expected Output:

nil

Test Case 2:

Input:

var baz = "foo";
var bar;
print bar;

Expected Output:

nil

Test Case 3:

Input:

var baz = 69;
var world;
var quz;
print world;

Expected Output:

nil

Test Case 4:

Input:

var quz = 73 + 26 * 20;
print quz;
var hello = 26 * 20;
print quz + hello;
var foo;
print foo;

Expected Output:

593
1113
nil

The tester will assert that the stdout of your program matches the format above, and that the exit code is 0.

Notes

Original stage bc1

7. Variables: Redeclare variables

In this stage, you’ll add support for redeclaring variables using the var statement.

Book reference

The code for this stage is implemented in Section 8.2: Global Variables.

Tests

The tester will run a series of tests with test.lox files that contain the var statement.

For example, if test.lox contains the following

var a = 1;
var a = 2;
print a;

The tester will run your program like this:

$ ./your_program.sh run test.lox
2

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

var baz = "before";
print baz;
var baz = "after";
print baz;

Expected Output:

before
after

Test Case 2:

Input:

var hello = "after";
var hello = "before";
var hello = hello;
print hello;

Expected Output:

before

Test Case 3:

Input:

var world = 2;
print world;
var world = 3;
print world;
var hello = 5;
print hello;
var world = hello;
print world;

Expected Output:

2
3
5
5

Test Case 4:

Input:

var baz = bar;

Expected Output:

Undefined variable 'bar'.
[line 1]

The tester will assert that the stdout of your program matches the format above, and that the exit code is 0.

Notes

Original stage dw9

8. Assignment operation

In this stage, you’ll add support for assigning values to variables using the = operator. You need to only support variables that have already been declared on the left side of the assignment. Note that assignment is right associative, so a = b = 1 is equivalent to a = (b = 1).

Book reference

The code for this stage is implemented in Section 8.4: Assignment.

Tests

The tester will run a series of tests with test.lox files that contain the assignment operation.

For example, if test.lox contains the following

var a;
var b = 2;
var a = b = 1;
print a;

The tester will run your program like this:

$ ./your_program.sh run test.lox
1

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

var quz;
quz = 1;
print quz;
print quz = 2;
print quz;

Expected Output:

1
2
2

Test Case 2:

Input:

var hello = 93;
var bar = 93;
bar = hello;
hello = bar;
print hello + bar;

Expected Output:

186

Test Case 3:

Input:

var quz;
var hello;

quz = hello = 16 + 34 * 92;
print quz;
print hello;

Expected Output:

3144
3144

Test Case 4:

Input:

var hello = 65;
var baz;
var quz;

hello = baz = quz = hello * 2;
print hello;
print baz;
print baz;

Expected Output:

130
130
130

The tester will assert that the stdout of your program matches the format above, and that the exit code is 0.

Notes

Original stage pl3

9. Block syntax

In this stage, you’ll add support for block syntax in your interpreter. Blocks are enclosed in curly braces {} and are used to group statements together. They are also used to create local scopes. We will test scopes in the next stage, in this stage you just need to handle the block syntax.

Book reference

The code for this stage is implemented in Section 8.5.2: Block syntax and semantics.

Tests

The tester will run a series of tests with test.lox files that contain the assignment operation.

For example, if test.lox contains the following

{
    var foo = "before";
    print foo;
}
{
    var foo = "after";
    print foo;
}

The tester will run your program like this:

$ ./your_program.sh run test.lox
before
after

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

{
    var hello = "baz";
    print hello;
}

Expected Output:

baz

Test Case 2:

Input:

{
    var world = "before";
    print world;
}
{
    var world = "after";
    print world;
}

Expected Output:

before
after

Test Case 3:

Input:

{
    var hello = 88;
    {
        var foo = 88;
        print foo;
    }
    print hello;
}

Expected Output:

88
88

Test Case 4:

Input:

{
    var bar = 11;
    var world = 11;
    {
        print bar + world;
}

Expected Output:

[line 6] Error at end: Expect '}' .

The tester will assert that the stdout of your program matches the format above, and that the exit code is 0. If there is any blocks that are opened but not closed, it should throw a syntax error, the exit code in that case should be 65.

Notes

Original stage vr5

10. Scopes

In this stage, you’ll add support for scopes in your interpreter. Scopes are created by blocks, and they are used to group variables together. We will test variables in local scopes, nested scopes, shadowing of variables, and accessing variables outside of the scope where they are defined.

Book reference

The code for this stage is implemented in Section 8.5: Scope.

Tests

The tester will run a series of tests with test.lox files that contain the assignment operation.

For example, if test.lox contains the following

{
    var world = "before";
    {
        var world = "after";
        print world;
    }
    print world;
}

The tester will run your program like this:

$ ./your_program.sh run test.lox
after
before

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

var baz = (91 * 16) - 61;
{
    var world = "quz" + "89";
    print world;
}
print baz;

Expected Output:

quz89
1395

Test Case 2:

Input:

{
    var quz = "before";
    {
        var quz = "after";
        print quz;
    }
    print quz;
}

Expected Output:

after
before

Test Case 3:

Input:

var bar = "global bar";
var world = "global world";
var hello = "global hello";
{
  var bar = "outer bar";
  var world = "outer world";
  {
    var bar = "inner bar";
    print bar;
    print world;
    print hello;
  }
  print bar;
  print world;
  print hello;
}
print bar;
print world;
print hello;

Expected Output:

inner bar
outer world
global hello
outer bar
outer world
global hello
global bar
global world
global hello

Test Case 4:

Input:

{
  var hello = "outer hello";
  {
    var hello = "inner hello";
    print hello;
  }
  print hello;
}
print hello;

Expected Output:

inner hello
outer hello
Undefined variable 'hello'.
[line 9]

The tester will assert that the stdout of your program matches the format above, and that the exit code is 0. Accessing a variable outside of its scope should throw a runtime error, the exit code in that case should be 70.

Notes

Original stage fb4

Back to contents

Control Flow

1. If statements

In this stage, you’ll add support for the if statement in your interpreter. The if statement is used to conditionally execute statements based on a boolean condition.

Book reference

The code for this stage is implemented in Section 9.2: Conditional execution.

Tests

The tester will run a series of tests with test.lox files that contain programs with if statements.

For example, if test.lox contains the following

if (true) print "good";

The tester will run your program like this:

$ ./your_program.sh run test.lox
good

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

if (true) print "bar";

Expected Output:

bar

Test Case 2:

Input:

if (true) {
  print "block body";
}

Expected Output:

block body

Test Case 3:

Input:

var a = false;
if (a = true) {
  print (a == true);
}

Expected Output:

true

Test Case 4:

Input:

var stage = "unknown";
var age = 50;
if (age < 18) { stage = "child"; }
if (age >= 18) { stage = "adult"; }
print stage;

var isAdult = age >= 18;
if (isAdult) { print "eligible for voting: true"; }
if (!isAdult) { print "eligible for voting: false"; }

Expected Output:

adult
eligible for voting: true

The tester will assert that the stdout of your program matches the format above, and that the exit code is 0.

Notes

Original stage ne3

2. Else statements

In this stage, you’ll add support for the else statement in your interpreter. The else statement is used to conditionally execute statements when the if condition is false.

Book reference

The code for this stage is implemented in Section 9.2: Conditional execution.

Tests

The tester will run a series of tests with test.lox files that contain programs with if statements.

For example, if test.lox contains the following

if (true) print "if branch"; else print "else branch";

The tester will run your program like this:

$ ./your_program.sh run test.lox
if branch

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

if (true) print "if branch"; else print "else branch";

Expected Output:

if branch

Test Case 2:

Input:

var age = 21;
if (age > 18) print "adult"; else print "child";

Expected Output:

adult

Test Case 3:

Input:

if (false) {
  print "if block";
} else print "else statement";

if (false) print "if statement"; else {
  print "else block";
}

Expected Output:

else statement
else block

Test Case 4:

Input:

var celsius = 67;
var fahrenheit = 0;
var isHot = false;

{
  fahrenheit = celsius * 9 / 5 + 32;
  print celsius; print fahrenheit;

  if (celsius > 30) {
    isHot = true;
    print "It's a hot day. Stay hydrated!";
  } else {
    print "It's cold today. Wear a jacket!";
  }

  if (isHot) { print "Remember to use sunscreen!"; }
}

Expected Output:

67
152.6
It's a hot day. Stay hydrated!
Remember to use sunscreen!

The tester will assert that the stdout of your program matches the format above, and that the exit code is 0.

Notes

Original stage st5

3. Else-if statements

In this stage, you’ll add support for the else-if statement in your interpreter. The else-if statement is used to conditionally execute statements when the if condition is false.

Book reference

The code for this stage is implemented in Section 9.2: Conditional execution.

Tests

The tester will run a series of tests with test.lox files that contain programs with if statements.

For example, if test.lox contains the following

if (false) print "if branch"; else if (false) print "else-if branch";

The tester will run your program like this:

$ ./your_program.sh run test.lox

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

if (true) print "if branch"; else if (false) print "else-if branch";

Expected Output:

if branch

Test Case 2:

Input:

if (true) {
  print "hello";
} else if (true) print "hello";

if (true) print "hello"; else if (true) {
  print "hello";
}

Expected Output:

hello
hello

Test Case 3:

Input:

var age = 88;
var stage = "unknown";
if (age < 18) { stage = "child"; }
else if (age >= 18) { stage = "adult"; }
else if (age >= 65) { stage = "senior"; }
else if (age >= 100) { stage = "centenarian"; }
print stage;

Expected Output:

adult

Test Case 4:

Input:

var age = 67;

var isAdult = age >= 18;
if (isAdult) { print "eligible for voting: true"; }
else { print "eligible for voting: false"; }

if (age < 16) { print "eligible for driving: false"; }
else if (age < 18) { print "eligible for driving: learner's permit"; }
else { print "eligible for driving: full license"; }

if (age < 21) { print "eligible for drinking (US): false"; }
else { print "eligible for drinking (US): true"; }

Expected Output:

eligible for voting: true
eligible for driving: full license
eligible for drinking (US): true

The tester will assert that the stdout of your program matches the format above, and that the exit code is 0.

Notes

Original stage fh8

4. Nested if statements

In this stage, you’ll add support for nested if statements in your interpreter. Nested if statements are if statements that are inside the body of another if statement.

Book reference

The code for this stage is implemented in Section 9.2: Conditional execution.

Tests

The tester will run a series of tests with test.lox files that contain programs with if statements.

For example, if test.lox contains the following

if (true) if (true) print "nested true";

The tester will run your program like this:

$ ./your_program.sh run test.lox
nested true

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

if (true) if (true) print "nested true";

Expected Output:

nested true

Test Case 2:

Input:

if (true) {
  if (false) print "quz"; else print "quz";
}

Expected Output:

quz

Test Case 3:

Input:

var stage = "unknown";
var age = 29;
if (age < 18) {
    if (age < 13) { stage = "child"; }
    else if (age < 16) { stage = "young teenager"; }
    else { stage = "teenager"; }
}
else if (age < 65) {
    if (age < 30) { stage = "young adult"; }
    else if (age < 50) { stage = "adult"; }
    else { stage = "middle-aged adult"; }
}
else { stage = "senior"; }
print stage;

var isAdult = age >= 18;
if (isAdult) {
    print "eligible for voting: true";
    if (age < 25) {
        print "first-time voter: likely";
    }
    else { print "first-time voter: unlikely"; }
}
else { print "eligible for voting: false"; }

if (age < 16) { print "eligible for driving: false"; }
else if (age < 18) {
    print "eligible for driving: learner's permit";
    if (age < 17) { print "supervised driving required"; }
    else { print "unsupervised driving allowed with restrictions"; }
}
else { print "eligible for driving: full license"; }

if (age < 21) { print "eligible for drinking (US): false"; }
else {
    print "eligible for drinking (US): true";
    if (age < 25) { print "remember: drink responsibly!"; }
}

Expected Output:

young adult
eligible for voting: true
first-time voter: unlikely
eligible for driving: full license
eligible for drinking (US): true

Test Case 4:

Input:

if (true) if (false) print "world"; else print "baz";

Expected Output:

baz

The tester will assert that the stdout of your program matches the format above, and that the exit code is 0.

Notes

Original stage xj4

5. Logical OR operator

In this stage, you’ll add support for the logical OR operator in your interpreter. The logical OR operator combines two conditions and returns the first value that is truthy.

Book reference

The code for this stage is implemented in Section 9.3: Logical Operators.

Tests

The tester will run a series of tests with test.lox files that contain programs with the logical OR operator.

For example, if test.lox contains the following

print nil or "ok";

The tester will run your program like this:

$ ./your_program.sh run test.lox
ok

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

if (false or "ok") print "baz";
if (nil or "ok") print "baz";

if (false or false) print "world";
if (true or "world") print "world";

if (24 or "bar") print "bar";
if ("bar" or "bar") print "bar";

Expected Output:

baz
baz
world
bar
bar

Test Case 2:

Input:

print 41 or true;
print false or 41;
print false or false or true;

print false or false;
print false or false or false;
print true or true or true or true;

Expected Output:

41
41
true
false
false
true

Test Case 3:

Input:

var a = "hello";
var b = "hello";
(a = false) or (b = true) or (a = "hello");
print a;
print b;

Expected Output:

false
true

Test Case 4:

Input:

var stage = "unknown";
var age = 23;
if (age < 18) { stage = "child"; }
if (age >= 18) { stage = "adult"; }
print stage;

var isAdult = age >= 18;
if (isAdult) { print "eligible for voting: true"; }
if (!isAdult) { print "eligible for voting: false"; }

Expected Output:

adult
eligible for voting: true

The tester will assert that the stdout of your program matches the format above, and that the exit code is 0.

Notes

Original stage wk8

6. Logical AND operator

In this stage, you’ll add support for the logical AND operator in your interpreter. The logical AND operator combines two conditions and returns the first falsy value. If all values are truthy, it returns the last value.

Book reference

The code for this stage is implemented in Section 9.3: Logical Operators.

Tests

The tester will run a series of tests with test.lox files that contain programs with the logical AND operator.

For example, if test.lox contains the following

print false and "ok";

The tester will run your program like this:

$ ./your_program.sh run test.lox
false

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

if (false and "bad") print "foo";
if (nil and "bad") print "foo";

if (true and "hello") print "hello";
if (97 and "baz") print "baz";
if ("baz" and "baz") print "baz";
if ("" and "bar") print "bar";

Expected Output:

hello
baz
baz
bar

Test Case 2:

Input:

print false and 1;
print true and 1;
print 23 and "hello" and false;

print 23 and true;
print 23 and "hello" and 23;

Expected Output:

false
1
false
true
23

Test Case 3:

Input:

var a = "quz";
var b = "quz";
(a = true) and (b = false) and (a = "bad");
print a;
print b;

Expected Output:

true
false

Test Case 4:

Input:

var stage = "unknown";
var age = 14;
if (age < 18) { stage = "child"; }
if (age >= 18) { stage = "adult"; }
print stage;

var isAdult = age >= 18;
if (isAdult) { print "eligible for voting: true"; }
if (!isAdult) { print "eligible for voting: false"; }

Expected Output:

child
eligible for voting: false

The tester will assert that the stdout of your program matches the format above, and that the exit code is 0.

Notes

Original stage jx4

7. While statements

In this stage, you’ll add support for while statements in your interpreter. while statements are used to execute a block of code repeatedly while a condition is true.

Book reference

The code for this stage is implemented in Section 9.4: While loops.

Tests

The tester will run a series of tests with test.lox files that contain programs with while statements.

For example, if test.lox contains the following

var foo = 0;
while (foo < 3) print foo = foo + 1;

The tester will run your program like this:

$ ./your_program.sh run test.lox
1
2
3

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

var foo = 0;
while (foo < 3) print foo = foo + 1;

Expected Output:

1
2
3

Test Case 2:

Input:

var quz = 0;
while (quz < 3) {
  print quz;
  quz = quz + 1;
}

Expected Output:

0
1
2

Test Case 3:

Input:

while (false) {
  print "should not print";
}

var product = 1;
var i = 1;

while (i <= 5) {
  product = product * i;
  i = i + 1;
}

print "Product of numbers 1 to 5: "; print product;

Expected Output:

Product of numbers 1 to 5:
120

Test Case 4:

Input:

var n = 10;
var fm = 0;
var fn = 1;
var index = 0;

while (index < n) {
  print fm;
  var temp = fm;
  fm = fn;
  fn = temp + fn;
  index = index + 1;
}

Expected Output:

0
1
1
2
3
5
8
13
21
34

The tester will assert that the stdout of your program matches the format above, and that the exit code is 0.

Notes

Original stage qy3

8. For statements

In this stage, you’ll add support for the for statement in your interpreter. The for statement executes a block of code repeatedly using a “initializer” clause, a “condition” clause and an “increment” clause.

Book reference

The code for this stage is implemented in Section 9.5: For Loops.

Tests

The tester will run a series of tests with test.lox files that contain programs with if statements.

For example, if test.lox contains the following

for (var baz = 0; baz < 3;) print baz = baz + 1;

The tester will run your program like this:

$ ./your_program.sh run test.lox
1
2
3

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

for (var baz = 0; baz < 3;) print baz = baz + 1;

Expected Output:

1
2
3

Test Case 2:

Input:

for (var world = 0; world < 3; world = world + 1) {
  print world;
}

Expected Output:

0
1
2

Test Case 3:

Input:

var world = 0;
for (; world < 2; world = world + 1) print world;

for (var foo = 0; foo < 2;) {
  print foo;
  foo = foo + 1;
}

Expected Output:

0
1
0
1

Test Case 4:

Input:

var quz = "after";
{
  var quz = "before";

  for (var quz = 0; quz < 1; quz = quz + 1) {
    print quz;
    var quz = -1;
    print quz;
  }
}

{
  for (var quz = 0; quz > 0; quz = quz + 1) {}

  var quz = "after";
  print quz;

  for (quz = 0; quz < 1; quz = quz + 1) {
    print quz;
  }
}

Expected Output:

0
-1
after
0

The tester will assert that the stdout of your program matches the format above, and that the exit code is 0.

Notes

Original stage bw6

9. Syntactic errors

In this stage, you’ll add support for syntactic errors in your interpreter. Syntactic errors are errors that occur when the code is not written in the correct syntax.

Book reference

The code for this stage is implemented in Section 9.5: For Loops.

Tests

The tester will run a series of tests with test.lox files that contain programs with syntactic errors.

For example, if test.lox contains the following

for (;;) var foo;

The tester will run your program like this:

$ ./your_program.sh run test.lox
[line 1] Error at 'var': Expect expression.

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

if (true) "ok"; else var foo;

Expected Output:

[line 1] Error at 'var': Expect expression.

Test Case 2:

Input:

for (var a = 1; {}; a = a + 1) {}

Expected Output:

[line 2] Error at '{': Expect expression.
[line 2] Error at ')': Expect ';' after expression.

Test Case 3:

Input:

for (var a = 1; a < 2; {}) {}

Expected Output:

[line 2] Error at '{': Expect expression.

Test Case 4:

Input:

for ({}; a < 2; a = a + 1) {}

Expected Output:

[line 2] Error at '{': Expect expression.
[line 2] Error at ')': Expect ';' after expression.

The tester will only assert that the exit code is 65, when there is a compilation error.

Notes
  • This output format matches the spec in the book’s repository
  • Error messages should be printed to stderr, not stdout.
  • The tester won’t check the exact error message in this stage, it will only check that the program exits with code 65.

Original stage vt1

Back to contents

Functions

1. Native functions

In this stage, you’ll add support for native functions in your lox interpreter.

You can just define a single native function for now, we will go with clock() which returns the number of seconds elapsed since midnight January 1, 1970 UTC.

The return type for clock() can be a floating point number or an integer, the tester will cast it to an integer and then check if it is in a reasonable range.

Book reference

The code for this stage is implemented in Section 10.2: Native Functions.

Tests

The tester will run a series of tests with test.lox files that contain programs with native functions.

For example, if test.lox contains the following

print clock();

The tester will run your program like this:

$ ./your_program.sh run test.lox
1731411035

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

print clock() + 75;

Expected Output:

1731411035

Test Case 2:

Input:

print clock() / 1000;

Expected Output:

1731410

Test Case 3:

Input:

var startTime = clock();
var timeoutSeconds = 2;

// Check if less than 2 seconds have elapsed
if ((clock() >= startTime) and (clock() <= (startTime + timeoutSeconds))) {
  print "Operation in progress...";
} else {
  print "Operation timed out!";
}

Expected Output:

Operation in progress...

Test Case 4:

Input:

// Countdown from 3 seconds
var startTime = clock();
var totalDuration = 3; // 3 seconds countdown
var lastCheck = startTime;
var completed = false;

while (!completed) {
  var currentTime = clock();
  var elapsedTime = currentTime - startTime;
  var remainingTime = totalDuration - elapsedTime;

  // Update progress every second
  if (currentTime >= lastCheck + 1) {
    if (remainingTime >= 2) {
      print "Plenty of time remaining: ";
      print remainingTime;
    } else if (remainingTime >= 1) {
      print "Getting closer: ";
      print remainingTime;
    } else if (remainingTime > 0) {
      print "Almost there: ";
      print remainingTime;
    }
    lastCheck = currentTime;
  }

  // Check for completion
  if (elapsedTime >= totalDuration) {
    completed = true;
    print "Countdown complete!";
  } else if (elapsedTime < 0) {
    // Handle clock overflow or system time changes
    print "Time error detected!";
    completed = true;
  }
}

Expected Output:

Plenty of time remaining:
2
Getting closer:
1
Countdown complete!

The tester will assert that the stdout of your program matches the format above, and that the exit code is 0.

Notes

Original stage av4

2. Functions without arguments

In this stage, you’ll add support for declaring, defining and interpreting user defined functions with no arguments in your lox interpreter.

Book reference

The code for this stage is implemented in Section 10.3: Function declarations.

Tests

The tester will run a series of tests with test.lox files that contain programs with user defined functions with no arguments.

For example, if test.lox contains the following

fun bar() { print 10; }
bar();

The tester will run your program like this:

$ ./your_program.sh run test.lox
10

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

fun foo() {
  print 7;
}
foo();

Expected Output:

7

Test Case 2:

Input:

fun f() {}
f();

Expected Output:

Test Case 3:

Input:

fun foo() {}
print foo;

Expected Output:

<fn foo>

Test Case 4:

Input:

fun cumulative_sum() {
    var n = 10;  // Fixed value
    var total = 0;
    var i = 1;
    while (i <= n) {
        total = total + i;
        i = i + 1;
    }
    print "The cumulative sum from 1 to 10 is: ";
    print total;
}

cumulative_sum();

Expected Output:

The cumulative sum from 1 to 10 is:
55

The tester will assert that the stdout of your program matches the format above, and that the exit code is 0.

Notes

Original stage pg8

3. Functions with arguments

In this stage, you’ll add support for declaring, defining and interpreting user defined functions with arguments in your lox interpreter.

Book reference

The code for this stage is implemented in Section 10.3: Function declarations.

Tests

The tester will run a series of tests with test.lox files that contain programs with user defined functions with arguments.

For example, if test.lox contains the following

fun foo(a) { print a; }
foo(10);

The tester will run your program like this:

$ ./your_program.sh run test.lox
10

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

fun f1(a) {
  print a;
}
f1(76);

Expected Output:

76

Test Case 2:

Input:

fun f3(a, b, c) { print a + b + c; }
f3(24, 24, 24);

Expected Output:

72

Test Case 3:

Input:

fun f8(a, b, c, d, e, f, g, h) { print a - b + c * d + e - f + g - h; }
f8(51, 51, 51, 51, 51, 51, 51, 51);

Expected Output:

2601

Test Case 4:

Input:

fun calculateGrade(score, bonus) {
  var finalScore = score + bonus;

  if (finalScore >= 90) {
    print "A";
  } else if (finalScore >= 80) {
    print "B";
  } else if (finalScore >= 70) {
    print "C";
  } else if (finalScore >= 60) {
    print "D";
  } else {
    print "F";
  }
}

var score = 81;
var bonus = 3;
print "Grade for given score is: ";
calculateGrade(score, bonus);

Expected Output:

Grade for given score is:
B

The tester will assert that the stdout of your program matches the format above, and that the exit code is 0.

Notes

Original stage lb6

4. Syntax errors

In this stage, you’ll add support for detecting and handling syntax errors in user defined functions in your lox interpreter.

Book reference

The code for this stage is implemented in Section 10.3: Function Declarations.

Tests

The tester will run a series of tests with test.lox files that contain programs with user defined functions with arguments.

For example, if test.lox contains the following

clock(;

The tester will run your program like this:

$ ./your_program.sh run test.lox
[line 2] Error at ';': Expect expression.

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

print clock(;

Expected Output:

[line 1] Error at ';': Expect expression.

Test Case 2:

Input:

print clock)));

Expected Output:

[line 1] Error at ')': Expect ';' after value.

Test Case 3:

Input:

fun f() 74;
print f();

Expected Output:

[line 2] Error at '74': Expect '{' before function body.

Test Case 4:

Input:

fun foo(a, b c, d, e, f) {}
foo();

Expected Output:

[line 2] Error at 'c': Expect ')' after parameters.

The tester will assert that the exit code of your program is 65, when there is a compilation error.

Notes
  • This output format matches the spec in the book’s repository
  • Error messages should be printed to stderr, not stdout.
  • The tester won’t check the exact error message in this stage, it will only check that the program exits with code 65.

Original stage px4

5. Return statements

In this stage, you’ll add support for return statements in functions in your lox interpreter.

Book reference

The code for this stage is implemented in Section 10.5: Return Statements.

Tests

The tester will run a series of tests with test.lox files that contain programs with return statements in functions.

For example, if test.lox contains the following

fun foo() { return 10; }
print foo();

The tester will run your program like this:

$ ./your_program.sh run test.lox
10

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

fun fib(n) {
  if (n < 2) return n;
  return fib(n - 2) + fib(n - 1);
}

var start = clock();
print fib(10) == 55;
print (clock() - start) < 5; // 5 seconds

Expected Output:

true
true

Test Case 2:

Input:

fun f() {
  if (false) return "no"; else return "ok";
}

print f();

Expected Output:

ok

Test Case 3:

Input:

fun f() {
  while (!true) return "ok";
}

print f();

Expected Output:

nil

Test Case 4:

Input:

fun f() {
  return;
  print "bad";
}

print f();

Expected Output:

nil

The tester will assert that the stdout of your program matches the format above, and that the exit code is 0.

Notes

Original stage rd2

6. Higher order functions

In this stage, you’ll add support for higher order functions in your lox interpreter.

Book reference

The code for this stage is implemented in Section 10.6: Local functions and Closures.

Tests

The tester will run a series of tests with test.lox files that contain programs with higher order functions.

For example, if test.lox contains the following

fun makeGreeter() {
  fun greet(name) {
    print "Hello " + name;
  }
  return greet;
}

var sayHello = makeGreeter();
sayHello("Bob");

The tester will run your program like this:

$ ./your_program.sh run test.lox
Hello Bob

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

fun makeGreeter() {
  fun greet(name) {
    print "Hello " + name;
  }
  return greet;
}

var sayHello = makeGreeter();
sayHello("Bob");

Expected Output:

Hello Bob

Test Case 2:

Input:

fun returnArg(arg) {
  return arg;
}

fun returnFunCallWithArg(func, arg) {
  return returnArg(func)(arg);
}

fun printArg(arg) {
  print arg;
}

returnFunCallWithArg(printArg, "foo");

Expected Output:

foo

Test Case 3:

Input:

fun square(x) {
  return x * x;
}

// This higher-order function applies a
// function N times to a starting value x.
fun applyTimesN(N, f, x) {
  var i = 0;
  while (i < N) {
    x = f(x);
    i = i + 1;
  }
  return x;
}

// 6 is squared once
print applyTimesN(1, square, 6);
// 6 is squared twice
print applyTimesN(2, square, 6);
// 6 is squared thrice
print applyTimesN(3, square, 6);

Expected Output:

36
1296
1679616

Test Case 4:

Input:

fun makeFilter() {
  fun filter(n) {
    if (n < 42) {
      return false;
    }
    return true;
  }
  return filter;
}

// This function applies a function to a list of numbers
fun applyToNumbers(f, count) {
  var n = 0;
  while (n < count) {
    if (f(n)) {
      print n;
    }
    n = n + 1;
  }
}

var greaterThanX = makeFilter();

print "Numbers >= 42:";
applyToNumbers(greaterThanX, 42 + 5);

Expected Output:

Numbers >= 42:
42
43
44
45
46

The tester will assert that the stdout of your program matches the format above, and that the exit code is 0.

Notes

Original stage ey3

7. Runtime errors

In this stage, you’ll add support for runtime errors in your lox interpreter.

Book reference

The code for this stage is implemented in Section 10.4: Function Objects.

Tests

The tester will run a series of tests with test.lox files that contain programs with runtime errors.

For example, if test.lox contains the following

85();

The tester will run your program like this:

$ ./your_program.sh run test.lox
Can only call functions and classes.
[line 1]

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

"not a function"();

Expected Output:

Can only call functions and classes.
[line 1]

Test Case 2:

Input:

fun f(a, b) {
  print a;
  print b;
}

f(1, 2, 3, 4);

Expected Output:

Expected 2 arguments but got 4.
[line 6]

Test Case 3:

Input:

fun f(a, b) {}

f(1);

Expected Output:

Expected 2 arguments but got 1.
[line 3]

Test Case 4:

Input:

false();

Expected Output:

Can only call functions and classes.
[line 1]

The tester will assert that the stdout of your program matches the format above, and that the exit code is 70.

Notes
  • This output format matches the spec in the book’s repository
  • Error messages should be printed to stderr, not stdout.
  • The tester won’t check the exact error message in this stage, it will only check that the program exits with code 70.

Original stage fj7

8. Function scope

In this stage, you’ll add support for global and local scope in your lox interpreter.

Book reference

The code for this stage is implemented in Section 10.6: Local functions & Closures.

Tests

The tester will run a series of tests with test.lox files that contain programs with global and local scope.

For example, if test.lox contains the following

var a = 38;

fun printAndModify() {
  print a;
  var a = 95;
  print a;
}

print a;
a = 68;
printAndModify();

The tester will run your program like this:

$ ./your_program.sh run test.lox
38
68
95

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

var a = 38;

fun printAndModify() {
  print a;
  var a = 95;
  print a;
}

print a;
a = 68;
printAndModify();

Expected Output:

38
68
95

Test Case 2:

Input:

var count = 3;

fun tick() {
  if (count > 0) {
    print count;
    count = count - 1;
    return false;
  }
  print "Blast off!";
  return true;
}

while (!tick()) {}

Expected Output:

3
2
1
Blast off!

Test Case 3:

Input:

var counter = 89;

fun incrementCounter(amount) {
  counter = counter + amount;
  print counter;
}

{
  counter = 83;
  incrementCounter(6);
  print counter;
}
print counter;

Expected Output:

89
89
89

Test Case 4:

Input:

var x = 1;
var y = 2;

fun printBoth() {
  if (x < y) {
    print "x is less than y:";
    print x;
    print y;
  } else {
    print "x is not less than y:";
    print x;
    print y;
  }
}

{
  var x = 10;
  {
    var y = 20;

    var i = 0;
    while (i < 3) {
      x = x + 1;
      y = y - 1;
      print "Local x: ";
      print x;
      print "Local y: ";
      print y;
      i = i + 1;
    }

    if (x > y) {
      print "Local x > y";
    }

    printBoth();
  }
}

Expected Output:

Local x:
11
Local y:
19
Local x:
12
Local y:
18
Local x:
13
Local y:
17
x is less than y:
1
2

The tester will assert that the stdout of your program matches the format above, and that the exit code is 0.

Notes

Original stage bz4

9. Closures

In this stage, you’ll add support for closures in your lox interpreter.

Book reference

The code for this stage is implemented in Section 10.6: Local functions & Closures.

Tests

The tester will run a series of tests with test.lox files that contain programs with closures.

For example, if test.lox contains the following

fun makeCounter() {
  var i = 0;
  fun count() {
    i = i + 1;
    print i;
  }

  return count;
}

var counter = makeCounter();
counter();
counter();

The tester will run your program like this:

$ ./your_program.sh run test.lox
1
2

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

fun makeCounter() {
  var i = 0;
  fun count() {
    i = i + 1;
    print i;
  }

  return count;
}

var counter = makeCounter();
counter();
counter();

Expected Output:

1
2

Test Case 2:

Input:

{
  var threshold = 50;

  fun isEven(n) {
    if (n == 0) return true;
    if (n > threshold) return false;
    return isOdd(n - 1);
  }

  fun isOdd(n) {
    if (n == 0) return false;
    if (n > threshold) return false;
    return isEven(n - 1);
  }

  print isEven(61);
}

Expected Output:

false

Test Case 3:

Input:

fun makeLogger(prefix) {
  var logCount = 0;

  fun log(message) {
    logCount = logCount + 1;
    print prefix + ": " + message;

    if (logCount > 6) {
      print prefix + ": Too many log lines!";
      logCount = 0;
    }
  }

  return log;
}

var debugLog = makeLogger("debug");
var errorLog = makeLogger("error");

debugLog("Starting");
debugLog("Processing");
debugLog("Finishing");
debugLog("Extra line");

errorLog("Failed!");
errorLog("Retrying...");

Expected Output:

debug: Starting
debug: Processing
debug: Finishing
debug: Extra line
error: Failed!
error: Retrying...

Test Case 4:

Input:

fun makeAccumulator(label) {
  var sum = 0;
  var count = 0;

  fun accumulate(value) {
    sum = sum + value;
    count = count + 1;

    print label;
    print count;
    print sum;
    print sum;

    if (count > 3) {
      print "reset";
      sum = 0;
      count = 0;
    }

    return sum;
  }

  return accumulate;
}

var acc1 = makeAccumulator("First:");
var acc2 = makeAccumulator("Second:");

acc1(2);
acc1(6);
acc1(3);
acc1(4);

acc2(6);
acc2(4);

Expected Output:

First:
1
2
2
First:
2
8
8
First:
3
11
11
First:
4
15
15
reset
Second:
1
6
6
Second:
2
10
10

The tester will assert that the stdout of your program matches the format above, and that the exit code is 0.

Notes

Original stage gg6

Back to contents

Resolving & Binding

1. Identifier Resolution

In this stage, you’ll add support for identifier resolution and binding at compile time.

You will have to implement a resolver that will traverse the AST and resolve identifiers to their corresponding bindings, and execute the resolver in a separate pass over the AST.

We say identifier resolution because in this stage you’ll resolve variable declarations, variable assignments, function declarations and all other AST nodes.

Book reference

The code for this stage is implemented in Section 11.3: A Resolver Class.

Tests

The tester will run a series of tests with test.lox files that contain programs with identifier resolution and binding.

For example, if test.lox contains the following:

var variable = "global";

{
  fun f() {
    print variable;
  }

  f();

  var variable = "local";

  f();
}

The tester will run your program like this:

$ ./your_program.sh run test.lox
global
global

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

fun global() {
  print "global";
}

{
  fun f() {
    global();
  }

  f();

  fun global() {
    print "local";
  }

  f();
}

Expected Output:

global
global

Test Case 2:

Input:

var x = "global";

fun outer() {
  var x = "outer";

  fun middle() {
    fun inner() {
      print x;
    }

    inner();

    var x = "middle";

    inner();
  }

  middle();
}

outer();

Expected Output:

outer
outer

Test Case 3:

Input:

var count = 0;

{
  fun makeCounter() {
    fun counter() {
      count = count + 1;
      print count;
    }
    return counter;
  }

  var counter1 = makeCounter();
  counter1();
  counter1();

  var count = 0;

  counter1();
}

Expected Output:

1
2
3

The tester will assert that the stdout of your program matches the format above, and that the exit code is 0.

Notes
  • This output format matches the spec in the book’s repository
  • The resolver should ensure that variables are resolved to their correct scopes at compile time

Original stage de8

2. Self Initialization

In this stage, you’ll add support for detecting invalid self-initialization of variables. This means catching cases where a variable tries to use itself in its own initializer before it has been fully defined.

Book reference

The code for this stage is implemented in Section 11.5: Resolution Errors.

Tests

The tester will run a series of tests with test.lox files that contain programs with variable self-initialization.

For example, if test.lox contains the following:

var a = "value";
var a = a;      // This is allowed in global scope
print a;        // Should print "value"

The tester will run your program like this:

$ ./your_program.sh run test.lox
value

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

var a = "outer";
{
  var a = a;    // Error: Can't read local variable in its own initializer
}

Expected Output:

[line 3] Error at 'a': Can't read local variable in its own initializer.

Test Case 2:

Input:

fun returnArg(arg) {
  return arg;
}

var b = "global";
{
  var a = "first";
  var b = returnArg(b);    // Error: Can't read local variable in its own initializer
  print b;
}

var b = b + " updated";
print b;

Expected Output:

[line 8] Error at 'b': Can't read local variable in its own initializer.

Test Case 3:

Input:

fun outer() {
  var a = "outer";

  fun inner() {
    var a = a;    // Error: Can't read local variable in its own initializer
    print a;
  }

  inner();
}

outer();

Expected Output:

[line 5] Error at 'a': Can't read local variable in its own initializer.

The tester will assert that for valid global self-initialization, the exit code should be 0. For invalid local self-initialization, the program should exit with code 65 and print an appropriate error message.

Notes
  • This output format matches the spec in the book’s repository
  • Self-initialization is allowed in global scope but not in local scopes
  • The error should be detected at compile time, not runtime
  • Error messages should be written to stderr, but the exact error message is not checked.

Original stage pt7

3. Variable Redeclaration

In this stage, you’ll add support for detecting invalid variable redeclarations in the same scope. This means catching cases where a variable is declared multiple times in the same local scope.

Book reference

The code for this stage is implemented in Section 11.3: A Resolver Class.

Tests

The tester will run a series of tests with test.lox files that contain programs with variable redeclarations.

For example, if test.lox contains the following:

{
  var a = "value";
  var a = "other";
}

The tester will run your program like this:

$ ./your_program.sh run test.lox
[line 3] Error at 'a': Already a variable with this name in this scope.

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

fun foo(a) {
  var a;
}

Expected Output:

[line 2] Error at 'a': Already a variable with this name in this scope.

Test Case 2:

Input:

fun foo(arg, arg) {
  "body";
}

Expected Output:

[line 1] Error at 'arg': Already a variable with this name in this scope.

Test Case 3:

Input:

var a = "1";
print a;

var a;
print a;

var a = "2";
print a;

{
  var a = "1";
  var a = "2";
  print a;
}

Expected Output:

[line 12] Error at 'a': Already a variable with this name in this scope.

The tester will assert that for valid global redeclarations, the exit code should be 0. For invalid local redeclarations, the program should exit with code 65 and print an appropriate error message.

Notes
  • This output format matches the spec in the book’s repository
  • Variable redeclaration is allowed in global scope but not in local scopes
  • The error should be detected at compile time, not runtime
  • Error messages should be written to stderr, but the exact error message is not checked.

Original stage pz7

4. Invalid Return

In this stage, you’ll add support for detecting invalid return statements. Return statements are only allowed within function bodies and should be detected as errors when they appear in top-level code or blocks outside of functions.

Book reference

The code for this stage is implemented in Section 11.5.1: Invalid Return Errors.

Tests

The tester will run a series of tests with test.lox files that contain programs with return statements in various contexts.

For example, if test.lox contains the following:

fun foo() {
  return "at function scope is ok";
}

return;

The tester will run your program like this:

$ ./your_program.sh run test.lox
[line 6] Error at 'return': Can't return from top-level code.

The tester will run multiple such tests with randomized expressions, for example:

Test Case 1:

Input:

fun foo() {
  if (true) {
    return "early return";
  }

  for (var i = 0; i < 10; i = i + 1) {
    return "loop return";
  }
}

if (true) {
  return "conditional return";
}

Expected Output:

[line 12] Error at 'return': Can't return from top-level code.

Test Case 2:

Input:

{
  return "not allowed in a block either";
}

fun allowed() {
  if (true) {
    return "this is fine";
  }
  return;
}

Expected Output:

[line 3] Error at 'return': Can't return from top-level code.

Test Case 3:

Input:

fun outer() {
  fun inner() {
    return "ok";
  }

  return "also ok";
}

if (true) {
  fun nested() {
    return;
  }

  return "not ok";
}

Expected Output:

[line 15] Error at 'return': Can't return from top-level code.

The tester will assert that for return statements inside functions, the code should compile successfully. For return statements outside functions (in top-level code or blocks), the program should exit with code 65 and print an appropriate error message.

Notes
  • This output format matches the spec in the book’s repository
  • The error should be detected at compile time, not runtime
  • Error messages should be written to stderr, but the exact error message is not checked.

Original stage eh3

Back to contents

Classes

1. Class Declarations

In this stage, you’ll add support for class declarations in your Lox interpreter. This will allow users to define classes using the class keyword, which can later be instantiated and used.

Book reference

The code for this stage is implemented in Section 12.2: Class Declarations.

Tests

The tester will run a series of tests with test.lox files that contain class declarations in various contexts.

For example, if test.lox contains the following:

class Spaceship {}
print Spaceship;

The tester will run your program like this:

$ ./your_program.sh run test.lox
Spaceship

The tester will run multiple such tests with class declarations in different contexts, for example:

Test Case 1:

Input:

// Multiple class declarations with empty body
class Robot {}
class Wizard {}
print Robot;
print Wizard;
print "Both classes successfully printed";

Expected Output:

Robot
Wizard
Both classes successfully printed

Test Case 2:

Input:

{
  // Class declaration inside blocks should work
  class Dinosaur {}
  print "Inside block: Dinosaur exists";
  print Dinosaur;
}
print "Accessing out-of-scope class:";
print Dinosaur; // expect runtime error

Expected Output:

Inside block: Dinosaur exists
Dinosaur
Accessing out-of-scope class:
Undefined variable 'Dinosaur'.
[line 8]

Test Case 3:

Input:

// Class declaration inside function should work
fun foo() {
  class Superhero {}
  print "Class declared inside function";
  print Superhero;
}

foo();
print "Function called successfully";

Expected Output:

Class declared inside function
Superhero
Function called successfully

The tester will assert that your program correctly handles class declarations and follows the scoping rules for classes.

Notes
  • This output format matches the spec in the book’s repository
  • Classes should follow the same scoping rules as variables
  • When a class is printed, it should display its name
  • The tester won’t check the exact error message in this stage, it will only check that the program exits with code 70.

Original stage vf4

2. Class Instances

In this stage, you’ll add support for class instances in your Lox interpreter. This will allow users to instantiate classes using the class name followed by parentheses, e.g., ClassName().

Book reference

The code for this stage is implemented in Section 12.3: Creating Instances.

Tests

The tester will run a series of tests with test.lox files that contain class instantiation in various contexts.

For example, if test.lox contains the following:

class Spaceship {}
var falcon = Spaceship();
print falcon;

The tester will run your program like this:

$ ./your_program.sh run test.lox
Spaceship instance

The tester will run multiple such tests with class instantiation in different contexts, for example:

Test Case 1:

Input:

// Creating multiple instances of the same class
class Robot {}
var r1 = Robot();
var r2 = Robot();

print "Created multiple robots:";
print r1;
print r2;

Expected Output:

Created multiple robots:
Robot instance
Robot instance

Test Case 2:

Input:

class Wizard {}
class Dragon {}

// Instantiating classes in a function should work
fun createCharacters() {
  var merlin = Wizard();
  var smaug = Dragon();
  print "Characters created in fantasy world:";
  print merlin;
  print smaug;
  return merlin;
}

var mainCharacter = createCharacters();
// An instance of a class should be truthy
if (mainCharacter) {
  print "The main character is:";
  print mainCharacter;
} else {
  print "Failed to create a main character.";
}

Expected Output:

Characters created in fantasy world:
Wizard instance
Dragon instance
The main character is:
Wizard instance

Test Case 3:

Input:

class Superhero {}

var count = 0;
while (count < 3) {
  var hero = Superhero();
  print "Hero created:";
  print hero;
  count = count + 1;
}

print "All heroes created!";

Expected Output:

Hero created:
Superhero instance
Hero created:
Superhero instance
Hero created:
Superhero instance
All heroes created!

The tester will assert that your program correctly handles class instantiation and that instances are printed with the format “ClassName instance”.

Notes
  • This output format matches the spec in the book’s repository
  • Class instances should be truthy when used in conditional expressions
  • When an instance is printed, it should display its class name followed by the word “instance”

Original stage yk8

3. Getters & Setters

In this stage, you’ll add support for getting and setting properties on class instances. Properties can be dynamically added to instances after creation and can hold any type of value.

Book reference

The code for this stage is implemented in Section 12.4: Properties on Instances.

Tests

The tester will run a series of tests with test.lox files that contain property access and modification.

For example, if test.lox contains the following:

// Basic property setting and getting
class Spaceship {}
var falcon = Spaceship();

falcon.name = "Millennium Falcon";
falcon.speed = 75.5;

print "Ship details:";
print falcon.name;
print falcon.speed;

The tester will run your program like this:

$ ./your_program.sh run test.lox
Ship details:
Millennium Falcon
75.5

The tester will run multiple such tests with property access in different contexts, for example:

Test Case 1:

Input:

// Multiple properties and conditional access
class Robot {}
var r2d2 = Robot();

r2d2.model = "Astromech";
r2d2.operational = false;

if (r2d2.operational) {
  print r2d2.model;
  r2d2.mission = "Navigate hyperspace";
  print r2d2.mission;
}

Expected Output:

(No output because the condition is false)

Test Case 2:

Input:

// Multiple instances with properties
class Superhero {}
var batman = Superhero();
var superman = Superhero();

batman.name = "Batman";
batman.called = 18;

superman.name = "Superman";
superman.called = 66;

print "Times " + superman.name + " was called: ";
print superman.called;
print "Times " + batman.name + " was called: ";
print batman.called;

Expected Output:

Times Superman was called:
66
Times Batman was called:
18

Test Case 3:

Input:

// Property manipulation in functions
class Wizard {}
var gandalf = Wizard();

gandalf.color = "Grey";
gandalf.power = nil;
print gandalf.color;

fun promote(wizard) {
  wizard.color = "White";
  if (true) {
    wizard.power = 100;
  } else {
    wizard.power = 0;
  }
}

promote(gandalf);
print gandalf.color;
print gandalf.power;

Expected Output:

Grey
White
100

The tester will assert that your program correctly handles property access and modification, including:

  • Setting properties with different types of values
  • Reading property values
Notes
  • This output format matches the spec in the book’s repository
  • Properties can be dynamically added to instances at any time
  • Properties can hold any valid Lox value (strings, numbers, nil, etc.)
  • Accessing undefined properties should result in a runtime error

Original stage yf3

4. Instance Methods

In this stage, you’ll add support for instance methods in your Lox interpreter. Methods are functions defined within a class that can be called on instances of that class.

Book reference

The code for this stage is implemented in Section 12.5: Methods on Classes.

Tests

The tester will run a series of tests with test.lox files that contain method definitions and calls.

For example, if test.lox contains the following:

class Robot {
  beep() {
    print "Beep boop!";
  }
}

var r2d2 = Robot();
r2d2.beep();

Robot().beep();

The tester will run your program like this:

$ ./your_program.sh run test.lox
Beep boop!
Beep boop!

The tester will run multiple such tests with methods in different contexts, for example:

Test Case 1:

Input:

{
  class Foo {
    returnSelf() {
      return Foo;
    }
  }

  print Foo().returnSelf();  // expect: Foo
}

Expected Output:

Foo

Test Case 2:

Input:

class Wizard {
  castSpell(spell) {
    print "Casting a magical spell: " + spell;
  }
}

class Dragon {
  breatheFire(fire, intensity) {
    print "Breathing " + fire + " with intensity: "
    + intensity;
  }
}

// Methods on different class instances
var merlin = Wizard();
var smaug = Dragon();

// Conditional method calling
if (true) {
  var action = merlin.castSpell;
  action("Fireball");
} else {
  var action = smaug.breatheFire;
  action("Fire", "100");
}

Expected Output:

Casting a magical spell: Fireball

Test Case 3:

Input:

class Superhero {
  useSpecialPower(hero) {
    print "Using power: " + hero.specialPower;
  }

  hasSpecialPower(hero) {
    return hero.specialPower;
  }

  giveSpecialPower(hero, power) {
    hero.specialPower = power;
  }
}

// Methods in functions
fun performHeroics(hero, superheroClass) {
  if (superheroClass.hasSpecialPower(hero)) {
    superheroClass.useSpecialPower(hero);
  } else {
    print "No special power available";
  }
}

var superman = Superhero();
var heroClass = Superhero();

if (true) {
  heroClass.giveSpecialPower(superman, "Flight");
} else {
  heroClass.giveSpecialPower(superman, "Strength");
}

performHeroics(superman, heroClass);

Expected Output:

Using power: Flight

The tester will assert that your program correctly handles methods, including:

  • Defining methods within classes
  • Calling methods on instances
Notes
  • This output format matches the spec in the book’s repository
  • Methods are defined within the class body
  • Methods can take parameters and return values
  • Methods can be used to manipulate instance properties

Original stage qr2

5. The 'this' keyword

In this stage, you’ll add support for the this keyword in your Lox interpreter. The this keyword allows methods to access the instance they were called on, enabling full object-oriented programming.

Book reference

The code for this stage is implemented in Section 12.6: This.

Tests

The tester will run a series of tests with test.lox files that use the this keyword in various contexts.

For example, if test.lox contains the following:

class Spaceship {
  identify() {
    print this;
  }
}

Spaceship().identify();

The tester will run your program like this:

$ ./your_program.sh run test.lox
Spaceship instance

The tester will run multiple such tests with this in different contexts, for example:

Test Case 1:

Input:

class Calculator {
  add(a, b) {
    return a + b + this.memory;
  }
}

var calc = Calculator();
calc.memory = 82;
print calc.add(92, 1);

Expected Output:

175

Test Case 2:

Input:

class Animal {
  makeSound() {
    print this.sound;
  }
  identify() {
    print this.species;
  }
}

var dog = Animal();
dog.sound = "Woof";
dog.species = "Dog";

var cat = Animal();
cat.sound = "Meow";
cat.species = "Cat";

// Swap methods between instances
cat.makeSound = dog.makeSound;
dog.identify = cat.identify;

cat.makeSound();
dog.identify();

Expected Output:

Woof
Cat

Test Case 3:

Input:

class Wizard {
  getSpellCaster() {
    fun castSpell() {
      print this;
      print "Casting spell as " + this.name;
    }

    return castSpell;
  }
}

var wizard = Wizard();
wizard.name = "Merlin";
wizard.getSpellCaster()();

Expected Output:

Wizard instance
Casting spell as Merlin

The tester will assert that your program correctly handles the this keyword, including:

  • Referring to the instance in methods
  • Accessing instance properties through this
  • Maintaining correct this binding when methods are passed around
Notes
  • When methods are called, this should be bound to the instance the method was called on
  • The this binding should persist even when methods are passed around as first-class values
  • The output formats in this stage match those in the book’s repository

Original stage yd7

6. Invalid usages of 'this'

In this stage, you’ll add validation for the this keyword to ensure it’s only used in appropriate contexts. This involves detecting and reporting errors when this is used incorrectly.

Book reference

The code for this stage is implemented in Section 12.6: The ‘this’ Keyword, specifically the error handling parts.

Tests

The tester will run a series of tests with test.lox files that contain invalid usages of this.

For example, if test.lox contains the following:

print this;

The tester will run your program like this:

$ ./your_program.sh run test.lox
[line 1] Error at 'this': Can't use 'this' outside of a class.

The tester will run multiple tests with invalid this usage, for example:

Test Case 1:

Input:

fun notAMethod() {
  print this;
}

Expected Output:

[line 2] Error at 'this': Can't use 'this' outside of a class.

Test Case 2:

Input:

class Person {
  sayName() {
    print this();
  }
}
Person().sayName();

Expected Output:

Can only call functions and classes.
[line 3]

Test Case 3:

Input:

class Confused {
  method() {
    fun inner(instance) {
      var feeling = "confused";
      print this.feeling;
    }
    return inner;
  }
}

var instance = Confused();
var m = instance.method();
m(instance);

Expected Output:

Undefined property 'feeling'.
[line 5]

The tester will assert that for valid usages of this, the exit code should be 0. For compilation errors, the program should exit with code 65. For runtime errors, the program should exit with code 70. Both errors should print an appropriate error message.

Notes
  • These error formats match those in the book’s repository
  • Error messages should be written to stderr, but the exact error message is not checked.

Original stage dg2

7. Constructor calls

In this stage, you’ll add support for constructors in your Lox interpreter. In Lox, a constructor is a method named init() that is automatically called when a class instance is created.

Book reference

The code for this stage is implemented in Section 12.7: Constructors and Initializers.

Tests

The tester will run a series of tests with test.lox files that contain constructor definitions and calls.

For example, if test.lox contains the following:

class Default {
  init() {
    this.x = "bar";
    this.y = 91;
  }
}
print Default().x;
print Default().y;

The tester will run your program like this:

$ ./your_program.sh run test.lox
bar
91

The tester will run multiple such tests with constructors in different contexts, for example:

Test Case 1:

Input:

class Robot {
  init(model, function) {
    this.model = model;
    this.function = function;
  }
}
print Robot("R2-D2", "Astromech").model;

Expected Output:

R2-D2

Test Case 2:

Input:

class Counter {
  init(startValue) {
    if (startValue < 0) {
      print "startValue can't be negative";
      this.count = 0;
    } else {
      this.count = startValue;
    }
  }
}

var instance = Counter(-52);
print instance.count;
print instance.init(52).count;

Expected Output:

startValue can't be negative
0
52

Test Case 3:

Input:

class Vehicle {
  init(type) {
    this.type = type;
  }
}

class Car {
  init(make, model) {
    this.make = make;
    this.model = model;
    this.wheels = "four";
  }

  describe() {
    print this.make + " " + this.model +
    " with " + this.wheels + " wheels";
  }
}

var vehicle = Vehicle("Generic");
print "Generic " + vehicle.type;

var myCar = Car("Toyota", "Corolla");
myCar.describe();

Expected Output:

Generic Generic
Toyota Corolla with four wheels

The tester will assert that your program correctly handles constructors, including:

  • Calling the init() method automatically when a class is instantiated
  • Passing constructor arguments correctly
  • Setting instance properties in the constructor
Notes
  • The init() method can be called explicitly like any other method
  • This output format matches the spec in the book’s repository

Original stage ou5

8. Return within constructors

In this stage, you’ll handle special return behavior for constructors. In Lox, constructors (init() methods) have special rules for return statements: they can contain an empty return, but cannot return a value.

Book reference

The code for this stage is implemented in Section 12.7: Constructors, specifically the parts about return statements in initializers.

Tests

The tester will run a series of tests with test.lox files that contain return statements within constructors.

For example, if test.lox contains the following:

class Person {
  init() {
    print "world";
    return;
  }
}

Person();

The tester will run your program like this:

$ ./your_program.sh run test.lox
world

The tester will run multiple such tests with different return patterns in constructors, for example:

Test Case 1:

Input:

class ThingDefault {
  init() {
    this.x = "foo";
    this.y = 42;
    return this;
  }
}
var out = ThingDefault();
print out;

Expected Output:

[line 5] Error at 'return': Can't return a value from an initializer.

Test Case 2:

Input:

class Foo {
  init() {
    return "something else";
  }
}

Foo();

Expected Output:

[line 3] Error at 'return': Can't return a value from an initializer.

Test Case 3:

Input:

class Foo {
  init() {
    return this.callback();
  }

  callback() {
    return "callback";
  }
}

Foo();

Expected Output:

[line 3] Error at 'return': Can't return a value from an initializer.

The tester will assert that for valid returns, the exit code should be 0. For invalid returns, the program should exit with code 65 (compile error) and print an appropriate error message.

Notes
  • This output format matches the spec in the book’s repository
  • Error messages should be written to stderr, but the exact error message is not checked.

Original stage eb9

Back to contents

Inheritance

1. Class Hierarchy

In this stage, you’ll add support for class inheritance in your Lox interpreter. This will allow users to define class hierarchies using the < operator to specify a superclass.

Book reference

The code for this stage is implemented in Section 13.1: Superclasses and Subclasses.

Tests

The tester will run a series of tests with test.lox files that contain class inheritance declarations.

For example, if test.lox contains the following:

class Doughnut {}

class BostonCream < Doughnut {}

print Doughnut();
print BostonCream();

The tester will run your program like this:

$ ./your_program.sh run test.lox
Doughnut instance
BostonCream instance

The tester will run multiple such tests with inheritance in different contexts, for example:

Test Case 1:

Input:

{
  class A {}

  // B is a subclass of A
  class B < A {}

  // C is also a subclass of A
  class C < A {}

  print A();
  print B();
  print C();
}

Expected Output:

A instance
B instance
C instance

Test Case 2:

Input:

class Vehicle {}

// Car is a subclass of Vehicle
class Car < Vehicle {}

// Sedan is a subclass of Car
class Sedan < Car {}

print Vehicle();
print Car();
print Sedan();

{
  // Truck is a subclass of Vehicle
  class Truck < Vehicle {}
  print Truck();
}

Expected Output:

Vehicle instance
Car instance
Sedan instance
Truck instance

The tester will assert that your program correctly handles class inheritance declarations and follows the same instance printing rules as regular classes.

Notes
  • This output format matches the spec in the book’s repository
  • Subclasses should print their instances in the same format as regular classes
  • Inheritance declarations should work in any scope where class declarations are valid

Original stage mf6

2. Inheriting Methods

In this stage, you’ll add support for method inheritance in your Lox interpreter. This allows subclasses to inherit and use methods defined in their superclass.

Book reference

The code for this stage is implemented in Section 13.2: Inheriting Methods.

Tests

The tester will run a series of tests with test.lox files that contain method inheritance.

For example, if test.lox contains the following:

class Doughnut {
  cook() {
    print "Fry until golden brown.";
  }
}

// BostonCream is a subclass of Doughnut
class BostonCream < Doughnut {}

// BostonCream class should inherit the cook
// method from Doughnut class
BostonCream().cook();

The tester will run your program like this:

$ ./your_program.sh run test.lox
Fry until golden brown.

The tester will run multiple such tests with method inheritance in different contexts, for example:

Test Case 1:

Input:

class Root {
  getName() {
    print "Root class";
  }
}

class Parent < Root {
  parentMethod() {
    print "Method defined in Parent";
  }
}

class Child < Parent {
  childMethod() {
    print "Method defined in Child";
  }
}

var root = Root();
var parent = Parent();
var child = Child();

// Root methods are available to all
root.getName();
parent.getName();
child.getName();

// Parent methods are available to Parent and Child
parent.parentMethod();
child.parentMethod();

// Child methods are only available to Child
child.childMethod();

Expected Output:

Root class
Root class
Root class
Method defined in Parent
Method defined in Parent
Method defined in Child

The tester will assert that your program correctly handles method inheritance, including:

  • Methods being inherited through multiple levels of inheritance
  • Constructors being inherited from parent classes
Notes
  • This output format matches the spec in the book’s repository
  • Methods should be inherited through the entire inheritance chain
  • Inherited methods should have access to instance properties
  • Constructors (init methods) should also be inherited

Original stage ky1

3. Overriding Methods

In this stage, you’ll add support for method overriding in your Lox interpreter. This allows subclasses to provide their own implementation of methods defined in their superclass.

Book reference

The code for this stage is implemented in Section 13.2: Inheriting Methods.

Tests

The tester will run a series of tests with test.lox files that contain method overriding.

For example, if test.lox contains the following:

class A {
  method() {
    print "A method";
  }
}

// B inherits method `method` from A
// and overrides it with a new implementation
class B < A {
  method() {
    print "B method";
  }
}

var b = B();
b.method();  // expect: B method

The tester will run your program like this:

$ ./your_program.sh run test.lox
B method

The tester will run multiple such tests with method overriding in different contexts, for example:

Test Case 1:

Input:

class Base {
  init(a) {
    this.a = a;
  }
}

// Constructors can also be overridden
class Derived < Base {
  init(a, b) {
    this.a = a;
    this.b = b;
  }
}

var derived = Derived(89, 32);
print derived.a;
print derived.b;

Expected Output:

89
32

Test Case 2:

Input:

class Animal {
  speak() {
    return "Animal speaks";
  }

  makeSound() {
    return "Generic sound";
  }

  communicate() {
    return this.speak() + " : " + this.makeSound();
  }
}

class Dog < Animal {
  speak() {
    return "Dog speaks";
  }

  makeSound() {
    return "Woof";
  }
}

class Puppy < Dog {
  speak() {
    return "Puppy speaks";
  }
}

var animal = Animal();
var dog = Dog();
var puppy = Puppy();

print animal.communicate();
print dog.communicate();
print puppy.communicate();

Expected Output:

Animal speaks : Generic sound
Dog speaks : Woof
Puppy speaks : Woof

The tester will assert that your program correctly handles method overriding, including:

  • Methods being correctly overridden in subclasses
  • Constructors being overridden with new signatures
  • Multiple levels of method overriding working correctly
Notes
  • This output format matches the spec in the book’s repository
  • Overridden methods should completely replace the superclass implementation
  • Method overriding should work through multiple levels of inheritance

Original stage ka5

4. Inheritance errors

In this stage, you’ll add validation for class inheritance to ensure valid class hierarchies. This involves detecting and reporting errors for invalid inheritance patterns.

Book reference

The code for this stage is implemented in Section 13.1: Superclasses and Subclasses, specifically the error handling parts.

Tests

The tester will run a series of tests with test.lox files that contain invalid inheritance patterns.

For example, if test.lox contains the following:

// A class can't inherit from itself.
class Foo < Foo {} // expect compile error

The tester will run your program like this:

$ ./your_program.sh run test.lox
[line 2] Error at 'Foo': A class can't inherit from itself.

The tester will run multiple tests with invalid inheritance patterns, for example:

Test Case 1:

Input:

fun A() {}

// A class can only inherit from a class.
class B < A {} // expect runtime error

print A();
print B();

Expected Output:

Superclass must be a class.
[line 4]

Test Case 2:

Input:

var A = "class";

// A class can only inherit from a class
class B < A {} // expect runtime error

print B();

Expected Output:

Superclass must be a class.
[line 4]

The tester will assert that for valid class hierarchies, the exit code is 0. For invalid class hierarchies which can be detected at compile time, the program should exit with code 65 (compile error), for invalid class instantiation which can only be detected at runtime, the program should exit with code 70 (runtime error) and print an appropriate error message.

Notes
  • This output format matches the spec in the book’s repository
  • Error messages should be written to stderr, but the exact error messages are not checked.

Original stage ab0

5. The super keyword

In this stage, you’ll add support for the super keyword in your Lox interpreter. The super keyword allows methods to call overridden methods from their superclass.

Book reference

The code for this stage is implemented in Section 13.3: Calling Superclass Methods.

Tests

The tester will run a series of tests with test.lox files that use the super keyword.

For example, if test.lox contains the following:

class Doughnut {
  cook() {
    print "Fry until golden brown.";
  }
}

// Super can be used to call the overridden method
// of the parent class
class BostonCream < Doughnut {
  cook() {
    super.cook();
  }
}

BostonCream().cook();

The tester will run your program like this:

$ ./your_program.sh run test.lox
Fry until golden brown.

The tester will run multiple such tests with super in different contexts, for example:

Test Case 1:

Input:

class Base {
  method() {
    print "Base.method()";
  }
}

class Parent < Base {
  method() {
    super.method();
  }
}

class Child < Parent {
  method() {
    super.method();
  }
}

var parent = Parent();
parent.method();
var child = Child();
child.method();

Expected Output:

Base.method()
Base.method()

The tester will assert that your program correctly handles the super keyword, including:

  • Calling superclass methods through multiple levels of inheritance
  • Maintaining correct method resolution in complex inheritance chains
  • Proper binding of super in various contexts
Notes

Original stage qi0

6. Invalid Usages of the super Keyword

In this stage, you’ll add validation for the super keyword to ensure it’s only used in appropriate contexts. This involves detecting and reporting errors when super is used incorrectly.

Book reference

The code for this stage is implemented in Section 13.3: Calling Superclass Methods, specifically the error handling parts.

Tests

The tester will run a series of tests with test.lox files that contain invalid usages of super.

For example, if test.lox contains the following:

class Foo {
  cook() {
    // Foo is not a subclass
    super.cook(); // expect compile error
  }
}

The tester will run your program like this:

$ ./your_program.sh run test.lox
[line 4] Error at 'super': Can't use 'super' in a class with no superclass.

The tester will run multiple tests with invalid super usage, for example:

Test Case 1:

Input:

// super can't be used outside of a class
super.notEvenInAClass(); // expect compile error

Expected Output:

[line 2] Error at 'super': Can't use 'super' outside of a class.

Test Case 2:

Input:

class A {}

class B < A {
  method() {
    // super must be followed by `.`
    // and an expression
    super; // expect compile error
  }
}

Expected Output:

[line 7] Error at ';': Expect '.' after 'super'.

The tester will assert that your program correctly detects and reports invalid uses of super with appropriate error messages and exit codes. For invalid uses of super the program should exit with code 65 (compile error).

Notes
  • The super keyword should only be used in subclasses.
  • The super keyword should always be followed by . and an expression.
  • This output format matches the spec in the book’s repository
  • Error messages should be written to stderr, but the exact error messages are not checked.

Original stage ib9

Back to contents

Source and licence

Stage material by CodeCrafters. Source snapshot · Original licence.

MIT License

Copyright (c) 2022 CodeCrafters

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.