Prebuild tasks let a package generate source files (typically .mbt) from other assets before compilation, via declarative rules in moon.pkg.
- Scope: Applies only to packages in the input module being built. Third-party dependencies are expected to already contain their generated outputs.
- Package-level prebuild tasks are separate from the experimental module-level prebuild configuration script, which supplies build configuration such as native link flags.
The --moonbit-unstable-prebuild field names a script relative to the module
root. Supported extensions select the runner:
| Extension | Runner |
|---|---|
.js, .cjs, .mjs |
Node.js |
.py |
Python |
.mbtx |
Compiled to Wasm, then executed with Moonrun |
For example:
name = "username/project"
options(
"--moonbit-unstable-prebuild": "build.mbtx"
)Every runner uses the module root as its working directory and receives the captured process environment with these additional variables:
| Variable | Value |
|---|---|
MOON_MOD |
Absolute path to the module's selected moon.mod or moon.mod.json manifest |
MOON_BUILD_DIR |
Absolute path to this module's writable prebuild output directory |
MOON_HOST_OS |
OS of the Moon process: linux, macos, or windows |
MOON_HOST_ARCH |
Architecture of the Moon process, using names such as x86_64 and aarch64 |
MOON_BACKEND |
Resolved project backend: native or llvm |
MOON_PROFILE |
Effective project profile: debug or release |
MOON_JOBS |
Build job limit as a decimal integer, honoring -j / --jobs |
These variables override any inherited values of the same names. Scripts can
read their inputs entirely from the environment. For compatibility, stdin still
supplies the original JSON shape: env contains the captured environment before
these overrides, and paths contains module_root and out_dir. module_root
remains the module directory; out_dir now contains the real directory provided
as MOON_BUILD_DIR.
The stdin JSON input is deprecated and will be removed. Input modules (including
workspace members) receive a migration warning when their manifest declares a
prebuild script; dependency modules do not. --quiet suppresses this warning.
The notice applies to the protocol and does not detect whether a script reads
stdin. Read inputs from the environment instead: MOON_MOD identifies the
manifest, MOON_BUILD_DIR replaces paths.out_dir, and the working directory
is the module root. Stdout JSON remains the script's result protocol.
Host OS and architecture describe the Moon process's platform. Backend and profile describe the project build, even when the prebuild script itself is compiled to Wasm. They reflect effective command defaults, manifest preferences, and explicit CLI overrides.
When --jobs is omitted, prebuild scripts and the build executor share the same
available-parallelism observation, captured once per Moon process. If that
observation is unavailable, the limit defaults to one. MOON_JOBS is a build
concurrency limit, not a physical CPU count or a jobserver protocol.
MOON_MOD reports the manifest using the same preference as module discovery:
moon.mod takes precedence over moon.mod.json. It is supplied to prebuild
scripts as information, not read by Moon as a module-selection override.
MOON_WORK remains the workspace-selection switch.
Moon creates MOON_BUILD_DIR before running the script. It resides under the
caller's target directory (including --target-dir), scoped by backend, profile,
command, and module. Files persist across repeated builds in that scope; scripts
must not assume the directory is empty. Dependencies receive their own output
directories under the consumer's target directory, so generated files need not
be written into dependency sources. The directory's internal layout is not part
of the script API.
This MVP does not register files as build inputs merely because they are written
to MOON_BUILD_DIR or referenced in link_flags or link_search_paths.
Rewriting such a file at the same path may therefore fail to trigger relinking.
Explicit generated-file dependency declarations and rerun controls remain
future work for the experimental protocol.
For actual builds, moonbuild::compile::BuildSession acquires the target-directory
lock before planning runs these scripts and keeps it through build execution.
This protects script writes and any build actions that read their outputs from concurrent
invocations. For dry runs, each backend planning pass acquires the lock only
if it will execute a module-level prebuild script, and keeps it through planning.
Passes that skip the scripts do not acquire the lock, including native and LLVM
passes when no resolved module declares a script.
Stdout must contain one build configuration JSON value with the optional fields
vars, link_configs, and rerun_if; rerun_if currently has no effect. Stderr
carries script diagnostics. A failed script or invalid JSON output fails the
build. Moonbuild owns these script transport types privately. After validating
package names against the resolved project, it supplies RR with the link
configuration and module output types defined in moonbuild_rupes_recta::prebuild.
MoonBit scripts use standalone .mbtx imports and incremental compilation.
Their target is always linear-memory Wasm, independently of the project backend;
compiling the script therefore skips module-level prebuild configuration. The
prebuild implementation calls moonbuild's standalone Wasm builder directly,
without constructing CLI flags, and preserves the outer command's --frozen
setting. Moonrun executes the compiled artifact, using normal
runtime discovery (including MOONRUN_OVERRIDE). Build progress stays off stdout
to preserve the JSON protocol.
Script compilation uses a stable per-script directory under the caller's target
directory, including when --target-dir is supplied. Both compiler artifacts and
private .mooncakes dependencies live there, so compilation does not write into
the script's source directory. This also applies to scripts in registry
dependencies shared between consumers.
The ordinary embedded .mbtx policy applies. Policy
filesystem roots are relative to the script directory, while the working
directory remains the module root. An environment policy filters the script's
environment, including the variables above, but does not filter the values
explicitly supplied in the compatibility JSON input.
--moonbit-unstable-prebuild in moon.mod supplies dynamic native build
configuration, such as toolchain selection and compiler or linker flags. It runs
only for the Native and LLVM target backends. Wasm, WasmGC, and JS builds skip
it, including moon build --target wasm --release and dry runs. This applies
to both project and standalone-file builds, using the resolved target backend.
Each backend planning pass runs the scripts separately, with MOON_BACKEND
identifying that pass's backend.
moon check skips this configuration for the checked project on every backend.
Native and LLVM build dry runs run these scripts,
because their output is needed to construct build commands.
Unlike package-level pre-build / dev_build code generation, whose outputs
should be generated before distribution, this configuration depends on the
consumer's build environment. MOON_IGNORE_PREBUILD continues to control
package-level generation; it does not suppress native or LLVM module-level
configuration scripts.
Use rule to declare a reusable command and dev_build to supply its inputs
and outputs in moon.pkg:
rule(name: "generate", command: "generator $input > $output")
dev_build(rule: "generate", input: "input.ext", output: "output.mbt")Rules can also be declared in moon.mod, making them available to every
package in that module. A package-local rule takes precedence over a module
rule with the same name. Multiple rule and dev_build declarations are
allowed.
Each dev_build entry supplies its inputs and outputs and exactly one of
rule (a reusable rule's name) or command (a direct command). Supplying both
is an error. The same requirement applies to legacy pre-build entries,
including in JSON manifests.
For example, to select a rule:
rule(
name: "generate",
command: "...",
)
dev_build(
rule: "generate",
input: "path/to/input.ext",
output: "path/to/output.mbt",
)- input: string or array of strings; paths are relative to the package directory.
- output: string or array of strings; paths are relative to the package directory.
- command: a string that supports placeholder substitution (below).
Notes:
input/outputpaths are package-relative in config and expand to prebuild-cwd-relative paths inside the command.- When arrays are used, placeholders expand to space-separated lists in declaration order.
- During ordinary input-module builds that plan package prebuild, each planned action's declared outputs are tracked as build outputs.
- Outputs of actions in the current
PackagePrebuildPlango through the same File Interpretation as paths in the Package File Set..mbtbecomes a conditionally classified MoonBit source,.mbt.mdbecomes a blackbox input, and.mbtpbecomes a check/prove proof input. Other output extensions, including.mbland.mby, remain ordinary tracked files. A declaration alone does not make an absent output a plan input when package prebuild does not apply, such as for third-party dependencies. MOON_IGNORE_PREBUILDdisables applicable custom actions and does not add their declared outputs to File Interpretation. Generated files already present in the Package File Set remain ordinary compiler inputs.- A virtual package's expected
pkg.mbtior legacy contract path may be a planned prebuild output. Build planning selects the preferred available contract after package prebuild actions are known. Other output extensions remain ordinary tracked files and can be consumed by later prebuild actions through matching paths.
Moon no longer runs bundled moonlex or moonyacc automatically. A .mbl or
.mby file directly in a package directory must be declared as an input or
output of a custom rule / dev_build task (or legacy pre-build entry);
otherwise package discovery reports a migration error. Such declarations treat
these files as ordinary assets and do not schedule an implicit generator.
Declare the generator command and its .mbt output explicitly. This example
assumes my-lexer is available as a command:
rule(name: "lexer", command: "my-lexer $input -o $output")
dev_build(rule: "lexer", input: "lexer.mbl", output: "lexer.mbt")Use the equivalent rule for parser generation. Generated .mbt files must be
included when distributing the package, since consumers do not run its
package-level prebuild rules. Watch mode still observes .mbl and .mby changes
so adding or removing an unhandled file updates the diagnostic.
- Discovery, formatting, and build planning use one constructor for declared
input/outputpaths, resolving them against the canonical package root in the same representation as discovered package files. Dot components are resolved lexically across the complete path, including parent components that leave and reenter the package. Absolute declarations are external path inputs; on Windows their drive/UNC prefixes are converted to that same representation. Files need not exist yet. Drive letters use their parsed uppercase spelling even for already-verbatim inputs: n2 interns raw strings, so Rust path equality alone does not establish graph identity. Consumers compare complete constructed paths, so equivalent declarations also receive the same discovery checks and generated-file formatting exclusion. $input/$outputexpand to paths relative to the prebuild command working directory. These substituted paths are lexically normalized and start with./, for example./src/lib/input.txt.$pkg_dir/$mod_direxpand to absolute directories.
Only the command field is substituted. The following placeholders are recognized:
-
$input
Expands to a space-separated list of normalized prebuild-cwd-relative paths for all declared inputs (in order). Ifinputis a single string, this is one path. -
$output
Expands to a space-separated list of normalized prebuild-cwd-relative paths for all declared outputs (in order). Ifoutputis a single string, this is one path. -
$mod_dir
Expands to the absolute path of the module root directory (the directory containingmoon.mod). -
$pkg_dir
Expands to the absolute path of the current package directory (the directory containing thismoon.pkg).
Substitution semantics:
- Substitution is textual on every platform. Moon does not interpret command options or embedded script languages, so attached forms such as
-I$pkg_dir/includeretain their meaning. $inputand$outputexpand to./...paths relative to the prebuild command working directory; substitution does not add quotes.- Directory placeholders expand to absolute, platform-native strings. On Windows, short directory paths use their ordinary spelling without an unnecessary
\\?\prefix, allowing commands to append their own separators and..components.- If paths may contain spaces or shell-special characters, quote or escape them in the command template.
- For array
input/output, items are joined by a single space in insertion order. - Replacement text is not scanned for further placeholders. Unknown tokens are left as-is.
If the command starts with the exact prefix :embed , it denotes the built-in embed tool.
Conceptually this is equivalent to invoking the Moon tool embed subcommand with
the remaining arguments and substituted placeholders.
- Form:
:embed [FLAGS...] -i $input -o $output [--name IDENT] - Purpose: Generate output file(s) that embed the content of input file(s) as MoonBit code.
- Common flags:
--text: embed as escaped text literal(s).--binary: embed as binary byte sequence(s).--name NAME: set the generated identifier name in the produced code.
- Input/output arity:
- Typical usage is one input → one output. If arrays are used,
$input/$outputexpand to space-separated lists; interpretation of multiple paths is defined by the embed tool’s CLI.
- Typical usage is one input → one output. If arrays are used,
Behavior:
:embedis a syntactic alias; after substitution, it represents the same arguments a direct embed invocation would receive.- Moon lowers
:embeddirectly to structuredmoon tool embedarguments; it does not execute the built-in invocation through a shell. - The argument tail supports platform-native quoting and escaping, but not shell expansion, redirection, pipelines, or command lists. Use a custom prebuild command when platform-specific shell behavior is required.
- The generated outputs are consumed as package sources in the same build.
- During ordinary input-module builds, each backend-specific Build Plan owns a
separate
PackagePrebuildPlancontaining the requested custom actions. PackagePrebuildPlanowns package file-generation actions as a peer of theBackendPlan; it is not a separate semantic artifact model. Package prebuild is therefore never represented as a backend node with an inapplicable target kind.- There is no explicit edge between two prebuild tasks solely because one is
written earlier in
pre-build. Their concrete inputs and outputs form a dependency only when the paths match in the completed Execution Plan. - Build Target Projection includes generated
.mbt,.mbt.md,.mbtp, and selected virtual.mbtipaths in the same package file sets as discovered paths. These package files are not Build Artifacts. - All planned package prebuild actions remain part of normal execution. Declared outputs that no backend action consumes are leaf outputs of the n2 graph, so they are still requested and the invocation waits for them.
- Generated
.mbt/.mbt.md,.mbtp, and the selected virtual.mbtipath retain the meanings described above. Lowering records them as concrete input and output observations; matching paths recover the producer relationship without a parallel package-file identity. - Each backend-specific Execution Plan still contains one complete package prebuild action. When the command layer composes a multi-backend invocation, it shares those providers by identical physical outputs and complete execution behavior before constructing the invocation's single n2 graph.
- Module-level prebuild configuration scripts receive a snapshot of the process
environment captured by
moonbuild::compilebefore prebuild execution. - Commands that skip prebuild configuration do not capture this environment.
- The snapshot is passed to each module prebuild script through its environment and the compatibility stdin input; it is not rediscovered inside individual module execution. The module paths are added as environment variables after applying the snapshot.
When a task is scheduled, it is considered failed if any of the following holds after substitution and tool semantics:
- Any declared
inputpath does not exist. - Any declared
outputcannot be created or written by the invoked tool. - A built-in
:embedargument tail contains malformed native quoting or escaping. - The invoked tool fails to produce all declared outputs.
A command that exits unsuccessfully fails its prebuild action even if it emits
no output. In rendered and JSON modes, the error identifies the prebuild action,
package, and executed command; captured output is also retained. Raw mode
forwards the tool's output as its failure explanation, with an action error for
silent failures. moon check --json reports prebuild failures as Moon-level
error messages rather than compiler diagnostics. This also applies when a
prebuild command prints JSON matching the compiler diagnostic schema: its
output remains literal tool output, without compiler filtering or rewriting.
:embeddetection is prefix-based and requires the literal prefix:embed.- Substitution does not add quoting. Quote or escape placeholders inside
commandas required by the receiving program or shell. - Ordinary Windows paths are supported. Long paths in user-defined prebuild commands are not guaranteed: use a shallow checkout, or tools with suitable long-path support. Enabling the Windows long-path setting alone does not make every generator compatible. This limitation does not change Moon's responsibility to construct valid declared dependency paths and build artifact paths.
- Using arrays for
outputexpands to a space-separated list; ensure your tool’s CLI accepts the intended arity. - On Unix-like platforms, custom prebuild command strings are executed through
sh -c. - On Windows, custom prebuild command strings are passed directly to
CreateProcessW. - The
:embedshorthand is a standalone structured built-in invocation on every platform and does not use either custom-command path. Shell syntax in its argument tail is never evaluated. - On Unix-like platforms, if the first word of the command looks like a relative path, it is currently resolved against the module root directory.
- Windows (PowerShell):
On Windows only, if the first word of thecommand(before any spaces) corresponds to a.ps1file that exists in the module root directory, the command is rewritten to execute that script via PowerShell using its absolute path. Example: if the command isgenerate-assets $input $outputandgenerate-assets.ps1exists in the module root, the effective command becomespowershell <absolute-path-to-module-root>/generate-assets.ps1 $input $output. Detection examines the first word before placeholder substitution.
Text embedding:
rule(
name: "generate",
command: ":embed --text -i $input -o $output --name readme_text",
)
dev_build(
rule: "generate",
input: "assets/readme.txt",
output: "readme_text.mbt",
)Binary embedding:
rule(
name: "generate",
command: ":embed --binary -i $input -o $output --name logo_data",
)
dev_build(
rule: "generate",
input: "assets/logo.bin",
output: "logo_data.mbt",
)Multiple inputs (tool interprets list):
rule(
name: "generate",
command: ":embed --text -i $input -o $output --name all_texts",
)
dev_build(
rule: "generate",
input: ["assets/a.txt", "assets/b.txt"],
output: "all_texts.mbt",
)Location placeholders:
rule(
name: "generate",
command: "custom-tool --assets \"$pkg_dir/assets\" -i \"$input\" -o \"$output\"",
)
dev_build(
rule: "generate",
input: "assets/something.dat",
output: "something.mbt",
)