Master the fundamental concepts of lexical analysis through this focused micro-challenge.
With dozens of reserved words, linear search over a keyword list is too slow for production lexers. GCC and Clang use hash tables or perfect hashing. A simple chained hash table keyed on the spelling gives O(1) average lookup and is what you will build here.
Insert each keyword at compile time (or lexer init) with its token type. At scan time, after reading an identifier spelling, hash the string, probe the bucket, and compare with strcmp. On match, return the keyword token; on miss, return an identifier.
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 hash table that maps keyword spellings to TokenType values. This exercise requires inserting reserved words, handling collisions, and integrating lookup into your identifier scanner so keywords are recognized in constant time.
Implement keyword recognition using a hash table for O(1) lookup.
Requirements:
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