Master the fundamental concepts of lexical analysis through this focused micro-challenge.
Every production compiler starts by carving source text into tokens. Clang's Token class, GCC's cpp_token, and CPython's tokenizer all carry the same core fields: a kind, the original lexeme, and a source location. Get this struct wrong and every later phase pays for it.
A token is the smallest meaningful unit the parser consumes. For int x = 42; the lexer must emit distinct tokens for the keyword, identifier, operator, literal, and semicolon. Each token needs enough metadata to drive parsing and diagnostics.
cLoading…
KW_INT with lexeme intIDENT with lexeme xINT_LIT with value 42SEMI with lexeme ;Line and column numbers are what let Rust and Clang print caret diagnostics instead of vague file-level errors.
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 the Token and TokenType definitions that every subsequent lexer function returns. This exercise asks you to nail down the data contract before writing scanning logic: enum variants for keywords, identifiers, literals, and punctuation, plus a struct wide enough to hold literal values and source positions.
Implement a complete Token structure and supporting types for a C compiler's lexer.
Define a TokenType enum with at least these categories:
TOKEN_INT, TOKEN_RETURN, TOKEN_IF, TOKEN_ELSE, TOKEN_WHILETOKEN_PLUS, TOKEN_MINUS, TOKEN_STAR, TOKEN_SLASH, TOKEN_ASSIGNTOKEN_EQ, TOKEN_NE, TOKEN_LT, TOKEN_GT, TOKEN_LE, TOKEN_GETOKEN_LPAREN, TOKEN_RPAREN, TOKEN_LBRACE, TOKEN_RBRACE, TOKEN_SEMICOLON, TOKEN_COMMATOKEN_NUMBER, TOKEN_IDENTIFIER, TOKEN_STRINGTOKEN_EOF, TOKEN_ERRORDefine a Token struct containing:
Implement helper functions:
token_create(): Allocate and initialize a tokentoken_destroy(): Free token memorytoken_type_to_string(): Return human-readable type namegcc -Wall -WextraThree 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