Master the fundamental concepts of semantic analysis through this focused micro-challenge.
After parsing, the compiler checks whether the program obeys language rules: types must match, variables must be declared, functions called correctly. Clang's Sema module and Java's javac attribution phase are large implementations of what you build in miniature.
Verify operators receive compatible operands (int + int, not int + struct). Ensure assignments match types. Confirm conditionals are boolean or truthy per language rules. Reject invalid implicit conversions before code generation.
cLoading…
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 a type checker that walks the AST and validates operator and assignment types. This exercise asks you to annotate expressions with types and emit errors when language rules are violated.
Implement a type checker for your C subset.
Define a type system:
Type enum: TYPE_INT, TYPE_CHAR, TYPE_VOID, TYPE_FLOAT, TYPE_ERRORImplement type checking functions:
check_expression(ASTNode*): Returns the type of an expressioncheck_statement(ASTNode*): Verifies statement type correctnesscheck_function(ASTNode*): Verifies function type correctnessType rules to enforce:
Error reporting:
TYPE_ERROR for invalid expressionsint x = "hello"; (type mismatch)int foo(int x) { return "bad"; }int x = 5; float y = x; (implicit promotion)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