Conceptcore
Tokens and lexing
Also called lexical structure, lexical analysis, lexer, tokenizer, scanner, token, maximal munch, longest match, keywords, literals, automatic semicolon insertion.
A lexer turns the characters of source text into tokens such as names, keywords, literals and operators. Its rules decide the longest match, comments, line breaks and indentation.
- Applies to
- core-languages
Idea
The lexical structure of a language is the set of rules that turns the characters of a source file into tokens: names, keywords, literals, operators and punctuation. A lexer, also called a scanner or tokenizer, reads the text from left to right, drops white space and comments, and gives the parser a stream of tokens. The lexical rules decide many details that programmers meet every day: which characters a name may contain, how to write a number in hex or with digit separators, how strings escape quotes, where comments start and end, and whether line breaks and indentation mean anything.
import re
KEYWORDS = {"if", "while", "print"}
TOKENS = [ # tried in order at each position
("SKIP", r"[ \t]+|#[^\n]*"), # spaces and comments make no token
("NEWLINE", r"\n"),
("NUMBER", r"\d[\d_]*"),
("NAME", r"[A-Za-z_]\w*"),
("STRING", r'"[^"\n]*"'),
("OP", r"\+=|==|\+\+|[+=:()<]"), # longer operators first
]
LEXER = re.compile("|".join(f"(?P<{k}>{p})" for k, p in TOKENS))
def tokens(text):
pos = 0
while pos < len(text):
m = LEXER.match(text, pos)
if not m:
raise SyntaxError(f"bad character {text[pos]!r} at {pos}")
kind, value = m.lastgroup, m.group()
if kind == "NAME" and value in KEYWORDS:
kind = "KEYWORD"
if kind != "SKIP":
yield kind, value
pos = m.end()
src = 'x += 1_000 # add\nif x == y: print("a+b")\n'
for kind, value in tokens(src):
print(f"{kind:8} {value!r}")
print([v for _, v in tokens("i+++j")]) # the longest operator wins
NAME 'x'
OP '+='
NUMBER '1_000'
NEWLINE '\n'
KEYWORD 'if'
NAME 'x'
OP '=='
NAME 'y'
OP ':'
KEYWORD 'print'
OP '('
STRING '"a+b"'
OP ')'
NEWLINE '\n'
['i', '++', '+', 'j']
The lexer is for a small toy language. Each token kind has a regular expression, and at each position the lexer tries them in order and takes the first that matches. Spaces and the comment produce no token, and a name that is in the keyword set becomes a keyword. The operators are listed longest first, so += and == are one token each, not two, and the last line shows the same rule splitting i+++j into i, ++, + and j. The string "a+b" is one token, because the lexer matches the whole literal before it looks for operators.
How it works
Two levels of grammar. Most languages describe their syntax in two layers. The lexical grammar says how characters form tokens, and the syntactic grammar says how tokens form expressions, statements and declarations. The Python reference describes the split: "A Python program is read by a parser. Input to the parser is a stream of tokens, generated by the lexical analyzer (also known as the tokenizer)."1 Tokens are simple enough that regular expressions describe them, so a lexer is a finite-state machine in practice, while the syntax of nested expressions needs a parser with a stack. The Rust reference states this: "Tokens are primitive productions in the grammar defined by regular (non-recursive) languages."2 See recursive descent parsing.
The longest match. When several tokens could start at a position, nearly every language takes the longest. The Go specification puts it in one sentence: "the next token is the longest sequence of characters that form a valid token."3 The Java specification adds that this holds "even if the result does not ultimately make a correct program while another lexical translation would."4 So i+++j is i ++ + j in C, C++, Java, C# and JavaScript. C and C++ call the rule maximal munch, and cppreference shows a case where it breaks valid-looking code: 0xE+foo is one preprocessing number and an error.5
Names, keywords and literals. A name is usually a letter or underscore followed by letters, digits and underscores, and most modern languages accept Unicode letters. Keywords are names that the language reserves. Newer languages add contextual or soft keywords, such as record in Java, var in C# and match in Python, which are keywords only in certain places, so old code that uses them as names still compiles. Some languages give an escape that makes a keyword a name: @class in C# and r#match in Rust. Literals have the richest rules: bases for integers, exponents and suffixes for numbers, separators such as 1_000 and 1'000, escape sequences in strings, and raw strings that turn escapes off.
White space, line breaks and indentation. In C, Java and Rust, white space only separates tokens, and line breaks mean nothing. In Python, the lexer measures the indentation of each line: "Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements."1 It emits INDENT and DEDENT tokens that act as braces. Go and JavaScript insert semicolons at some line breaks. Go's rule is lexical and simple: "a semicolon is automatically inserted into the token stream immediately after a line's final token" if that token could end a statement.3 JavaScript's rule depends on the parser: MDN notes that return followed by a line break and then an expression "is transformed by ASI into" return; followed by the expression.6
Comments and phases. Comments disappear at the lexical level, so they cannot appear inside a token. Some languages do work before tokens form. C and C++ splice lines that end in a backslash and run the preprocessor on tokens before the compiler sees them. Java replaces Unicode escapes such as \u0041 with their characters before it forms tokens, so an escape is valid anywhere in a program, even in a name. The order of these phases explains many puzzles of a language.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Standard library | |
| C++ | Absent | |
| Java | Library | |
| C | Absent | |
| C# | Library | |
| JavaScript | Library | |
| TypeScript | Library | The TypeScript compiler package exposes a scanner for TypeScript and JavaScript source. |
| Go | Standard library | |
| Rust | Library | |
| Kotlin | Library | The Kotlin compiler and tools such as ktlint have lexers, but the standard library has none; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Does not apply | Each database has its own lexer for SQL text, with no portable interface for programs. |
| Bash | Does not apply | The shell splits words and expands them at run time, and gives scripts no tokenizer for shell source. |
| PowerShell | Standard library | The Parser class of System.Management.Automation.Language returns the tokens of a script; no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Does not apply | The HTML standard defines a tokenizer, but markup cannot call it. |
| CSS | Does not apply | The CSS Syntax specification defines a tokenizer, but style sheets cannot call it. |
| Regular expressions | Does not apply | A pattern has metacharacters and escapes but no interface to its own tokens. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | stdlib | tokenize; indentation tokens; soft keywords |
| JavaScript | library | Acorn, Esprima; automatic semicolon insertion |
| TypeScript | library | the scanner of the TypeScript compiler |
| Java | library | JavaParser; Unicode escapes before lexing; text blocks |
| Kotlin | library | the lexer of the Kotlin compiler; soft keywords |
| C# | library | Roslyn; verbatim and raw strings; @ names |
| Go | stdlib | go/scanner; semicolons inserted at line ends |
| Rust | library | proc_macro, proc-macro2, syn; raw strings and names |
| C | absent | maximal munch; preprocessing tokens; libclang |
| C++ | absent | as C; digit separators; raw strings |
| Bash | n/a | words split and expanded at run time |
| PowerShell | stdlib | System.Management.Automation.Language.Parser |
| SQL | n/a | a lexer in each database |
| Regex | n/a | metacharacters and escapes, no token API |
| HTML | n/a | the HTML tokenizer is not open to markup |
| CSS | n/a | the CSS tokenizer is not open to style sheets |
Every language has lexical rules, so the table measures something narrower: whether a program can get the tokens of its own language from the standard library. Python's tokenize, Go's go/scanner and PowerShell's parser give the same tokens as the real implementation, which makes formatters, linters and code generators easy to write and keeps them exact. The other languages rely on separate parser libraries or on the compiler's own libraries, such as Roslyn for C# and Clang for C and C++.
Each example file shows the lexical rules that are particular to its language. The Python and Go files print a token stream, with the indentation tokens of Python and the inserted semicolons of Go. The C, C++, Java, C# and JavaScript files show the longest-match rule on i+++j, which gives 11, with i then 2. The others show literals: numeric bases and separators, raw strings, escapes and keywords used as names. The wrong block of the JavaScript file and the fails blocks of the Go and C files show three ways in which the lexer, not the parser, decides the meaning of a program.
import io
import keyword
import tokenize
src = "if n > 0x_ff: # a comment\n total = 1_000\n"
for tok in tokenize.generate_tokens(io.StringIO(src).readline):
print(f"{tokenize.tok_name[tok.type]:9} {tok.string!r}")
print(0x_ff, 1_000, keyword.iskeyword("match"), keyword.issoftkeyword("match"))
NAME 'if'
NAME 'n'
OP '>'
NUMBER '0x_ff'
OP ':'
COMMENT '# a comment'
NEWLINE '\n'
INDENT ' '
NAME 'total'
OP '='
NUMBER '1_000'
NEWLINE '\n'
DEDENT ''
ENDMARKER ''
255 1000 False True
- Verdict: stdlib. The
tokenizemodule of the standard library runs the lexer of Python on source text and gives the same tokens as the interpreter, comments included. Python is the core language whose lexer does the most work: it turns changes of indentation intoINDENTandDEDENTtokens, which take the place of braces. Underscores group digits in any numeric literal.matchis a soft keyword, a name that is a keyword only where amatchstatement can start, so old code that uses it as a variable still runs.
#include <iostream>
#include <vector>
int main() {
int i = 1, j = 10;
int k = i+++j; // lexed as i ++ + j
std::cout << k << ' ' << i << '\n';
std::cout << 1'000'000 << ' ' << 0b1010 << ' ' << 017 << ' ' << 0xff << '\n';
const char *raw = R"(He said "hi" to C:\temp)"; // a raw string
std::cout << raw << '\n';
std::vector<std::vector<int>> v{{1, 2}}; // >> closes two lists since C++11
std::cout << v[0].size() << '\n';
int x = 10, y = 3;
std::cout << (x<y and y not_eq 0) << '\n'; // and and not_eq are tokens too
}
11 2
1000000 10 15 255
He said "hi" to C:\temp
2
0
- Verdict: absent. C++ has no standard library for its tokens; tools use Clang's libraries. C++ forms tokens as C does, by the longest match, and adds the apostrophe as a digit separator and raw strings in the form
R"(...)". Since C++11,>>closes two template argument lists. The alternative tokensand,orandnot_eqare keywords that mean&&,||and!=.
public class Main {
public static void main(String[] args) {
int i = 1, j = 10;
int k = i+++j; // lexed as i ++ + j
System.out.println(k + " " + i);
System.out.println(1_000_000 + " " + 0b1010 + " " + 017 + " " + 0xff + " " + 10L);
// Unicode escapes are replaced before lexing: \u0041 is the letter A
char a = '\u0041';
System.out.println(a);
String block = """
two lines,
indent removed""";
System.out.println(block);
var record = 5; // record is a contextual keyword, so it can be a name
System.out.println(record);
}
}
11 2
1000000 10 15 255 10
A
two lines,
indent removed
5
- Verdict: library. The JDK has no public API for the tokens of Java source, so tools use libraries such as JavaParser or the compiler tree API of the
jdk.compilermodule. Java translates Unicode escapes such as\u0041before it forms tokens, so they work anywhere in the source, even outside strings. Text blocks remove the common indentation, and contextual keywords such asrecordandvarremain usable as names.
#include <stdio.h>
int main(void) {
int i = 1, j = 10;
int k = i+++j; /* lexed as i ++ + j */
printf("%d %d\n", k, i);
printf("%d %d %d\n", 017, 0xff, 'A');
const char *s = "hello, " "world"; /* adjacent strings join */
printf("%s\n", s);
int a = 8, *p = &a;
int half = a / *p; /* a space keeps / * from starting a comment */
printf("%d\n", half);
return 0;
}
11 2
15 255 65
hello, world
1
This code does not compile, on purpose.
#include <stdio.h>
int main(void) {
int foo = 1;
int bar = 0xE+foo; /* 0xE+foo is one preprocessing number */
printf("%d\n", bar);
return 0;
}
- Verdict: absent. C has no library for its own tokens; tools use libclang or a parser of their own. The preprocessor forms tokens by the longest match, so
i+++jisi++ + j, anda/*pwould start a comment, which is why the example puts a space after the/. Adjacent string literals join into one, which lets a long string span several lines. - The fails block writes
0xE+foo. A preprocessing number can containe+andE+for exponents, so the longest match makes0xE+fooone token, which is not a valid number, and the compiler rejects it. Spaces around+fix it.
int i = 1, j = 10;
int k = i+++j; // lexed as i ++ + j
Console.WriteLine($"{k} {i}");
Console.WriteLine($"{1_000_000} {0b1010} {0xff} {10L} {1.5m}");
string path = @"C:\temp\new"; // verbatim: no escapes
string raw = """He said "hi"."""; // raw string literal
Console.WriteLine(path);
Console.WriteLine(raw);
int @class = 3; // @ turns a keyword into a name
var var = @class * 2; // var is a contextual keyword
Console.WriteLine(var);
11 2
1000000 10 255 10 1.5
C:\temp\new
He said "hi".
6
- Verdict: library. The Roslyn compiler, in the
Microsoft.CodeAnalysis.CSharppackage, gives programs the tokens and trees of C# source. C# has three kinds of string literal: regular strings with escapes, verbatim strings with@that keep backslashes, and raw strings with three or more quotes. An@before a keyword makes it a name, and contextual keywords such asvarcan be names where the grammar allows.
let i = 1, j = 10;
const k = i+++j; // lexed as i ++ + j, the longest operator first
console.log(k, i);
console.log(1_000_000, 0b1010, 0o17, 0xff, 1e3);
const name = "world";
console.log(`hello ${name}`, "a\tb".length, String.raw`a\tb`.length);
const café = "identifiers can use Unicode letters";
console.log(café.length);
11 2
1000000 10 15 255 1000
hello world 3 4
35
This code runs but gives a wrong answer on purpose.
function settings() {
return
{
debug: true;
}
}
console.log(settings());
undefined
- Verdict: library. JavaScript has no tokenizer in its standard library, but parsers such as Acorn, Esprima and the TypeScript compiler expose one. The lexer reads the longest operator it can, so
i+++jisi++ + j. Numeric separators, binary and octal literals and template literals are tokens of the language, and identifiers can use Unicode letters. - The wrong block puts a line break after
return. Automatic semicolon insertion ends the statement there, so the function returnsundefined, and the object below becomes a block with a label that never runs. Put the value on the same line asreturn.
package main
import (
"fmt"
"go/scanner"
"go/token"
)
func main() {
src := []byte("x := 0b1010 + 1_000\nif x > 2 {\n\tx++\n}\n")
fset := token.NewFileSet()
file := fset.AddFile("x.go", -1, len(src))
var s scanner.Scanner
s.Init(file, src, nil, 0)
for {
_, tok, lit := s.Scan()
if tok == token.EOF {
break
}
if tok == token.SEMICOLON && lit == "\n" {
lit = "inserted at a newline"
}
fmt.Printf("%-6s %q\n", tok, lit)
}
fmt.Println(0b1010+1_000, 0o17, 'A', len(`C:\new`))
}
IDENT "x"
:= ""
INT "0b1010"
+ ""
INT "1_000"
; "inserted at a newline"
if "if"
IDENT "x"
> ""
INT "2"
{ ""
IDENT "x"
++ ""
; "inserted at a newline"
} ""
; "inserted at a newline"
1010 15 65 6
This code does not compile, on purpose.
package main
import "fmt"
func main() {
x := 3
if x > 2
{ // a semicolon was inserted after the 2
fmt.Println("big")
}
}
- Verdict: stdlib. The
go/scannerandgo/tokenpackages of the standard library are the lexer that Go tools use. The output shows the semicolons that the lexer inserts at the end of a line that ends with a name, a literal,++or a closing brace. Go has binary, octal and hex literals with underscores, rune literals that are numbers, and raw strings in backquotes. - The fails block puts the opening brace of an
ifon the next line. The lexer inserts a semicolon after2, so the parser seesif x > 2;with no block and rejects it. This is why Go style puts the brace on the same line.
fn main() {
let big = 1_000_000u64; // a suffix fixes the type of a literal
println!("{big} {} {} {} {}", 0b1010, 0o17, 0xff, b'A');
let raw = r#"He said "hi" to C:\temp"#; // a raw string with # delimiters
println!("{raw}");
let r#match = 3; // r# turns a keyword into a name
println!("{}", r#match * 2);
let s = "é";
println!("{} {}", s.len(), s.chars().count());
let v: Vec<Vec<i32>> = vec![vec![1]]; // >> closes two generic lists
println!("{v:?}");
}
1000000 10 15 255 65
He said "hi" to C:\temp
6
2 1
[[1]]
- Verdict: library. The compiler passes token streams to procedural macros through the
proc_macrocrate, and theproc-macro2andsynlibraries parse Rust source in other programs. A suffix such asu64gives a literal its type,b'A'is a byte, raw strings with#delimiters hold quotes and backslashes, andr#turns a keyword into a name. The parser splits>>into two closing brackets where a type needs them.
Variations and related ideas
- Lexer generators. Tools such as lex, flex and re2c build a lexer from a list of regular expressions, and parser generators such as ANTLR include one.
- Scannerless parsing. Some parsers, such as many parsing expression grammars, work on characters directly with no separate lexer, which helps with languages whose tokens depend on context.
- Context-dependent lexing. The lexer must sometimes know the state of the parser:
/is division or the start of a regular expression in JavaScript,>>closes two generic lists in C++ and Rust, and template literals and string interpolation nest code inside strings. - Off-side rule. Python, Haskell, F# and YAML use indentation to show structure, and the lexer turns it into tokens.
- Macros and token streams. C's preprocessor and Rust's macros work on tokens before parsing. See syntactic macros.
- Lexical scope. A different meaning of the word lexical: names resolve by where they appear in the program text. See lexical scope.
- Abstract syntax trees. The parser builds a tree from the tokens, and later phases work on the tree. See abstract syntax trees.
Pitfalls
- A line break after
return. In JavaScript, automatic semicolon insertion ends the statement, and the function returnsundefined, as the wrong block of the JavaScript file shows. - Braces on the next line in Go. The lexer inserts a semicolon at the end of the line, and the code does not compile, as the fails block of the Go file shows.
- Maximal munch surprises.
0xE+fooin C and C++ anda/*p, which starts a comment, lex differently from what a reader expects. Put spaces around operators. - Octal literals. In C, C++ and Java, a leading zero makes a number octal, so
017is 15. Use0o17where the language has it, and never pad decimal numbers with zeros. - Mixed tabs and spaces. Python rejects indentation that is ambiguous between tabs and spaces. Configure editors to insert spaces.
- Look-alike characters. Unicode names can contain letters that look like ASCII letters, and invisible or bidirectional control characters can make code read differently from how it compiles. Compilers and linters warn about these, and review tools should show them.
Cost
A lexer reads each character once or a few times and runs in time linear in the length of the source, and in most compilers it is a small part of the total time. Generated lexers run as table lookups, one per character; hand-written lexers in compilers such as those for Go, Rust and Clang switch on the first character of each token and are often faster. Keeping comments and white space as trivia attached to tokens, as Roslyn and formatters do, costs memory but lets tools rewrite source without losing the layout.
History
FORTRAN, in 1957, ignored blanks everywhere, even inside names, so DO 10 I = 1.10 was an assignment to a variable named DO10I, a famous source of bugs. The Algol 60 report of 1960 separated the reference language from its hardware representations, which made the lexical level a part of the language design. Ken Thompson's work on regular expressions in the 1960s and Mike Lesk and Eric Schmidt's lex at Bell Labs in 1975 made lexers that a tool generates from patterns standard practice.
C formalized the phases of translation and maximal munch in its 1989 standard, and Java, in 1996, defined Unicode source text and the translation of Unicode escapes before tokens.4 Python used indentation from its first release in 1991, following ABC. Go, in 2009, chose semicolon insertion by a simple lexical rule, which also fixes where an opening brace must go.3 Later additions to many languages, such as digit separators, raw strings and soft keywords, are mostly lexical changes, designed so that old programs keep the same tokens.
References
- Lexical analysis, The Python Language Reference, 2. Lexical analysis and 2.1.8 Indentation
- Tokens, The Rust Reference, Introduction
- The Go Programming Language Specification, Tokens and Semicolons
- Chapter 3, Lexical Structure, The Java Language Specification, Java SE 25 Edition, 3.2 Lexical Translations
- Phases of translation, cppreference.com, Phase 3, maximal munch
- Lexical grammar, MDN Web Docs, Automatic semicolon insertion
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 7N9YBR Edit this page History Report an error Markdown