Sub topic 1
Where Lexing, Parsing, and Translation Fit in a Compiler
Prerequisites
Assume you know regular expressions, finite automata, context-free grammars, parse trees, stacks, and basic recursion. This chapter uses “front end” for the compiler stages that analyze source text before target-machine code is generated.
The compiler front end
A compiler transforms source code into a lower-level form. Its front end checks the source and builds structured information for later stages.
The lexical analyzer, or lexer, consumes characters and produces tokens. The parser consumes tokens and checks whether their sequence follows a context-free grammar. It usually produces a parse tree or an abstract syntax tree, abbreviated AST. Translation then attaches meaning to that structure. It may produce an intermediate representation, evaluate expressions, build an AST, or emit target code.
| Stage | Consumes | Produces | Typical failure |
|---|---|---|---|
| Lexical analysis | Characters | Tokens | Invalid character |
| Parsing | Tokens | Parse tree or AST | Invalid token sequence |
| Translation | Tree and attributes | Values, IR, or code | Type or meaning error |
These stages are logically distinct, although compiler tools may combine them. For example, a parser can call lexer functions as it requests the next token. A syntax-directed translation scheme can execute semantic actions while parsing.
Tokens, lexemes, and patterns
A token is a category used by the parser, such as ID, NUM, PLUS, or LPAREN. A lexeme is the actual character sequence that matches a token category. A pattern is the rule that describes which lexemes belong to that category.
For example, in total = price + 7:
total,price, and7are lexemes.totalandpricemay produceIDtokens.7may produce aNUMtoken.=and+produce operator tokens.- The identifier pattern might be
[A-Za-z_][A-Za-z0-9_]*. - The number pattern might be
[0-9]+.
The lexer often records an attribute with a token. An ID token can carry the identifier’s spelling, while a NUM token can carry the integer value.
import re
rules = [
("NUM", r"\d+"),
("ID", r"[A-Za-z_][A-Za-z0-9_]*"),
("OP", r"[=+]"),
("WS", r"\s+"),
]
master = re.compile("|".join(f"(?P<{n}>{p})" for n, p in rules))
def tokenize(text):
position = 0
while position < len(text):
match = master.match(text, position)
if match is None:
raise SyntaxError(f"invalid character at {position}")
kind = match.lastgroup
if kind != "WS":
value = match.group()
yield kind, value
position = match.end()
print(list(tokenize("total = price + 7")))A lexer must also define priority rules. When several patterns match at the same position, languages commonly choose the longest match, called maximal munch. If lengths tie, the earlier rule wins. Thus a keyword rule usually appears before the general identifier rule, or the lexer checks the identifier’s text against a keyword table after matching it.
Exercise
For count = 42, name the lexeme and token produced for 42.
Show answer
The lexeme is 42; the lexer produces a NUM token, usually with numeric value 42 as its attribute.