This document reflects the state of the repository around 2025.12. Please use the actual implementation as the ultimate source of truth.
This documentation describes how each package is built. For the overview of the architecture, pipeline and vocabulary, see Architecture.
There are a lot of knobs to tweak within a package, but we will focus on those related to how it is compiled in this section.
This document assumes non-virtual packages. For virtual packages, see Virtual Packages.
There are 4 kinds of source files within each package:
- Source. These are the regular
.mbtfiles within a package. All files in the current package with.mbtextension and does not to any below belong to this kind. - Whitebox test. These files are suffixed
_wbtest.mbt. - Blackbox test. These files are suffixed
_test.mbt. - C stub. These are C files manually specified in
moon.pkg, and recognized by the build system to be built.
Standalone inputs are represented as synthetic single-file packages. Their
source format is recorded while resolving the input. In particular, an
original .mbtx input is kept as a regular, unconditional source file. Both
moonc build-package and moonc check receive -ignore-import-declaration
when lowering that synthetic package. This does not make .mbtx a source
extension discovered in ordinary packages.
moon build <file.mbtx> and moon check <file.mbtx> always select this
standalone representation, even when the file is located under an ordinary
package root. Each command accepts one standalone .mbtx path and supports
single- and multi-backend target selection; watch mode remains project-only.
All standalone-file commands use <source-dir>/_build/<filename> as their
default target directory, including the complete extension in <filename>, so
differently named inputs in one source directory do not share synthetic package
artifacts or incremental build state. With --target-dir <dir>, the target
directory is <dir>/<filename>; the option relocates the target root without
adding source-path identity, so callers are responsible for using distinct
target roots for equal filenames from different source directories.
Private .mooncakes dependencies also live under that per-script target root,
so standalone commands do not install dependencies beside the source file.
Moon creates the selected build root and resolves it with
std::fs::canonicalize before assigning artifact locations. Source discovery
also preserves the canonical prefix on its existing scan root, and standalone
inputs preserve it on their parent directory. Existing toolchain roots are
canonicalized before appending toolchain paths. On Windows this establishes
extended-length syntax (\\?\) even when the root is short.
Keep that prefix throughout internal path construction: a short root can grow into a long descendant, including an output that does not exist yet. Internal artifact paths retain the same identity in clean and incremental builds.
At tool boundaries, apply dunce::simplified to the complete path argument.
This removes an unnecessary prefix when safe and preserves long or otherwise
verbatim-only paths. Use the same rule for compiler sources, dependencies,
outputs, runtime entrypoints, native inputs/outputs, and documentation files.
Compiler arguments are rendered before selecting inline or response-file
transport; the response-file argument follows the same rule. No filesystem
canonicalization or absolute-path resolution takes place in argument builders.
Opaque user flags are passed through without trying to interpret embedded paths.
Keep intermediate native output directories prefixed when the driver will append object filenames. Other consumer directory options retain their explicit boundary handling; support for long descendants ultimately requires support in the receiving tool. The execution graph registers and looks up original paths, while user package selectors compare compatible spellings.
Watcher containment checks treat ordinary and verbatim drive/UNC prefixes as equivalent. This comparison does not alter artifact paths or require event paths to exist, so a removed output subtree remains ignored.
Consumer support still limits some commands. MSVC needs short source-file
arguments simplified and does not accept long generated-C inputs. Node 22
rejects long verbatim entrypoint paths. moondoc joins package paths with /,
which is invalid beneath a verbatim Windows prefix, so its output directory is
a compatibility exception: Moon simplifies it where possible to preserve ordinary
documentation builds. Long documentation paths still fail during output directory
creation, after the compiler has produced the package interface. Windows tests
distinguish these downstream failures from MoonBit compiler output creation.
Source files may also be conditionally included into the build -- see Conditional Compilation for more information.
There are 4 build targets (see Architecture)1 for each package, each with its own list of source files (and thus acting like an actual "package" to build with):
| Build target kind | Source | Whitebox | Blackbox | C stub | Enable test | Note |
|---|---|---|---|---|---|---|
| Source | ☑️ | ☑️ | no | The package itself | ||
| Inline test | ☑️ | ☑️ | yes | |||
| Whitebox test | ☑️ | ☑️ | ☑️ | yes | ||
| Blackbox test | ☑️ | yes |
The detailed semantics of tests are in the corresponding section.
The imported packages are specified in import { ... } blocks in moon.pkg,
and are available to all three build targets.
Test targets (whitebox and blackbox) can also have imports that are not used in regular targets,
specified in import { ... } for "wbtest" and import { ... } for "test" blocks.
Executable packages (pkgtype(kind: "executable")) are on a stricter migration path:
- Release N warns when another package depends on a main package through regular, whitebox-test, or blackbox-test imports.
- Release N+1 will reject such dependencies as hard errors.
The intended structure is to keep a main package as an entrypoint only, and move reusable APIs into a non-main package that other packages may import.
There are two build commands that are used to build the source files, both working on the source code of a single package (more precisely, a build target).
moonc build-package(build plan nodeBuildPackage) is the command used to compile source file. It reads the interface files of dependency packages, and compiles the source code of a package into an intermediate representation called CoreIR, and the package interface file (see below for details about file types).moonc check(build plan nodeCheck) is used for typecheck source files without compiling. It only outputs the package interface, not the CoreIR.
Unless the user explicitly passes --debug or --release, Moon resolves the
default optimization profile by subcommand:
moon build,moon run,moon test,moon fmt, andmoon checkuse the debug profile.moon benchandmoon bundleuse the release profile.
This policy is centralized in BuildFlags::effective_profile() in
crates/moon/src/cli/build_flags.rs. Commands select a BuildConfiguration
containing backend and profile before package resolution. The CLI adapter's
BuildFlags::compile_config() retains that selection and interprets the remaining
flags into DebugInfoRequest, selecting requested symbol detail and native
runtime backtrace support separately. A default moon run for the Native target
backend requests source backtraces. After selecting the Native Payload Form,
backend planning retains MoonBit debug information for generated C and omits it
for direct object output, which uses -O0 -stacktrace for unoptimized code
and lightweight stack-trace metadata.
The generated-C compiler step separately retains the source locations emitted
by MoonBit. This includes C output selected by
MOONBIT_NEW_NATIVE=0, an unsupported direct-object host, a MOON_CC compiler
for another target, or package C compiler flags. Explicit --debug or --no-strip retains full debug information, while
--strip and ordinary release builds omit it.
A debug-profile moon run --strip still requests native runtime backtrace
support, without requesting program debug information. The CLI captures that distinction
in DebugInfoRequest; planning and lowering do not infer it again from the run
mode or profile. Backend Plan owns the MoonBit compiler's debug-information
decision. C-stub and executable action metadata each own their native compiler
debug and optimization settings; selecting generated C does not enable C-stub
debug information. Runtime build metadata owns whether to enable the reporter,
and GenerateDsym action membership records any required macOS symbol generation.
Lowering consumes these planned decisions without a separate debug option.
See native compiler debug information and optimization
for the distinct compiler and linker flags.
When actually building a package, the pipeline depends on the backend:
- Build each individual package, via
moonc build-package/BuildPackagenode, into CoreIR. - Link into executable, via
moonc link-core/LinkCorenode. This step reads in all CoreIR files produced by the package and all its transitive dependencies, and links into an executable output. For JS/WASM backends, this already outputs the final executable. When the prebuilt standard library is injected, the stdlib packages reached through imports (including the implicitpreludeandbuiltinimports) are linked from their installed<core>/_build/<backend>/release/bundle/<pkg>/<name>.corefiles, in the same dependency order as local packages. The bundledcore.coreis not used for linking. - Compile generated C, via
CompileGeneratedC, whenLinkCoreemits C. This produces aGeneratedCObject, using one compile-only invocation. Direct-object and LLVM payloads already are object files and skip this step. - Make native executable, via the native toolchain /
MakeExecutablenode. Native and LLVM backends link the payload object together with C stubs and runtime archives to produce the final executable. Non-native backends skip it. A foreign-library package builds a static library instead; see foreign libraries on native backends.
macOS debug builds that emit native object code add one post-link step:
- Generate debug symbols, via
dsymutil/GenerateDsym. This action depends on the completed executable and produces its.dSYMbundle. The linker anddsymutilremain separate structured commands, so n2 can schedule and track each tool invocation independently.
After a successful build, moon build lists each requested Executable and
ForeignLibrary artifact on stdout, in the order of the selected target
backends. Each row shows the package, the target backend and the absolute
path, last so it is easy to copy:
Artifacts:
username/demo/cmd/main wasm-gc /p/_build/wasm-gc/debug/build/cmd/main/main.wasm
username/foreign/lib native /p/_build/native/release/build/lib/lib.a
The list is a Command Result, so --quiet does not hide it. It reads the same
whether or not stdout is a terminal; programs use --output-json, which
writes each artifact as a JSON line next to the compiler's diagnostic
messages:
{"$message_type":"artifact","package":"username/foreign/lib","target_backend":"native","path":"/p/_build/native/release/build/lib/lib.a"}Other requested artifacts, such as a library package's CoreIR, are build intermediates and are not listed. A dry run lists commands instead, and a failed build lists nothing.
A package needs all its transitive dependencies' interface files to be built
before running BuildPackage for any of its build targets.
In the build plan, this means each BuildPackage node depends only on:
- the interface files (
.mi) of its direct dependency build targets (the build graph executor tracks transitive dependencies), and - any toolchain/backend preparation nodes.
There are no other hidden cross-package dependencies.
Once those prerequisites are satisfied,
each build target's BuildPackage node can be scheduled in any order
or in parallel with other BuildPackage nodes.
The BuildPackage node produces two main output files.
.core/ CoreIR: This is the intermediate representation the code in this package compiles to..mi/ Interface file: This is the binary representation of the public interface of the package. This file is passed to the compiler when other packages import this package.
The LinkCore node produces a single backend-specific compilation output,
containing all compiled MoonBit code for the package to build:
- For JS, WASM and WASM-GC backend, this is the final executable to use: A JavaScript or WASM file.
- The Native backend outputs either generated C or a direct object file, according to the selected Native Payload Form.
- The LLVM backend outputs an object file to be linked with the system library.
Release-profile binary WASM and WASM-GC outputs carry a human-readable module
name in the optional WebAssembly name custom section. The name identifies the
package being linked as module/package@version when its module manifest
declares a version, or as module/package otherwise. Release-profile test build
targets use the owning source package's identity rather than a synthetic
test-target suffix. This name is debugging information that tools may strip or
rewrite; it is not trusted provenance. Moon does not request this name for debug
builds or plain WAT output.
With MOON_SEPARATE_COMPILATION=1, captured in BackendConfig::Wasm, an
executable on the linear-memory Wasm backend is linked from one relocatable
wasm1 object per package instead of one whole-program link-core, so that an
edit recompiles only the objects that read the edited .core files. It needs
a moonc that supports -pkg-type library and moonc wasm-ld.
Every object reads the .core files of its package's transitive
dependencies, followed by those of moonbitlang/core/json,
moonbitlang/core/debug and their dependencies that it does not already read.
moonc gives each error constructor an object uses an entry in the error
table, whose methods call into those two packages, and not every standard
library package that uses errors depends on them (builtin does not). For a
program package they are already among its dependencies through prelude.
BuildWasmObject(WasmObject) compiles both kinds of object with
moonc link-core; the executable's target never runs LinkCore.
BuildWasmObject(WasmObject::Main(BuildTarget))writes the object of the executable's main package target, theWasmMainObjectartifact, to{package_dir}/__moonbit_link_core__/{artifact}.o. It carries what applies to the executable alone: the package's link configuration, its exports and the test driver's entry points.BuildWasmObject(WasmObject::Library(PackageId))writes the library object of every other package the executable links, theWasmLibraryObjectartifact, to{package_dir}/{package}.o, withlink-core -pkg-type library. The object compiles its package's source target alone, so every executable using the package shares it; it does not read the package's link configuration.LinkWasmObjects(BuildTarget)provides theExecutablewithmoonc wasm-ld. It links the objects of the packages the main object reads, in the same dependency order, then the main package's object. The linker initializes packages in this order and drops what the program does not use. An object refers only to packages whose.corefiles it reads, sincemoonckeeps a definition local to an object when its owning package is not loaded; the packages each linked object reads are among those the main object reads, so every reference is linked. The objects and the linker get the same-wasi, allocator and trial-deletion settings, and-gkeeps names.
BuildPlanConstructor::links_wasm_objects decides per target, and keeps the
whole-program LinkCore for: --output-wat; targets other
than main packages and tests; the blackbox tests of main packages, which
would need a main package's library object; packages with link.wasm
settings and modules with link flags, which objects cannot carry;
targets reaching a virtual package, since each executable resolves virtual
packages with its own overrides while a library object is shared by every
executable using it; and source, inline-test and
whitebox-test targets that would link a library object depending on their
own package, such as a whitebox test importing a dependent of the package
under test, or a test of an error table package or of a package they depend
on. A
library object cannot refer to the package the main object compiles, and
would be initialized before it. Release builds do not name the linked
module.
Assume we have a dependency graph as following (edge point from one item to its dependency):
graph BT;
A --> B --> D
A --> C --> D
E --> C
If we're building the executable for A and E, the build plan will look like:
graph BT;
bp_a[BuildPackage A] --mi--> bp_b[BuildPackage B] --mi--> bp_d[BuildPackage D]
bp_a --mi--> bp_c[BuildPackage C] --mi--> bp_d
bp_e[BuildPackage E] --mi--> bp_c
lc_a[LinkCore A] --core--> bp_a & bp_b & bp_c & bp_d
me_a[MakeExecutable A] --c--> lc_a
lc_e[LinkCore E] --core--> bp_e & bp_c & bp_d
me_e[MakeExecutable E] --c--> lc_e
The edges still point from dependents to dependencies.
The text on the edge represent the files needed between nodes.
As you may be able to see, BuildPackage of C and D s shared between the two builds.
MoonBit allows native-backend programs to compile some C files alongside MoonBit code,
called C stubs.
These files are per-package, specified in moon.pkg.
MoonBit code might reference the functions defined in them in e.g. extern "C" fns.
Compiling C stubs of a package involves 3 steps:
BuildCStub-- The C files are compiled independently using a C compiler. Each action conservatively tracks every package-local.h,.hh,.hpp, and.hxxfile because MoonBuild does not interpret transitive#includedirectives. Dot-prefixed directories, ignored generated directories, and nested module or package roots are outside the Package File Set, so headers under those boundaries are not discovered automatically.ArchiveOrLinkCStubs-- All C stubs in a package are archived using AR.- For every package that transitively depends on this package with C stubs,
the archived compilation output is added to the input list of
MakeExecutable.
For ordinary native builds, each C translation unit shipped under the
toolchain's lib/runtime/ directory is compiled by a BuildRuntimeObject
node. BuildRuntimeLib archives those objects into one static library, which
is shared by every MakeExecutable node in the build plan. Release builds also
enable and archive supported prebuilt SIMDUTF objects.
Static archives are always created from their complete member list. An
update-style archiver runs through moon tool archive, which
deletes the previous archive first, so adding, removing, or renaming a runtime
translation unit, or changing the selected SIMDUTF members, cannot leave a
removed member behind. See
archive commands for which archivers this
applies to.
A package declared with pkgtype(kind: "foreign_library") (or the legacy
link: true) and no main is built for a foreign host. On Native and LLVM,
moon build requests a ForeignLibrary artifact, provided by
ArchiveForeignLibrary, and plans no executable link. Wasm and JS still
request the package's Executable, which their LinkCore provides; moving
them to ForeignLibrary is a pending change marked in the intent code.
ArchiveForeignLibrary creates one static archive whose members are objects,
because static archives do not nest:
- the MoonBit payload: the
LinkCoreobject for direct-object Native and LLVM, or for generated-C Native the object aCompileGeneratedCaction compiles from the generated C with the package'scc-flags; - the C stub objects of every package the payload links, in link order;
- the native runtime objects and, in release builds, the selected SIMDUTF objects;
libmoonbitrun.owhen the selected allocator links it.
The archive shares its stem with the package's executable, such as
lib.a or lib.lib for package lib, so it never collides with the
package's lib{package} C stub archive. Like the runtime archive, it is
created from exactly its current members, with update-style archivers run
through moon tool archive. Objects from different packages may share a file
name, such as two stub.o. Each supported archiver keeps every input of a
newly created archive, so both become members.
The archive cannot carry link flags. link.native.cc-link-flags, prebuild
link arguments, system libraries, and, for builds with runtime backtraces,
libbacktrace.a remain the foreign host's responsibility.
A .mbti file is the textural representation of .mi.
It is used for users to ensure compatibility of the public API of the package,
as well as the input of virtual packages' interfaces.
(See virtual package info in Virtual packages).
A .mbti file can be losslessly transform to and from a .mi file
given the package configuration (mainly, the import list for it to resolve imports).
Two build plan nodes are responsible for this:
GenerateMbti, viamooninfo, converts a.mifile to.mbtifile.BuildVirtual, viamoonc build-interface, converts a.mbtifile to.mifile.
MoonBit allows some files in the source directory to be generated at compile time. These are called prebuild tasks, and executed in a form similar to Makefiles. Each task may have a list of input and outputs file, and a command line to execute. Custom tasks are stored in a package prebuild subplan rather than the backend dependency graph. They are lowered into the same n2 graph, where matching physical input and output paths establish their dependencies. See Prebuild for the detailed lifecycle.
There are three types of tests in a MoonBit package. In detail:
-
Inline tests are tests written alongside the source code. They don't get their own imports.
-
Whitebox tests are tests written in files suffixed with
_wbtest. These tests are compiled alongside the source code, and can see the package-private symbols in the source code. They get additional imports fromimport { ... } for "wbtest"blocks. -
Blackbox tests are tests written in files suffixed with
_test, as well as in the doc comments in the source code. These tests can only see the public symbols exported from the package. They get additional imports fromimport { ... } for "test"blocks.Implementation-wise, they form a package that depend on the source package, but gets special treatments to be able to import symbols in the source package without qualification.
Main packages are being tightened here as well:
- Release N warns if a main package still declares blackbox test inputs such
as
_test.mbt, doctests,.mbt.md, ortest-import. - Release N+1 will stop generating blackbox test targets for main packages.
If you need blackbox tests for public behavior, move that behavior into a non-main package and keep the main package focused on wiring and process entry.
- Release N warns if a main package still declares blackbox test inputs such
as
All three test targets are compiled to an executable in the corresponding backend.
For now, the build graph still models main-package blackbox tests so release N can warn users before the behavior is removed. Release N+1 will make main packages an exception and only generate inline/whitebox tests for them.
The different build targets have the following dependency relationship:
graph BT;
source["A (source)"]
inline["A (inline test)"]
wb["A (whitebox test)"]
bb["A (blackbox test)"]
source & inline & wb & bb --> imports
wb --> wbtest-imports
bb ---> test-imports
bb --> source
To run tests, one must first know what are the tests to run. In MoonBit, this is done by scanning the source code for tests, and then generate a test driver and related metadata.
- The test driver is a MoonBit source file containing the mapping between test identifiers and the test blocks (test functions), and the entry point to tests.
- The test metadata is a JSON file containing metadata of the test cases.
It is used by
moonitself to get the list of tests, and determine the tests to run based on user request.
Both files are generated per-build-target via moon generate-test-driver (GenerateTestInfo).
The driver is used in BuildPackage like a regular source file.
Backend build-plan nodes and package prebuild actions are peer action kinds.
TargetKind appears only inside backend nodes for which it has meaning.
| Build plan node | Command | Outputs | Dependencies | Note |
|---|---|---|---|---|
Check(BuildTarget) |
moonc check |
.mi |
source files, .mi of dependency packages |
Typecheck the target |
BuildPackage(BuildTarget) |
moonc build-package |
.mi, .core |
same as above | Build the target |
LinkCore(BuildTarget) |
moonc link-core |
backend-specific | .core of all transitive deps |
Links all transitive deps into output |
BuildWasmObject(WasmObject) |
moonc link-core |
wasm1 object | .core of the target and its deps |
Main or library object (separate compilation) |
LinkWasmObjects(BuildTarget) |
moonc wasm-ld |
executable | wasm1 main object, library objects | Links Wasm objects (separate compilation) |
MakeExecutable(BuildTarget) |
C compiler | executable | LinkCore outputs, C stubs, runtime |
Compiles/links the final executable (optional) |
GenerateDsym(BuildTarget) |
dsymutil |
.dSYM bundle |
executable | Generates macOS debug symbols (optional) |
CompileGeneratedC(BuildTarget) |
C compiler | object file | generated-C LinkCore output |
Compiles a foreign library's payload |
ArchiveForeignLibrary(PackageId) |
archiver | static library | payload, C stub and runtime objects | Builds a native foreign library |
BuildCStub(PackageId, int) |
C compiler | object file | N/A | Builds a single C stub file |
ArchiveOrLinkCStub(PackageId) |
C compiler | archive file | BuildCStub outputs |
Collect C stub output |
BuildRuntimeObject(int) |
C compiler | object file | N/A | Builds one runtime translation unit |
BuildRuntimeLib |
archiver or C compiler | runtime library | runtime objects, release SIMDUTF objects | Collects the native runtime |
GenerateMbti(BuildTarget) |
mooninfo |
.mbti |
.mi |
Get text repr of .mi |
GenerateTestInfo(BuildTarget) |
moon generate-test-driver |
test driver, metadata | source files | Generate the test driver and metadata |
GenerateNodeTestPackageConfig(PackageId) |
moon tool generate-node-test-package-config |
package.json |
N/A | Create a type-neutral Node package boundary |
BuildVirtual(PackageId) |
moonc build-interface |
.mi |
.mbti |
Get interface from .mbti |
PackagePrebuildKey identifies custom actions by their manifest declaration
position because a valid command may have no output or the same outputs as
another command.
Whitebox tests are the more special kind of test within them. While source is just source code itself, and blackbox test is just another package depending on the source files, whitebox tests can see private definitions within the source files.
This requirement, in reality, is implemented with whitebox tests compiling with the regular source files, so it takes no further effort to reveal private defs. This whitebox-aided test replaces the original package's position within the original graph.
There might be import loops between whitebox tests and its test dependencies,
as we can already seen in moonbitlang/core.
(More practically, it's A(whitebox) -> B -> A(source),
so it's technically not a loop.
However, only one version of each package can be linked into the final executable,
so you will encounter a loop when linking.)
Such "loop"s should be accepted.
Practically, you may continue using the regular build graph with source and test targets separated. When performing Link-core of whitebox tests (no action is needed in other stages), replace the source node in the topo-sorted import list with the whitebox one. No other actions should be needed.
The following is an example build graph generated for whitebox test of A, written as A', with whitebox and regular build separated into different nodes:
graph BT;
A --> E
B --> A
C --> A
C --> D
A' -- regular--> E
A' -- test --> B
A' -- test --> C
A["A (Source)"]
A'["A' (A with whitebox test)"]
It should be topo-sorted when performing Link-core as if it was:
graph BT;
A' --> E
B --> A'
C --> A'
C --> D
An example resulting sort is: E, A', B, D, C.
Footnotes
-
The internal
SubPackagetarget kind is reserved for future work on dependency cycles. Package manifests no longer exposesub-packagedeclarations or import flags; these are ignored like other unknown fields. Source-subset selection and linking are not implemented. ↩