Skip to content

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/:

FileResponsibility
tokenizer.rsScanning loop: entry points for whitespace, comments, symbols, identifiers, numbers, strings, and f-strings
tokens.rsTokenKind (the sole source of token kinds) and token structures
symbols.rsKeyword and symbol tables
literals.rsNumbers (various bases/separators/suffixes), characters, strings, escapes, and f-string literals
state.rsLexical 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/ and locales/; whenever the wording changes, update all language versions simultaneously.

Syntax ​

src/frontend/core/parser/:

FileResponsibility
mod.rsEntry points: parse_module, expression parsing, and the interface with callers
parser_state.rsToken cursor, accumulation of in-scope declarations, and TypeEnvProbe injection
pratt/precedence.rsThe only precedence and operator property table
pratt/nud.rsPrefix/atomic parsing (literals, identifiers, groups, blocks, if, match, lambda…)
pratt/led.rsInfix/postfix parsing (binary operators, assignments, calls, fields, indexing, ?, as, in…)
statements/Statements and declarations: bindings, functions, types, imports, patterns, and type syntax
probe.rsTypeEnvProbe 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 + 1 must not be relied upon.
  • The parser does 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 uses state.probe().
  • When constructing Type::Name, the probe determines the NameKind; subsequent matches no longer compare strings.
  • Parentheses follow currying semantics: (T) is a complete type (Paren), while (a: T) -> R is a parameter group; NamedParen only carries a named binder in return position.
  • Formal parameter names in function signatures belong to Type::Fn.params (Param carries its own name); no parallel array of names is introduced.

Error Recovery ​

  • Syntax errors produce Expr::Error / StmtKind::Error placeholder 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 Error nodes 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 ​

RepresentationLocationRole
ast::Typesrc/ast/mod.rsSyntax-layer type expression; constructed by the parser and used only in L2/L3 compile-time semantics
MonoTypesrc/frontend/core/types/mono.rsL3 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 consume MonoType.
  • 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 as TypeVar, MetaType, Literal, and ConstExpr must not appear in instruction operands, function signatures, or type_table.
  • Type equality = identity + type arguments; the field table is computed on demand by apply_params from the shared StructBody and 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, and MonoType::TypeRef carry Nominal;
  • StructBody.interfaces stores interface identities;
  • flat paths with module="" represent built-ins, type parameters, or synthetic names;
  • every type declared through TypeDefinition must carry a module, with no exception for std; 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 / String have no lowercase or alias spellings.
  • () is the type notation for Void, carried by Type::Name{"()"}, and is not an independent variant.
  • The authoritative resolution table is MonoType::from_builtin_name (types/mono.rs); the type-tables --report T2 gate cross-checks it against CONST_PARAM_TYPES and the LSP type-name list.

Name Classification and Probe ​

The parser does not own type semantics:

  • parser/probe.rs defines the TypeEnvProbe trait and NameKind; when constructing Type::Name, the parser uses state.probe() to classify the name once and for all.
  • The production entry point injects BuiltinProbe; unit tests use NullProbe.
  • CONST_PARAM_TYPES belongs to L3 (sema/probe.rs); the parser must not hard-code built-in type names or predicate names (check-boundary.py B6).

Operator Representations ​

  • ast::BinOp / ast::UnOp are the primary syntax-layer representations.
  • const_data::BinOp / UnOp are the representations used for compile-time constant evaluation; both sides are semantically aligned, with the sole mapping point at const_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):

CheckContentsFailure Condition
T1 Construction-point classificationScan ast::Type variants and count construction sites in three categories: parser forward construction / AST→AST reconstruction / reverse bridge, then compare against the baselineA 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 consistencyfrom_builtin_name, CONST_PARAM_TYPES, and the LSP built-in name listThe same name is inconsistent across the three tables, or a deleted spelling is reintroduced
T4 Variant→arm consistencyList of Type variants vs. the match arms of From<ast::Type> for MonoTypeA 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.rs pins the associativity and precedence level of each operator; every new operator requires an additional test case.
  • Corpus: tests/yaoxiang/ and tests/yaoxiang-multifile/ cover end-to-end syntactic forms.