RFC-029: Module Semantics System
Summary
Integrate the module system into the compilation pipeline to support multi-file compilation.
Core definition: A module = all top-level bindings in a single .yx file. The type of a module = the types of those bindings (inferred). use = record destructuring. There is no pub, no private, no export, and no visibility mechanism.
Core principles:
- The type checker queries only the prebuilt ModuleRegistry and never touches disk
- Files within a package are merged into a single compilation unit (AST concatenation), so circular references between files within a package are naturally allowed
- The Registry is loaded on demand: it loads only modules reachable from the entry point through
use
Not included: Caching, file watching, hot reload, incremental recompilation, or handling cross-package circular dependencies.
Motivation
Current Issues
- The compiler supports only a single file:
Pipeline::run(name, source)receives one string and cannot handle cross-file dependencies usecan only resolve std modules: All localusedeclarations between files report "Unknown variable"- The module resolver is in the wrong place: The only path-resolution logic is in
package/source/module_resolver.rs, whilefrontend/module/resolver.rsactually performs compile-time predicate normalization (RFC-027)
Design Goals
- A project can compile multiple
.yxfiles - The semantics of
usestatements are clear: record destructuring, not a special mechanism - Single-file usage continues to work without requiring
yaoxiang.toml - The pipeline (
Pipeline) requires no changes; multi-file support is the orchestration layer's responsibility - No new keywords, AST nodes, or concepts are introduced
Proposal
1. Module = Record of Bindings
A module is all top-level bindings in a .yx file.
// math/geometry.yx
Point: Type = { x: Float, y: Float }
distance: (a: Point, b: Point) -> Float = { ... }The contents of this module are { Point: Type, distance: (Point, Point) -> Float }.
A module is not a special entity. It is an instance of the name: type = value model—a record that happens to be defined at a file boundary. A module's type is inferred from its bindings and never requires an explicit annotation.
Bindings introduced by use are also part of the module's contents:
// math/mod.yx
use geometry.{Point, distance}The contents of the math module = { Point: Type, distance: (Point, Point) -> Float }. Outside the module, use math.{Point} can obtain the binding. use math.geometry.{Point} can obtain it as well. Both paths point to the same binding.
2. use = Record Destructuring
Every form of use consists of record field access plus binding:
use math.geometry.{Point, distance}This is equivalent to:
Point = math.geometry.Point
distance = math.geometry.distance| Syntax | Semantics |
|---|---|
use path.{item} | Retrieve the item field of the path record and bind it in the current scope |
use path.{a, b} | Retrieve multiple fields |
use path | Retrieve the path record itself and bind it to the last path segment's name |
use path as alias | Retrieve the path record itself and bind it to alias |
Nonexistent Syntax
: Wildcard import. Not needed; list bindings explicitly.use path.*: Python style. Not adopted.from path use item: Aliases inside braces. Optional in Phase 4 and does not block the main path.use path.{item as alias}
Import Conflicts
Bindings with the same name produce an immediate error:
名字 `Point` 冲突:
math.geometry.Point
graphics.shapes.Point
请使用不同名字或模块别名。3. Visibility: None
This RFC does not introduce any visibility mechanism. Every top-level binding is visible to all code that can construct its path.
This is an intentional design decision, not an oversight.
Rationale
| Intended Meaning | How | Mechanism |
|---|---|---|
| "This is the API" | Put it in a published package | Distribution |
| "This is internal" | Put it in an unpublished package | Distribution |
| "This is inside a function" | Write it in the function body | Scope |
All three rely on existing mechanisms: packages, files, and scopes. Nothing new is needed.
Why No pub
- Anything you do not want others to use should not be placed at the top level (put it in a local scope)
- Put helper functions shared by multiple files in a separate, unpublished package
- "Whether it can be prevented" and "whether there should be a signal" are two different things. There is no third-party ecosystem at the current stage, so a signal is meaningless
- Doors do not lock. Using the door is courtesy; climbing over the wall is freedom. The language does not govern courtesy
Future
Once the ecosystem matures and enforced boundaries are needed, they may be introduced through a separate RFC. Adding restrictions is backward compatible (public by default → explicitly marked as internal). However, this RFC neither presupposes that direction nor promises that it will happen.
4. Path Resolution
Module Path → File
use math.geometry.{Point}The lookup order is:
- Module already registered in the Registry:
math.geometryis already in the Registry → use it directly - Standard library:
stdorstd.*→ built-in module - Importer's directory:
<importer_dir>/math/geometry.yx(local modules take priority) - Project root (the nearest ancestor containing
yaoxiang.toml):<project_root>/math/geometry.yx - Vendor directory:
.yaoxiang/vendor/<pkg>-*/src/(future)
File locations are attempted in this order:
base/name.yx
base/name/mod.yxStop as soon as the first match is found. If both exist → report an error:
模块路径歧义:`math.geometry` 同时匹配:
src/math/geometry.yx
src/math/geometry/mod.yx
请删除其中一个。Likewise, if the same module key matches one file under each of two roots and both are referenced—for example, tests/lib.yx and <root>/lib.yx are referenced by the tests/ entry point and the root entry point respectively—report the same ambiguity error rather than silently shadowing one.
Revised on 2026-08-03 (driven by RFC-036): Discovery and resolution have been implemented as described. Discovery follows
usetracing (the protocol established in §5 of this RFC), replacing the directory recursion of the initial implementation—compile errors in unrelated files no longer block execution, which is what makes test-file isolation underyaoxiang testpossible. In the dual-root rule, "importer directory takes priority" preserves the behavior of projects in the same directory; "project-root fallback" lets a subdirectory entry point such astests/foo_test.yximport modules from the project root. When thesrc/layout (the RFC-014 package) is implemented, it will be handled at the vendor layer as well and will not affect local dual roots.
mod.yx = Directory Entry (Convention)
mod.yx is the entry file for a directory. Using use math loads src/math/mod.yx.
This is a convention, not a requirement. Users can directly use math.geometry to reach a child file. mod.yx is the "recommended entry" (the street number), not the "only entry" (the lock).
Unified Resolver
The only current path-resolution logic is in package/source/module_resolver.rs. Move it to frontend/module/resolver.rs, replacing the currently misnamed predicate-normalization file; predicate normalization moves to frontend/core/types/eval/.
5. Project Compilation Flow
Path A: Merge ASTs
All files within a package are merged into a single compilation unit. The pipeline requires zero changes.
编排器(Pipeline 之上):
1. 确定入口文件
2. 解析入口文件的 use 语句(只读 use 行,不解析函数体)
3. 沿 use 路径发现文件,加入队列
4. 对队列中的文件,解析它们的 use 语句
5. 重复 3-4 直到队列为空(按需发现)
6. 逐个完整解析所有发现的文件 → 多个 AST
7. 合并为一个 Module(所有顶层 items 拼接,Span 保留来源文件)
8. 喂给 Pipeline::run()(管线不知道有多个文件)Circular References Within a Package: Allowed
Because all files are merged into one AST, mutual use declarations between files within a package are equivalent to mutual references within a single file:
// tree.yx
use node.{Node}
Tree: Type = { root: Node }
// node.yx
use tree.{Tree}
Node: Type = { value: Int, parent: Tree }After merging, the AST contains two type definitions that refer to each other. The compiler already supports this.
Cross-Package Cycles: To Be Reconsidered
Packages are the unit of distribution, and cross-package dependencies require a topological order. There is currently no third-party package ecosystem, so this is not handled for now. If one is encountered, simply report an error.
Entry File Selection
The priorities are:
[run].main(yaoxiang.toml)- The
pathof the first[[bin]] src/main.yx(the conventional default)
Without a yaoxiang.toml, compile the provided file directly. The Registry contains only std. This is not a "single-file mode"—it is the "natural result of an empty discovery result."
On-Demand Registry Loading
The contents of the Registry = all modules reachable from the entry point through use. Unreachable modules are not parsed, not registered, and do not exist. This is not an optimization; it is the definition.
6. std Modules and User Modules Are Equivalent
For type checking, use std.io.{println} and use math.geometry.{Point} operate exactly the same way:
- Find the module record in the Registry
- Retrieve the field
- Bind it in the current scope
Source (Std / User / Vendor) is metadata and does not affect resolution logic. Special handling of native functions is deferred to the IR gen / codegen layer.
Compiler Changes
| Component | Change |
|---|---|
frontend/module/resolver.rs | Rewrite: It currently contains predicate normalization (RFC-027), which moves to frontend/core/types/eval/. This file will instead implement actual module path resolution, migrated from package/source/module_resolver.rs |
frontend/module/mod.rs | Extend: Add the source-file tracking needed to merge ASTs (Span carries the file name) |
frontend/module/registry.rs | Extend: Support registering user modules (currently only std is registered) |
frontend/module/orchestrator.rs | New: Multi-file orchestrator (discovery → parsing → merging → invoking Pipeline) |
frontend/pipeline.rs | No changes |
frontend/core/parser/statements/imports.rs | No changes (use parsing is already implemented) |
package/source/module_resolver.rs | Delete; move the logic to frontend/module/resolver.rs |
frontend/core/typecheck/ | Change use handling to query the Registry (currently only std is queried) |
AST is_pub: bool | pub keyword; implemented on 2026-10-08, see 029g) |
Nonexistent Files (the Old RFC Claimed They Were "Implemented", but They Do Not Actually Exist)
— Does not exist; its responsibilities are handled by the orchestratorfrontend/module/loader.rs— Does not exist; no topological sorting is needed within a package (AST merging)frontend/module/dep_graph.rs— Does not exist; it belongs to sub-RFC 029afrontend/module/cache.rs— Does not exist; it belongs to sub-RFC 029bfrontend/module/hot_reload.rs
Implementation Strategy
Phase 1: Unified Path Resolution
- Move predicate normalization from
frontend/module/resolver.rstofrontend/core/types/eval/ - Migrate the path-resolution logic from
package/source/module_resolver.rstofrontend/module/resolver.rs - Detect ambiguous module paths (both
name.yxandname/mod.yxexist → report an error)
Phase 2: Multi-File Orchestrator
- Create
frontend/module/orchestrator.rs - Implement on-demand discovery (recursively following
usefrom the entry point) - Implement AST merging (concatenating items from multiple files, with Span retaining the source file)
- Add
compile_project(project_root)tocompiler.rsto invoke the orchestrator
Phase 3: use Name Resolution
- Change
process_use_stmtin typecheck to query the Registry (no longer only std) - Add import conflict detection (report an error for identical names)
- Add an E2E test: use local modules in a multi-file project
Phase 4 (Optional, Does Not Block the Main Path)
- Aliases inside braces:
use path.{item as alias} - Vendor directory resolution (in conjunction with RFC-014)
Dependencies
- RFC-014 (Package Manager) —
yaoxiang.tomlfields and vendor directory structure (needed only in Phase 4) - No other prerequisite dependencies
Sub-RFC Plan
| Sub-RFC | Capability | Prerequisite |
|---|---|---|
| 029a | Module caching and incremental recompilation | Stable orchestrator |
| 029b | File watching and hot reload | 029a |
| 029d | CLI --entry entry-point override | Orchestrator available |
| 029e | Multi-file diagnostics with --json output | Diagnostic aggregation |
| 029f | Compilation target roles and import-surface semantics (accepted 2026-09-13, #334) | Stable orchestrator |
| 029g | Remove the pub keyword and automatic binding (final decision on visibility mechanisms; accepted 2026-10-02) | None |
Deleted: 029c (re-export) — Unnecessary. use is re-exporting; there is no "pub use" concept.
Design Decision Record
| Decision | Resolution | Date | Rationale |
|---|---|---|---|
| What a module is | A record of a file's top-level bindings | 2026-07-30 | Unified name: type = value model from RFC-010 |
use semantics | Record destructuring | 2026-07-30 | No new mechanism; reuses existing record semantics |
| Visibility | None | 2026-07-30 | Scope + distribution boundaries cover all scenarios; no new keywords are needed |
pub keyword | Do not use | 2026-07-30 | "If you do not want others to use it, do not put it at the top level or publish that package" |
mod.yx semantics | Directory entry (convention, not mandatory) | 2026-07-30 | Python __init__.py model: doors do not lock |
| Module type annotations | Not needed | 2026-07-30 | Internal bindings already carry types; annotations are redundant |
| Within-package cycles | Allowed (merged AST) | 2026-07-30 | Path A: zero pipeline changes, the model within a Rust crate |
| Cross-package cycles | Not handled for now | 2026-07-30 | No third-party ecosystem; report an error when encountered |
| Registry loading | On demand (only reachable modules) | 2026-07-30 | Not an optimization, but the definition |
| Single file vs. project | Same mechanism | 2026-07-30 | Registry contents differ; lookup logic is the same |
References
- RFC-010: Unified Type Syntax —
name: type = valuemodel - RFC-009: Ownership Model — Imports are compile-time name resolution
- RFC-011: Generic Type System — Structured types
- RFC-014: Package Management System Design — Package names and vendor directory
- RFC-026: Core FFI Mechanism — StdModule registration
- RFC-030: assert Assertion Mechanism — Precedent for unified StdModule registration
