Skip to content

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 ​

  1. The compiler supports only a single file: Pipeline::run(name, source) receives one string and cannot handle cross-file dependencies
  2. use can only resolve std modules: All local use declarations between files report "Unknown variable"
  3. The module resolver is in the wrong place: The only path-resolution logic is in package/source/module_resolver.rs, while frontend/module/resolver.rs actually performs compile-time predicate normalization (RFC-027)

Design Goals ​

  • A project can compile multiple .yx files
  • The semantics of use statements 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.

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

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

yaoxiang
use math.geometry.{Point, distance}

This is equivalent to:

yaoxiang
Point = math.geometry.Point
distance = math.geometry.distance
SyntaxSemantics
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 pathRetrieve the path record itself and bind it to the last path segment's name
use path as aliasRetrieve the path record itself and bind it to alias

Nonexistent Syntax ​

  • use path.*: Wildcard import. Not needed; list bindings explicitly.
  • from path use item: Python style. Not adopted.
  • use path.{item as alias}: Aliases inside braces. Optional in Phase 4 and does not block the main path.

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 MeaningHowMechanism
"This is the API"Put it in a published packageDistribution
"This is internal"Put it in an unpublished packageDistribution
"This is inside a function"Write it in the function bodyScope

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:

  1. Module already registered in the Registry: math.geometry is already in the Registry → use it directly
  2. Standard library: std or std.* → built-in module
  3. Importer's directory: <importer_dir>/math/geometry.yx (local modules take priority)
  4. Project root (the nearest ancestor containing yaoxiang.toml): <project_root>/math/geometry.yx
  5. Vendor directory: .yaoxiang/vendor/<pkg>-*/src/ (future)

File locations are attempted in this order:

base/name.yx
base/name/mod.yx

Stop 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 use tracing (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 under yaoxiang test possible. 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 as tests/foo_test.yx import modules from the project root. When the src/ 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:

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

  1. [run].main (yaoxiang.toml)
  2. The path of the first [[bin]]
  3. 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:

  1. Find the module record in the Registry
  2. Retrieve the field
  3. 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 ​

ComponentChange
frontend/module/resolver.rsRewrite: 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.rsExtend: Add the source-file tracking needed to merge ASTs (Span carries the file name)
frontend/module/registry.rsExtend: Support registering user modules (currently only std is registered)
frontend/module/orchestrator.rsNew: Multi-file orchestrator (discovery → parsing → merging → invoking Pipeline)
frontend/pipeline.rsNo changes
frontend/core/parser/statements/imports.rsNo changes (use parsing is already implemented)
package/source/module_resolver.rsDelete; 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: boolNo change (overturned by 029g: it is removed together with the pub keyword; implemented on 2026-10-08, see 029g)

Nonexistent Files (the Old RFC Claimed They Were "Implemented", but They Do Not Actually Exist) ​

  • frontend/module/loader.rs — Does not exist; its responsibilities are handled by the orchestrator
  • frontend/module/dep_graph.rs — Does not exist; no topological sorting is needed within a package (AST merging)
  • frontend/module/cache.rs — Does not exist; it belongs to sub-RFC 029a
  • frontend/module/hot_reload.rs — Does not exist; it belongs to sub-RFC 029b

Implementation Strategy ​

Phase 1: Unified Path Resolution ​

  1. Move predicate normalization from frontend/module/resolver.rs to frontend/core/types/eval/
  2. Migrate the path-resolution logic from package/source/module_resolver.rs to frontend/module/resolver.rs
  3. Detect ambiguous module paths (both name.yx and name/mod.yx exist → report an error)

Phase 2: Multi-File Orchestrator ​

  1. Create frontend/module/orchestrator.rs
  2. Implement on-demand discovery (recursively following use from the entry point)
  3. Implement AST merging (concatenating items from multiple files, with Span retaining the source file)
  4. Add compile_project(project_root) to compiler.rs to invoke the orchestrator

Phase 3: use Name Resolution ​

  1. Change process_use_stmt in typecheck to query the Registry (no longer only std)
  2. Add import conflict detection (report an error for identical names)
  3. Add an E2E test: use local modules in a multi-file project

Phase 4 (Optional, Does Not Block the Main Path) ​

  1. Aliases inside braces: use path.{item as alias}
  2. Vendor directory resolution (in conjunction with RFC-014)

Dependencies ​

  • RFC-014 (Package Manager) — yaoxiang.toml fields and vendor directory structure (needed only in Phase 4)
  • No other prerequisite dependencies

Sub-RFC Plan ​

Sub-RFCCapabilityPrerequisite
029aModule caching and incremental recompilationStable orchestrator
029bFile watching and hot reload029a
029dCLI --entry entry-point overrideOrchestrator available
029eMulti-file diagnostics with --json outputDiagnostic aggregation
029fCompilation target roles and import-surface semantics (accepted 2026-09-13, #334)Stable orchestrator
029gRemove 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 ​

DecisionResolutionDateRationale
What a module isA record of a file's top-level bindings2026-07-30Unified name: type = value model from RFC-010
use semanticsRecord destructuring2026-07-30No new mechanism; reuses existing record semantics
VisibilityNone2026-07-30Scope + distribution boundaries cover all scenarios; no new keywords are needed
pub keywordDo not use2026-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 semanticsDirectory entry (convention, not mandatory)2026-07-30Python __init__.py model: doors do not lock
Module type annotationsNot needed2026-07-30Internal bindings already carry types; annotations are redundant
Within-package cyclesAllowed (merged AST)2026-07-30Path A: zero pipeline changes, the model within a Rust crate
Cross-package cyclesNot handled for now2026-07-30No third-party ecosystem; report an error when encountered
Registry loadingOn demand (only reachable modules)2026-07-30Not an optimization, but the definition
Single file vs. projectSame mechanism2026-07-30Registry contents differ; lookup logic is the same

References ​