Module System Specification
This document defines YaoXiang’s module system specification: how modules are defined, how use imports bindings, what the export surface is, and how scopes are divided.
Design basis: RFC-029 Module Semantics, RFC-029g Removing the pub Keyword and Automatic Binding.
For a user-facing how-to guide, see Module System.
Chapter 1: Module Definitions
1.1 A Module Is a File
Modules use files as their boundary. Every .yx file is a module; there are no module or mod declaration keywords.
// math/geometry.yx
Point: Type = { x: Float, y: Float }
distance: (a: Point, b: Point) -> Float = { ... }1.2 A Module Is a Set of Top-Level Bindings
The “contents” of a module are simply its set of top-level bindings. In the preceding example, the contents of module math.geometry are equivalent to:
{ Point: Type, distance: (Point, Point) -> Float }A module is therefore an open record—there is no export list that must be declared item by item; a module is all of its top-level bindings.
1.3 Path Mapping
Module paths map segment by segment to files, file first, directory second:
| Module Path | Lookup Order |
|---|---|
a.b | <base>/a/b.yx → if not found, <base>/a/b/mod.yx |
a | <base>/a.yx → if not found, <base>/a/mod.yx |
mod.yx is the convention for a directory entry file (the “house number”), not its only entry point (the “lock”)—both a.yx and a/mod.yx can host module a.
Do Not Use index.yx The Rust convention of index.yx is not recognized in YaoXiang.
When src/helper/index.yx is used, use helper reports E5001. Directory entry files must be named mod.yx. :::
If both forms exist simultaneously, module path ambiguity is triggered and an error is reported (RFC-029 §4).
1.4 Lookup Starting Point
<base> is tried in the following order:
- The importer’s directory
- The project root
Chapter 2: Module Imports
use is record destructuring: it brings bindings from the target module into the current scope.
2.1 Grammar
Import ::= 'use' ModuleRef ImportSpec?
ImportSpec ::= 'as' Identifier
| '{' ImportItems '}'
ImportItems ::= ImportItem (',' ImportItem)* ','?
ImportItem ::= Identifier ('as' Identifier)?
ModuleRef ::= Identifier ('.' Identifier)*2.2 Forms
| Syntax | Semantics | Example |
|---|---|---|
use path | Introduces the path namespace, accessed as path.x | use std.io → io.print(...) |
use path.{x, y} | Binds x and y directly in the current scope | use std.math.{sqrt} → sqrt(...) |
use path.{x as y} | Binds x as y | use std.io.{print as say} → say(...) |
use path as alias | Introduces the path namespace and renames it | use helper as h → h.label(...) |
use path.{a, b} binds two paths to the same set of top-level bindings, so use a.{Point} and use a.geometry.{Point} refer to the same binding.
2.3 Explicitly Unsupported Syntax
The following forms are explicitly rejected in RFC-029 and are likewise rejected by the implementation:
| Syntax | Disposition | Actual Behavior |
|---|---|---|
use path.* | Wildcard import; not adopted | Parse error |
from path use item | Python-style; not adopted | Parse error |
use path.{item} as alias | Positional alias; not adopted | Parse error; suggests the inline form use path.{item as alias} |
use .relative | Relative import; not included in the design | Parse error (E0011) |
Positional and Inline Aliases Are Not the Same use std.io.{print} as p (an alias
after the braces) is explicitly rejected; use std.io.{print as p} (inside the braces) is supported. The compiler’s error message points this out. :::
2.4 Name Conflicts
When two module paths refer to a binding with the same name, the import fails. An inline alias must be used to distinguish them.
Chapter 3: Export Surface
3.1 No Visibility Mechanism
The language introduces no visibility mechanism. There is no pub, no private, and no export.
RFC-029 made this decision, and RFC-029g further removed the pub keyword entirely from the lexer, AST, type checker, dead-code exemptions, formatter, and LSP.
3.2 All Top-Level Bindings Are Importable by Default
Every top-level binding in a module—functions, types, and constants, with or without type annotations—is visible to all code that can write the module’s path.
// helper/mod.yx — note that plain has no modifiers
plain: () -> string = "no pub keyword at all"
// Another module can import it directly
use helper
main = () => {
print(helper.plain())
}Therefore, there is no such thing as “private by default.” Debating whether a binding is exported is an invalid question in YaoXiang.
Accessing a name that does not exist on a module, or is not top-level, reports E1043, “the module does not export that member.” To introduce only selected names, use the brace form use helper.{plain}.
Regarding the history of the
pubkeyword: before 029g decided to remove it,pubonly affected dead-code exemptions (the W1001 family) and never participated in export determination—writingpubdid not affect whether a binding could be imported. The old documentation’s statement that “all items are private by default” was the opposite of the implementation.
3.3 Method Bindings Are Explicit
Methods are not automatically bound through pub. The method form is an explicit composition:
Point: Type = { x: Float, y: Float }
// Explicit method: the first parameter is self
Point.distance: (self: &Point, other: &Point) -> Float = {
dx = self.x - other.x
dy = self.y - other.y
(dx * dx + dy * dy).sqrt()
}The explicit form is strictly more expressive (it supports multi-position binding and unit binding) and is the only method form.
Chapter 4: Scopes
4.1 Scope Hierarchy
- Module scope: bindings at the top level of a file
- Block scope: each
{}establishes a scope; inner declarations do not leak into the outer scope - Function scope: inside a function body
4.2 Declarations and Shadowing
YaoXiang has no let keyword. Is x = value a declaration or an assignment? One principle applies:
Assignment takes precedence. A declaration occurs only once, whereas assignments may occur hundreds of times. Keep high-frequency operations on the shortest path.
x = value:
沿作用域链向外查找 x
→ 找到 mut x :赋值,OK(通过 &mut 令牌)
→ 找到 x(不可变,存活):E2010 不可重新赋值
→ 找不到:在当前作用域新声明(唯一的声明路径)
mut x = value:
→ 当前作用域已存在 x :E2002 重复定义
→ 外层作用域存在 x :E2013 禁止遮蔽(显式新声明不能与外层同名)
→ 无冲突:新可变声明- Same scope: Any name may be declared only once (E2002)
- No
mutin the inner scope: Look outward first, then assign or report an error mutin the inner scope: An explicit new declaration; shadowing an outer name is prohibited (E2013)
Blocks are real scopes: The premise of “look up along the scope chain” is that every
{}block really establishes a scope—names declared inside do not leak outward.
Same Scope
x = 10
x = 20 // E2010: 'x' is immutable and cannot be reassigned
mut y = 10
y = 20 // OK: same binding, reassigned
mut y = 30 // E2002: 'y' is already defined in this scope (explicit new declaration collides with the name)
z = 10
mut z = 20 // E2002: 'z' is already defined in this scope (mut cannot overwrite an existing declaration)Note that x = 20 reports E2010 (cannot be reassigned), not E2002 (duplicate definition): Without mut, x = value is semantically an assignment (it looks up the scope chain), rather than “declaring another x.” Only mut x = value is an explicit new declaration, and only a collision there reports E2002.
Rebinding After a Move
When an immutable variable owns its value and that value is moved (consumed), the original binding enters the moved state—the name still occupies its scope slot, but the value is no longer accessible.
A moved state is not considered when determining whether a declaration is allowed. The way to reclaim the name is an explicit redeclaration:
// Pipeline data flow: each step consumes the old value and produces a new one
mut data = fetch() // Explicit mutable declaration
mut data = transform(data) // E2002: data already exists in the same scopeWhy “already moved → redeclarable” is not used:
A move is a path-sensitive dataflow property—after
if c { move p },phas been moved on one path but not yet on another, so it is “possibly moved” rather than a Boolean truth value. A binding-level flag structurally cannot represent the merge of branches; treating it as a switch that permits the name to be redeclared would produce incorrect diagnostics (a move on a single branch would be treated as moved).The actual move analysis is in
layers/ownership.rs: it constructs the function-body CFG and performs dataflow over theAlive < Moved < Droppedlattice, taking the max (conservative) at branch merges and reporting E2014/E2018 at read checkpoints. It answers “can this be read here?”, while “can this name be declared again?” is answered independently by the assignment-first rule in 4.2.The two have different responsibilities and should not be coupled. This is also why the old text’s “already moved branch” state was never reachable: it depended on a flag that was never written.
Rebinding relies on an explicit mut declaration:
// Equivalent explicit form
mut data1 = fetch()
data2 = transform(data1) // data1 is moved and cannot be used again
mut data3 = filter(data2)Semantic separation:
| Operation | Meaning | Mechanism | Syntax |
|---|---|---|---|
| Rebinding | The old value disappears and a new value is born | move + new declaration | mut x = f(x) (new name or mut) |
| In-place modification | The value at the same memory location changes | mut assignment | mut x = v; x = w |
Constraints:
- Only values that own their data can be moved. References (
&T,&mut T) are copied rather than moved - Move checking is performed at compile time (CFG + dataflow); reading a variable in the moved state in any expression reports E2014
- A declaration must have an initializer:
LetStmt ::= ('mut')? Identifier (':' TypeExpr)? '=' Expr—a pure annotation declaration such asx: Intis not grammatical and reports E0012
// Reading after a move → error
data = fetch()
result = process(data) // data is moved
print(data) // E2014: 'data' has been moved and cannot be used again
// References do not trigger a move
ref_data = &value
copy1 = ref_data // Copies the reference; ref_data remains usable
copy2 = ref_data // OK
// Across scopes: the moved state propagates
data = fetch()
{
data = transform(data) // Moves the outer data → rebinds it (new inner declaration)
print(data) // OK: uses the inner data
}
print(data) // E2014: the outer data has been movedCross-Scope
// Outer immutable; inner assignment → the immutable variable cannot be reassigned
x = 10
{
x = 20 // E2010: 'x' is immutable and cannot be reassigned
}
{
mut x = 20 // E2013: cannot shadow existing variable 'x' (explicit declaration of a new binding)
}
// Outer mut; inner assignment → modifies the same binding
mut y = 10
{
y = 20 // OK: same binding, modified through the &mut token
}
print(y) // 20
// Outer mut; inner scope cannot declare the same name
mut z = 10
{
z = 30 // OK: same binding
}
{
mut z = 30 // E2013: cannot shadow existing variable 'z'
}
// Multi-level nesting: mut penetrates every level
mut a = 0
{
{
a = 10 // OK
}
}
print(a) // 10
// Immutable also cannot be reassigned through every level
b = 0
{
{
b = 10 // E2010: 'b' is immutable and cannot be reassigned
}
}for Loops
// The loop variable is a new binding on each iteration, not a modification
for i in 1..5 {
print(i) // OK: binds a new value on each iteration
i = 10 // E2010: immutable loop variable cannot be reassigned
}
for mut i in 1..5 {
i = 10 // OK: mutable loop variable
}
// The loop variable cannot shadow an outer variable
i = 0
for i in 1..5 { // E2013: cannot shadow existing variable 'i'
}
// A mutable outer accumulator can be modified in the loop body
mut sum = 0
for i in 1..5 {
sum = sum + i // OK: same binding, modified through the &mut token
}
print(sum) // 15
// An immutable outer variable cannot be modified in the loop body
sum2 = 0
for i in 1..5 {
sum2 = sum2 + i // E2010: 'sum2' is immutable and cannot be reassigned
}Related Error Codes
| Error Code | Message | Trigger Scenario |
|---|---|---|
| E2002 | '{name}' is already defined in this scope | Duplicate declaration in the same scope (whether mut or not) |
| E2010 | Cannot assign to immutable variable '{name}' | Inner assignment without mut, where the outer variable is immutable and has not been moved |
| E2013 | Cannot shadow existing variable '{name}' | Explicit inner declaration (mut x or x: Type) has the same name as an outer one |
| E2014 | '{name}' has been moved and cannot be used | Reads a variable that has been moved |
Chapter 5: Directory Organization
5.1 Structure
src/
├── main.yx // Top-level file
├── math/
│ ├── mod.yx // Directory entry point (module math)
│ ├── vector.yx // Module math.vector
│ └── matrix.yx // Module math.matrix
└── utils/
├── mod.yx // Directory entry point (module utils)
└── string.yx // Module utils.string5.2 Directory Entry Point
The mod.yx file in a directory serves as that directory’s module entry point:
// math/mod.yx
use math.vector
use math.matrix
Vector = vector.Vector
Matrix = matrix.MatrixNotice that there is no pub here—Vector and Matrix are ordinary top-level bindings and are directly visible to importers (see §3.2).
Chapter 6: Diagnostics
| Error Code | Meaning | Typical Trigger |
|---|---|---|
| E5001 | Module not found | Incorrect path; index.yx used as a directory entry point; dependency not installed |
| E5003 | The requested export does not exist in the module | Misspelled import name (such as read instead of read_line) |
In project mode, E5001 includes an additional hint: when a dependency is missing, it recommends running yx install.
