Skip to main content

Parser and AST

The parser transforms .cham schema files into a validated Abstract Syntax Tree (AST) using LALRPOP, a Rust parser generator based on LR(1) grammar.

Overview

The parsing pipeline consists of:
  1. Lexical Analysis - Tokenize input using LALRPOP’s built-in lexer
  2. Syntax Analysis - Build AST from tokens following grammar rules
  3. Error Enhancement - Add source context and helpful suggestions
  4. AST Construction - Create immutable schema representation

Architecture

Parser Entry Point

Location: chameleon-core/src/parser/mod.rs:13
Key features:
  • Zero-copy parsing where possible
  • Enhanced error messages with source snippets
  • Line/column precision for all syntax errors

LALRPOP Grammar

Location: chameleon-core/src/parser/schema.lalrpop

Entry Point

Entity Syntax

Field Syntax

Supported Types

Whitespace and Comments

AST Structures

Location: chameleon-core/src/ast/mod.rs

Schema

Entity

Field

Field constraints:
  • primary_key - Entity identifier (required, exactly one per entity)
  • unique - Unique constraint (enforced at DB level)
  • nullable - NULL allowed (defaults to NOT NULL)

FieldType

Relation

Backend Annotations

Error Enhancement

Location: chameleon-core/src/parser/mod.rs:80 The parser enhances errors with:

1. Source Context

Example output:

2. Position Calculation

3. Smart Suggestions

Common suggestions:
  • Keyword typos: entiyentity, primryprimary
  • Missing colons: “Fields must have a type after the colon”
  • Unclosed braces: “Missing closing brace”
  • EOF errors: “You may be missing a closing brace }“

Build Process

Location: chameleon-core/build.rs
Generated artifacts:
  • $OUT_DIR/parser/schema.rs - LR(1) parser state machine
  • Compile-time only - not included in library distribution

Performance Characteristics

Memory usage:
  • Schema AST: ~50 bytes per field + ~80 bytes per relation
  • Parser state machine: ~200KB (generated at compile time)

Example Usage

Basic Parsing

Accessing AST

Error Handling

Testing

Location: chameleon-core/src/parser/mod.rs:170 Test coverage:
  • Simple entities with fields
  • Relations (HasMany, BelongsTo, etc.)
  • Backend annotations (@cache, @olap, @vector)
  • Vector types with dimensions
  • Array types ([string], [decimal])
  • Complex multi-backend schemas
Example test:

See Also