Master the fundamental concepts of lexical analysis through this focused micro-challenge.
Real compilers encounter garbage characters, unterminated strings, and malformed numeric literals constantly. Clang's lexer reports precise diagnostics and recovers so parsing can continue. A lexer that aborts on the first unexpected byte makes the compiler useless on incomplete or generated code.
When the lexer sees an invalid character, it should record an error with line and column, skip or consume the offending input, and return either an error token or continue scanning. Never read past the buffer end. Pair every error with enough context that the user can fix the source.
cLoading…
TOK_ERROR or a dedicated invalid token for the parser to handleProduction 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 add error detection and reporting to your lexer so invalid input produces clear messages instead of silent mis-tokenization. This exercise requires handling unexpected characters and malformed literals while keeping the scan loop running.
Extend your lexer with comprehensive error handling and reporting.
Create an error reporting system:
LexerError struct with message, line, columnHandle these error cases:
/* */123abc patternsImplement error tokens:
TOKEN_ERROR with descriptive messageAdd functions:
lexer_get_errors(): Return array of collected errorslexer_has_errors(): Check if any errors occurredlexer_error_count(): Return number of errorsThree 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