Lexical analysis
Đã giới thiệu
5:58
Lý thuyết tính toán và trình biên dịch
This course asks what machines can decide, and how text becomes meaning. The first three units are theory: automata and regular languages, context-free…
Thuyết minh tiếng Anh · Có thể chuyển đổi phụ đề tiếng Anh và tiếng Trung
Trong bài học này
| English | Ý nghĩa |
|---|---|
| tokens/ˈtəʊkənz/ | thông từ |
| lexer/ˈleksə/ | the compiler stage that groups characters into tokens |
| longest match/ˈlɒŋɡɪst mætʃ/ | the lexer rule that takes the longest piece of input that forms a token |
| minimises/ˈmɪnɪmaɪzɪz/ | reduces a DFA to the fewest states that accept the same language |
| keyword table/ˈkiːwɜːd ˈteɪbl/ | a table the lexer checks to tell reserved words from ordinary identifiers |
Characters in, tokens out
- To a compiler,
count = a1 + b2;arrives as 16 separate characters. Before it can check any grammar, it must cut them into words, the way you read "count", "=", "a1" rather than letters. - That first stage is the lexer 词法分析器. It turns characters into tokens 记号, each a (type, text, position) triple such as IDENT("count", column 1). Spaces and comments are dropped; positions are kept for error messages.
- Each token type is a regular expression, run as one DFA. Where patterns overlap, the lexer takes the longest match 最长匹配.

The lexer emits —
Độ khó 1/5 · 100 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Type for the parser, lexeme for messages, position for errors.
Why longest match
- The patterns for
if, identifiers and numbers overlap at the start. Longest match readsifxas one IDENT, notif+x; when two patterns match the same length, a priority order decides. Get this wrong and every variable that starts withifbreaks. - The course line
count = a1 + b2;gives IDENT(count) ASSIGN IDENT(a1) PLUS IDENT(b2) SEMI, at columns 1, 7, 9, 12, 14, 16.
The input ifx lexes as —
Độ khó 1/5 · 100 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Greedy longest match: the ident regex permits the longer lexeme.
Put the tokens of count = a1 + b2; in the order the lexer emits them.
Độ khó 3/5 · 200 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Whitespace is discarded and each lexeme takes the longest match, so a1 is one IDENT, not IDENT(a) then NUM(1).
The error policy is part of the specification
12abclexes greedily as NUM(12) then IDENT(abc). Some languages allow this; others call it an error. Ours reports it: the error policy belongs in the lexer's specification, not as an afterthought.- If you throw positions away, every later error message gets worse: positions flow from the lexer through the parser into the type errors.
The course line count = a1 + b2; lexes to — tokens
Độ khó 1/5 · 100 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
IDENT ASSIGN IDENT PLUS IDENT SEMI - six.
How a lexer is built
- A lexer generator such as flex turns each regular expression into an NFA (Thompson's construction), joins them, makes a DFA with the subset construction, and then minimises 最小化 it by merging states that no input can tell apart. The result needs one table lookup per character.
- Keywords are cheaper as lookups: lex every word as an identifier, then check a keyword table 关键字表. That keeps the DFA small and makes adding a keyword a one-line change.
x1 = x1 * 10;gives $6$ tokens: IDENT ASSIGN IDENT TIMES NUM SEMI.
How many tokens does total = total + rate * 12; produce?
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
IDENT ASSIGN IDENT PLUS IDENT TIMES NUM SEMI: 8 tokens.
The usual way to recognise keywords is —
Độ khó 1/5 · 100 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
One identifier rule plus a lookup keeps the DFA small.
A regular expression for real numbers
[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?reads digits, an optional fraction and an optional exponent. It accepts42,2.5and2.5E-3.- It rejects
3.(a fraction needs a digit) and.5(the number must start with a digit). Writing these cases down is the specification; the regular expression only encodes it.
Which string does [0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)? accept?
Độ khó 1/5 · 100 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
The others lack a digit where the regex requires one.
Worked example: count the tokens
while (i <= 10) i += 2;lexes to WHILE LPAREN IDENT(i) LE NUM(10) RPAREN IDENT(i) PLUSEQ NUM(2) SEMI: $\mathbf{10}$ tokens.- Longest match makes
<=one token, not<then=, and+=one token, not+then=. Spaces separate tokens but are not tokens.
How many tokens does if (x >= 3) y -= 1; contain?
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
IF ( x >= 3 ) y -= 1 ;
With longest match, <= lexes as two tokens, < và =.
Độ khó 1/5 · 100 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
The longest token that matches wins: LE.
Marks that slip away
- Shortest match.
ifxmust lex as one IDENT, not the keywordiffollowed byx. - Dropping positions. Every later error message needs the line and column the lexer saw.
- Asking the lexer to count. Balanced brackets are the parser's job; a lexer built from regular expressions cannot match nesting.
Recap
- Token classes are regular expressions; the lexer emits (type, lexeme, position).
- Longest match, then priority:
| Input | Tokens |
|---|---|
ifx |
IDENT, not if + x |
<= |
LE, not < + = |
+= |
PLUSEQ, not + + = |
12abc |
NUM(12), IDENT(abc): our lexer reports it |
- The error policy is part of the specification; positions feed every later error message.
Đã xảy ra vấn đề gì? Chỉ đội ngũ trang web nhìn thấy thông tin này.