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 a base_offset so sub-expressions inside interpolated strings ("sum = {a + b}") preserve exact original source spans for diagnostics.
  • Preserves raw string distinction via TokenKind::RawStr(String) vs TokenKind::Str(String).
  • Collects Comment { text, span, is_line } entries alongside tokens during tokenize_with_comments(), enabling lossless comment preservation in format_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_lit context flag inside if, while, and match headers to disambiguate if cond { ... } from struct literals Point { x: 1 }.
  • Uses is_closure_ahead() lookahead on ( to distinguish TypeScript-style closures (x: Int) => x * 2 from 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)

  1. Pass 1 (Type Names): Registers all struct and enum names so mutually recursive or forward-referenced types resolve cleanly.
  2. Pass 2 (Signatures): Resolves struct field types, enum variant payloads, function signatures, and impl method tables.
  3. 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, and http_serve.
  • Exhaustiveness checking for match over Enum, Option, and Result.
  • Task<T> inference across explicit returns, tail expressions, nested spawn blocks, and fallthrough detection (block_definitely_returns).
  • Deep immutability (check_lvalue_mutability) walking nested Index/Field lvalues to their root binding.