Internals · 02
Lexer, Parser & Type Checker
Inside ochre-syntax and ochre-types — byte-indexed lexing, string interpolation, Pratt parsing, comment-preserving formatting, and 3-pass static type checking.
The frontend (ochre-syntax and ochre-types) transforms raw UTF-8 source text into a validated AST and a SymbolTable used by downstream compilers and ochre-lsp.
Lexer (ochre-syntax/src/lexer.rs)
- Operates directly on
&[u8]with abase_offsetso sub-expressions inside interpolated strings ("sum = {a + b}") preserve exact original source spans for diagnostics. - Preserves raw string distinction via
TokenKind::RawStr(String)vsTokenKind::Str(String). - Collects
Comment { text, span, is_line }entries alongside tokens duringtokenize_with_comments(), enabling lossless comment preservation informat_source(). - Supports nested block comments (
/ ... / ... / ... /).
Pratt Parser (ochre-syntax/src/parser.rs)
- Top-down recursive descent for items (
import,struct,enum,impl,fn) and statements, combined with Pratt precedence climbing for expressions. - Uses a
no_struct_litcontext flag insideif,while, andmatchheaders to disambiguateif cond { ... }from struct literalsPoint { x: 1 }. - Uses
is_closure_ahead()lookahead on(to distinguish TypeScript-style closures(x: Int) => x * 2from parenthesized expressions(x + 1). - Recovers from syntax errors via
synchronize()so multiple diagnostics can be reported in a single pass.
3-Pass Type Checker (ochre-types/src/lib.rs)
- Pass 1 (Type Names): Registers all
structandenumnames so mutually recursive or forward-referenced types resolve cleanly. - Pass 2 (Signatures): Resolves struct field types, enum variant payloads, function signatures, and
implmethod tables. - Pass 3 (Bodies): Type-checks function bodies, method bodies, and top-level statements, enforcing:
- Polymorphic built-in checking via
Type::Builtin(BuiltinKind)(immune to variable aliasing and empty-collection bypasses). - Contextual parameter type hints when checking closures passed to
map,filter,reduce, andhttp_serve. - Exhaustiveness checking for
matchoverEnum,Option, andResult. Task<T>inference across explicit returns, tail expressions, nestedspawnblocks, and fallthrough detection (block_definitely_returns).- Deep immutability (
check_lvalue_mutability) walking nestedIndex/Fieldlvalues to their root binding.