Master the fundamental concepts of lexical analysis through this focused micro-challenge.
Identifiers and keywords look identical in the source: a letter followed by letters and digits. The lexer reads the full spelling, then checks a keyword table. Clang and GCC both use hash tables or trie structures for this lookup; CPython caches interned identifier strings.
Start at the first alphabetic character (or underscore). Consume while characters are alphanumeric or underscore. Buffer the spelling. If the spelling matches a reserved word in the keyword table, emit a keyword token; otherwise emit an identifier token carrying the name.
cLoading…
While and while differentlyProduction 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 identifier scanning and keyword disambiguation in your lexer. The exercise asks you to read alphanumeric sequences, consult a keyword table, and emit the correct token type so the parser can distinguish int the keyword from int as a variable name.
Implement efficient identifier scanning with keyword recognition.
Implement scan_identifier() that:
Implement lookup_keyword() that:
TOKEN_IDENTIFIER otherwiseSupport these C keywords (minimum):
int, char, void, float, doubleif, else, while, for, returnstruct, const, sizeofHandle edge cases:
int123 is identifier, not keyword + number_private is valid identifierINT is identifier, not keyword)int recognized as TOKEN_INTinteger recognized as TOKEN_IDENTIFIER_int recognized as TOKEN_IDENTIFIERThree 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