Lexical analysis
도입됨
5:58
계산 이론 및 컴파일러
This course asks what machines can decide, and how text becomes meaning. The first three units are theory: automata and regular languages, context-free…
영어 내레이션 · 영어와 중국어 자막 전환 가능
이 수업의 내용
| English | 의미 |
|---|---|
| tokens/ˈtəʊkənz/ | 토큰 |
| 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 —
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
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 —
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
Greedy longest match: the ident regex permits the longer lexeme.
Put the tokens of count = a1 + b2; in the order the lexer emits them.
난이도 3/5 · 200코인 + 오늘 첫 완료 시 작은 보너스 추가
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
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
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?
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
IDENT ASSIGN IDENT PLUS IDENT TIMES NUM SEMI: 8 tokens.
The usual way to recognise keywords is —
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
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?
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
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?
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
IF ( x >= 3 ) y -= 1 ;
With longest match, <= lexes as two tokens, < 및 =.
난이도 1/5 · 100코인 + 오늘 첫 완료 시 작은 보너스 추가
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.
어떤 문제가 있었나요? 사이트 팀만 이 내용을 볼 수 있습니다.