Skip to content
BoWen Chai's Notes
Go back

Write Markdown Lexer and Parser in Zig

Updated:
AIWriteEdit page

Table of contents

Open Table of contents

Overview

Markdown syntax is context-sensitive—indentation matters, and characters like # or * mean different things depending on where they appear. In mdz, instead of pulling in a parser generator, the lexer and parser are written by hand as a pull-based DFA using Zig’s tagged unions (union(enum)) and exhaustive switch checks.

Architecture: Dumb Lexer, Stateful Parser

+--------------+       +--------------+       +--------------+
|  Source Code | ----> |    Lexer     | ----> |    Parser    | ----> AST (Blocks)
+--------------+       +--------------+       +--------------+
                              |                      ^
                              |                      |
                        [Context-Free]         [Context-Aware]
                        - Tab                  - State: Empty
                        - Space                - State: MaybeTitle
                        - Sign (#, *, etc)     - State: CodeBlock
                        - Str                  - ...

The lexer does zero semantic work. It does not care whether # starts a heading or sits inside a code fence; it just emits Sign('#'). That keeps tokenization small and straightforward to scan or SIMD-accelerate later.

All context lives in the parser’s State, which advances one token at a time.

Pull Loop (src/parser.zig)

The parser drives the lexer by calling lexer.next() until the DFA enters .Done and yields a completed block:

pub fn next(self: *Self, lexer: *Lexer) ParseError!?Block {
    var state = if (self.recover_state) |state|
        State{ .state = state, .allocator = self.allocator }
    else
        State.empty(self.allocator);

    while (lexer.next()) |value| {
        switch (value.item) {
            .ok => |token| {
                try DFA.f(&state, token, value.span);

                switch (state.state) {
                    .Done => {
                        self.recover_state = state.recover_state;
                        return state.value;
                    },
                    else => continue,
                }
            },
            // ... error handling ...
        }
    }
    return null;
}

Why pull instead of push?

  1. Block-at-a-time control: Parser.next() returns ?Block, so callers can stop or inspect after any block without buffering the whole file.
  2. No callback inversion: Pulling a token is a plain function call—no visitor boilerplate, queues, or channel overhead for a single-threaded parser.
  3. Cleaner boundary handling: Markdown block boundaries often depend on the next token; the parser can hold recover_state across calls without asking the lexer to rewind.

Inline Formatting: BitFlags Instead of a Tree

Most Markdown parsers represent inline styles as nested AST nodes (e.g., Strong wrapping Emphasis wrapping Text), which adds allocations and pointer chasing. mdz flattens inline text into (Span, Decorations) pairs using a 5-bit static bitset:

pub const TextKind = enum(u8) {
    Bold,
    Italic,
    Strikethrough,
    LaTex,
    Code,
};

pub const Decorations = std.bit_set.StaticBitSet(5);

pub const Text = struct {
    decorations: Decorations, // e.g. { Bold, Italic }
    span: Span,
};

For **bold *italic***, the parser emits two flat spans:

  1. "bold " -> [Bold]
  2. "italic" -> [Bold, Italic]

Trade-offs:

Lexer (src/lexer.zig)

Tokens are modeled with union(enum) so variants only carry payloads when needed:

pub const TokenItemTag = enum {
    Tab,
    Space,
    LineEnd,
    Sign,
    AsciiNumber,
    Str,
    EOF,
};

pub const TokenItem = union(TokenItemTag) {
    const Self = @This();

    Tab: void,
    Space: void,
    LineEnd: void,
    Sign: u8,
    AsciiNumber: []const u8,
    Str: []const u8,
    EOF: void,

    // ... constructors (e.g. TokenItem.sign('#'))
};

Lexer walks the input buffer via std.unicode.Utf8Iterator:

pub const Lexer = struct {
    buffer: []const u8,
    index: usize = 0,
    utf8_iterator: UTF8Iterator,

    pub fn next(self: *Self) ?Token {
        // ... check buffer bounds ...
        if (self.next_code()) |code|
            switch (code) {
                0x9 => self.tab(),
                '\n' => self.lineEnd(false),
                '0'...'9' => {
                    // consume full number
                },
                // ASCII punctuation / Markdown control characters
                0x21...0x2F, 0x3A...0x40, 0x5B...0x60, 0x7B...0x7E => |c| self.sign(@intCast(c)),
                else => {
                    // consume plain text run
                },
            }
        else
            null;
        // ... update index ...
    }
};

Parser State Machine (DFA)

Parser state uses the same tagged-union pattern—each state variant carries only the context it needs:

pub const StateKind = enum {
    Empty,
    MaybeTitle,
    MaybeTitleContent,
    MaybeCodeBlock,
    MaybeThematicBreak,
    NormalText,
    Done,
    // ...
};

pub const StateItem = union(StateKind) {
    Empty: void,
    MaybeTitle: usize,        // count of leading '#'
    MaybeTitleContent: usize, // heading level once space is seen
    NormalText: Span,
    Done: void,
    // ...
};

Transition Dispatch (src/dfa/lib.zig)

DFA.f maps (current state, token) to the next state. Because Zig switches are exhaustive, adding a new token forces every dispatch site to handle it at compile time.

pub fn f(s: *State, token: Token, span: Span) ParseError!ReturnType {
    try switch (token) {
        .Sign => |sign| switch (sign) {
            '`' => Sign.code(s, span),
            '#' => Sign.title(s, span),
            '*' => Sign.boldItalic(s, span),
            // ...
            else => Sign.normal(s, span),
        },
        .Tab => Ends.tab(s, span),
        .Space => Ends.space(s, span),
        .LineEnd => Ends.lineEnd(s, span),
        .Str => |str| unicodes(s, str, span),
        // ...
    };
}

Example: Heading Handler (src/dfa/sign/title.zig)

When # arrives, Sign.title inspects state.state and updates or transitions it:

pub fn title(state: *State, span: Span) Error!void {
    switch (state.state) {
        .Empty => {
            state.state = .{ .MaybeTitle = 1 };
        },
        .MaybeTitle => |*size| {
            size.* += 1;
        },
        .MaybeFencedCodeBegin => |s| {
            try state.value.?.Paragraph.addCode(state.allocator, ...);
            state.toNormalText(span);
        },
        .NormalText => |*s| {
            _ = s.enlarge(span.len);
        },
        // ...
    }
}

Trace: # Hello

  1. Start: Empty, value = null
  2. Sign('#'): Sign.title -> MaybeTitle(1)
  3. Space: Ends.space -> MaybeTitleContent(1) (space confirms valid H1 prefix)
  4. Str("Hello"): unicodes initializes Block.Title(level = 1) -> NormalText
  5. LineEnd: Ends.lineEnd -> Done; Parser.next() returns the block

Trace: #Invalid (No Space)

  1. Start: Empty
  2. Sign('#'): Empty -> MaybeTitle(1)
  3. Str("Invalid"): unicodes sees text without a space after #, so this is not an ATX heading. It widens the NormalText span to include the preceding # plus "Invalid" and falls back to a paragraph.

The lexer never backtracks—the parser simply reinterprets the span using the current state.

Why Zig Fits This Pattern


Edit page
Share this post:

Previous Post
Use Tailscale Behind a Transparent Proxy (sing-box / Momo)
Next Post
2026 Aug Film Records