Skip to content

Lesson 1 of 9 · 23m

Lexing Without Mythology: Turning Bytes into Tokens

Build a lexer as a lossy-but-accountable boundary between raw text and grammar, with spans, diagnostics, and recovery treated as first-class features.

The first lexer I inherited looked elegant: one giant regular expression, no positions, no errors, and a quiet tendency to turn malformed input into valid-looking tokens. It passed the demo and failed the first user who pasted smart quotes into a config file. A lexer is not glamorous, but it is the first place your language either respects or betrays the person writing it.

The lexer is a security boundary

Lexing converts bytes into tokens. The important part is not recognizing keywords; it is deciding what is allowed to exist at all. Treat the input as hostile even when the language is internal. Editors paste Unicode, files have CRLF endings, and generated code can contain surprising bytes.

let total = price * count;
^^^ ^^^^^ ^ ^^^^^ ^ ^^^^^ ^
kw  ident = ident * ident ; op/punctuation depends on design

Every token should carry at least its kind, text or decoded value, and source span. The span is not optional bookkeeping. It is how you produce errors humans trust.

A practical token shape

from dataclasses import dataclass

@dataclass
class Token:
    kind: str
    text: str
    start: int
    end: int
    line: int
    column: int

Keep token representation boring. A lexer is consumed constantly; clever inheritance trees and regex-generated class hierarchies make debugging worse. Store offsets as well as line and column because slicing original source by offsets is often the only way to render exact context.

Hand-written beats regex soup

A small loop with explicit character classes is easier to maintain than a stack of nested expressions:

def lex_identifier(src, i):
    start = i
    while i < len(src) and (src[i].isalnum() or src[i] == "_"):
        i += 1
    return Token("identifier", src[start:i], start, i, 0, 0), i

The real implementation must update line and column. Handle longest-match rules deliberately: == before =, >= before >, and multi-line comments before single-character operators. Ambiguity belongs in a table or explicit ordered branches, not in whatever order regex alternation happens to try first.

Numbers, strings, and escapes are where bugs breed

Do not lex integers by accepting every digit run. Decide whether 0123, 0x10, 1_000, 1e9, and .5 are valid. Strings need termination, escape validation, and a decision about interpolation. A lexer can reject \q immediately or preserve it for a parser error; either is fine if documented, but silently treating it as q is not.

Error recovery is part of lexing

A production-quality lexer keeps going after bad input. Emit an error token with a precise span, skip one byte or one grapheme cluster, and continue. Never loop forever on an unterminated construct. If your scanner depends on lookahead, bound it.

Field notes

  • isalpha() and Unicode identifiers are policy decisions; write them down instead of inheriting accidental locale behavior.
  • Byte offsets, UTF-16 code units, and grapheme clusters are different. Pick byte or Unicode scalar offsets and be consistent.
  • Do not intern or decode strings during lexing unless you can still reconstruct exact source slices for diagnostics.
  • A lexer that panics on malformed input becomes a denial-of-service primitive when exposed to uploaded code.

Was this lesson helpful?

Sign in to rate