Master the fundamental concepts of syntax analysis through this focused micro-challenge.
Most production parsers start as recursive descent: one function per grammar rule, mutual recursion for expressions and statements. Python's parser, many DSL compilers, and Clang's early parsing paths use this style because it maps directly onto the grammar and produces great errors.
Write parse_expression(), parse_statement(), parse_function() that consume tokens and return AST nodes. Each function checks the current token, dispatches on it, and recursively calls sub-parsers. Left recursion in the grammar must be rewritten or handled with precedence climbing.
cLoading…
peek() inspects without consuming; advance() moves forwardProduction compilers embed this step inside a longer pipeline. GCC flows through cpp, cc1, assembly, and ld; Clang uses the driver, Sema, LLVM IR passes, and a target backend. LLVM bitcode, JVM bytecode, and WASM are other familiar IRs at the same layer. The exercise isolates one pass so you can test it alone before chaining it to the next stage.
You will implement a recursive descent parser that consumes your lexer's token stream and builds an AST. This exercise requires parsing expressions with correct operator precedence and handling statements, function declarations, and blocks.
Implement a recursive descent parser for arithmetic expressions with proper precedence.
Create a Parser struct with:
Implement grammar rules as functions:
parse_expression(): Entry point, handles lowest precedenceparse_equality(): == !=parse_comparison(): < > <= >=parse_term(): + -parse_factor(): * /parse_unary(): - !parse_primary(): literals, identifiers, grouped expressionsImplement helper functions:
parser_create(Lexer* lexer)parser_advance()parser_check(TokenType type)parser_match(TokenType type)parser_consume(TokenType type, const char* message)Handle parentheses for grouping: (2 + 3) * 4
2 + 3 * 4 with correct precedence(2 + 3) * 4 with parentheses-x + y with unary minusThree hints are available for this task, revealed one at a time inside the code workspace so you can struggle productively before seeing them.
All starter code and reference implementations are available for your local setup.
View on Github