Master the fundamental concepts of syntax analysis through this focused micro-challenge.
While expressions compute values, statements perform effects: assignment, control flow, return. C's grammar separates statement parsing from expression parsing because dangling-else and declaration-vs-expression ambiguities require distinct code paths. GCC's parser and Clang's ParseStmt routines mirror this split.
Assignment: id = expr;. If-else: if (expr) stmt else stmt. While: while (expr) stmt. Return: return expr;. Block: { stmts }. Each form starts with a distinguishing token or identifier pattern.
cLoading…
;) are valid in C}Production 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 statement parsing functions that recognize assignments, conditionals, loops, returns, and blocks. This exercise asks you to extend your parser beyond expressions and produce statement AST nodes the semantic analyzer can walk.
Extend your parser to handle statements and statement lists.
Implement statement parsing functions:
parse_statement(): Dispatch to specific statement parsersparse_expression_statement(): Expression followed by semicolonparse_return_statement(): return expr;parse_if_statement(): if (cond) stmt [else stmt]parse_while_statement(): while (cond) stmtparse_block(): { stmt* }Handle expression statements:
;; alone) are validHandle return statements:
return; (void return)return expr; (value return)Handle if statements:
if (condition) statementelse statementelse binds to nearest ifHandle blocks:
return 42;if (x > 0) return x; else return -x;{ int x; x = 5; return x; }Three 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