Master the fundamental concepts of lexical analysis through this focused micro-challenge.
Clang, GCC, V8, and Go's gc compiler all scan source with hand-rolled loops like the one you are writing. A lexer walks the input buffer, skips whitespace and comments, classifies the next lexeme, and emits a Token. Flex can generate scanners, but production compilers prefer explicit control for error messages and performance.
The lexer maintains a cursor into the source and repeatedly: skip trivia, peek at the current character, decide what kind of token starts here, consume characters until the lexeme is complete, then return the token with line and column metadata.
cLoading…
= vs ==)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 next_token() and the helper functions that drive a complete scan over a small C-like subset. The task requires a working lexer that emits the token stream your parser will consume, so focus on correct classification and position tracking.
Implement a lexer that tokenizes a subset of C code.
Create a Lexer struct containing:
Implement these functions:
lexer_create(const char* source): Initialize lexer statelexer_destroy(Lexer* lexer): Clean up resourceslexer_next_token(Lexer* lexer): Return the next tokenlexer_peek(Lexer* lexer): Look at next token without consumingHandle these token types:
+ - * / ( ) { } ; ,== != <= >= && ||42, 0, 123)[a-zA-Z_][a-zA-Z0-9_]*int, return, if, else, whileSkip whitespace and single-line comments (//)
int main() { return 42; }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