---
tag: 7N9YBR
kind: concept
slug: tokens-and-lexing
name: Tokens and lexing
aliases: [lexical structure, lexical analysis, lexer, tokenizer, scanner, token, maximal munch, longest match, keywords, literals, automatic semicolon insertion]
area: syntax-and-semantics/lexical-structure
level: core
summary: >-
  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
viz: optional
formal: none
history:
  year: 1975
  people: [Mike Lesk, Eric Schmidt, Ken Thompson]
  note: Lesk and Schmidt wrote lex at Bell Labs in 1975, which generates a lexer from regular expressions, and C fixed maximal munch in its 1989 standard.
see_also: [finite-state-machines, recursive-descent-parsing, abstract-syntax-tree, syntactic-macros, lexical-scope, characters-and-code-points, order-of-evaluation]
same_as:
  wikidata: Q835922
  wikipedia: Lexical_analysis
sources:
- url: https://docs.python.org/3/reference/lexical_analysis.html
  title: Lexical analysis, The Python Language Reference
  locator: 2. Lexical analysis and 2.1.8 Indentation
- url: https://doc.rust-lang.org/reference/tokens.html
  title: Tokens, The Rust Reference
  locator: Introduction
- url: https://go.dev/ref/spec#Tokens
  title: The Go Programming Language Specification
  locator: Tokens and Semicolons
- url: https://docs.oracle.com/javase/specs/jls/se25/html/jls-3.html
  title: Chapter 3, Lexical Structure, The Java Language Specification, Java SE 25 Edition
  locator: 3.2 Lexical Translations
- url: https://en.cppreference.com/w/cpp/language/translation_phases.html
  title: Phases of translation, cppreference.com
  locator: Phase 3, maximal munch
- url: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar
  title: Lexical grammar, MDN Web Docs
  locator: Automatic semicolon insertion
---

## 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.

```python run id=idea
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
```

```output for=idea
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](/finite-state-machines/) 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](/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 | 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.

## 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](/syntactic-macros/).
- **Lexical scope.** A different meaning of the word lexical: names resolve by where they appear in the program text. See [lexical scope](/lexical-scope/).
- **Abstract syntax trees.** The parser builds a tree from the tokens, and later phases work on the tree. See [abstract syntax trees](/abstract-syntax-tree/).

## Pitfalls

- **A line break after `return`.** In JavaScript, automatic semicolon insertion ends the statement, and the function returns `undefined`, 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+foo` in C and C++ and `a/*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 `017` is 15. Use `0o17` where 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
