Syntax Specification
This document defines the syntax specification of the YaoXiang programming language, including its lexical structure, grammar rules, and operator precedence.
Chapter 1: Lexical Structure
1.1 Source Files
YaoXiang source files must use UTF-8 encoding. Source files generally use the .yx extension.
1.2 Lexical Token Categories
| Category | Description | Examples |
|---|---|---|
| Identifier | Starts with a letter or underscore | x, _private, my_var |
| Keyword | Reserved by the language | use, mut, and |
| Literal | Fixed value | 42, "hello", true |
| Operator | Operation symbol | +, -, *, / |
| Separator | Syntactic separator | (, ), {, }, , |
1.3 Keywords
YaoXiang has 17 keywords (keyword_from_str in src/frontend/core/lexer/state.rs, with each one corresponding to a TokenKind):
use spawn ref mut
if else match while for
in return break continue
as unsafe and orand / or are keywords for logical AND / OR (Zig-style; and has higher precedence than or; see levels 10–11 in §2.2). Unary negation uses the symbol ! and is orthogonal to them.
These keywords have special meanings in every context and cannot be used as identifiers.
typeis no longer a keyword (RFC-010): use theName: Type = { ... }notation to define a type. Bothkeyword_from_strand theTokenKindenum header (src/frontend/core/lexer/tokens.rs) are marked with “RFC-010: 'type' keyword removed”.
pubis no longer a keyword (RFC-029g, accepted on 2026-10-02): the language has no visibility mechanism.pubhas been removed entirely from lexing, the AST, type checking, dead-code exemptions, the formatter, and the LSP (RFC-029g). It is now merely an ordinary identifier—the old formpub x = 1reports E1001 as an undefined name. All top-level bindings are importable by default, and modifiers make no difference to visibility (RFC-029).
1.4 Reserved Words
YaoXiang's “reserved words” are divided into three layers, recognized by the parser and type checker at different stages:
1.4.1 Literal Reserved Words
These literal identifiers have dedicated parser tokens and cannot be used as ordinary identifiers:
| Identifier | Type | Description |
|---|---|---|
true | Bool | Boolean true value |
false | Bool | Boolean false value |
void | Void | Void literal (Unit value). Lowercase void is a value literal; uppercase Void is a type name (see §1.4.3). |
Typeis not in this layer: it has no dedicatedTokenKind(it is absent from theTokenKindenum insrc/frontend/core/lexer/tokens.rs, andkeyword_from_strhas no corresponding branch). The parser treats it as an ordinary identifier, while the type checker recognizes it as a meta type in type positions. Therefore, in expression positions,Typecan be shadowed by a local binding. It is a meta type name, not a keyword.
1.4.2 Variant Names
Variant names are recognized by the parser in pattern contexts (bare names are adjudicated using the variant set of the scrutinee type; see §2.8). In expression contexts, variants must be type-qualified when constructed—Result(Int, String).ok(5), Option(T).some(v), and Color.green() (RFC-010 record types and types: variant constructors are function-typed fields in type definitions; a bare name such as ok(5) is not a constructor call).
| Variant name | Owning type | Description |
|---|---|---|
some(T) | Option | Option value variant construction |
ok(T) | Result | Result success variant |
err(E) | Result | Result error variant |
1.4.3 Built-in Type Names
The following type names are pre-registered by the type checker and can be used in type positions without importing anything. The parser treats them as ordinary identifiers—they are not reserved words and can be shadowed by local bindings (not recommended).
| Type name | Logical equivalent | Description |
|---|---|---|
Void | ⊤ (true/Unit) | Zero-field product type with exactly one inhabitant (the void literal; see §1.4.1) |
Never | ⊥ (false/empty type) | A type with zero variants and zero inhabitants. No expression can produce a Never value. Never <: T holds for every T (explosion principle). |
Int | — | Signed integer |
Float | — | Floating-point number |
Bool | — | Boolean value: true / false |
Char | — | Unicode character |
String | — | String |
1.5 Identifiers
An identifier starts with a letter or underscore. Subsequent characters may be letters, digits, or underscores. Identifiers are case-sensitive.
Special identifiers:
_is used as a placeholder to indicate that a value is ignored.- Identifiers beginning with an underscore denote private members.
1.6 Literals
1.6.1 Integers
Decimal ::= [0-9][0-9_]*
Octal ::= 0o[0-7][0-7_]*
Hex ::= 0x[0-9a-fA-F][0-9a-fA-F_]*
Binary ::= 0b[01][01_]*1.6.2 Floating-Point Numbers
Float ::= [0-9][0-9_]* '.' [0-9][0-9_]* ([eE][+-]?[0-9][0-9_]*)?1.6.3 Strings
String ::= '"' ([^"\\] | EscapeSequence)* '"'
Escape ::= '\\' ([nrt'"\\] | UnicodeEscape)
Unicode ::= 'u' '{' HexDigit+ '}'1.6.4 Collections
List ::= '[' Expr (',' Expr)* ']'
Dict ::= '{' String ':' Expr (',' String ':' Expr)* '}'
Array ::= '[' Expr (',' Expr)* ']' // When the target type annotation is Array(T, N), the literal resolves to a fixed-length arrayDictionary literals require at least one key-value pair:
{}is not an empty dictionary—it is an empty block (valueVoid; see §2.9). To create an empty dictionary, use the constructordict.new():yaoxiangempty = dict.new() // ✅ Empty dictionary d = { "a": 1 } // ✅ Dictionary literal wrong = {} // ❌ Not a dictionary; this is an empty block (Void)The criterion is the content: the
Dictgrammar requires at least oneString ':' Expr. Since{}has no content on which to base a decision, it takes the zero form of the block structure. A non-empty form is self-describing ({ "k": v }has a key-value pair → dictionary)—the same principle under whichf = { 5 }is anIntvalue rather than a function: the type is determined by the content.
Set has no literal grammar and no runtime representation—when set types are planned and the requirement arises, they will be completed using the Dict model (std.set + HeapValue::Set). The resolution of List/Dict literals is determined by the contextual type annotation: a bare literal and a
List(T)annotation both resolve to a growable list. The growable list's type face has the single nameVec(T), and aList(T)annotation is normalized by source name to the same type face asVec(T). AnArray(T, N)annotation applied directly to a literal resolves to a fixed-length array. Implicit List→Array conversion is forbidden.Array literal semantics:
- The number of elements must equal N; otherwise, compile-time E1002 is reported. An empty literal with a nonzero N is likewise rejected.
- Every element type must be compatible with T; otherwise, compile-time E1002 is reported.
- The grammatical form of N is an integer literal (which may be negative), a constant name, or a constant expression beginning with a reference to a compile-time value parameter and continuing with infix arithmetic, such as
2+3orN+1. The folded value participates in count validation (2+3and5have the same shape).- Parse-time rejection: floating-point/string seeds (E0010) and incomplete expressions such as
2+(E0012); an identifier followed by(follows the constructor type path—a function call cannot be used as a type-position actual argument (E1003).- When N is a symbolic constant (such as a function const parameter in
Array(Int, n)), count validation is deferred to the refined-type stage.- In v1, nested array literals (
Array(Array(Int,2),2) = [[1,2],[3,4]]) are rejected at compile time; each layer must be constructed explicitly. Recursive resolution is deferred to a later version.
1.6.5 List Comprehensions
ListComp ::= '[' Expr ( 'for' Identifier 'in' Expr ( 'if' Expr )? )+ ']'#401 (implementation completion):
iffilters and multiple generator clauses are implemented as of this version. Previously, the grammar was written as(',' Expr)* ('if' Expr)?, with no implementation for either the comma-separated additional expressions or multiple generators, and the parser omitted theiffilter entirely (after parsing the iterable, it directly expected']', reportingE0010 Expected RBracket, found KwIf). The semantics now follow common industry practice: there may be one or more generator clauses, expanded as nested loops; each clause may carry at most oneiffilter, whose condition must beBool(a non-Bool condition reportsE1054). The iterable and condition of later clauses may reference iteration variables bound by earlier clauses.
Tightened behavior (migration record): the iteration-variable grammar was already
'for' Identifier 'in', but the old implementation parsed the pattern using the full Pratt parser—afterinwas registered as an infix operator,xwould swallowin itemsas a membership expression. After the fix, non-identifier patterns fail to parse directly and no longer fall back to_as the old implementation did, silently swallowing the error. Impact: forms such as[x for (a, b) in pairs]that previously parsed now report an error. This form never had defined behavior (the variable was always_), so tightening it is correct and incurs no semantic migration cost.
1.6.6 Membership Tests
Membership ::= Expr 'in' Expr
inis a binary relational operator that returnsBool—trueon a match andfalseotherwise, without reporting an error. The semantic split is:[]asserts existence and retrieves a value (failure is an error), whereasinasks whether something exists (a miss is a normalfalse). Right-operand coverage: List / Array / Dict (key set) / Tuple / String (substring) / Range (interval).inis a first-class Horn predicate and serves as the basis for compile-time provable propositions during the refined-type stage. (Set was removed from the right-operand list—Set has no runtime representation; see §1.6.4.)
1.7 Comments
// Single-line comment
/* Multi-line comment
can span multiple lines */1.8 Indentation Rules
Code must use four spaces for indentation. Tab characters are forbidden. This is a mandatory syntax rule.
Chapter 2: Grammar Rules
2.1 Expression Categories
Expr ::= Literal
| Identifier
| FnCall
| MemberAccess
| IndexAccess
| UnaryOp
| BinaryOp
| TypeCast
| RangeExpr
| ErrorPropagate
| RefExpr
| IfExpr
| MatchExpr
| Block
| Lambda2.2 Operator Precedence
| Priority | Operator | Associativity |
|---|---|---|
| 1 | () [] . ? | Left-to-right |
| 2 | as | Left-to-right |
| 3 | Unary prefix ! - + | Right-to-left |
| 4 | * / % | Left-to-right |
| 5 | + - | Left-to-right |
| 6 | .. | Left-to-right |
| 7 | << >> | Left-to-right |
| 8 | & | ^ | Left-to-right |
| 9 | == != < > <= >= | Left-to-right |
| 10 | and | Left-to-right |
| 11 | or | Left-to-right |
| 12 | if...else | Right-to-left |
| 13 | = += -= *= /= | Right-to-left |
Unary prefix operators (
!-+) bind tightly: they bind less tightly only than calls and member access, and more tightly than every binary operator. Therefore,!a == b≡(!a) == b(Zig-style semantics).!is a purely unary operation, does not participate in short-circuit control flow, and is orthogonal to theand/orkeywords, which short-circuit (RFC-010 is the authoritative definition).
Range binding strength:
..has binding strengths (6, 7)—the left side, 6, binds less tightly than addition (7), while the right side, 7, consumes addition but not same-level... Before and after the change:
Expression Before the change (level 1, right-associative) After the change ((6,7), left-associative) x in 1..10x in 1..10(inhas a right-operand level of 4, and level-1..cannot consume it, so it cannot actually be parsed)x in (1..10)—the entire range is the right operand ofin0..n+2(0..n)+2(right-associativity trap: the upper bound is consumed, causing theforloop to report E3004 directly)0..(n+2)—the upper bound is an arithmetic expressiona == b..ca == (b..c)(level-1..< level-3==, so it is naturally one unit)a == (b..c)—semantics unchanged;..still binds more tightly than comparison1..2*3(1..2)*31..(2*3)—the upper bound is an arithmetic expressiona..b..ca..(b..c)(right-associative chain, an meaningless Range nested in a Range)(a..b)..c—step form (cis the step size)Net effect: a composite upper bound in
for i in 0..n+2changes from “parses successfully but reports E3004” to “directly usable”;x in 1..10changes from “cannot be parsed” to “an interval check”; anda..b..cchanges from “meaningless nesting” to “a step component”. Level 6 falls between+(level 5) and<<(level 7), following mathematical convention: intervals are tightly bound constructs, so the upper bound naturally forms a complete arithmetic expression.
2.3 Function Calls
FnCall ::= Expr '(' ArgList? ')'
ArgList ::= Expr (',' Expr)* (',' NamedArg)* | NamedArg (',' NamedArg)*
NamedArg ::= Identifier '=' ExprNamed arguments use name = value (RFC-010 §Function Definitions, RFC-011 §Constructor Forms). Positional arguments must precede named arguments; parameters specified by name may appear in any order among named arguments:
add: (a: Int, b: Int) -> Int = a + b
add(3, 5) // Positional
add(a = 3, b = 5) // Named
add(b = 5, a = 3) // Any order
add(3, b = 5) // Mixed, with positional arguments firstAn incorrect named-argument name reports E1014. A positional argument and named argument occupying the same formal-parameter slot, or a positional argument after a named argument, reports E1111. Naming the same formal parameter more than once reports E1015. A mismatched argument count reports E1010 (see the RFC-013 error-code table).
Unnamed parameters and named arguments: signature parameter positions permit a bare type form (mk: (Int, Int) -> Int), which denotes unnamed typed parameters—type constraints apply positionally, while the names belong to the implementation (provided by the lambda header; see the shorthand rules in RFC-007) and are not part of the contract. An unnamed parameter cannot be referenced by a named argument (because there is no name to reference) and can only be passed positionally. To place a name in the contract, use mk: (a: Int, b: Int) -> Int. A bare identifier must be a declared type; failure to resolve the type is an error (see type-system §3.5).
Conversely, named parameters place names in the contract, with the declaration as authoritative. Parameter names in an implementation header (the parameter list after =>) are merely local names inside the body and are bound by position—in f: (a: Int) -> Int = (b) => b, the implementation header uses b, but callers still write f(a = 7). Type annotations in the implementation header are used only for comparison; a mismatch with the declaration reports E1011. If the implementation header has more parameters than the declaration's runtime parameter slots, it reports E1112 (f: () -> Int = (a: Int) => a)—in both cases, the declaration is the authoritative source. The reverse case, where the implementation omits parameters, is not an error: the type layer checks arity against the declaration, but parameter positions omitted from the implementation header have no runtime slots, and arguments assigned to them are discarded on the IR side (see the gap recorded in type-system §3.5).
2.4 Member Access
MemberAccess::= Expr '.' Identifier2.5 Index Access
IndexAccess ::= Expr '[' Expr ']'Three-layer semantics (RFC-011b):
a[i]is dispatched according to the type ofa: ① built-in containers (List/Vec/Array/Dict/Tuple) use native indexing instructions (the fast path); ② user types that implement theIndexinterface are dispatched to theirindexmethod (instantiatingIndex(Grid, Int, Float)in the type body and providing aGrid.indexmethod); ③ RFC-004'sf[0]positional binding exists only in binding declarations and is not part of this grammar. For multidimensional indexing, the keys ofa[0, 1]are packed into a tuple. Other types that do not implementIndexare rejected at the type level.
2.6 Type Casting
TypeCast ::= Expr 'as' TypeExprImplementation status (pre-existing gap, not introduced in this version): the preceding text defines only the grammar and precedence (§2.4, level 2); the semantics have not yet been implemented. The following facts can be independently verified: ① Parsing: the
KwAsinfix arm atparser/pratt/led.rs:81producesast::Expr::Cast; ② Type checking:typecheck/inference/expressions.rs:3847-3853performs only a silent reannotation forExpr::Cast—let _ = self.infer_expr(expr)?;discards the inner result and then directly returns thetarget_typeMonoType; ③ There is no convertibility validation anywhere in the repository, nor is there a corresponding diagnostic code (there is no cast entry inutil/diagnostic/codes/); ④ir_gengenerates no instructions (middle/core/ir_gen.rsonly obtains the span and free variables ofExpr::Castat:5111/:5918/:9381—the first two are span arms forget_expr_span/expr_span, and the third iscollect_free_vars_expr; none of the three generates instructions); ⑤ Consequently,x as Intcurrently reports no error and performs no runtime conversion.
2.7 Conditional Expressions
IfExpr ::= 'if' Expr Block ('else' 'if' Expr Block)* ('else' Block)?2.8 Pattern Matching
MatchExpr ::= 'match' Expr '{' MatchArm (ArmSeparator MatchArm)* '}'
MatchArm ::= Pattern ('|' Pattern)* ('if' Expr)? '->' Expr
ArmSeparator ::= ',' | <newline>
Pattern ::= Literal
| Identifier
| Wildcard
| RangePattern
| StructPattern
| TuplePattern
| EnumPattern
| OrPattern
RangePattern ::= ('-')? Literal '..' ('-')? Literal // Endpoints may have a negative sign prefix; negative values are normalized—see the "range pattern" note belowArm arrows and separators: arms use
->;=>is used only for lambdas. Arms are separated by newlines or,—the same rule as the “newline or;” rule for statements (RFC-038).
Variant-set requirement for variant destructuring (RFC-010b):
EnumPattern(such asok(v)orsome(x), with variant names adjudicated by the scrutinee) requires the scrutinee's type to be a sum type with a variant set present. Variant sets enter the checker only through type definitions oruseimports—ResultandOptionare defined bystd.resultandstd.option, souse std.result/use std.optionare required before use (both whole-module and groupeduse std.{...}forms have equal status); otherwise, variant destructuring reports E1002. Exhaustiveness checking uses the same source: a fallback arm is exempt from exhaustiveness, and without a fallback arm, all variants are checked.
Pattern bindings, or-patterns, and guards (RFC-010b):
- Bindings: a bare identifier in a pattern introduces a new name—it is neither a comparison nor an assignment. The name is visible within the arm, shadows an outer variable of the same name, and expires upon leaving the arm. A discriminant (such as
okinok(v)) is adjudicated using the scrutinee's variant set; a bare name not found in that set is a binding.- Or-patterns:
p1 | p2tries alternatives in order; if a non-final alternative fails, the next is tried, and if the final alternative fails, control moves to the next arm. All alternatives must bind the same set of names, or E1033 is reported. A binding with the same name exists only once at arm level, and the arm body necessarily reads the value written by the matching alternative.- Guards: after a pattern matches, the
ifcondition is evaluated with the pattern bindings in scope; the condition must produceBool; if it is false, control moves to the next arm. A guarded arm does not count toward exhaustiveness coverage (the guard might not match), but a repeated variant arm with a guard is reachable (it refines the preceding arm).- Diagnostics: a missing branch reports E1030, an unreachable arm reports E1031, a duplicate binding within the same pattern reports E1032, inconsistent bindings in an or-pattern reports E1033, and a struct pattern with a missing field reports E1034; see the error-code reference for the code table and messages.
Range patterns (issue #405):
lo..hiis a two-sided closed interval test—on the Int domain,x matches lo..hi ⟺ lo <= x <= hi, so both 80 and 89 match80..89. Endpoints must be integer literals (a negative sign prefix is normalized to a negative value, such as-5..-1). Other literal types (Float/Bool/String/Char) are syntactically valid but rejected by type checking (E1002; the first version does not support Float ranges). An identifier endpoint in a pattern position is a binding name with no matching semantics and is rejected at the syntax level (E0010). When both endpoints can be determined at compile time, a reversed range (lo > hi) is empty, never matches, and reports unreachable (E1031); a duplicate range arm with identical endpoints also reports E1031.Exhaustiveness interaction: range patterns are in the same category as literal patterns—checked, partially covering, and non-fallback. Because the Int domain is open, a range arm cannot be exhaustive, so a match containing a range arm still requires a wildcard/identifier arm as a fallback (E1030); a range arm may serve as an or-pattern alternative and may have a guard (a failed guard moves to the next arm, consistent with the existing guard rules).
Semantic separation from the §2.12 Range expression:
lo..hiin a pattern position does not construct a Range value; it only performs branch matching, with endpoints that define a two-sided closed interval. The expression forma..b(foriteration,ininterval checks, and first-class Range values) retains its left-closed, right-open semantics. The two..semantics are intentionally separate: a pattern is a matching predicate over a discrete value domain, whereas an expression is notation for constructing an iteration sequence.
2.9 Block Expressions
Block ::= '{' Stmt* Expr? '}'Statement termination rules: separation between statements and newline behavior (explicit
;separators, newline termination, continuation exceptions, and lines beginning with(/[that are never merged) are defined by RFC-038. Adjacent statements without a separator are a syntax error. The same rule (newline or explicit separator) is used for match arms (see §2.8).
2.9.1 The Three Forms of {
In expression position, { has exactly three possible interpretations, determined once by its content:
| Form | Notation | Type | Example |
|---|---|---|---|
| Empty block | {} | Void | x: Void = {} |
| Dictionary literal | { "k": v, ... } | Dict(K, V) | d = { "a": 1 } |
| Block | { Stmt* Expr? } | Tail-expression type | y = { 1 + 1 } |
Decision order:
{}(no content) → empty block, valueVoid- The first element is a
String ':' Exprkey-value pair → dictionary literal - Otherwise → block, with the value provided by the tail expression
Why
{}is not an empty dictionary: the “emptiness” of an empty dictionary cannot describe itself (it could be eitherDict(K, V)or an empty block), whereas the dictionary grammar §1.6.4 requires at least one key-value pair. When there is no content on which to base a decision, the zero form of the block structure is used: this is consistent withunsafe {}/spawn {}and introduces no special case. To create an empty dictionary, usedict.new().Why functions require an annotation:
f = { stmt }is a value (with the tail expression's type), not a function. To define a function, specify an Fn annotation:f: () -> Int = { 5 }. This follows the same principle as dictionaries: the type is determined by the content, not by whether an annotation is present. (See RFC-010a, Appendix D.)
Unified semantics: the values of all {} blocks are provided by the tail expression, and return is a non-local exit of type Never.
| Block type | Value exit | Empty block {} |
|---|---|---|
Ordinary {} | Tail expression | Void |
unsafe {} | Tail expression | Void |
spawn {} | Tail expression | Void |
Core principles (see RFC-010a for details):
- A block's value is its tail expression (the final expression), its sole exit, with no exceptions.
- If the final element is an assignment statement, the block's value is
Void; to obtainVoid, explicitly writeVoid. returnexits the nearest function boundary (passing through every block, rather than “returning to the block”) and has typeNever;Never <: T
holds for every type (explosion principle), so it may appear in any return-type position. The module-initialization layer (the Script top level) has no function boundary, so
returnis rejected at compile time there (E1109; see §3.11).
- The expression form
= exprdirectly provides the value.
// Ordinary {} block: the tail expression provides the value
result = {
x = compute()
x // The block's value
}
// unsafe {} block: the tail expression provides the type definition
SqliteDb = unsafe {
SqliteDb: Type = {
handle: *Void
}
SqliteDb // The block's value
}
// spawn {} block: the tail expression provides the result
(a, b) = spawn {
result1 = fetch("url1"),
result2 = fetch("url2")
(result1, result2) // The block's value
}
// return: passes through the block and exits the function
f: (n: Int) -> Int = {
if n < 0 {
return 0 // Exits the if and the function body, exiting the function
}
n * 2 // Tail expression = the block's value
}Is name = { ... } a Function or a Block Value?
name = { ... } may be either a function definition (RFC-007's “simplest empty parameter list”) or a block-value binding. The decision is made by annotation priority and a function-by-default rule (RFC-010a, Appendix D):
| Case | Result | Example |
|---|---|---|
The value is a Lambda (=>) | Function | f = () => 5 → f() = 5 |
| The annotation is a function type | Function | f: () -> Int = { 5 } → f() = 5 |
| The annotation is a non-function type | Block value | x: Int = { 5 } → x = 5 |
| No annotation | Function | f = { 5 } → f() = 5 |
The annotation is the type: x: Int = ... declares that x is an Int, so { ... } evaluates to an Int; f: () -> Int = ... declares that f is a function, so { ... } is a function body.
To evaluate { ... } immediately, write the target type; no new syntax is required:
// Block value: evaluated immediately
x: Int = {
y = 5
y // x = 5
}
// Function: defaults to a function without an annotation
f = { 5 } // f() = 5Nested Function Types: Curried or Returning a Function?
There are two ways to read a nested function type on the right-hand side of ->, distinguished by parentheses (RFC-004):
| Form | Meaning | Invocation |
|---|---|---|
(a: Int) -> (b: Int) -> Int | Curried | f(1)(2) |
(a: Int) -> ((b: Int) -> Int) | Returns a function | g(1) yields a function |
The basis is: the annotation is the type. g: (a: Int) -> ((b: Int) -> Int) declares that g(1) : (b: Int) -> Int, so g(1) must be that function, rather than the “next set of arguments.”
// Curried: two sets of arguments applied layer by layer
add: (a: Int) -> (b: Int) -> Int = { a + b }
add(1)(2) // → 3
// Returns a function: only the outer set of arguments is applied here; the result is the function
adder: (n: Int) -> ((x: Int) -> Int) = (x) => x + n
adder(10)(5) // → 15
h = adder(10) // The returned function can be stored in a variable or passed aroundAn unparenthesized nested Fn is always curried (including RFC-011's type-parameter form):
identity: (T: Type) -> (x: T) -> T = (x) => x // Curried
identity(5) // → 5Type checking: parentheses declare the return type, so the body must produce that type. f: () -> (() -> Int) = { 7 } is an error—the expected type is () -> Int, but the actual type is Int (E1002).
2.10 Lambda Expressions
Lambda ::= '(' ParamList? ')' '=>' Expr
| '(' ParamList? ')' '=>' Block
| Identifier '=>' Expr
裸单参形态(`Identifier '=>' Expr`)只允许**单个标识符、不带类型注解**;多参或带注解一律用括号式。Parameters in a lambda header must be named: the name is the only way to refer to a parameter inside the body. Bare type items belong only to signature positions; their names are supplied by the lambda header—see type-system §3.5 for the two forms of signature parameters and the ownership of names.
2.11 Error Propagation Operator
ErrorPropagate ::= Expr '?'The ? operator is postfix and has the same precedence as .. For the Result(T, E) type:
- When the value is
Ok(v), extractvand continue execution. - When the value is
Err(e), propagate the error upward (return Err(e)).
process: (data: Data) -> Result(Data, Error) = {
validated = validate(data)? // Extract the value on success; propagate upward on failure
transform(validated)
}2.12 Range Expressions
RangeExpr ::= Expr '..' Expr ('..' Expr)?.. creates a range value (Range is a first-class value, not syntactic sugar).
for i in 0..10 { print(i) }
slice = array[0..5]
// Range is a value: it can be bound, passed, and tested for membership
r = 1..10
assert.assert(5 in r, "membership")
for i in r { print(i) }
// Step form (third component, default 1)
for i in 0..10..2 { print(i) } // 0, 2, 4, 6, 8
for i in 10..0..(-2) { print(i) } // 10, 8, 6, 4, 2Step semantics: in
a..b..c,cis the step size. The literalc = 0is rejected at compile time; a dynamiccreceives a runtime zero check (E6001 family; it will be promoted to Result once the error system is implemented).c < 0is valid, and the direction of the interval reverses with the sign (10..0..(-2)is descending).Separation in pattern positions: a match range pattern
lo..hi(§2.8) does not construct a Range value; its endpoints define a two-sided closed interval test. The expression forma..bin this section remains left-closed and right-open.
2.13 ref Expressions
RefExpr ::= 'ref' Exprref creates shared ownership. The compiler automatically selects Rc (single-task) or Arc (cross-task), and users need not concern themselves with implementation details.
data = ref heavy_data
spawn { use(data) } // Across tasks: the compiler automatically selects Arc2.14 unsafe Expressions
UnsafeExpr ::= 'unsafe' Blockunsafe blocks are used to define opaque types and operate on raw pointers. Use return to return a type definition to the enclosing scope.
Semantics:
- Types and raw-pointer operations may be defined within
unsafe {}. - A returned type is available outside
unsafe {}. - Accessing the fields of a type requires unsafe permission.
// Define an opaque type inside an unsafe block
SqliteDb = unsafe {
SqliteDb: Type = {
handle: *Void // Raw pointer
}
return SqliteDb
}
// SqliteDb is available outside the unsafe block
db = sqlite3_open("test.db")2.15 Scopes
Basic rules:
- Every
{}block creates a scope. - An inner scope can access variables from an outer scope.
- An outer scope cannot access variables from an inner scope.
- Variable declarations follow the “assignment first” principle.
// Block scope
{
x = 10
// x is visible within this scope
}
// x is not visible outside this scope
// Function scope
add: (a: Int, b: Int) -> Int = {
result = a + b
return result
}
// result is not visible outside the functionVariable declarations and shadowing:
x = value: searches outward through the scope chain forx; if found, assigns to it, and if not found, declares a new binding.mut x = value: explicitly declares a new mutable binding and forbids the same name in an outer scope.- Any name may be declared only once within the same scope.
Detailed definition: see the module system specification for the complete rules on scopes, variable declarations, and shadowing.
Chapter 3: Statements
3.1 Statement Categories
StmtList ::= Stmt (StmtSep Stmt)*
StmtSep ::= ';' | <newline>
Stmt ::= LetStmt
| DestructureStmt
| ExprStmt
| ReturnStmt
| BreakStmt
| ContinueStmt
| IfStmt
| MatchStmt
| WhileStmt
| ForStmt
| SpawnStmt3.2 Variable Declarations
LetStmt ::= ('mut')? Identifier (':' TypeExpr)? '=' Expr3.2.1 Destructuring Assignment
DestructureStmt ::= '(' Pattern (',' Pattern)* ')' '=' ExprThe elements of the right-hand value are bound positionally to the patterns. A bare identifier in a pattern introduces a new name (following the same rule as match patterns); it is neither a comparison nor an assignment to an existing name. The right-hand value's arity must match the arity of the destructuring pattern.
(a, b) = (1, 2)3.3 return Statements
ReturnStmt ::= 'return' Expr?Semantics: return is a non-local exit that exits the nearest function boundary (passing through every block—including if / while / for / match / bare blocks / spawn / unsafe) and passes its value to the caller. It does not “return to the block.”
Type: return e : Never (e : T). Never <: T' holds for every T' (explosion principle; see Type System §2.2), so return may appear in any return-type position without requiring additional rules.
Relationship with block evaluation: a block's value is always its tail expression (see §2.9). As a block, { return n } has the value n and type Never; at the same time, return exits the function. Both facts hold simultaneously, coexisting through the explosion principle.
Together, return and tail expressions make “early return” possible without requiring any special rule that limits return to functions—see RFC-010a.
factorial: (n: Int) -> Int = {
if n <= 1 {
return 1 // Exits the if and exits the function (type Never)
}
n * factorial(n - 1) // Tail expression = the block's value
}3.4 break Statements
BreakStmt ::= 'break'Semantics: immediately terminates the innermost enclosing while/for loop, transferring control to after that loop's body.
- Exits only the nearest level:
breakalways applies to the innermost loop containing it. To jump out of multiple levels in nested loops, extract the inner loop into a function and usereturn, or use a flag (break/continue have no labels; if loop labels are introduced in the future, their syntax will be determined on the loop-declaration side through the RFC process, together with the multi-exit design of the proof pipeline). - Permitted only inside a loop body:
breakmay appear only in the body of awhile/forloop (including nested blocks/if/match statements within the body). Use outside a loop is a compile-time error (E1102'break' outside of a loop). - Does not affect termination proofs:
breakdoes not participate in termination arguments—it neither provides a measure nor constitutes a decreasing measure step. The loop's termination obligation is independent ofbreakand is triggered by refined types (see type-system §8.5). - Borrow semantics: the control-flow edge of a break participates in the structural cut performed by RFC-009a's reverse-BFS liveness analysis (an exited iteration does not participate in back-edge liveness derivation).
mut i = 0
while i < 10 {
i = i + 1
if i == 3 {
break // Control flows to after the loop; i == 3
}
}
// Nested loops: break exits only the inner loop
while j < 3 {
while k < 10 {
if k == 2 { break } // Terminates only the inner loop
}
j = j + 1 // Executes here after every outer iteration
}3.5 continue Statements
ContinueStmt::= 'continue'Semantics: skips the remaining statements in the current iteration and proceeds directly to the next iteration of the innermost enclosing loop—while reevaluates its condition, while for takes the next element.
- Applies only to the nearest level: like
break, it has no labels. - Permitted only inside a loop body: use outside a loop is a compile-time error (E1102).
mut sum = 0
mut n = 0
while n < 5 {
n = n + 1
if n == 3 {
continue // Skips the addition below; n == 3 is not included
}
sum = sum + n
}
// sum == 12 (1 + 2 + 4 + 5)3.6 if Statements
IfStmt ::= 'if' Expr Block ('else' 'if' Expr Block)* ('else' Block)?3.7 match Statements
MatchStmt ::= 'match' Expr '{' MatchArm+ '}'3.8 while Statements
WhileStmt ::= 'while' Expr Block3.9 for Statements
ForStmt ::= 'for' 'mut'? Identifier 'in' Expr Block3.9.1 Semantics: Each Iteration Binds a New Value
YaoXiang's for-loop semantics differ from those of traditional languages: each iteration binds a new value rather than modifying the same variable.
// Example: for i in 1..5
for i in 1..5 {
print(i)
}Execution process:
| Iteration | Loop-variable behavior |
|---|---|
| First | Creates a new binding i = 1, executes the body, and prints 1 |
| Second | Creates a new binding i = 2 (the previous binding is destroyed), executes the body, and prints 2 |
| Third | Creates a new binding i = 3, executes the body, and prints 3 |
| Fourth | Creates a new binding i = 4, executes the body, and prints 4 |
| End | The loop body ends and the binding is destroyed |
Key point: after each iteration ends, the binding created during that iteration is destroyed. The next iteration uses an entirely new binding, unrelated to the previous iteration's binding.
3.9.2 Difference Between for and for mut
| Syntax | Loop-variable mutability | Description |
|---|---|---|
for i in 1..5 | Immutable | The binding cannot be modified in the loop body |
for mut i in 1..5 | Mutable | The binding can be modified in the loop body |
// Valid: each iteration binds a new value, so no modification is needed
for i in 1..5 {
print(i) // Reads the value of i
}
// Invalid: an immutable binding cannot be modified
for i in 1..5 {
i = i + 1 // Error: cannot modify an immutable binding
}
// Valid: for mut permits modifying the binding
for mut i in 1..5 {
i = i + 1 // Modification is permitted
}3.9.3 Shadowing Checks
YaoXiang prohibits variable shadowing. A for-loop variable cannot have the same name as a variable in an outer scope:
// Invalid: i has already been declared in the outer scope
i = 10
for i in 1..5 {
print(i)
}
// Valid: use a different variable name
i = 10
for j in 1..5 {
print(j)
}This rule applies to all code blocks. See 4.3 Shadowing Rules for details.
3.9.4 Comparison with Other Languages
| Language | for-loop variable semantics |
|---|---|
| YaoXiang | Binds a new value on every iteration |
| Rust | Modifies the same variable (requires mut) |
| Python | Modifies the same variable (does not require mut) |
| C/C++ | Requires a pointer or reference |
Design rationale: YaoXiang adopts binding semantics because:
It better matches natural semantics. In natural language, “for each element x in a set” means that each x is an independent individual. YaoXiang's
for i in 1..5reads as “for each i from 1 through 5,” and the i in each iteration is an entirely new binding, consistent with human intuition.It prevents accidental modification. The default immutable-binding semantics means that the loop variable cannot be accidentally modified inside the loop body. There is no need to worry about accidentally writing
i = ...somewhere in a complex loop body and introducing a difficult-to-trace bug.A high-performance solution is readily available. When it is genuinely necessary to reuse a variable between iterations (for example, an accumulator or cache),
for mutswitches to mutable-binding mode. This is clearer than implicit shared state—the intent is expressed explicitly through syntax rather than hidden in runtime behavior.
3.10 spawn Statements
SpawnBlock ::= '(' Pattern (',' Pattern)* ')' '=' 'spawn' '{' Expr (',' Expr)* '}'
SpawnFor ::= Identifier '=' 'spawn' 'for' 'mut'? Identifier 'in' Expr '{' Expr '}'
SpawnStmt ::= SpawnBlock | SpawnForspawn block: explicitly declares a concurrency scope, and expressions within the block execute concurrently.
(result_a, result_b) = spawn {
parse(fetch("url1")),
parse(fetch("url2"))
}spawn loop: a data-parallel loop.
results = spawn for item in items {
process(item)
}A spawn block captures outer variables (RFC-024 §2.3, value-capture semantics):
- A reference to an outer variable in the block body constitutes a Move value capture: the value is snapshotted into the closure environment at the spawn creation point, and the block body reads it through the environment (LoadUpvalue).
- Primitive types (Int/Float/Bool/Char) are copied, leaving the outer variable unaffected.
- Handle types (Struct/String/List, etc.) are snapshotted as handle copies that share the underlying object; in the Embedded runtime (the default), the same thread and heap are used, so the handle remains valid.
- Sharing between multiple tasks requires an explicit
ref(§2.13; the compiler automatically selects Rc/Arc). - A
returnin the block that references an outer variable captures it in the same way.
t1 = 1 + 1
t2 = 2 + 2
result = spawn {
return t1 + t2 // t1/t2 are captured by value; result == 6
}3.11 Program Entry Point and Top-Level Statements
From the compiler's perspective, a source file has two roles, determined by whether yaoxiang.toml exists:
| Role | Determination | Program body |
|---|---|---|
| Script | A single file run directly, without yaoxiang.toml | Top-level statements (executed in source order); main is an ordinary binding |
| Bin | yaoxiang.toml exists | The main function; top-level executable statements are forbidden |
Script: Top-Level Statements Are the Program
Without a manifest, the file is a “script,” and top-level statements execute in source order (top-level binding initialization as a whole occurs first; see “Top-Level Binding Initialization” below):
use std.io
io.println("hello") // Executes directly
x: Int = { 42 } // Top-level binding: initialized at runtime
io.println(x) // 42In this mode, main is not special—it is merely an ordinary binding. To run main, it must be called explicitly:
use std.io
main: () -> Void = { io.println("only runs if called") }
main() // ← This line is requiredWhy
mainis not invoked automatically: top-level statements are already the program body. Ifmainwere also invoked implicitly, a script that explicitly containsmain()would execute twice. The two rules cannot coexist, so Script mode has only one execution entry point: “top-level statements.”
The top level must likewise not use return: the Script top level is the module-initialization layer and has no function boundary to exit (RFC-010a rule ②). It reports compile-time E1109, rather than silently terminating initialization at runtime and skipping the remaining top-level statements. To end a section of top-level logic early, place it in a function and control it at the call site.
Bin: main Is the Entry Point
When a manifest is present, the file is an “executable target,” and:
- A binding named
mainmust be defined, with either a value or a function (#388 establishes the rule: entry-point detection is based on the existence of the binding—functions are already values, and the two differ only in evaluation strategy). A functionmainis called with no arguments at entry; a valuemainis evaluated during initialization. - Top-level executable statements are forbidden—the program body is
main.
main: () -> Void = {
print("hello")
}A value main is equally valid—evaluating it during initialization executes it within the initialization sequence (following global-binding topological order, with independent bindings following source order):
main = {
print("hello")
}A missing main is a compile error (without main, all functions are unreachable). A non-callable value main (such as main: Int = 5) is valid but has no observable effect—analogous to Rust's empty fn main() {}.
Library files: files imported by other files through
use, or files referenced by[lib].path/[exports], do not requiremain—they are not program entry points.
Top-Level Binding Initialization
Top-level binding initialization values are evaluated at runtime and need not be compile-time constants:
answer: Int = { 42 } // Block value
inc: (Int) -> Int = (x) => x + 1
computed: Int = inc(41) // Function callInitialization executes in dependency order, independently of source order (dependencies are initialized first; bindings without dependencies follow declaration order):
derived: Int = base * 3 // References base, which is declared later
base: Int = 7 // Initialized first (topological sort)Furthermore, all binding initialization occurs before any top-level statement executes—side effects in binding initializers occur before those in any top-level statement, regardless of how the two are interleaved in the source:
print("a") // Executes later
x = { print("b") } // Executes first (binding initialization as a whole occurs first)
print("c") // Output order: b, a, cCyclic dependencies are compile errors (the names on the cycle are listed):
a: Int = b + 1
b: Int = a + 1 // Error: a → b → aDesign basis: RFC-029f (file-role model) and RFC-010a, Appendix D (block-binding decision).
Appendix: Syntax Quick Reference
A.0 Keywords (17)
use spawn ref mut
if else match while for
in return break continue
as unsafe and ortype is no longer a keyword (RFC-010; use Name: Type = { ... } instead); pub was removed entirely under RFC-029g and is now an ordinary identifier. See §1.4.1 for the literal reserved words true / false / void, and §1.4.3 for the meta type name Type and the built-in type names Void / Never / Int / Float / Bool / Char / String.
A.1 Control Flow
if Expr Block (else if Expr Block)* (else Block)?
match Expr { MatchArm+ }
while Expr Block
for 'mut'? Identifier 'in' Expr Block
break | continue // Only inside loop bodies (§3.4 / §3.5)A.2 Error Handling
Expr '?' // Error propagation (Result type)A.3 match Syntax
match value {
pattern1 -> expr1,
pattern2 if guard -> expr2,
_ -> default_expr,
}