Expression Parser
You'll turn the string 2 + 3 * (4 - 1) into a tree and then into the number 11, by hand, with no parsing library.
About
Parsing is the skill behind every compiler, config loader and query language. It feels like magic until you write a tokenizer and a recursive descent parser, and then it feels like a loop with a few rules. Start with arithmetic. By the end you'll have a calculator that gets precedence right and a clear path to a real language in the Epic tier.
At a glance
- Per requirement
- 35 XP
- Completion bonus
- 300 XP
- Requirements
- 6
- Takes
- Two to three weeks
- Skill level
- Advanced (years of practice)
- Cost
- Free
- Supplies
- Nothing special
- Where
- At home
- Other people
- On your own
Requirements
-
1
Write a tokenizer that turns a string into a list of numbers, operators and parentheses. Handle whitespace, multi-digit numbers and decimals. Reject anything else with an error that names the bad character and its position. Take a screenshot of the tokens for 12.5 * (3 + 4) and an error for 3 $ 4. Photo
-
2
Write a grammar for arithmetic on paper, with precedence and parentheses. You want expression, term and factor, in three or four rules. If you can't fit it on an index card, it's wrong. Take a photo of the grammar. Photo
-
3
Build a recursive descent parser that returns a tree. Write one function per grammar rule. Print the tree with indentation. For 2 + 3 * 4 the multiply should show up under the add, not the other way around. Take a screenshot of the printed tree. Photo
-
4
Evaluate the tree and get the right answer on 20 test expressions. Include nested parentheses, unary minus, and division by zero with a clean error. Compare each one against a calculator. Take a screenshot of the tests passing. Photo
-
5
Add variables and assignment so that x = 5 followed by x * 2 works. A dictionary makes a fine environment. Referencing an undefined variable should give a clear error. Take a screenshot of a session with three assignments and a use. Photo
-
6
Make it a REPL that reads a line, evaluates it, prints the result and loops until the user quits. Errors should print and the loop should carry on. Ctrl-C exits cleanly. Film a 30-second session with a few expressions and one error. Video