Skip to content

Type System Specification ​

This document defines the type system specification of the YaoXiang programming language, including primitive types, compound types, generics, and traits.


Chapter Zero: Theoretical Foundations ​

0.1 Curry-Howard Isomorphism ​

The Curry-Howard isomorphism (Curry-Howard correspondence) is the theoretical foundation of the YaoXiang type system. It reveals the deep correspondence between the type systems of programming languages and mathematical logic:

LogicProgramming Language
Proposition (P)Type Type
Proof (p: P)Program x: T = ...
Implication (P \rightarrow Q)Function type (P) -> Q
Conjunction (P \wedge Q)Product type { a: P, b: Q }
Disjunction (P \vee Q)Sum type { a(P) | b(Q) }
Universal quantification (\forall x:T. P(x))Generics (T: Type) -> ...
True (\top)Void (Unit, with a default value)
False (\bot)Never (zero constructors, with no inhabiting values)
Type universe (Type_n : Type_{n+1})Universe stratification (prevents Russell's paradox)
case analysisType-level match

Note: Type-level match is case analysis, not mathematical induction. Induction requires a type-level recursive function plus a compiler termination check.

0.2 Types Are Propositions, Programs Are Proofs ​

In YaoXiang, this correspondence is a first-class design principle:

  • Terminating type-level computations correspond to correct constructive proofs. YaoXiang type families (such as case analysis and recursive calls for Add over Nat) are essentially type-level encodings of mathematical induction—provided that the compiler can perform a termination check.
  • Type checking is proof verification. When a program passes type checking, a logical proposition has been constructively proved.

0.3 Impact on Language Design ​

The concrete manifestations of the Curry-Howard isomorphism in YaoXiang are:

  1. Universe stratification (RFC-010): Type₀ : Type₁ : Type₂ … avoids the logical paradox caused by Type: Type (Girard's paradox).
  2. Type families (RFC-011): Type-level case analysis and recursive calls over the natural-number type Nat(Zero/Succ) correspond to the Peano axioms—provided that the compiler performs a termination check.
  3. Conditional types (RFC-011): If: (C: Bool, T: Type, E: Type) -> Type corresponds to case disjunction in logic.
  4. Value-dependent types (RFC-011): Array: (T: Type, N: Int) -> Type corresponds to the finite quantification “for each integer N, there exists a type.”

Chapter One: Type Classification ​

1.1 Type Expressions ​

TypeExpr    ::= PrimitiveType
              | RecordType
              | InterfaceType
              | TupleType
              | FnType
              | GenericType
              | TypeRef
              | TypeUnion
              | TypeIntersection

Design note: Although RFC-010 proposes a unified “everything is an assignment” model (name: type = value), types and values must still be distinguished at the syntactic level. In the compiler implementation, Type and Expr are two independent AST enums (ast.rs:406 and ast.rs:25). As a BNF placeholder, TypeExpr corresponds to the implementation's Type enum and means “a type is expected in this position.”


Chapter Two: Primitive Types ​

2.1 Primitive Types ​

There are 15 built-in type names; this section is the authoritative table: Never / Void / () / Bool / Int / Int8 / Int16 / Int32 / Int64 / Float / Float32 / Float64 / Char / String / Bytes. The single source of truth in the implementation is MonoType::from_builtin_name (src/frontend/core/types/mono.rs). This table is consistent with it name by name—the T2 gate of tools/type-tables --report compares this table, CONST_PARAM_TYPES, and the LSP type-name list in all three directions.

TypeLogical CorrespondenceDescriptionDefault Size
Type—Meta type (not a value type name; see below)0 bytes
Never⊥ (false/empty type)Zero constructors and no values. Return type for divergence/panic. Never <: T holds for every T.0 bytes
Void⊤ (true/Unit)Has a default void value and is a zero-field product type. x: Void = <default> is valid.0 bytes
Bool—Boolean value: true / false1 byte
Int—Signed integer (= Int64)8 bytes
Int8—8-bit signed integer1 byte
Int16—16-bit signed integer2 bytes
Int32—32-bit signed integer4 bytes
Int64—64-bit signed integer8 bytes
Float—Floating-point number (= Float64)8 bytes
Float32—32-bit floating-point number4 bytes
Float64—64-bit floating-point number8 bytes
String—UTF-8 stringVariable
Char—Unicode character4 bytes
Bytes—Raw bytesVariable

() is the type notation for Void (a zero-element tuple = the unit type) and is synonymous with Void: standard-library signature strings write () -> Void, and the parser table places () and Void in the same arm.

There is only one spelling. Int is not int; Int64 is not int64/i64; String is not string/str; Bool is not bool; Void is not void; Never is not never; Float is not float/f64; Char is not char; and Bytes is not bytes. Any noncanonical spelling in a type position produces an unknown-type error and is never silently coerced to a user-defined type.

DateTime is not a built-in name. The now / parse_time functions in std.time return Int timestamps; std signature strings write Int directly, and writing a bare DateTime annotation produces the same unknown-type error as any other unknown type name.

There are no unsigned integer types. Uint (and Int128) are not usable type names—MonoType has no unsigned variant. When unsigned semantics are needed, use Int with an explicit lower-bound convention.

2.2 Never and Void: ⊥ and ⊤ ​

Never and Void are the logical primitives of the type system, corresponding respectively to false (⊥) and true (⊤).

Never (⊥, false/empty type) — three non-negotiable properties:

  1. Zero constructors: No literal or expression can produce a value of type Never. There is no right-hand side for x: Never = ....
  2. Principle of explosion: Never <: T holds for every type T. assert(false) returns Never, after which the code can pass type checking (although it is never reached).
  3. Divergence marker: f: (...) -> Never means that f is guaranteed not to return. The compiler uses this to perform dead-code analysis and match branch confluence.

Never is a built-in type name, registered through the same path as Int/Bool; it is not a keyword.

Void (⊤, true/Unit) — exactly one inhabitant (the default void value). Void is the monoid of zero-field product types. x: Void = <default> is valid. A block's value is given by its tail expression (an empty block {} has type Void). See RFC-010a for details.

2.3 Type Identity and Equality ​

Every nominal type (one produced by a type declaration) has a definition site: the module containing the declaration plus the type name. Types with the same name but defined in different modules have different identities and cannot be assigned to one another. Alias imports (use a.{T as U}) do not change identity; U and a.T are the same type.

Type equality is determined by identity + type arguments:

  • Two nominal types are equal ⇔ they have the same identity and their type arguments are equal position by position;
  • Anonymous record, tuple, and function types are compared structurally (field names, field types, parameter types, and return types);
  • Built-in types and type parameters have no module ownership and are distinguished by name (flat paths).

Display: Diagnostics display bare names by default. When a single diagnostic mentions two or more types with the same name but different identities, those types use qualified names (Module.TypeName).

An undeclared name is not a type identity; an unknown name in a type position produces an unknown-type error.


Chapter Three: Compound Types ​

3.1 Record Types ​

Unified syntax: Name: Type = { field1: Type1, field2: Type2, ... }

RecordType  ::= '{' FieldList? '}'
FieldList   ::= Field (',' Field)* ','?
Field       ::= Identifier ':' TypeExpr
            |  Identifier                 // Interface constraint
yaoxiang
// Simple record type
Point: Type = { x: Float, y: Float }

// Empty record type
Empty: Type = {}

// Generic record type
Pair: (T: Type) -> Type = { first: T, second: T }

// Record type implementing interfaces
Point: Type = {
    x: Float,
    y: Float,
    Drawable,
    Serializable
}

Rules:

  • Record types are defined using curly braces {}.
  • A field name is followed directly by a colon and a type.
  • An interface name inside the type body indicates that the type implements the interface.
  • Fields are divided into data fields and evidence fields according to the proof-space criterion (§8.3): if a normalized field type falls in the proof space (Proof), the field is an evidence field, occupies no constructor argument position, and occupies no runtime data slot. Any field falling in the data space (Data) is a data field.

Namespace ownership: A Type.name prefix (such as Point.draw) indicates that the function belongs to Point's namespace. It does not trigger any implicit binding. To make . call syntax such as p.draw() work, an explicit binding is required: Point.draw = draw[0]. See RFC-004 and RFC-010 for details.

3.1.1 Field Default Values ​

A type field may specify a default value, in which case it may be omitted during construction:

yaoxiang
// Fields with defaults — optional during construction
Point: Type = {
    x: Float = 0,
    y: Float = 0
}

// Usage
Point()           // -> Point(x=0, y=0)
Point(x=1)       // -> Point(x=1, y=0)
Point(x=1, y=2) // -> Point(x=1, y=2)

// Fields without defaults — required during construction
Point2: Type = {
    x: Float,
    y: Float
}

// Usage
Point2(x=1, y=2) // Correct
Point2()          // Error

Rules:

  • field: Type = expression -> has a default value and is optional during construction
  • field: Type -> has no default value and is required during construction
  • Evidence fields have no runtime value and therefore have no default values (§8.3)

3.1.2 Built-in Bindings ​

Methods may be bound directly inside a type definition:

yaoxiang
// Method 1: bind by referencing an external function
distance: (a: Point, b: Point) -> Float = { ... }
Point: Type = {
    x: Float = 0,
    y: Float = 0,
    distance = distance[0]    // Bind to position 0
}
// Call: p1.distance(p2) -> distance(p1, p2)

// Method 2: anonymous function + positional binding
Point: Type = {
    x: Float = 0,
    y: Float = 0,
    distance: ((a: Point, b: Point) -> Float)[0] = ((a, b) => {
        dx = a.x - b.x
        dy = a.y - b.y
        return (dx * dx + dy * dy).sqrt()
    })
}
// Syntax: ((params) => body)[position]
// Call: p1.distance(p2) -> distance(p1, p2)

3.2 Interface Types ​

InterfaceType ::= '{' FnField (',' FnField)* ','?
FnField       ::= Identifier ':' FnType
FnType        ::= '(' ParamTypes? ')' '->' TypeExpr

Syntax: An interface is a record type whose fields are all function types.

yaoxiang
// Interface definition
Drawable: Type = {
    draw: (Surface) -> Void,
    bounding_box: () -> Rect
}

Serializable: Type = {
    serialize: () -> String
}

// Empty interface
EmptyInterface: Type = {}

Interface implementation: A type implements an interface by listing the interface name at the end of its definition.

yaoxiang
// Type implementing an interface
Point: Type = {
    x: Float,
    y: Float,
    Drawable,        // Implements the Drawable interface
    Serializable     // Implements the Serializable interface
}

Direct interface assignment: A concrete type may be assigned directly to a variable of an interface type (structural subtyping).

yaoxiang
// Direct assignment (the concrete type is statically known -> zero-overhead call)
d: Drawable = Circle(1)
d.draw(screen)        // After compilation: direct call to circle_draw, no vtable

// Function return value (not statically known -> vtable call)
d: Drawable = get_shape()
d.draw(screen)        // Method lookup through the vtable

// Interface as a function parameter
process: (d: Drawable) -> Void = d.draw(screen)

Compile-time optimization strategy:

ScenarioInference ResultCall Method
Direct assignment of a concrete typeThe concrete type is knownDirect call (zero overhead)
Function return valueUnknownvtable
Heterogeneous collectionMultiple typesvtable

Coherence and orphan rules (not applicable; closure note): YaoXiang interfaces are structural types (an interface is a record whose fields are all function types), not nominal traits. There is therefore no cross-crate/module “who may implement what for whom” ownership issue, and Rust-style orphan rules and coherence checks have no applicable targets (see RFC-011 §2.1 for the decision record). The corresponding guarantee in a structural world is rejection of duplicate implementations: defining the same method signature more than once on a type is a compile-time error (RFC-011a §3, which prohibits overriding; overloading is legal).

3.3 Tuple Types ​

TupleType   ::= '(' TypeList? ')'
TypeList    ::= TypeExpr (',' TypeExpr)* ','?

3.4 Constructors ​

Record types (§3.1) automatically generate constructors. Constructor arguments correspond only to data fields—compile-time evidence fields (evidence fields, §8.3) occupy no constructor argument position.

FieldConstructor Argument PositionRuntime Data Slot
Data fieldOccupies one position, in field declaration orderOccupies one slot
Evidence fieldDoes not occupy a positionDoes not occupy a slot
Function-typed field (method)Does not occupy a positionDoes not occupy a slot

Compile-time arity = runtime arity = number of data fields. Evidence is not a constructor argument: it comes from a proof obligation automatically generated at the construction site (§8.3.2), which the compiler synthesizes itself or verifies using an independently supplied proof function. There is no source-level “evidence argument position.” Passing one extra argument does not match any data parameter slot and produces an argument error in the E1010 / E1014 family; it is never silently ignored.

Fields with default values may be omitted during construction, while fields without default values are required (§3.1.1).

Construction sites carry proof obligations. Each evidence field creates a proof obligation at the construction site: substitute the compile-time values of the strictly preceding data fields into that field's proposition, obtain a closed proposition, and have the proof kernel verify it under the current logical signature (§8.3.2). If the obligation is disproved, compilation fails and provides a counterexample. If it cannot be proved, supply an independent proof function or a named proof from a proof library (§8.3.2), rather than an additional constructor argument—there is no evidence argument position at a construction site.

Two views of the same construction:

  • Compile-time view: Data arguments are bound in declaration order. Evidence fields occupy no argument positions, but each carries a proof obligation awaiting verification.
  • Runtime view: Only data fields enter the runtime layout. Evidence fields and their certificates are completely erased at runtime (§8.3.6).
yaoxiang
Pos: (v: Int) -> Type = { v > 0 }

Box: Type = {
    v: Int,          // Data field: constructor argument position 0, runtime data slot 0
    w: Pos(v),       // Evidence field: Pos is a proof-space family, Pos(v) is a proposition
    z: Int,          // Data field: constructor argument position 1, runtime data slot 1
}

b = Box(3, 5)       // arity = 2 (v, z); only v=3 and z=5 exist at runtime; w is compile-time evidence

Design basis: RFC-027 §14.1–§14.2 (field position rules and construction views), RFC-027 §4 (proof kernel and logical signatures).

Implementation status: Evidence determination for non-generic records (proof space → position → category), construction-site proof obligations and data-field arity, and propagation of quantifiers through the record model into the IR have been implemented. Generic records, const parameters, and proof-family instantiation determination have also been implemented (B.2b): constructor arguments count only data fields, while evidence-field evidence is synthesized automatically and determined at construction sites—a false proposition reports E4018, and an unproven proposition reports E2031. Value-level reads report E1114, and mutable writes report E1115. Type-level b.w (B.3) has been implemented (admission reading style, D2 ruling A). Cross-module export (B.4) has been implemented (V1 re-verification only: per-library source fingerprint comparison + importer re-verification; translation/bridging awaits the §4.1 kernel; the evidence_ref/certificate_ref slots are not materialized, D1 ruling A).

3.5 Function Types ​

FnType      ::= '(' ParamList? ')' '->' TypeExpr
ParamList   ::= Param (',' Param)*
Param       ::= Identifier ':' TypeExpr    // Named parameter
              | TypeExpr                   // Unnamed parameter (bare type)

Two parameter forms, with different ownership of names (the type-side counterpart of RFC-007's shorthand rules):

  • Named (a: Int): The name enters the contract and may be referenced by a named argument (f(a = 3), see syntax §2.3). When the signature has declared parameter names and types, the lambda header may be omitted (add: (a: Int, b: Int) -> Int = a + b, RFC-003-ir-and-criteria § shorthand rules).
  • Unnamed (a bare type, such as (Int, Int) -> Int): Type constraints apply by position, while the names belong to the implementation. The lambda header must provide parameter names (mk: (Int, Int) -> Int = (x, y) => x + y; RFC-007: a lambda header may be omitted if and only if the signature has declared parameter names). Such parameters cannot be referenced by named arguments and may only be called by position. Bare identifiers are resolved in the type namespace, and an unresolved identifier that is not a declared type produces an unknown-type error—there are no bare identifiers in parameter positions that are “neither a type nor a type parameter.”

Annotation binding semantics: An annotation is a declaration, not a comment. Binding statements are checked against their annotations—the parameter types drive the lambda header position by position, and the function body's exits (tail expression and return) are checked uniformly against the annotated return type. The type registered for callers is the annotated form. Unannotated bindings use HM inference (RFC-007). x: Int = "hello" and f: () -> Int = () => "hello" are rejected under the same rule; binding semantics do not diverge according to the syntactic form of the value (lambda / block / expression / named function reference).

An implementation header's formal parameters are positional binders (f: (a: Int) -> Int = (b) => b + 1):

  • Names and types follow the declaration: The i-th parameter of the implementation header corresponds to the first N positions of the declaration's value-level signature (N = the number of implementation-header parameters; value-level signature = the parameter sequence after removing compile-time positions—T: Type, type-level function positions, and const positions—from the declaration). The implementation header only declares “what the i-th parameter is called inside the body.” Renaming it does not affect the call site—the usable name for f(a = 7) comes from the declaration, independently of the implementation header's name.
  • Annotations in the implementation header are used only for comparison: If the type at the same position differs from the declaration, report E1011 (the declaration is authoritative, and the author's annotation must not be silently overridden).
  • Reporting more implementation-header formal parameters than the declaration has runtime parameter positions reports E1112: the extra positions have no values to bind (type positions T: Type, type-level function positions, and const positions do not occupy runtime parameter positions).
  • The reverse case (the implementation specifies fewer parameters) is not an error (the “pass” cell in the t1 behavior matrix before D54 must not be reclassified): at the type level, arity is still checked against the declaration (f(1) is legal and f(1, 2) reports E1010), and missing positions are filled positionally by the declaration into the type-checking scope. The implementation header has no corresponding runtime slots, however, so arguments landing in those positions are discarded on the IR side and do not participate in computation inside the body (the f(1) in f: (a: Int) -> Int = () => 1 is unrelated to the argument). This has been registered as a gap—making the runtime also receive the declared arity is a class-D behavior change and requires a separate ruling.
  • Unified exits: Whenever the tail expression or return (the arrow sugar => x and the explicit return x are two AST forms) does not match the declared return position, report E1012, with the location pointing to the annotation.

Implementation status: Binding-period checking for Fn annotations has been implemented: positional parameter driving (parser and typecheck use the same alignment rule: the first N positions of the value-level signature) / comparison against implementation-header annotations (E1011; the author's annotation is retained and any mismatch is an error) / unified exits (E1012) / the declared form is used for registration (usable names for named arguments).


Chapter Four: Generics ​

4.1 Generic Parameter Syntax ​

Generic parameters are part of a function type and use the same () syntax as ordinary parameters:

GenericType     ::= Identifier '(' TypeArgList ')'
TypeArgList     ::= TypeExpr (',' TypeExpr)* ','?
TypeBound       ::= Identifier
                 |  Identifier '+' Identifier ('+' Identifier)*

In a generic type definition, (T: Type) is the parameter signature of a type constructor, and -> Type denotes the return type:

yaoxiang
List: (T: Type) -> Type = { ... }
Map: (K: Type, V: Type) -> Type = { ... }

4.1.1 Container Types ​

Container types are generic type constructors, not built-in primitives—they receive the same treatment as user-defined generics and are handled through the unified generic-instantiation path. The ownership of length information is the fundamental distinction among these container concepts:

TypeLengthSemanticsFoundation
Array(T, N)TypeFixed-length array (const generic N)Core primitive (stack/inline preferred)
Vec(T)Runtime valueRaw buffer with runtime length; can growCore primitive (contiguous heap buffer)
List(T)Runtime valueGrowable-list annotation with the source name ListSame as Vec(T) (source-name landing is normalized)
Dict(K, V)Runtime valueKey-value mapHeapValue::Dict

List(T) is not a type independent of Vec(T): since 22a67d93, std/list.yx uses Vec(T) as its foundation throughout and no longer defines a List record. The source name List is uniformly normalized to the Vec side in the type domain. All growable semantics (when to grow, by how much, and whether sharing is possible) are implemented in the library and are not the compiler's concern. Vec(T) is the minimal foundational primitive.

Set(T) has been retired: it has no literal, no runtime representation, and no std.set. If the need arises, complete it following the Dict model.

Key rules:

  • The landing site of a literal is determined by context: a bare [...] literal and a List(T) annotation land on a growable list. The type-side name of a growable list is solely Vec(T); a List(T) annotation is normalized from its source name and lands on the same type side as Vec(T). An Array(T, N) annotation applied directly to a literal lands on a fixed-length array. Landing validation: the element count must equal N and the element type must be compatible with T; a mismatch produces compile-time E1002. When N is a symbolic constant (a const parameter), count validation is deferred to the refinement-type stage. A user-defined record named List is no longer expanded through a List(T) annotation—the annotation uniformly lands on the Vec side, and field access on that record produces a formal diagnostic (E1053).
  • Implicit List→Array conversion is prohibited: fixed-length semantics are guaranteed by the type layer—push accepts only a Vec(A) receiver.
  • Performance tiers: Performance decreases and flexibility increases from bottom to top: Array > Vec.
  • Index-failure contract (runtime errors are a transitional state; the target state is compile-time refinement coverage through value-dependent types; see §8.5):
    • Out-of-bounds indexing, including negative indices → E6003
    • Missing Dict key → E6008
  • String indexing convention (#385): s[i] indexes characters by Unicode scalar value (code point) and produces a single-character String. This uses the same unit as len / index_of / substring / chars / char_code in std.string, so combinations do not become misaligned. Out-of-bounds access, including negative indices, follows the index-failure contract above: E6003.
  • in membership predicate: Returns Bool without an error. Its right operand covers List/Array/Dict(keys)/Tuple/String/Range. As a first-class Hoare predicate, it forms the foundation of propositions that refinement types can prove at compile time.`

In generic functions, type parameters are likewise declared in the signature, and the compiler infers them automatically from the arguments:

yaoxiang
map: (T: Type, R: Type) -> ((list: List(T), f: (T) -> R) -> List(R)) = ...

4.2 Generic Type Definitions ​

yaoxiang
// Basic generic type
Option: (T: Type) -> Type = {
    some: (T) -> Option(T),
    none: () -> Option(T)
}

Result: (T: Type, E: Type) -> Type = {
    ok: (T) -> Result(T, E),
    err: (E) -> Result(T, E)
}

List: (T: Type) -> Type = {
    data: Array(T),
    length: Int,
    push: (self: List(T), item: T) -> Void,   // self is only a conventional name, not a keyword
    get: (self: List(T), index: Int) -> Option(T)
}

? propagation and the Try interface: expr? is interface-driven error propagation. The receiver type must implement the Try interface (the four members is_failure / success / residual / from_error). On failure, the current function returns early with the result of from_error(residual(t)); on success, the expression's value is success(t). The enclosing function's return type must also implement Try, and its residual type must match the receiver's (E1081 / E1082 / E1083). Result(T, E) and Option(T) provide Try implementations through std.result / std.option (the residual type of Option is Void). A user-defined sum type can participate in ? by writing Try(Self, T, E) in its type body. The lowering of ? does not distinguish built-in from user-defined types—the same interface and the same path are used.

A sum type's variant set enters the checker with its definition or a use import: Result/Option must be imported with use std.result / use std.option before use (whole-module and grouped use std.{...} imports have equal authority). Variant construction (the type-qualified form), match-variant destructuring, and exhaustiveness determination all use this registry as their sole criterion. A native function signature returning Result(Float, Error) mints a Generic with the same name, which has the same identity by name as the sum type in std.result and may be match-destructured after use.

4.3 Generic Constructor Calls and Type Inference ​

The field list of a generic type definition automatically generates a constructor: each data field corresponds to one constructor argument, and the field name is the argument name. Fields with default values may be omitted during construction, while fields without default values are required. Function-typed fields (methods) do not generate constructor arguments. Evidence fields (§8.3) do not generate constructor arguments—their evidence is verified by the compiler at the construction site and is not passed through an argument position.

yaoxiang
// Type definition
Container: (T: Type) -> Type = {
    value: T,        // No default → constructor argument required
    extra: T,
}
// Fully expanded form (compiler's internal view; users need not write it):
// Container: (T: Type) -> (value: T, extra: T) -> Type = {
//     value: T = value,
//     extra: T = extra,
// }
// The expansion lists only data fields; evidence fields do not generate constructor arguments (§3.4)

// Calls: call the automatically generated constructor
c  = Container(42, 43)            // Constructor arguments are filled in field order; T is automatically unwrapped from the element = Int
c2 = Container("a", "b")          // T = String
c3 = Container(Int)(42, 43)       // Explicit type argument + positional constructor arguments
c4 = Container(Int)(extra=43, value=42)  // Named by field; any order
c5 = Container(Int)()             // Empty construction: fields take default/zero values (data assigned afterward)

// Field default values → constructor arguments may be omitted
Point: (T: Type) -> Type = { x: T = 0, y: T = 0 }
p  = Point(1.5, 2.5)              // T = Float, x←1.5, y←2.5
p2 = Point(Int)()                 // x=0, y=0

Call rules (single-parenthesized, matched position by position against declared parameters, from left to right):

  1. Arguments are matched position by position against the type declaration's parameters: a Type position accepts a type argument, while a compile-time value parameter position (such as Int) accepts a compile-time constant.
  2. If a compile-time value parameter position matches successfully (a partial match), construction is handled as a type construction: every parameter position is checked, and errors report the first mismatched or missing parameter in declaration order.
  3. If the arguments do not correspond to the declared parameters at all (all are values and no compile-time value parameter position matches), they are handled as constructor arguments: positional arguments fill fields in order, and type parameters are automatically unwrapped from the element types.
yaoxiang
Matrix: (T: Type, Rows: Int, Cols: Int) -> Type = {
    _assert_rows: Assert(Rows > 0),       // Evidence field: Assert is a proof-space family (§8.3)
    data: Array(Array(T, Cols), Rows),    // Data field: Array is a data-type family
}

m: Matrix(Int, 3, 4)              // Type position: one level of type construction
m2 = Matrix(Int, 3, 4)(data=[[1,2,3,4],[5,6,7,8],[9,10,11,12]])  // Two levels: type + constructor arguments
m3 = Matrix(Int, 3, 4)()          // Empty construction (RFC-011 §9.3 pattern; data assigned afterward)

Matrix(42)    // ❌ Position 0: T←42 does not match (42 is not a type); position 1: Rows←42 matches;
              //    position 2: Cols is missing → report the first error: T expects Type, but 42 was found
Container(42) // ❌ Missing constructor argument extra
Container(42, 43, 44)  // ❌ Too many constructor arguments

Type inference: A generic type constructor's type parameters are automatically unwrapped from constructor-argument elements (Container(42, 43) → T=Int); a generic function's type parameters are automatically unwrapped from argument types (map(numbers, f) → T=Int, R=String; see §4.1). Explicit arguments are required when automatic unwrapping is impossible.


Chapter Five: Type Constraints ​

5.1 Single Constraint ​

ConstrainedType ::= '(' Identifier ':' TypeBound ')' TypeExpr
yaoxiang
// Interface type definition (used as a constraint)
Clone: Type = {
    clone: () -> Clone
}

// Using a constraint
clone: (T: Clone)(value: T) -> T = value.clone()

5.2 Multiple Constraints ​

Source of constraint solving (RFC-011b): Solving an operator constraint name (Add / Subtract / Multiply / Divide / Modulo / Equal / Index) means looking up the interface-implementation registry— T: Add ≜ an Add(T, T, T) instantiation is registered; Equal additionally has structural inference (records whose fields are all comparable are automatically comparable). Names such as Zero / One / PartialOrd do not yet have a definition source and are dangling constraint names.

yaoxiang
// Multiple-constraint syntax
combine: (T: Clone + Add)(a: T, b: T) -> T = {
    a.clone() + b
}

// Sorting a generic container
sort: (T: Clone + PartialOrd)(list: List(T)) -> List(T) = {
    result = list.clone()
    quicksort(&mut result)
    return result
}

5.3 Function-Type Constraints ​

yaoxiang
// Higher-order function constraint
call_twice: (T: Type, F: () -> T)(f: F) -> (T, T) = (f(), f())

compose: (A: Type, B: Type, C: Type, F: (A) -> B, G: (B) -> C)(a: A, f: F, g: G) -> C = g(f(a))

Chapter Six: Associated Types ​

6.1 Associated Type Definitions ​

AssociatedType ::= Identifier ':' TypeExpr
yaoxiang
// Iterator trait (using record-type syntax)
Iterator: (T: Type) -> Type = {
    Item: T,                    // Associated type
    next: () -> Option(T),
    has_next: () -> Bool
}

// Using the associated type
collect: (T: Type, I: Iterator(T))(iter: I) -> List(T) = {
    result = List(T)()
    while iter.has_next() {
        if let Some(item) = iter.next() {
            result.push(item)
        }
    }
    return result
}

6.2 Generic Associated Types (GATs) ​

yaoxiang
// More complex associated types
Container: (T: Type) -> Type = {
    Item: T,
    IteratorType: Iterator(T),  // The associated type may also be generic
    iter: () -> IteratorType
}

Chapter Seven: Compile-Time Generics ​

7.1 Compile-Time Value Parameters ​

LiteralType   ::= Identifier ':' Int          // Compile-time constant (candidate)

The criterion is reference in a type position, rather than “being annotated with a concrete type”: in add: (a: Int, b: Int) -> Int = a + b, a/b are runtime value parameters (neither appears in any type position).

Terminology: Whether a generic parameter annotated with a concrete type other than Type (such as Int) enters compile time depends on whether its value is referenced in a type position (value dependency). No const keyword is needed (the implementation previously referred to this as “const generics,” while the documentation uniformly uses “compile-time value parameter”).

Design basis: RFC-011 §4.1 Compile-Time Value Parameters.

The determination is driven by strength declarations locally readable within a signature: when the author writes a reference to a value parameter in a type position ((k: N), Array(T, N), Assert(N > 0)), that reference is a strength declaration; the quantity is its mechanical reading. Each binding infers a quantity q ∈ {0, 1, ω}: q=0 means compile-time computation, runtime erasure, and no slot allocation; q=1 is linear (Move); q=ω is unrestricted (Dup)—see Chapter Eleven, Type Attributes, for 1/ω. This is not implicit: the appearance of a value name in a type position is a declaration written personally by the author, and is the same act as writing b: Positive(b) (§8.4).

“Type position” means all Type subtrees in a declaration—annotated parameter types, function return types, field types in type bodies, inner Fn types, Assert predicates, and type-construction argument positions such as Array(T, N). The determination traverses allType subtrees without making positional distinctions; missing even one subtree—for example, the return type—would misclassify a compile-time value parameter as a runtime value parameter.

“Referenced” is determined by namespace resolution, not by literal comparison of names:

  1. An identifier is first resolved in the type namespace—declared type names and type parameters (T: Type);
  2. If it resolves to a declared type, it is unrelated to the formal parameter. A formal parameter name and type name having the same spelling does not constitute shadowing: the value and type namespaces do not consult the same table (see the scope and shadowing rules in modules). The two Int occurrences in (Int: Int) -> Int belong to different namespaces;
  3. If it does not resolve, but a formal parameter with the same name is a candidate, the strength declaration matches and that parameter has q=0;
  4. If neither resolves, report an error: there are no bare identifiers in type positions that are “neither a type nor a type parameter.”

Self-reference is handled with a monotone fixed point (the set only grows, for at most |candidates| rounds).

Slot allocation uses q as its sole input. The call site's argument sequence and the implementation header's binding sequence are two derived views of the same function:

  • Call-site argument view = formal parameters − type parameters (in declaration order). A q=0 parameter still occupies an argument position: in f(42)(5), 42 is supplied for N and 5 for n; the argument positions carry the values the author filled in declaration order.
  • Implementation-header binding view = formal parameters − type parameters − q=0 parameters (in declaration order). The implementation header binds only names for which a runtime value exists: = (n) => n is legal, while = (N, n) => n reports E1112.

E1011 and E1112 are both counted according to the implementation-header binding view.

FormDeterminationReason
add: (a: Int, b: Int) -> Int = a + ba/b are runtime value parametersThey appear only in value positions, with no strength declaration
Array: (T: Type, N: Int) -> Type = { data: Array(T, N) }N is a compile-time value parameterN appears in a type-construction argument position
factorial: (N: Int) -> (k: N) -> IntN is a compile-time value parameterN serves as the type of the inner parameter k
Foo: (T: Type, N: Int) -> Type = { x: T }N is an ordinary parameterN is not referenced in the type body, so there is no strength declaration

Core design: (N: Int) compile-time value parameters and (k: N) value parameters distinguish compile-time constants from runtime values. The call site's obligation is checked according to the declared strength: the legality of f(y) depends on whether the argument y carries compile-time evidence (a literal, a value environment, single-value pinning, a Γ equation), rather than on a global analysis of f's declaration. Without evidence, the error is reported at the call site, with the location pointing to the q=0 slot visible in f's type. A missed candidate (one that has the candidate shape but is not referenced in a type position) is an ordinary parameter without a strength declaration, is handled normally with q=1/ω, and has no separate routing code.

yaoxiang
// Compile-time value parameter: N is referenced in a type position (the Array length slot)
Measure: (T: Type, N: Int) -> Type = {
    data: Array(T, N),      // N appears in a type-construction argument position → compile-time value parameter
    length: N
}

// Usage: factorial(5) is evaluated in a type position (at compile time), and the result 120 is embedded in the type
arr: Measure(Int, factorial(5))  // The compiler computes factorial(5) = 120 at compile time

// Value dependency: N serves as the type of the inner parameter k
// N is a compile-time value parameter (it appears in the type position of (k: N));
// k is a runtime value parameter whose type is the literal type N (single-value type).
// Single-value pinning: k's value is pinned by its single-value type and is known at compile time,
// so k - 1 carries compile-time evidence and may fill the N position of the recursive call.
factorial: (N: Int) -> (k: N) -> Int = {
    match k {
        0 -> 1,
        _ -> k * factorial(k - 1)(k - 1)
    }
}

7.2 Compile-Time Constant Arrays ​

yaoxiang
// Matrix type usage
Matrix: (T: Type, Rows: Int, Cols: Int) -> Type = {
    data: Array(Array(T, Cols), Rows)
}

// Compile-time dimension validation
identity_matrix: (T: Add + Zero + One, N: Int)(size: N) -> Matrix(T, N, N) = {
    // ...
}

Chapter Eight: Conditional Types and Dependent Records ​

8.1 If Conditional Type ​

IfType        ::= 'If' '(' BoolExpr ',' TypeExpr ',' TypeExpr ')'
yaoxiang
// Type-level If
If: (C: Bool, T: Type, E: Type) -> Type = match C {
    True -> T,
    False -> E
}

// Example: compile-time branch
NonEmpty: (T: Type) -> Type = If(T != Void, T, Never)
// IsTrue bridge and Assert refinement types (see §8.4 for details)
IsTrue: (b: Bool) -> Type = match b {
    true -> Void,       // ⊤, execution continues
    false -> Never,     // ⊥, divergence/compile error
}
Assert: (cond: Bool) -> Type = IsTrue(cond)

8.2 Type Families ​

yaoxiang
// Compile-time type conversion
AsString: (T: Type) -> Type = match T {
    Int -> String,
    Float -> String,
    Bool -> String,
    _ -> String
}

8.3 Dependent Record Σ: Evidence Fields ​

A dependent record Σ is a record type in which “later fields may reference earlier fields.” Σ's fields fall into two categories:

  • Data fields: Fields whose types fall in the data space. They occupy runtime data slots and participate in construction and access like ordinary fields.
  • Evidence fields: Fields whose types fall in the proof space (propositions)—that is, “an assertion awaiting proof.” They are not runtime data but compile-time evidence: when constructing the record, the compiler must provide a certificate verified by the proof kernel.

The sole criterion for this division is the proof-space criterion: normalize the field type and take the result type family's space as registered under the current logical signature— Proof (proposition / refinement / proof-family result) or Data (runtime data). A result in Proof ⇒ enter evidence determination; a result in Data ⇒ data field, regardless of how many preceding fields it references. The space is provided by the logical signature's sort registration and the library manifest; it is not guessed from field names, argument shapes, or syntax that “looks like a predicate.”

This section calls them evidence fields; diagnostic messages call them witness fields (E1114 / E1115). Both terms refer to the same kind of field.

Design basis: RFC-027 §14 (complete semantics of dependent records Σ), RFC-027 §4.1 (sort registration in logical signatures).

Implementation status: Field classification for non-generic records (proof space → position → category), construction-site proof obligations (evidence synthesized automatically and submitted to the sole determination unit; the current determination levels are direct evaluation / exact Γ / proof functions, with SMT not acting as a proof source), propagation of quantifiers through the record model into the IR, and user-reachable E4018 / E2031 / E1114 / E1115 have been implemented ; generic records, const parameters, and proof-family instantiation determination have also been implemented (B.2b). Quantity representation, runtime erasure, and the 5A criterion itself were completed in an earlier round. Type-level b.w (B.3) has been implemented (admission reading style, D2 ruling A); cross-module export (B.4) has been implemented (V1 re-verification + per-library fingerprint comparison; translation/bridging awaits the §4.1 kernel). The evidence_ref / certificate_ref slots are not added with B.3; B.4 under D1 ruling A still does not materialize the two slots (there is no producer, pending the §4.1 kernel batch); the explicit evidence entry point in B.2 is a proof function in a constraint, not a constructor argument. Illegal declaration positions reuse E1092 / E1042 (D1 ruling).

8.3.1 Field Position Rules: Proof-Space Criterion ​

Suppose the fields of a record R appear in source order as f₀, f₁, …, fₙ₋₁, and the type of field fᵢ is Tᵢ. Determination takes three steps: first determine the space (proposition family or data family), then determine the argument position (preceding / self / forward), and finally determine the field category.

First step: Determine the space. Normalize Tᵢ and take the space registered for its result type family under the current logical signature:

  • If the space is Proof (proposition / refinement type / Assert / Terminates / proof-family result) ⇒ enter evidence determination;
  • If the space is Data (Int, Array, Vec, ordinary records, or applications of data-type families) ⇒ data field, regardless of how many preceding fields it references.

The n in data: Array(Int, n) references a preceding data field and changes the “length of a data slot”; it does not “generate a proof.” Classifying it as evidence would erase the buffer from the runtime layout—the misclassification this rule is intended to eliminate.

Second step: Determine the position (only effective for fields whose space is Proof). There are three cases according to the positions indicated by the arguments:

  • All arguments are strictly preceding data fields fₕ (h < i), compile-time constants, compile-time value parameters, or type parameters ⇒ the third step classifies the field as evidence (a compile-time value parameter takes a concrete constant after instantiation and is counted as a compile-time constant; §8.3.3);
  • The argument is fᵢ itself (self-referential refinement such as v: Pos(v)) ⇒ the third step classifies it as a data field (admission): the field carries a value, and its constraint merely checks that value rather than proving a fact elsewhere;
  • A forward reference to a later field, a reference to another evidence field, or using fᵢ itself as an evidence argument while mixing it with other fields (SelfMixed) ⇒ rejected at declaration time.

Third step: Determine the category.

#FormDeterminationRuntime Layout
1Space Proof; all arguments are strictly preceding data fields / compile-time constants / compile-time value parameters / type parameters (positive example w: Pos(v))Evidence fieldDoes not occupy a slot; base does not enter the runtime layout
2Space Data: ordinary value types (n: Int), data-type family applications (positive example data: Array(Int, n)), ordinary recordsData fieldOccupies a data slot
3Space Proof, but the argument is fᵢ itself (self-referential refinement v: Pos(v))Data field (admission)Occupies a data slot; the constraint is determined at the construction site under the existing refinement obligation (§8.4)
4Space Proof, but there is a forward reference to a later field, a reference to another evidence field, or fᵢ itself is used as an evidence argument while being mixed with other fields (SelfMixed)Illegal: rejected at declaration time, with no silent downgradeProduces no field

The four rows are not conflated: Row 2 means that “ordinary value types / data families” are always data fields; Row 3 means that “proposition families with self-reference” are admission data fields; and Row 4 means that “proposition families with illegal positions” are always rejected at declaration time. There is no path in which “a forward reference also counts as a data field”—a forward reference occupies neither a data slot nor a runtime data index.

yaoxiang
Pos: (v: Int) -> Type = { v > 0 }     // Space Proof

Box: Type = {                         // Positive example: w is evidence
    v: Int,          // Data field
    w: Pos(v),       // Evidence: Pos is a Proof family, and v is a strictly preceding data field
    z: Int,          // Data field; runtime index = 1 (skipping w)
}

Buf: Type = {                         // Negative example: data is still a data field
    n: Int,                 // Data field
    data: Array(Int, n),    // Data field: Array is a Data family, and n only determines the length; it does not generate a proof
}

Admission: Type = {                   // Self-referential refinement: data field, not evidence
    v: Pos(v),           // Proof family, but the argument is itself ⇒ admission (Row 3 of the table)
}

Evidence fields may depend only on strictly preceding data fields. Their arguments must not reference another evidence field, a later field, or themselves. This constraint guarantees that, when construction reaches such a field in declaration order, all arguments already have compile-time values, making the proposition a closed term that may be verified by the proof kernel.

base does not enter the runtime layout. The base type of an evidence field (the base of a refinement type) is type information used solely for kernel equality and normalization; a runtime slot is never allocated for such a field. Evidence fields also have no default values, because they have no runtime value to supply.

8.3.2 Construction-Site Obligations and Proofs ​

Source-level construction has only one form: data arguments. Evidence fields occupy no constructor argument position whatsoever—there is neither a form that passes a witness as a value nor an “evidence argument position.” Construction arity counts only data fields: compile-time arity = runtime arity = number of data fields.

Evidence is not a constructor argument; it comes from a proof obligation automatically generated at the construction site. When constructing a record, the compiler generates a proof obligation for each evidence field:

  1. Take the compile-time value of the strictly preceding data field referenced by that field's arguments;
  2. Substitute it into the field's proposition to obtain a closed proposition (Pos(3) reduces to 3 > 0);
  3. Submit it to the proof kernel for verification under the current logical signature (RFC-027 §4).

The result is three-valued:

Determination ResultCompile-Time Behavior
ProvedPasses; the certificate is retained at compile time and erased at runtime
DisprovedCompile error + counterexample (E4018)
UnprovenCompile error + unproven proposition + reason + evidence-supplement hint (E2031)

Unproven does not mean that the proposition is false, nor does it allow the program through. Evidence is supplied through an independent declaration, not by rewriting the construction expression: write an independent proof function whose return type equals the proposition, or register a named proof in a proof library and reference it from the construction obligation (RFC-027 §4.3). There is no form that “fills in an incorrect witness value”—evidence fields have no argument position at construction sites. Passing an extra evidence argument at source level (Box(3, 5, evidence)) matches no data parameter slot and produces an argument error in the E1010 / E1014 family; it is never silently ignored.

A self-referential refinement field (v: Pos(v)) is a data field: its constraint is determined at the construction site under the existing refinement obligation (§8.4). It creates no evidence obligation and does not change the field's runtime index.

8.3.3 Generic Records: Proof Family Parameter P: T -> Proposition ​

A generic record may carry a proof family parameter P—its kind is T -> Proposition: it accepts a type parameter and returns a proposition. Proposition is the sort alias for the Proof space in the logical signature (RFC-027 §4.1), not a source-level type name. Its source-level syntax has the same shape as an ordinary type-level function parameter, and kind constraints are checked at declaration and instantiation:

yaoxiang
Pos: (v: Int) -> Type = { v > 0 }

Cell: (T: Type, P: (T: Type) -> Type) -> Type = {
    v: T,        // Data field
    w: P(v),     // Evidence: P is a Proof family, and v is a strictly preceding data field
}
  • The kind of P comes from the same source as the criterion in §8.3.1: the result space must be Proof. Passing a data-type family such as Array to P is a kind mismatch and is rejected directly at declaration or instantiation; this is a type error, not a case in which “w degenerates into a data field.”
  • P is a compile-time parameter position and does not occupy a runtime slot. When Cell(Int, Pos) is instantiated, P is bound to the proof family Pos, the proposition for w becomes Pos(v), and evidence determination is exactly the same as in §8.3.1.
  • Determination is rerun after instantiation.
  • When P is unbound (the generic is not instantiated), the result space for w is still Proof (its kind has been declared), but the proposition is an open term, and the construction site returns Unproven—it is neither silently allowed nor downgraded to a data field.

8.3.4 Cross-Module Export ​

When a record containing evidence fields is used across modules, its propositions and evidence are exported together with the type definition, and the importer does not guess them again by field name. The exported artifact carries: the kinds of type-family parameters (including proof-family parameters), the proof obligation for each evidence field, and the evidence slot for each evidence field—the proposition, an explicit evidence source or verified certificate, and the hash of the logical signature that produced it.

The importer verifies these propositions using its own current logical signature: if the signature hashes differ, RFC-027 §4.1's three explicit paths are used—translation items, bridging axioms, or reproof under the importer's signature. The importer must not directly reuse the exporter's conclusions.

A referenced proof-library entry must appear in the importer's library list; otherwise the conclusion is Unproven, and the diagnostic recommends registering the library or writing a bridging axiom.

Implementation status (V1): The current implementation performs importer-side reproof + per-library source fingerprint comparison only; translation items and bridging axioms await the RFC-027 §4.1 kernel; the evidence_ref/certificate_ref slots are not materialized (D1 A), and signature_hash is the exporter-side evidence-payload fingerprint.

8.3.5 Type-Level Use and Value-Level Rejection ​

Evidence fields may only be used at the type level. b.w in a type position is user-writable type-level syntax referring to the field's evidence item (proof item), not a runtime value: it points to the evidence reference registered for that field and may serve as a premise for another proposition. V1's semantics are admission (the proposition in the evidence slot was proved at the construction point; see 6.9.5-B.3 §5), not replay under the logical signature (§4.2 is not implemented).

yaoxiang
Pos: (v: Int) -> Type = { v > 0 }

Box: Type = {
    v: Int,
    w: Pos(v),
}

// Type-level use: treat bb.w as an evidence premise, not as a value fetch
Holds: (bb: Box) -> Type = { bb.w }
needW: (b: Box, h: Holds(b)) -> Int = { b.v }

Value-level reads of evidence fields are always rejected: reading b.w in a value expression reports E1114 (witness_field_not_readable). A field path is not a value term, and neither the evaluator nor the runtime representation produces a value for it. When runtime data is required, define the field as an ordinary data field.

yaoxiang
b = Box(3)
x = b.w        // ❌ Value-level read of a witness field → E1114

Design basis: RFC-027 §14.5 (term forms for type-level use, replacing the statement in 4A that “type-level user syntax does not exist”). The syntax and parsing of type-level field paths have been implemented: type positions accept a single-layer ident.ident; value-level reads still report E1114.

8.3.6 Immutability, Erasure, and Diagnostic Codes ​

5A: A record containing evidence fields is immutable as a whole. Data fields must not declare mut, undergo field assignment, be borrowed through &mut, or serve as the receiver of a mutating method (including automatic write borrows). Otherwise, an evidence proposition might become invalid after a field is rewritten. A violation reports E1115 (witness_record_immutable). Records without evidence fields are not subject to this restriction.

Erasure. Evidence fields do not occupy runtime slots, and the runtime layout contains only data fields; proof certificates are retained at compile time and completely erased at runtime (RFC-027 §13). Runtime data indices count only data fields—the data index of z in a record { v, w, z } is 1, skipping the witness field w. Boolean checks in runtime mode (§8.4) are unrelated to evidence—they inspect runtime values, not certificates.

Division of diagnostic codes (each code covers one aspect and does not replace another):

CodeTriggerSemantics
E4018An evidence proposition at a construction site is disprovedA refinement predicate is violated; a counterexample is attached
E2031An evidence proposition at a construction site is Unproven (refinement channel)The refinement constraint cannot be proved; a hint to supply explicit evidence is provided
E1114A value-level read of an evidence fieldEvidence fields cannot be read at the value level
E1115A mutable write to an evidence recordThe record is immutable as a whole
E4023General Unproven outside the refinement channelGeneral inability to prove; includes the proposition, reason, and location

Declaration-time rejection list (consistent item by item with the four-category table in RFC-027 §14.6): when a field whose space is Proof has one of the following forms, it is rejected directly at the declaration. It does not proceed to construction and is not silently downgraded to a data field:

#Rejected FormDescription
1Forward reference to a later field fₕ (h > i)Illegal position
2Reference to another evidence field as an argumentIllegal position
3Use of fᵢ itself as an evidence argument while mixing it with other fields (SelfMixed, such as P(fᵢ, fₕ))Illegal position; pure self-reference P(fᵢ) is the admission data field in Row 3 of §8.3.1 and is not rejected
4The kind of proof-family parameter P is a data-type family (§8.3.3)Kind mismatch; a type error at declaration/instantiation

Evidence fields must not have default values (w: Pos(v) = expr, DefaultOnEvidence): an evidence field has no runtime value to supply, and the construction view has no argument position for it, so specifying a default is rejected at declaration time. This is an independent field-declaration check; it is not merged with the four categories above and is not silently treated as “a data field with a default value.” StructFieldInfo.has_default is always false for a witness. The default-value rules in §3.1.1 (a field with a default may be omitted during construction; one without a default is required) apply only to data fields.

A data-type family application whose space is Data, and a pure self-referential refinement whose space is Proof (v: Pos(v), admission), are both legal data fields and do not fall under illegal positions. When a generic is not instantiated, the proposition is an open term and the construction site returns Unproven (§8.3.3); this is not a declaration-time rejection.

8.4 Assert Refinement Types and assert Assertions ​

assert and Assert are two sides of the same refinement primitive—the dispatch pipeline automatically selects between them based on "whether the predicate's free variables are accessible at compile time."

Core signature: assert: (cond: Bool, ?msg: String | Error) -> Assert(IsTrue(cond))

Dispatch rules:

CriterionModeBehavior
All free variables are known at compile time (generic parameters, compile-time constants)CompileTimeEnters the proof pipeline: true → erased to Void; false → compile error (Never is uninhabited)
Runtime free variables exist (function parameters, external input)RuntimeInserts a runtime Bool check and injects refinement facts into the flow-sensitive assumption set Γ

Dispatch is an instance of checking according to declared strength (§7.1). The same principle covers the entire strength ladder: classic types without a strength declaration do not enter the proof pipeline or undergo quantity inference; predicate annotations (this section), q=0 slots (§7.1), dependent-record fields (§8.3), and relational predicates each perform the corresponding checks according to their declared form. Cost follows the declared strength and is not determined by global analysis.

Flow-sensitive assumption set Γ:

The compiler maintains a set of known propositions at each control-flow point:

yaoxiang
assert(x > 0)       // Γ = {x > 0}
y = x + 1           // Γ = {x > 0, y > 1}  ← SP propagation
mut x = x - 5       // Γ = {}  ← mut kill set: the old assumption is invalidated

After assigning to a mut variable, all assumptions involving that variable are removed (kill set). When branches are merged, Γ is the intersection of the branches' assumption sets.

8.5 Terminates: Termination Measure Predicates ​

Terminates is a built-in predicate, belonging to the core primitives alongside Int and Never (a built-in name, not a keyword). It binds a measure to a computation, declares that the computation terminates, and supplies a witness of termination.

Forms: Two arities using the same predicate:

FormAnchorUse
Terminates(m)Name of the containing bindingDefault form—self-recursive functions, loops
Terminates(FnType, m)Explicit function typeWhen the measure's ownership must be specified explicitly (the measure is defined elsewhere, or the same measure serves multiple computations)
yaoxiang
// Measure: an ordinary function; independently testable and reusable; not involved at runtime
gcd_measure: (a: Int, b: Int) -> Int = { b }

// Binary form: the measure is defined elsewhere; ownership is specified explicitly
gcd: Terminates((a: Int, b: Int) -> Int, gcd_measure) = {
    if b == 0 { return a }
    return gcd(b, a % b)
}

// Unary form: the anchor is the binding name, and the measure is an expression in scope
// The loop body is a `{}` block, whose value is given by the tail expression (spec §2.9): the body is not `Void` only if its tail contains an expression
loop: (n: Int) -> Int = {
    mut i = 0
    acc: Terminates(n - i) = while i < n {
        i = i + 1
        i
    }
    return acc
}

Semantics: The Terminates(m) refinement applies to the value type of the computation annotated in that type position. The obligation falls on that computation—on functions at every recursive call site, and on loops at back edges—and requires that “the next state's measure is strictly less than the current state's measure,” evaluated under that point's path guard.

The call-site obligation is m(callee_args) < m(caller_args); the back-edge obligation is m(next iteration) < m(current iteration). The two have the same form.

Why loops are covered: A loop is an anonymous construction and usually cannot be referred to. The binding name is the name—acc: Terminates(n - i) = while ... gives the loop an anchor, making it referable. This is why the unary form of Terminates can apply to a loop.

Measure: The return type is unrestricted (there is no requirement that it be a natural number); its “strict decrease” uses a well-founded order available on that type. Whether the measure is well-founded—for example, whether Int is >= 0—is an independent obligation, determined by the compile-time proof pipeline just like the decrease obligation.

Trigger: Termination checking is triggered by refinement types—once a type is refined, it enters verification mode. Ordinary types that are not refined (such as bare while loops or functions without refined signatures) do not enter verification mode and do not generate termination obligations.

Automatic exploration takes priority: The compiler first automatically explores measures (four templates: linear ranking functions, predicate-violation counts, bounded increment/decrement, and multiplicative scaling), and an explicit Terminates is needed only when automatic exploration fails.

Runtime representation: A pure compile-time entity, erased together with its witness and absent from the runtime binary.

See RFC-027 §6.9 for the complete semantics and RFC-027a for the implementation mechanism.


Chapter Nine: Type Unions and Intersections ​

9.1 Type Unions ​

TypeUnion     ::= TypeExpr '|' TypeExpr

9.2 Type Intersections ​

TypeIntersection ::= TypeExpr '&' TypeExpr

Syntax: The type intersection A & B denotes a type that satisfies both A and B.

yaoxiang
// Interface composition = type intersection
DrawableSerializable: Type = Drawable & Serializable

// Using an intersection type
process: (T: Drawable & Serializable)(item: T, screen: Surface) -> String = {
    item.draw(screen)
    return item.serialize()
}

Chapter Ten: Function Overloading and Specialization ​

10.1 Function Overloading ​

yaoxiang
// Basic specialization: use function overloading (the compiler selects automatically)
sum: (arr: Array(Int)) -> Int = {
    return native_sum_int(arr.data, arr.length)
}

sum: (arr: Array(Float)) -> Float = {
    return simd_sum_float(arr.data, arr.length)
}

// General implementation
sum: (T: Add)(arr: Array(T)) -> T = {
    result = Zero::zero()
    for item in arr {
        result = result + item
    }
    return result
}

10.2 Platform Specialization ​

yaoxiang
// Platform type enum (defined by the standard library)
Platform: Type = { X86_64: () -> Platform, AArch64: () -> Platform, RISC_V: () -> Platform, ARM: () -> Platform, X86: () -> Platform }

// P is a predefined generic parameter name representing the current compilation platform
sum: (P: X86_64)(arr: Array(Float)) -> Float = {
    return avx2_sum(arr.data, arr.length)
}

sum: (P: AArch64)(arr: Array(Float)) -> Float = {
    return neon_sum(arr.data, arr.length)
}

Chapter Eleven: Type Attributes ​

YaoXiang has only one type-attribute distinction: linear versus duplicable. It is inferred automatically by the compiler.

11.1 Move (Default Ownership Transfer) ​

All types follow Move semantics by default. Assignment, argument passing, and return all transfer ownership.

yaoxiang
// A struct containing a heap-buffer field does not derive Dup (its fields land in Move) → defaults to Move
Buf: Type = { data: Vec(Float) }
b: Buf = Buf([1.0, 2.0])
q = b           // Move; b can no longer be read

11.2 Dup (Shallow Copy: Copy the Handle, Share the Data) ​

The Dup attribute is intended for reference/token types and internally reference-counted handle value types. Assigning a Dup type performs a shallow copy—the handle/token is copied while the underlying data is shared. Multiple holders refer to the same block of data.

TypeAttributeDescription
&TDupZero-sized read token; copying the token gives multiple views of the same data
ref TDupCopying an Rc/Arc increments the reference count and shares the heap data
String, BytesDupInternal reference counting; assignment copies the handle and shares the underlying buffer
&mut TLinearZero-sized write token; exclusive and non-duplicable
structDerivedDup if all fields are duplicable (primitive value types ∪ Dup); otherwise Move (#398)
tupleDerivedDetermined element by element, using the same rule as structs (#398)
All other typesMoveDefault ownership transfer

Primitive value types (Int, Float, Bool, Char) receive special treatment built into the compiler: values are copied automatically on assignment, and the two values are completely independent. This is native compiler behavior and is not part of the Dup type attribute.

Derivation rules (finalized in #398)—the rule “automatically derive Dup when all fields are Dup” cannot be applied literally: primitive fields such as Int are not themselves Dup, so { x: Int, y: Int } would be misclassified as Move. The executable form is:

  1. Duplicable field set = primitive value types (Int / Float / Bool / Char / Range) ∪ Dup (&T, ref T, String / Bytes, function values (#352), and composite types already determined to be Dup);
  2. struct: If all fields are in the duplicable field set → derive Dup; if any field is Linear (&mut T) or Move (a nested Move struct / containers such as Vec and Dict / resources), the struct as a whole remains Move (there is no intermediate “partially duplicable” state). Evidence fields have no runtime value and do not participate in derivation (§8.3);
  3. tuple: Uses the same rule as a struct, determined element by element; the empty tuple (unit) is Void;
  4. Derivation is recursive: When a field has a named type (such as target: Point), its definition is expanded before determination. A = { b: B } follows B's derivation result. Cyclic aliases conservatively become Move at the depth limit;
  5. Outside the scope of derivation (remain Move; handled separately): containers (Vec / Dict / Set / Option / Result / Array) and enums.
yaoxiang
// &T: Dup; freely aliasable
view: &Point = &p
view2 = view     // Dup: copies the token; both remain valid
print(view.x)    // Valid
print(view2.x)   // Valid

// &mut T: Linear; cannot be copied
mut_ref: &mut Point = &mut p
// r2 = mut_ref  // ❌ &mut T is not Dup and cannot be copied

11.3 Clone (Explicit Deep Copy) and Its Relationship to Dup ​

Clone is the explicit deep-copy interface. Every type may implement Clone and provide a .clone() method.

yaoxiang
// Clone interface definition (standard library)
Clone: Type = {
    clone: () -> Clone
}

// Usage
p: Point = Point(1.0, 2.0)
backup = p.clone()    // Deep copy; p remains usable
p2 = p.clone()        // May be cloned multiple times

The difference between Dup and Clone:

DupClone
SemanticsShallow copy: copies the handle/token and shares the underlying dataDeep copy: creates a complete independent copy
InvocationImplicit (automatic on assignment/argument passing)Explicit (.clone())
Effect of mutationMutations affect one another (shared underlying data)No effect on one another (independent copies)
Applicable types&T tokens, ref TAny type implementing the Clone interface
CostZero overhead (a token is a zero-sized type)Depends on the type

Dup does not imply Clone, and Clone does not imply Dup—they are two orthogonal concepts:

yaoxiang
// Dup type: copies the token and shares the underlying data
view: &Point = &p
view2 = view        // Dup: copies the token; both point to the same p
print(view.x)       // Valid
print(view2.x)      // Valid; sees the same data

// Primitive value type: the compiler automatically copies the value (not Dup)
x: Int = 42
y = x               // Value copy; x and y are completely independent
print(x)            // Valid

// Clone: explicit deep copy that creates an independent copy
p: Point = Point(1.0, 2.0)
q = p.clone()       // Clone: deep copy; p remains usable

// Non-Dup type (a field lands in Move and is not derived): Move transfers ownership
buf: Buf = Buf([1.0, 2.0])
buf2 = buf          // Move: Buf contains a Vec field and does not derive Dup (see the derivation rules in §11.2)

Design intent:

  • Dup is used for tokens/references and solves the problem of “multiple views of the same data.”
  • Clone is used where an independent copy is required; explicit invocation makes the cost visible.
  • Copying primitive value types (Int/Float/Bool/Char) is built-in compiler behavior and is not part of Dup.
  • Custom types default to Move (zero-copy, high performance); Dup is derived automatically when all fields are duplicable (the derivation rules in §11.2).

Chapter Twelve: Borrow Token Types ​

12.1 Core Concepts ​

&T and &mut T are zero-sized compile-time token types. They are not "references," but "type-level proofs of access permission."

&T      →  零大小,冻结源数据(禁止 WriteToken 在此期间获取),
          冻结保证下多份只读安全 → Dup(可复制)
&mut T  →  零大小,独占读写(禁止任何其他令牌),
          独占访问下复制无意义 → Linear(非 Dup)

Key properties:

  • A token is an ordinary type and follows the same scope rules as every other type.
  • No lifetime annotation 'a is required.
  • No dedicated borrow checker is needed—the type attributes (Dup/Linear) naturally derive permissions.
  • The token disappears completely after compilation, with zero runtime overhead.

12.2 Basic Usage ​

yaoxiang
// Method side: declaring parameter types determines the required permissions
Point.print: (self: &Point) -> Void = {
    print(self.x)               // The &Point token grants read permission
    print(self.y)
}

Point.shift: (self: &mut Point, dx: Float, dy: Float) -> Void = {
    self.x = self.x + dx        // The &mut Point token grants write permission
    self.y = self.y + dy
}

// Call site: the compiler automatically selects a borrow or Move
p = Point(1.0, 2.0)
p.print()                       // The compiler automatically creates an &Point token
p.shift(1.0, 1.0)               // The compiler automatically creates an &mut Point token
p.print()                       // OK; the previous token was released when the shift call ended

// Multiple &T tokens may coexist—Dup types permit free copying
distance: (a: &Point, b: &Point) -> Float = {
    sqrt((a.x - b.x)**2 + (a.y - b.y)**2)
}
d = distance(p, p2)

12.3 Token Scope and Propagation ​

Tokens are ordinary types and therefore support all operations available to ordinary types:

Returning tokens—the token propagates together with the return value:

yaoxiang
// ✅ The child token is returned together with the parent token
Point.get_x: (self: &Point) -> (&Float, &Point) = {
    return (&self.x, self)
}

p = Point(1.0, 2.0)
(px_ref, p) = p.get_x()        // The token is returned to the caller
print(px_ref)                    // OK; the token remains in scope

Storing tokens in structs—a struct may carry token fields:

yaoxiang
// ✅ A struct carries a token as a field
Window: Type = {
    target: Point,
    view: &Point,              // Token field—holds a read-only view of target
}

Closures do not capture; context is fixed at the creation point—a closure consumes only its own parameters. When outer data is needed, currying fixes the value into the closure at the creation point:

yaoxiang
// ✅ Context is fixed through currying: threshold is a parameter, and gt_point(threshold) fixes the value into the closure at the creation point
gt_point: (t: Float) -> (p: Point) -> Bool = (p) => p.x > t
filter_by_threshold: (items: List(Point), threshold: Float) -> List(Point) = {
    items.filter(gt_point(threshold))
}

Note: After a closure (function value) escapes, the scope of its definition may have ended, so it must not implicitly capture outer variables. The call site (creation point), however, necessarily remains alive, and fixing the context there as a value inside the closure is safe.

12.4 Automatic Borrow Selection ​

The compiler selects automatically at the call site according to the following priorities:

1. 如果实参后续还有使用 → 优先创建令牌(&T 或 &mut T,根据方法签名)
2. 如果实参后续不再使用 → Move
3. 优先匹配顺序:&T < &mut T < Move
yaoxiang
p = Point(1.0, 2.0)
p.print()          // The parameter type of print is &Point → the compiler creates an &Point token
p.shift(1.0, 1.0)  // The parameter type of shift is &mut Point → the compiler creates an &mut Point token
p2 = p             // No subsequent use → Move

The method receiver follows signature semantics (following the receiver spelling convention of RFC-011a): a receiver of &T → read-only borrow token; &mut T → mutable borrow token; by value → Move (consumes the receiver). Borrow tokens generated at the call site are released when the call ends (transient; interval semantics in §12.5). An interface's borrowed receiver must be explicitly declared by the interface author as &Self, and after replacing Self ↦ impl type, the impl signature must exactly match the interface (RFC-011a §3).

12.5 Token Conflict Detection ​

Token conflict detection is the borrowing Hoare proposition (RFC-009a), not a separate flow-sensitive analysis. The compiler automatically generates borrowing propositions (borrow_conflict/use_after_move/use_after_drop/mut_violation) and submits them to the proof pipeline for verification. Token liveness is the interval [created_at, last_use] (see RFC-009a § reverse BFS liveness analysis):

yaoxiang
// ❌ &mut and a derived &T cannot be active simultaneously
bad_alias: (p: &mut Point) -> Void = {
    p.x = 10.0                   // ✅ Normal use of a WriteToken
    print(p.y)
}

// ✅ The token is automatically released after its scope ends
good_seq: (p: &mut Point) -> Void = {
    {
        // Inner scope
        print(p.x)               // Uses &mut Point
    }
    // End of inner scope
    p.x = 10.0                   // ✅ The WriteToken is still usable
}

// ❌ The same argument cannot simultaneously create an &mut token and another token
alias_bad: (a: &mut Point, b: &Point) -> Void = { ... }
p = Point(1.0, 2.0)
alias_bad(p, p)                  // ❌ p simultaneously derives an &mut token and an & token

12.6 Compiler Internals: The Branding Mechanism ​

Users never interact with brands. Internally, the compiler assigns each token a unique compile-time identifier:

用户看到的编译器内部表示
────────────────────────────────────────
&Point         →  ReadToken(Point, #N)    // #N 是编译期唯一整数
&mut Point     →  WriteToken(Point, #M)   // #M 是编译期唯一整数

Brands serve the following purposes:

  • Preventing forgery: A token may only be obtained from its owner's capsule and cannot be constructed from nothing.
  • Association tracking: A derived &Float carries a derived brand (#N.field_x), allowing the compiler to trace it back to the parent token.
  • Conflict detection: A WriteToken and a derived ReadToken from the same source cannot be active simultaneously.

Brands disappear completely after monomorphization and inlining, and do not exist in the generated machine code. Zero runtime overhead.

12.7 Token Sum Type ​

&BorrowToken ::= &T          // ReadToken (freezes source data → safe to Dup)
               | &mut T      // WriteToken (exclusive read/write → Linear)

12.8 Borrow Tokens vs ref ​

&T / &mut Tref
PurposeTake a look/modify in placeShared ownership
ScopeFollows the token value's scopeCrosses scopes
CostZero overhead (zero-sized type; disappears after compilation)Rc or Arc (compiler-selected)
EscapeAllowed (the token propagates through return values/structs)Intended for escaping
Cross-taskNot allowed (tokens do not implement cross-task transfer)Allowed (the compiler automatically selects Arc)
Cycle detectionNot involvedSilent within a task; a lint across tasks

Note (undefined): How to read the contents after creating a ref (dereference/method/automatic behavior) has not yet been defined in the specification; the current implementation reports E1052 for *a. This section will be updated after it is defined.


Appendix: Type Definition Quick Reference ​

A.1 Type Definitions ​

// === 记录类型(花括号) ===

// 记录类型
Point: Type = { x: Float, y: Float }

// 带变体的记录类型(使用函数字段)
Result: (T: Type, E: Type) -> Type = { ok: (T) -> Result(T, E), err: (E) -> Result(T, E) }

// === 依赖记录 Σ(evidence 字段,见 §8.3) ===

// 编译期谓词 + evidence 字段:w 不占构造参数位与运行期数据槽
Pos: (v: Int) -> Type = { v > 0 }
Box: Type = { v: Int, w: Pos(v) }

// === 接口类型(花括号,字段全为函数) ===

// 接口定义
Serializable: Type = { serialize: () -> String }

// 实现接口的类型
Point: Type = {
    x: Float,
    y: Float,
    Serializable    // 实现 Serializable 接口
}

// === 函数类型 ===

Adder: Type = (Int, Int) -> Int

// === 终止测度(内置谓词,见 §8.5) ===

// 一元:锚点即绑定名(自递归函数、循环)
// 体尾须给出值——`while` 的值 = 循环体块的值 = 尾表达式(spec §2.9)
loop: (n: Int) -> Int = {
    mut i = 0
    acc: Terminates(n - i) = while i < n { i = i + 1; i }
    return acc
}

// 二元:显式指明测度归属(测度定义在别处)
gcd_measure: (a: Int, b: Int) -> Int = { b }
gcd: Terminates((a: Int, b: Int) -> Int, gcd_measure) = {
    if b == 0 { return a }
    return gcd(b, a % b)
}

A.2 Generic Syntax ​

// 泛型类型
List: (T: Type) -> Type = { data: Array(T), length: Int }
Result: (T: Type, E: Type) -> Type = { ok: (T) -> Result(T, E), err: (E) -> Result(T, E) }

// 泛型函数
map: (T: Type, R: Type)(list: List(T), f: (T) -> R) -> List(R) = { ... }

// 类型约束
clone: (T: Clone)(value: T) -> T = value.clone()
combine: (T: Clone + Add)(a: T, b: T) -> T = body

// 关联类型
Iterator: (T: Type) -> Type = { Item: T, next: () -> Option(T) }

// 编译期泛型:N 在类型位置 (k: N) 被引用 → 编译期值参数
factorial: (N: Int)(k: N) -> Int = { ... }
Measure: (T: Type, N: Int) -> Type = { data: Array(T, N), length: N }

// proof family 参数:kind 是 T -> Proposition(结果空间必须是 Proof)
Cell: (T: Type, P: (T: Type) -> Type) -> Type = { v: T, w: P(v) }

// 条件类型
If: (C: Bool, T: Type, E: Type) -> Type = match C { True -> T, False -> E }

// 函数特化
sum: (arr: Array(Int)) -> Int = { ... }
sum: (arr: Array(Float)) -> Float = { ... }

A.3 Type Attribute Quick Reference ​

// === Move(默认) ===
// 所有类型默认 Move。赋值、传参、返回 = 所有权转移

// === 原语值类型(编译器内置) ===
Int, Float,     // 赋值时自动值复制,两个值完全独立
Bool, Char      // 不是 Dup,是编译器对原语的内置处理

// === Dup(浅拷贝:复制句柄,共享底层数据) ===
&T              // 零大小读取令牌,复制令牌 = 多个视角指向同一数据
ref T           // Rc/Arc 复制 = 引用计数+1,共享堆数据
String, Bytes   // 内部引用计数,复制句柄共享底层 buffer
struct / tuple  // 派生:所有字段 ∈(原语值类型 ∪ Dup)→ Dup(#398)

// === 不派生(保持 Move) ===
Vec/Dict/Set    // 容器与 enum 不在派生范围(#398)

// === Linear ===
&mut T          // 零大小写入令牌,Linear(独占,不可复制)

// === Clone(显式深复制) ===
value.clone()   // 创建独立副本,修改不影响原值

A.4 Borrow Token Quick Reference ​

// === 借用令牌 ===
&T              // 零大小编译期读令牌,冻结源数据 → Dup(可复制)
&mut T          // 零大小编译期写令牌,独占读写 → Linear(不可复制)

// 调用端自动选择
// 1. 实参后续还有使用 → 创建令牌
// 2. 实参后续不再使用 → Move
// 3. 优先匹配:&T < &mut T < Move

// 令牌传播
// ✅ 可返回、可存结构体、可被闭包捕获
// ❌ 不可跨任务(令牌未实现跨任务传递)