Skip to content

Lesson 1 of 9 · 22m

Lexing: From Bytes to Tokens

What a lexer really buys you, how to tokenize without regex spaghetti, and why source locations are non-negotiable.

The first compiler I worked on treated lexing as an inconvenient warm-up before the interesting part. That attitude cost weeks. Lexing is where source text stops being a bag of characters and becomes a stream of meaningful symbols; if you get sloppy here, every later stage inherits the mess.

Tokens are a contract

A scanner moves left to right and emits atomic units — identifiers, numbers, punctuation, keywords — while dropping whitespace and most comments. It must also remember where every token came from.

@dataclass(frozen=True)
class Token:
    kind: str      # "ident", "number", "plus", "let", "eof"
    text: str      # exact source spelling
    line: int
    column: int

That location looks like bookkeeping until a user writes x + on line 847. Then it is the difference between error near '+' and line 847, column 18: expected expression after '+'.

The scanner loop is simple on purpose

A hand-written lexer is usually three moves: peek, consume, emit.

while i < len(src):
    ch = src[i]
    if ch.isspace():
        i += 1
    elif ch.isalpha() or ch == "_":
        start = i
        while i < len(src) and (src[i].isalnum() or src[i] == "_"):
            i += 1
        emit(keyword_or_ident(src[start:i]), src[start:i])
    elif ch.isdigit():
        scan_number()
    else:
        scan_operator_or_error()
emit("eof", "")

Parser generators can automate this, but write one by hand first. When generated lexers misbehave, this loop is the mental model you fall back on.

The mistakes that bite later

Match longest operators first (== before =), reject malformed numbers such as 123abc, report unterminated strings, and preserve identifier spelling. Do not emit parser-visible tokens for whitespace unless your language is indentation-sensitive; the parser rarely wants that noise.

Field notes

  • Keep a real eof token. Parsers become cleaner when they can always peek one token forward.
  • Tokenize lazily for very large files, but materializing the stream is fine for a first interpreter.
  • Write a golden test: small source file, exact token stream. It catches accidental keyword and operator changes forever.
  • Comments may matter to formatters and documentation tools even when the parser ignores them; decide before deleting them.

Was this lesson helpful?

Sign in to rate