Frontend and Types
This article describes the lexical, syntactic, and type-representation boundaries of L2: how tokens are produced, how the Pratt parser is organized, and how types are converted between the AST and
MonoType. For layering and routing, see 01-architecture.md; for the IR and acceptance criteria, see 03-ir-and-criteria.md.
Lexical Analysis
src/frontend/core/lexer/:
| File | Responsibility |
|---|---|
tokenizer.rs | Scanning loop: entry points for whitespace, comments, symbols, identifiers, numbers, strings, and f-strings |
tokens.rs | TokenKind (the sole source of token kinds) and token structures |
symbols.rs | Keyword and symbol tables |
literals.rs | Numbers (various bases/separators/suffixes), characters, strings, escapes, and f-string literals |
state.rs | Lexical state (position, interpolation stack, error collection) |
Rules:
- Every token carries an absolute source-file span (starting and ending line/column/offset); later stages must not recalculate or guess positions.
- Number scanning has only one path: parse according to the radix and consistently handle separators, prefixes, exponents, and overflow; do not duplicate scanning logic at call sites.
- Escape decoding has only one implementation, shared by strings, characters, and f-strings.
- During lexical analysis, f-strings are split into text segments and interpolation expressions; interpolation spans record absolute source offsets. Expressions inside interpolations are passed to the parser, and the lexer does not perform a nested full tokenization pass.
- Invalid literals must report a diagnostic and produce a token that allows parsing to continue (error recovery); they must not panic or be silently swallowed.
- Lexical error codes and help text are defined in
src/util/diagnostic/codes/andlocales/; whenever the wording changes, update all language versions simultaneously.
Syntax
src/frontend/core/parser/:
| File | Responsibility |
|---|---|
mod.rs | Entry points: parse_module, expression parsing, and the interface with callers |
parser_state.rs | Token cursor, accumulation of in-scope declarations, and TypeEnvProbe injection |
pratt/precedence.rs | The only precedence and operator property table |
pratt/nud.rs | Prefix/atomic parsing (literals, identifiers, groups, blocks, if, match, lambda…) |
pratt/led.rs | Infix/postfix parsing (binary operators, assignments, calls, fields, indexing, ?, as, in…) |
statements/ | Statements and declarations: bindings, functions, types, imports, patterns, and type syntax |
probe.rs | TypeEnvProbe trait and NameKind; the parser asks the type layer only through this interface |
Rules:
- Pratt parsing has a single binding-power ladder, all of which is defined in
precedence.rs. Adding an operator requires changes only to this table + the token +ast::BinOp+ the SPEC + tests. - Associativity is explicitly declared in the table; implicit conventions such as
bp_right = bp_left + 1must not be relied upon. - The
parserdoes not own type semantics: it does not identify built-in type names, identify predicate names, or perform type checking; when such facts are needed, it usesstate.probe(). - When constructing
Type::Name, the probe determines theNameKind; subsequent matches no longer compare strings. - Parentheses follow currying semantics:
(T)is a complete type (Paren), while(a: T) -> Ris a parameter group;NamedParenonly carries a named binder in return position. - Formal parameter names in function signatures belong to
Type::Fn.params(Paramcarries its own name); no parallel array of names is introduced.
Error Recovery
- Syntax errors produce
Expr::Error/StmtKind::Errorplaceholder nodes and skip ahead to a synchronization point (synchronize(): statement boundary, declaration start, block closure). - Parsing continues after recovery so that a single compilation can report multiple independent errors where possible; the entire tree must not be discarded because of one syntax error.
- An error node’s span points to the offending token; later stages suppress errors at
Errornodes and do not report the same error again. - Multi-file setups are isolated per unit: a parse failure in one file does not affect diagnostic collection in other units.
Two Representations
| Representation | Location | Role |
|---|---|---|
ast::Type | src/ast/mod.rs | Syntax-layer type expression; constructed by the parser and used only in L2/L3 compile-time semantics |
MonoType | src/frontend/core/types/mono.rs | L3 working representation and IR type annotations; carries resolved type arguments, type variables, and refinement information |
ast::Type currently has 13 variants: Name / Struct / NamedStruct / Tuple / Fn / Generic / Literal / Ptr / Ref / MetaType / ConstExpr / Paren / NamedParen. Among them, Literal / ConstExpr / MetaType and the parenthesized forms are compile-time only; they must not enter the IR.
MonoType covers Never / Void / Bool / Int / Float / Char / Struct / Enum / Fn / TypeVar / TypeRef / Generic / Union / Intersection / Ref / AssocType / MetaType / Literal / Refined / dependent function types, and more; TypeVar and substituted forms exist only during type checking and must not enter the IR.
Conversion Boundaries
- The only production-side conversion is
impl From<ast::Type> for MonoType(types/mono.rs). Type checking, monomorphization, and IR construction all consumeMonoType. - On the production side, there is no reverse conversion from
MonoType→ast::Type; monomorphization only writes back structured results and does not reconstruct syntactic types. - IR type annotations may only use the resolved subset of
MonoType: compile-time-only forms such asTypeVar,MetaType,Literal, andConstExprmust not appear in instruction operands, function signatures, ortype_table. - Type equality = identity + type arguments; the field table is computed on demand by
apply_paramsfrom the sharedStructBodyand is not inlined into type values.
Type Identity
The identity of a nominal type is its canonical path, not its bare name. Identity has only one encoding: Nominal in the type layer (wrapping TypePath), and DefPath plus the current compilation handle DefId in the binding layer. DefPath::project is the sole qualified-name projection, and projection is one-way (the identity string must not be split on dots or truncated to reverse-resolve it).
Carriers (types/mono.rs and types/identity.rs):
StructType.identity,EnumType.name,MonoType::Generic.name, andMonoType::TypeRefcarryNominal;StructBody.interfacesstores interface identities;- flat paths with
module=""represent built-ins, type parameters, or synthetic names; - every type declared through
TypeDefinitionmust carry a module, with no exception forstd; names that were never declared (phantom names) do not constitute identities.
Method identities use the same mechanism: the method-table key is DefPath, typecheck resolves it through the single sema::import_face path, and the IR only reads the resolved projection. For user-visible semantics, see Language Specification §2.3.
Built-in Type Names
There are 15 built-in type names: Never / Void / () / Bool / Int / Int8 / Int16 / Int32 / Int64 / Float / Float32 / Float64 / Char / String / Bytes.
- Each name has only one spelling; names such as
Int/Int64/Stringhave no lowercase or alias spellings. ()is the type notation forVoid, carried byType::Name{"()"}, and is not an independent variant.- The authoritative resolution table is
MonoType::from_builtin_name(types/mono.rs); thetype-tables --reportT2 gate cross-checks it againstCONST_PARAM_TYPESand the LSP type-name list.
Name Classification and Probe
The parser does not own type semantics:
parser/probe.rsdefines theTypeEnvProbetrait andNameKind; when constructingType::Name, the parser usesstate.probe()to classify the name once and for all.- The production entry point injects
BuiltinProbe; unit tests useNullProbe. CONST_PARAM_TYPESbelongs to L3 (sema/probe.rs); the parser must not hard-code built-in type names or predicate names (check-boundary.pyB6).
Operator Representations
ast::BinOp/ast::UnOpare the primary syntax-layer representations.const_data::BinOp/UnOpare the representations used for compile-time constant evaluation; both sides are semantically aligned, with the sole mapping point atconst_eval::convert_ast_binop.- Do not rename or duplicate a third enum merely for alignment; adding an operator requires changes only to the precedence table,
ast, and the mapping point.
Type Table Gates
tools/type-tables runs at build time (build.rs invokes type_tables::build_gate):
| Check | Contents | Failure Condition |
|---|---|---|
| T1 Construction-point classification | Scan ast::Type variants and count construction sites in three categories: parser forward construction / AST→AST reconstruction / reverse bridge, then compare against the baseline | A forward-zero construction variant is not registered, a registered variant has construction sites, an exemption point does not match, or the baseline or counting criteria drift |
| T2 Name-table consistency | from_builtin_name, CONST_PARAM_TYPES, and the LSP built-in name list | The same name is inconsistent across the three tables, or a deleted spelling is reintroduced |
| T4 Variant→arm consistency | List of Type variants vs. the match arms of From<ast::Type> for MonoType | A variant has no arm, or an arm targets a removed variant (compile-time checks already guarantee most cases) |
T1/T2 are hard build failures; REGISTERED_ZERO_FORWARD and DEAD_VARIANTS_03 are currently both empty tables.
Tests
- Lexical analysis:
lexer/tests/literals.rs(different bases, escapes, f-strings, and invalid forms). - Syntax:
parser/tests/(expressions, statements, declarations, types, patterns, and error recovery). - Precedence:
parser/tests/associativity.rspins the associativity and precedence level of each operator; every new operator requires an additional test case. - Corpus:
tests/yaoxiang/andtests/yaoxiang-multifile/cover end-to-end syntactic forms.
