Skip to main content

Compiler Design

Lexical Analysis & Phases

Start Compiler Design here: memorise the phase order and what each phase consumes and produces, then learn how a scanner turns characters into tokens using regular expressions and the longest-match rule.

~4 hrs ~0.5–1 marks · High 10 samples · 8 practice · 10 cards

GATE CSE compiler phases and lexical analysis — analysis vs synthesis, the six phases, symbol table, tokens/lexemes/patterns, maximal munch, regular expressions to scanners, which phase catches which error, with sample questions, flashcards and drills.

Learning outcomes

  • List the compiler phases in order with the input, output and typical errors of each
  • Distinguish token, lexeme and pattern and count tokens in a C statement using maximal munch
  • Explain how a lexical analyzer is built from regular expressions (Thompson NFA → DFA)
  • Decide whether an error is lexical, syntactic or semantic, and separate analysis from synthesis, front end from back end

Phases of a compiler

  • A compiler translates a source program into an equivalent target program and reports errors. It has two halves: the ANALYSIS part (front end) breaks the source into pieces and builds an intermediate representation, and the SYNTHESIS part (back end) builds the target program from that representation.
  • Six phases in order: (1) lexical analysis, (2) syntax analysis, (3) semantic analysis, (4) intermediate code generation, (5) code optimization, (6) code generation. The symbol table and the error handler are used by every phase.
  • Lexical analysis converts the character stream into tokens. Syntax analysis (parsing) checks the token stream against a context-free grammar and builds a parse/syntax tree. Semantic analysis checks meaning: types, scope, declare-before-use, argument counts.
  • Intermediate code generation produces machine-independent code such as three-address code. Code optimization improves that code (faster / smaller). Code generation selects instructions, allocates registers and emits target code.
  • Analysis phases (lexical, syntax, semantic) depend only on the SOURCE language. Code generation depends on the TARGET machine. Intermediate code generation and machine-independent optimization sit between them, so a front end for one language can be reused with several back ends.
  • A PASS is one complete traversal of the source or of its intermediate form. Several phases can be grouped into one pass (a single-pass compiler cannot do global optimization); a multi-pass compiler reads the program several times and can optimize more but needs more memory and time.
  • The symbol table stores each name with its attributes (type, scope, size, offset, number of parameters). It is usually a hash table, built during lexical/syntax analysis and used by semantic analysis and code generation.
  • Compiler vs interpreter: a compiler translates the whole program first and the target program then runs fast; an interpreter executes the source statement by statement (easier debugging, slower execution). An assembler translates assembly into machine code; a linker/loader resolves addresses.
  • A cross compiler runs on one machine but generates code for another. Bootstrapping means writing a compiler for a language in that same language and compiling it with an earlier, simpler version.
PhaseInputOutputTypical errors found
Lexical analysischaracterstokensillegal character, malformed number, unclosed string
Syntax analysistokensparse / syntax treemissing semicolon, unbalanced parentheses
Semantic analysisparse treeannotated treetype mismatch, undeclared variable, wrong argument count
Intermediate code gen.annotated treethree-address code—
Code optimizationintermediate codebetter intermediate code—
Code generationintermediate codetarget (machine) code—

Worked example

Problem. Trace the statement position = initial + rate * 60 (position, initial, rate are floats) through the phases.

Solution. Lexical: id1 = id2 + id3 * 60. Syntax: tree with = at the root, + below it and * below +. Semantic: 60 is an integer, so insert inttofloat(60). Intermediate code: t1 = inttofloat(60); t2 = id3 * t1; t3 = id2 + t2; id1 = t3. Optimization: t1 = id3 * 60.0; id1 = id2 + t1 (constant folded, temporaries removed). Code generation: LDF R2, id3; MULF R2, R2, #60.0; LDF R1, id2; ADDF R1, R1, R2; STF id1, R1.

Lexical analysis — tokens, lexemes and patterns

  • The lexical analyzer (scanner) reads the source characters and returns a stream of TOKENS to the parser, one on each “get next token” request. It also strips white space and comments, keeps track of line numbers for error messages, and enters identifiers into the symbol table.
  • TOKEN = (token name, optional attribute value), e.g. <id, pointer-to-symbol-table-entry>, <num, 60>, <relop, LE>. LEXEME = the actual character sequence matched in the source (rate, 60, <=). PATTERN = the rule describing the lexemes of a token, usually a regular expression such as letter(letter|digit)*.
  • Typical tokens: keywords (if, while), identifiers, constants, string literals, operators (+, <=, ++), and punctuation ( ) { } ; ,. Each reserved word is normally its own token; one token class (id) covers all identifiers.
  • Longest match (maximal munch): the scanner always takes the LONGEST prefix of the remaining input that matches some pattern. So “>=” is one token, not “>” followed by “=”, and “ifx” is an identifier, not the keyword if followed by x.
  • If two patterns match the same longest lexeme, the rule listed FIRST wins. That is why keyword rules are written before the identifier rule: “if” matches both, and listing keywords first makes it a keyword.
  • Counting tokens: split the statement into lexemes, applying maximal munch. Each identifier, keyword, constant, string literal, operator and punctuation mark is one token. A string literal “...” is ONE token even if it contains spaces, commas or % signs.
  • Input buffering: scanners use a pair of buffers (two halves of N characters, each ended by a sentinel character such as EOF) with two pointers, lexemeBegin and forward, so that looking ahead one or more characters costs at most one extra test per character.
  • The scanner is a deterministic finite automaton; therefore it can recognise only regular patterns. Checking balanced parentheses, matching begin/end or nested comments is NOT a lexical job; that needs a context-free grammar (the parser).

Formulas to remember

  • identifier = letter ( letter | digit )*
  • integer constant = digit+ ; float = digit+ . digit+ ( E [+-]? digit+ )?
  • tokens = (token name, attribute) ; lexeme = matched characters ; pattern = regular expression
LexemeTokenPattern (informal)
ififthe characters i f
count1idletter followed by letters / digits
3.14numdigits . digits
<=relop (LE)< or <= or == or != or > or >=
"hello, world"literalany characters surrounded by double quotes

Worked example

Problem. How many tokens are in the C statement printf("i=%d, &i=%x", i, &i); ?

Solution. Lexemes: printf, (, "i=%d, &i=%x", ",", i, ",", &, i, ), ; — the string literal is a single token and the commas inside it are not separate tokens. Count: printf(1) ((2) literal(3) ,(4) i(5) ,(6) &(7) i(8) )(9) ;(10) = 10 tokens.

From regular expressions to a scanner

  • A scanner generator (Lex/Flex) takes a list of rules “pattern { action }”. It converts each regular expression to an NFA (Thompson construction), combines them with a new start state, converts the NFA to a DFA (subset construction), minimizes it and emits the table-driven scanner.
  • Thompson construction: every NFA has exactly one start and one final state, no transitions leave the final state, and each state has at most two outgoing transitions. The NFA for a regular expression r has at most 2·|r| states (|r| = number of symbols and operators). The NFA for a single symbol a has 2 states; for a* it has 4 states (new start, the two states of a, new final).
  • Scanner run: the DFA keeps reading input until it gets stuck; it then backs up to the LAST accepting state seen (this implements longest match) and returns that token. Input is then restarted after the lexeme.
  • Rule order resolves ties; longest match resolves prefixes. Example rules: (1) if → IF, (2) [a-z]+ → ID. For input “if” both match 2 characters, rule 1 wins (IF). For “ifx” the identifier rule matches 3 characters, which is longer, so the token is ID.
  • Lexical errors are rare in practice: a character that begins no token (such as # in the middle of an expression, or an unterminated string). The scanner reports it and uses panic-mode recovery: delete characters until a valid token start is found. Misspelling a keyword (“whille”) is NOT a lexical error; it is just an identifier, and the parser will complain.
  • Why use regular expressions for tokens and CFGs for syntax? Tokens are simple (regular), a DFA scanner is fast, and separating the two phases keeps the front end modular and portable. A CFG is only needed for nesting and recursion.
  • Lexical analysis is usually the most time-consuming part of a compiler front end simply because it touches every character of the input, so buffering and DFA tables are optimised heavily.

Formulas to remember

  • states in Thompson NFA ≤ 2 × (number of symbols + operators of the regex)
  • DFA from n-state NFA: ≤ 2^n states (then minimize)

Worked example

Problem. How is the input x = a+++b; split into tokens by a scanner using maximal munch?

Solution. After x and =, the scanner sees a+++b. Identifier a is matched. Next, the longest operator starting at “+++” is “++” (there is no “+++” token), then the next token is “+”, then b. Tokens: x, =, a, ++, +, b, ; — 7 tokens (parsed as (a++) + b).

Which phase catches which error? (exam traps)

  • Lexical error: illegal character, malformed constant such as 12.3.4 or 09 in some languages, unterminated string or comment. Syntax error: missing or extra token in the structure — missing semicolon, unmatched bracket, “a = b + ;”, “if x > 0” without parentheses.
  • Semantic error: assigning a string to an int, using an undeclared variable, wrong number or types of arguments, break outside a loop, duplicate declaration, missing return type. Semantic analysis uses the symbol table and a type system.
  • Not detected at compile time (runtime or logical): division by zero, array index out of range (in most languages), infinite loops, wrong algorithm. Some uninitialized-variable cases are only warnings.
  • Analysis vs synthesis: lexical, syntax and semantic analysis are analysis (front end); intermediate code generation is the bridge; code optimization and code generation are synthesis (back end). The symbol table is shared by all phases.
  • Output of each phase in one line: scanner → tokens; parser → parse tree; semantic analyzer → annotated tree; ICG → three-address code; optimizer → better three-address code; code generator → target code.
  • Peephole optimization is a machine-dependent optimization performed on the generated target code over a small sliding window of instructions; it is the usual last step in the back end.
  • Tools: Lex/Flex build scanners; Yacc/Bison build LALR(1) parsers; syntax-directed translation engines and code-generator generators exist for later phases.
Error examplePhase that reports it
int x = 5 @ 3; (illegal symbol @)Lexical
x = (a + b; (missing right parenthesis)Syntax
int x; x = "abc"; (type mismatch)Semantic
y = z + 1; where z is never declaredSemantic
"abc (string never closed)Lexical
a = b + ;Syntax

Worked example

Problem. A programmer writes while (i < 10 i++; Which phase reports the error?

Solution. The token stream while ( i < 10 i ++ ; is lexically valid (every lexeme is a legal token) but violates the grammar: a closing parenthesis is missing. The parser, i.e. the syntax analysis phase, reports the error.

Exam tips

  • Memorise the order: lexical → syntax → semantic → intermediate code → optimization → code generation.
  • When counting tokens, apply maximal munch and treat a whole string literal or a multi-character operator (++, <=, ->) as ONE token.
  • A scanner is a DFA, so anything needing counting or nesting (balanced parentheses) cannot be a lexical task.
  • Keyword vs identifier: same length → first rule wins; longer match always wins.
  • Type errors and undeclared names are semantic; missing semicolons and brackets are syntactic; illegal characters are lexical.
Exam pattern · 10 questions

GATE sample questions & answers

10 GATE-style MCQs for Lexical Analysis & Phases with full explanations. Attempt each question before revealing the answer.

Q1 Classic GATE token-count pattern

The number of tokens in the following C statement is printf("i = %d, &i = %x", i, &i);

  • A) 3
  • B) 26
  • C) 10
  • D) 21
Show answer & explanation

Answer: C

Tokens: printf, (, the string literal (one token), comma, i, comma, &, i, ), ; — total 10.

Q2

Which one of the following is a lexical error?

  • A) a missing semicolon at the end of a statement
  • B) assigning a string value to an integer variable
  • C) an unterminated string literal
  • D) use of an undeclared variable
Show answer & explanation

Answer: C

An unterminated string cannot be turned into a valid token, so the scanner reports it. A is syntactic; B and D are semantic.

Q3

The output of the lexical analyzer is:

  • A) a parse tree
  • B) a stream of tokens
  • C) intermediate code
  • D) a symbol table only
Show answer & explanation

Answer: B

The scanner reads characters and returns a stream of tokens (with attributes) to the parser.

Q4

Which of the following is NOT a function of the lexical analysis phase?

  • A) removing white space and comments
  • B) recognising keywords and identifiers
  • C) checking that parentheses are balanced
  • D) reporting illegal characters
Show answer & explanation

Answer: C

Balanced parentheses require a context-free grammar (a stack), so this belongs to the parser, not to the DFA-based scanner.

Q5 Maximal munch

A scanner using maximal munch reads the C fragment x = a+++b; How many tokens does it produce?

  • A) 5
  • B) 6
  • C) 7
  • D) 8
Show answer & explanation

Answer: C

x, =, a, ++, +, b, ; — the longest operator at “+++” is “++”, leaving “+” as a separate token.

Q6

Which one of the following is NOT part of the analysis (front-end) phases of a compiler?

  • A) lexical analysis
  • B) syntax analysis
  • C) semantic analysis
  • D) code generation
Show answer & explanation

Answer: D

Code generation builds the target program, so it belongs to synthesis (the back end).

Q7

A lexical analyzer has the rules (1) if → IF and (2) [a-z]+ → ID, listed in this order. The tokens returned for the input ifx if are respectively:

  • A) IF ID IF
  • B) ID IF
  • C) IF ID
  • D) ID ID
Show answer & explanation

Answer: B

“ifx” matches only rule 2 over 3 characters (longest match) so it is ID; the second lexeme “if” matches both rules with the same length, and the first rule wins, so it is IF.

Q8

The number of states in the Thompson NFA for the regular expression a* is:

  • A) 1
  • B) 2
  • C) 3
  • D) 4
Show answer & explanation

Answer: D

The NFA for a has 2 states; the star construction adds a new start and a new final state, giving 4 states.

Q9

Which data structure is most commonly used to implement the symbol table in a compiler for fast insertion and lookup?

  • A) linked list
  • B) stack
  • C) hash table
  • D) queue
Show answer & explanation

Answer: C

A hash table gives expected O(1) insertion and lookup of identifiers, which is why it is the usual choice.

Q10

The statement int x = "abc"; is reported as an error by the:

  • A) lexical analyzer
  • B) syntax analyzer
  • C) semantic analyzer
  • D) code optimizer
Show answer & explanation

Answer: C

Every token is valid and the declaration is grammatically correct; the type mismatch is found by semantic analysis.

Topic drill · 8 questions

8 practice questions — Lexical Analysis & Phases

Extra page-specific practice beyond the GATE samples. Attempt all 8, then reveal answers to check your reasoning.

P1

The number of tokens in the C statement if (a >= b) x = y; is:

  • A) 8
  • B) 9
  • C) 10
  • D) 11
Show answer & explanation

Answer: C) 10

if, (, a, >=, b, ), x, =, y, ; = 10 tokens (>= is a single token).

P2

In which phase is the type of an expression such as a + b (int + float) checked and a conversion inserted?

  • A) lexical analysis
  • B) syntax analysis
  • C) semantic analysis
  • D) code generation
Show answer & explanation

Answer: C) semantic analysis

Type checking and implicit coercions (inttofloat) are done by the semantic analyzer.

P3

The longest-match rule in a lexical analyzer means:

  • A) the shortest lexeme is returned
  • B) the longest prefix that matches some pattern is returned
  • C) keywords are always preferred over identifiers
  • D) only the first token on a line is recognised
Show answer & explanation

Answer: B) the longest prefix that matches some pattern is returned

Maximal munch: the scanner consumes the longest prefix that matches a pattern.

P4

Which of the following phases is machine independent?

  • A) register allocation
  • B) instruction selection
  • C) intermediate code generation
  • D) peephole optimization of target code
Show answer & explanation

Answer: C) intermediate code generation

Intermediate code is designed to be independent of the target machine; A, B and D depend on it.

P5

The regular expression that describes C-like identifiers (letter or underscore first) is:

  • A) (letter | _)(letter | digit | _)*
  • B) (letter | digit)*
  • C) letter(digit)*
  • D) (letter)* (digit)*
Show answer & explanation

Answer: A) (letter | _)(letter | digit | _)*

The first character must be a letter or underscore; the rest may also be digits.

P6

The symbol table is used by:

  • A) only the lexical analyzer
  • B) only the code generator
  • C) several phases including semantic analysis and code generation
  • D) only the parser
Show answer & explanation

Answer: C) several phases including semantic analysis and code generation

Names are entered during scanning/parsing and used later for type checking, offsets and code generation.

P7

Thompson’s construction gives an NFA with how many final states for any regular expression?

  • A) exactly one
  • B) at least two
  • C) as many as symbols
  • D) none
Show answer & explanation

Answer: A) exactly one

Thompson NFAs always have one start and one final state, with no outgoing edges from the final state.

P8

Which of the following is a syntax error rather than a lexical or semantic error?

  • A) int @x;
  • B) float f = “3.5”;
  • C) for (i = 0; i < 10; i++ { }
  • D) y = z + 1; with z undeclared
Show answer & explanation

Answer: C) for (i = 0; i < 10; i++ { }

The missing closing parenthesis violates the grammar; the tokens themselves are valid.

Topic FAQs

What is the difference between a token, a lexeme and a pattern?

A pattern is the rule (usually a regular expression) that describes a class of strings, a lexeme is one concrete string in the source that matches the pattern, and a token is the (name, attribute) pair handed to the parser — for example the lexeme count1 matches the id pattern and becomes the token <id, pointer to symbol table>.

Why is the scanner separate from the parser?

Tokens are regular, so a fast DFA can recognise them; the parser only needs to handle nesting. Separation simplifies the design, speeds up scanning with buffering, and makes the front end more portable.

Which compiler phases are machine dependent?

Code generation (instruction selection, register allocation) and peephole optimization on target code are machine dependent. Lexical, syntax, semantic analysis, intermediate code generation and machine-independent optimization depend only on the source language and the IR.

Is a missing semicolon a lexical error?

No. Every token is valid; the structure is wrong. A missing semicolon is detected by the parser (syntax analysis).

Quick revision · 10 cards

10 flashcards — Lexical Analysis & Phases

Hover a card to reveal the answer with a 3D flip. On touch devices, tap the card or use Show answer.

Q1 List the phases of a compiler in order.
Q2 What is the difference between analysis and synthesis?
Q3 Token, lexeme, pattern?
Q4 What is maximal munch?
Q5 Why can a lexer not check for balanced parentheses?
Q6 How many states does Thompson’s NFA for a regex r have at most?
Q7 What is a pass of a compiler?
Q8 Which phase reports a type mismatch or an undeclared variable?
Q9 Which phases are machine dependent?
Q10 What is a cross compiler?