Sub topic 2
Tokens, lexemes, and patterns
This chapter defines the three terms the lexical analyzer (lexer) is built on. It assumes you know basic regular expressions and have read the previous chapter on compiler phases. Later chapters build on it: regular expressions, automata, and the lexer implementation.
Three terms, three jobs
The lexer reads characters and groups them into meaningful units. Three words describe this, and GATE questions often test whether you can tell them apart.
| Term | Meaning | Example |
|---|---|---|
| Token | A category of input, plus an optional attribute value. This is what the parser consumes. | `ID`, `NUM`, `IF` |
| Lexeme | The actual character sequence in the source that matched a pattern. | `count`, `42`, `if` |
| Pattern | A rule that describes every lexeme a token can have. It is usually a regular expression. | `[A-Za-z_]\w*` |
A token is a class, a lexeme is one member of that class, and a pattern is the membership rule. In count = 42, the lexeme count is an instance of the token ID, matched by the identifier pattern.
What the parser receives
The parser does not see lexemes directly. It sees pairs of the form <token-name, attribute-value>.
- The token name is the abstract symbol the parser uses. It is a terminal in the grammar.
- The attribute value carries what the later phases still need. For
ID, this is usually a pointer to the symbol table entry. ForNUM, it is the numeric value. - Some tokens need no attribute. The keyword
ifis fully described by its name.
Several lexemes can share one token. a, b2, and total are all ID. The grammar for E -> id + id does not care which names appear. Later phases do care, which is why the attribute value exists.
The parser pulls tokens on demand. It asks for the next token when it needs one. The lexer does not run to completion first.
What counts as a token
Each class of input is handled in a standard way.
- Keywords such as
ifandwhileusually get their own token each. They match the identifier pattern, so lexers either list them in a reserved-word table or put their rules before the identifier rule. - Identifiers are one token,
ID, however many different names appear. - Constants are tokens such as
NUMorSTRING. A whole string literal, including spaces inside the quotes, is one lexeme. - Operators and punctuation are single tokens. Often each symbol is its own token, such as
;,(, and+. - Whitespace and comments are matched by patterns but produce no token. The lexer discards them, so the parser never sees them.
Consider this line:
float limit = 3.14;It has five lexemes: float, limit, =, 3.14, and ;. The spaces are consumed but yield nothing, so the token count is 5.
A small lexer showing all three
The code below separates the three ideas. Each entry in TOKEN_SPEC pairs a token name with its pattern. The matched text is the lexeme. A keyword table reclassifies identifiers.
import re
KEYWORDS = {"if", "else", "while"}
TOKEN_SPEC = [
("NUM", r"\d+"),
("ID", r"[A-Za-z_]\w*"),
("OP", r"[+\-*/()=;]"),
("WS", r"\s+"),
]
MASTER = re.compile("|".join(f"(?P<{name}>{pattern})" for name, pattern in TOKEN_SPEC))
def tokenize(text):
pos = 0
while pos < len(text):
m = MASTER.match(text, pos)
if m is None:
raise SyntaxError(f"bad character {text[pos]!r} at position {pos}")
kind, lexeme = m.lastgroup, m.group()
if kind == "ID" and lexeme in KEYWORDS:
kind = "KW"
if kind != "WS":
yield (kind, lexeme)
pos = m.end()
tokens = list(tokenize("if x1 = 42;"))
print(tokens)
print(len(tokens))
# [('KW', 'if'), ('ID', 'x1'), ('OP', '='), ('NUM', '42'), ('OP', ';')]
# 5The token ID has two lexemes in a program like x1 = x1 + y. The lexeme x1 appears twice, and both occurrences are separate tokens in the output stream.
Common errors
- Confusing token count with distinct token names. GATE asks for the number of tokens in a code fragment. Count every lexeme occurrence, not the number of categories. If
iappears three times, that is threeIDtokens. - Splitting what is one lexeme. A string literal, a floating-point constant like
3.14, and a multi-character operator like>=are each one token. Splitting them into pieces gives a wrong count. - Counting whitespace or comments. They are not tokens.
- Treating a keyword as an identifier.
ifmatches the identifier pattern, but it is a keyword token. Order or a reserved-word table fixes this. - Assuming the pattern fixes the attribute. The pattern only says which lexemes belong to the token. The attribute is extra information the lexer attaches.
Counting tokens
Count tokens by scanning left to right and cutting a lexeme at each place the pattern for a token ends. For printf("i = %d, &i = %x", i, &i);, the lexemes are printf, (, the whole string literal, ,, i, ,, &, i, ), and ;. The text inside the quotes does not split, because the lexer treats the entire literal as one lexeme.
Exercise
How many tokens does the lexer produce for the C statement printf("i = %d, &i = %x", i, &i);?
Show answer
10. The tokens are printf, (, the string literal "i = %d, &i = %x" (one token, including its spaces and commas), a comma, i, a comma, &, i, ), and ;. The characters inside the quotes belong to the single string token.
Exercise
A program contains x = x + y1;. How many tokens are produced, and how many distinct token names are used (counting ID, OP, and NUM as the names)?
Show answer
There are 6 tokens: x, =, x, +, y1, and ;. Only 2 token names appear, ID and OP, because both x occurrences are separate ID tokens and = + ; are all OP tokens in the lexer above.