TL;DR
Lexical analysis, also called scanning, reads a program's text and groups its characters into tokens: names, numbers, operators, keywords and punctuation. Each token type is described by a regular expression, and a state machine matches those patterns as it reads. The later stages, parsing and checking, then work with a clean list of tokens instead of raw characters, which keeps them simpler.
Builds on: Regular Expression, State Machine · Leads to: Abstract Syntax Tree, Compiler Pipeline
Where it's used
Compilers. Every compiler for a programming language starts with a scanner. In total = price * 2, the scanner sees a name, an equals sign, a name, a star and a number. The compiler's parser then checks that these tokens form a valid statement, and the rest of the compiler works on that structure.
Code editors and syntax highlighting. An editor colours keywords, names, strings and numbers differently. It does this with the same kind of scan, run as the user types, because the colour of each piece depends only on which token it is.
Search and data formats. Log analysers, configuration readers and query tools often split their input into tokens before they interpret it. A CSV reader, for example, first separates values by commas and quote marks, and only then decides what each value means.
How it works
Take a tiny language with these token types. A name is a letter followed by any letters or digits. A number is one or more digits. The symbols = and + each form their own token. Spaces separate tokens and are thrown away. Input: n=12+y.
-
Start at the first character. The scanner is at position 0, the letter
n. It tries every token pattern from here. Only the name pattern can start with a letter, and it matchesnalone, because=cannot be part of a name. Emit the token NAME(n) and move to position 1. Check: the name pattern covers 1 character here, so the token is NAME(n). -
Read the
=. At position 1 only the=pattern matches. Emit EQUALS and move to position 2. Check: one character, one token. -
Read the number. At position 2 the input is
12+y. The number pattern matches1and also12, because it can keep repeating digits. The scanner takes the longest match,12, and moves to position 4. Check: taking only1would leave a stray2to be read as a separate number, which is wrong. -
Read the
+. At position 4 only the+pattern matches. Emit PLUS and move to position 5. Check: the next character isy, which is not a plus sign. -
Read the last name. At position 5 the name pattern matches
y. Emit NAME(y). The position is now at the end of the input, so scanning stops. Check: the output is NAME(n), EQUALS, NUMBER(12), PLUS, NAME(y), five tokens for six characters, since the two digits make one number.
flowchart LR
A["Characters: n = 1 2 + y"] --> B["Scanner matches patterns"]
B --> C["NAME n"]
B --> D["EQUALS"]
B --> E["NUMBER 12"]
B --> F["PLUS"]
B --> G["NAME y"]
C --> H["Token list to the parser"]
D --> H
E --> H
F --> H
G --> H
The math
Let be the input text, a string of characters. Let be the token patterns, where pattern names the set of strings of token type . A scanner starts at position and repeats this rule until the input ends: choose the length and the type such that the substring belongs to the set of pattern , with as large as possible. Emit the token and set . Ties in length go to the pattern listed first. Whitespace patterns emit no token.
This rule is called longest match, or maximal munch. The scanner always takes the longest possible token at the current position.
Step 1 in symbols: the first token
At the substring belongs to the name set. The substring does not belong to any set, because = is not a letter or digit. So and the token is NAME(n).
Step 2 in symbols: a one-character token
At the only set containing is the EQUALS set, so and the token is EQUALS.
Step 3 in symbols: the longest number
At the substrings and both belong to the number set. The substring does not. So the largest is 2, and the token is NUMBER(12).
Step 4 and Step 5 in symbols
The remaining positions are handled the same way. gives PLUS with , and gives NAME(y) with . When reaches the length of , the scan is complete.
Worked examples
Input: x+1. Token patterns: name, number, +.
- Position 0 is
x. The name pattern matchesx, and no longer match exists, since+is not a name character. Token: NAME(x). - Position 1 is
+. Only the plus pattern matches. Token: PLUS. - Position 2 is
1. The number pattern matches1, and the input ends there. Token: NUMBER(1). - The result is three tokens: NAME(
x), PLUS, NUMBER(1). Check: three characters gave three tokens because no character sequence was longer than one character.
Input: if x==10. Token patterns: keyword if, name, number, =, and ==, with the keyword pattern listed before the name pattern. Spaces are skipped.
- Position 0 is
i. Both the name pattern and the keyword pattern matchif, a length of 2. The lengths tie, so the earlier pattern wins, and the keyword is chosen. Token: KEYWORD(if). - Position 2 is a space. It matches the whitespace pattern and emits nothing. The position moves to 3.
- Position 3 is
x. The name pattern matchesx, and the next character is=, which cannot continue a name. Token: NAME(x). - Position 4 is
=, followed by=10. The==pattern matches==, a length of 2. The single=pattern matches only length 1. The longer match wins. Token: EQEQ. - Position 6 starts
10. The number pattern matches10, the longest match. Token: NUMBER(10). - The result is KEYWORD(
if), NAME(x), EQEQ, NUMBER(10). Check: the scanner spent four tokens on eight characters, because the space was dropped and the two-character operator counts once.
Consider the statement return count + 1; in a C-like language. The token patterns are keywords, names, numbers, + and ;, with whitespace skipped.
returnmatches the name pattern and the keyword pattern at the same length, so the keyword wins. Token: KEYWORD(return).countmatches the name pattern alone, since the space that follows is not a name character. Token: NAME(count).+matches the plus pattern. Token: PLUS.1matches the number pattern. Token: NUMBER(1).;matches the semicolon pattern. Token: SEMICOLON.- The parser now receives five tokens and checks that they form a return statement. The scanner never checks that the statement is meaningful. It only groups characters.
Try it: Scan x<=10 with patterns for names, numbers, < and <=. Which tokens come out?
Answer: At position 1 the <= pattern matches two characters and the < pattern matches one, so <= wins. The tokens are NAME(x), LESS_EQUAL, NUMBER(10). A scanner that stopped at the first one-character match, <, would leave a stray = for the parser to reject, which is why the longest match rule exists.
Common mistakes and tradeoffs
It is tempting to think the scanner checks whether a program is correct. In fact it only groups characters into tokens. The input x + + 1 produces valid tokens, and the parser is the stage that rejects it because the two plus signs do not form a valid expression.
It is tempting to think the first matching pattern always wins. In fact the scanner takes the longest match at each position, and only breaks ties by the order of the patterns. Putting < before <= in the list does not break <= into two tokens here, because the longest match is still chosen. The order matters only when two patterns match the same length, as with keywords and names.
It is tempting to think whitespace and comments are tokens the rest of the compiler must handle. In fact the scanner usually discards them, because the parser needs only the meaningful pieces. Comments and blank lines still matter for error messages, so scanners keep their positions in the source.
Regular expressions suit token patterns because each token type is a flat pattern with no nesting. They cannot describe nested structures such as balanced brackets, which need a context-free grammar and a parser. That is why the scanner and the parser are separate stages. Many production compilers write the scanner by hand, because a hand-written version can be faster and can give better error messages. A generator, such as the Lex tool, is convenient when the token rules are simple and the speed of a generated scanner is good enough.
History
Stephen Kleene showed in 1956 that regular expressions and finite automata describe the same class of sets, which made pattern matching a question about machines. Ken Thompson used the same idea in 1968 to build fast regular-expression search, and the approach reached scanning through the tools that followed. In 1975, Mike Lesk and Eric Schmidt at Bell Labs wrote Lex, a program that turns a list of token patterns into a scanner. Lex and its successor flex made writing a scanner a matter of listing patterns, and their style still shapes how compilers are built.
Recap
- A scanner turns characters into tokens such as names, numbers and operators.
- Each token type is a regular expression, and a state machine matches it.
- The scanner takes the longest match at each position, and ties go to the earlier pattern.
- Whitespace is usually dropped, and the scanner does not check meaning.
- The parser then uses the token list to check structure.
Next, read Abstract Syntax Tree to see the structure that the parser builds from these tokens, and Compiler Pipeline for where scanning sits among the other stages.
Check yourself
QuestionWhat is the difference between a token and a character?Show answer
QuestionScan the input 007+2 with a number pattern and a plus pattern. What tokens come out, and why is the number one token?Show answer
007), PLUS, NUMBER(2). The number pattern matches 0, 00 and 007, and the longest match is 007. Its digits are all in one token because the longest match is taken, so the scanner does not split it into several numbers.QuestionWhy does the scanner take the longest match instead of the first pattern in the list?Show answer
<= could be read as < followed by =, which would change the meaning of the program. The list order is used only to break ties between patterns of the same length.QuestionA language has a keyword `while` and a name pattern that matches any letters. The input is `whilex`. What does the scanner produce, and why?Show answer
whilex). At position 0 the name pattern matches all six characters, which is longer than the keyword's five, so the longest match is a name. The keyword wins only when it ties with the name at the same length, as in while (x), where both match while at length 5 and the keyword is listed first.