Chapter 1

Lexical analysis and compiler organisation

The lexer groups characters; the parser groups tokens; semantic analysis checks their permitted meanings. Keep these interfaces separate when identifying the phase that detects an error.

1.1 Compiler phases and symbol tables

Past papers · CS 2014–2026 (23 papers): 11 questions, 11 marks

A phase is a logical task; a pass is a traversal of the program representation. Several phases may share a pass. A compiler can perform type checking while parsing, but type checks still belong conceptually to semantic analysis.

PhaseMain input → outputTypical responsibility
Lexical analysisCharacters → tokens with attributesRecognise identifiers, literals and punctuation; skip specified whitespace/comments
Syntax analysisTokens → parse tree or ASTCheck phrase structure using a grammar
Semantic analysisTree and declarations → checked/annotated treeResolve names, check types and permitted uses
Intermediate code generationAnnotated structure → intermediate representationExpress computations and control independently of a particular machine
OptimisationRepresentation → equivalent representationRemove redundancy and improve cost while preserving behaviour
Target code generationRepresentation → target instructionsSelect instructions, assign registers, establish calling conventions

The front end is mainly source-language dependent and target independent. The back end is target dependent. A machine-independent optimiser can serve several front ends and back ends through a common intermediate representation. An interpreter executes the program's operations rather than necessarily producing a separate target program.

A symbol table associates a declared entity with its name, type, scope, storage class, size, offset and other needed information. It is shared across phases; it is not itself a program IR. An identifier spelling may be interned by the lexer; declaration-specific entries and scope information are commonly added later. A hash table, search tree or stack of scope tables may implement it. Separate declarations with the same spelling need separate bindings.

FaultUsual classification
Unclosed quoted literal; character matching no token ruleLexical
Missing operand or unmatched delimiter in a token sequenceSyntactic
Undeclared name, incompatible operand/argument type, assigning a void resultSemantic
Stack exhaustion or failure of a dynamic allocationRuntime

1.2 Tokens and longest matching prefixes

Past papers · CS 2014–2026 (23 papers): 2 questions, 3 marks

A token kind is a class such as identifier or number. A lexeme is the actual character sequence, such as rate7. A pattern describes all lexemes of a kind. A token often carries an attribute such as a symbol-table reference or literal value.

A keyword rule before an identifier rule recognises while as a keyword on a tie, but while9 remains a single identifier if that longer match is legal. Recognise a quoted string as one literal token, even when its contents contain spaces or punctuation. Multi-character operators such as <= are one token when defined that way. A minus sign is normally a separate operator, not part of an integer token; follow the supplied patterns.

1.3 Lexer construction and scanning

Regular expressions specify token patterns. A usual implementation combines their NFAs, converts the result to a DFA and optionally minimises it. See Theory of Computation for these automaton constructions. Here an accepting state also records the selected token/action, so minimisation must preserve that output distinction.

To implement maximal munch, continue while transitions exist and remember the most recent accepting position and action. On failure, return to that position and emit the remembered token. Reaching a nonaccepting state does not by itself end a token. If no accepting position was seen, recovery must consume or otherwise resolve the invalid character to avoid an infinite retry.

Lexers often use two input buffers with sentinels to reduce end-of-buffer tests. A lexeme may cross a buffer boundary, so the start and forward positions must remain meaningful. End of buffer is not necessarily end of file. Do not assume a particular buffer size in a question unless given.

Nested arbitrary-depth syntax is generally the parser's task. Regular expressions suffice for the usual identifiers and numeric literals, not for unbounded nesting of matching delimiters. A fixed DFA's transition per character is constant work; a naive scanner that repeatedly rescans a long failed suffix need not have linear total time.

Last-minute recall

  • Character stream → lexer; token stream → parser.
  • A lexeme is an instance; a token kind is a category.
  • Longest match precedes rule priority.
  • Comments and whitespace are skipped only where the token rules say so.
  • Symbol tables remain useful after parsing.
  • A phase and a pass are different concepts.

Revise offline: the whole Compiler Design handbook as one PDF

43 pages · 2.0 MBFree to read online. Sign in to download the PDF.We save the handbook, version and request time in My downloads. Privacy policy

All chapters · Corrections