Moved to https://docs.moonbitlang.com/en/latest/toolchain/index.html
This page only retains the command-line documentation, backend build configuration, and the configuration JSON Schema.
Command-Line Help for moon
This document contains the help content for the moon command-line program.
Command Overview:
moon↴moon new↴moon build↴moon check↴moon fix↴moon prove↴moon run↴moon test↴moon testcli↴moon clean↴moon fmt↴moon doc↴moon explain↴moon info↴moon bench↴moon add↴moon remove↴moon install↴moon tree↴moon fetch↴moon run-postadd↴moon search↴moon view↴moon work↴moon work init↴moon work use↴moon work sync↴moon login↴moon whoami↴moon register↴moon publish↴moon package↴moon deprecate↴moon update↴moon coverage↴moon coverage analyze↴moon coverage report↴moon coverage clean↴moon generate-build-matrix↴moon upgrade↴moon shell-completion↴moon version↴
moon
Usage: moon <COMMAND>
Subcommands:
new— Create a new MoonBit modulebuild— Build the current packagecheck— Check the current package, but don’t build object filesfix— Apply compiler-proposed source fixes (experimental)prove— Prove the current packagerun— Run a main packagetest— Test the current packagetestcli— Run CLI tests with the current toolchain’s mooncramclean— Remove local build outputs or configured global cachesfmt— Format source codedoc— Generate documentation or searching documentation for a symbolexplain— Explain compiler diagnostics and language topicsinfo— Generate public interface (.mbti) files for all packages in the module or workspacebench— Run benchmarks in the current packageadd— Add a dependencyremove— Remove a dependencyinstall— Install a binary package globallytree— Display the dependency treefetch— Download a package to .repos directory (unstable)run-postadd— Explicitly run a legacy postadd script (temporary compatibility command)search— Search modules and package summaries in the registryview— View a registry module or a user’s published moduleswork— Workspace maintenance commandslogin— Log in to your accountwhoami— Show login status and usernameregister— Register an account at mooncakes.iopublish— Publish the current modulepackage— Package the current moduledeprecate— Deprecate or restore all existing versions of a published moduleupdate— Refresh registry metadata and report dependency updatescoverage— Code coverage utilitiesgenerate-build-matrix— Generate build matrix for benchmarking (legacy feature)upgrade— Upgrade toolchainsshell-completion— Generate shell completion for bash/elvish/fish/pwsh/zsh to stdoutversion— Print version information and exit
moon new
Create a new MoonBit module
Usage: moon new [OPTIONS] <PATH>
Arguments:
<PATH>— The path of the new project
Options:
--user <USER>— The username of the module. Default to the logged-in username--name <NAME>— The name of the module. Default to the last part of the path
moon build
Build the current package
A successful build also lists each executable and foreign library it built on stdout, with its package, target backend and absolute path. --quiet does not hide the list. With --output-json, each one is an artifact JSON message instead.
Usage: moon build [OPTIONS] [PATH]...
Arguments:
<PATH>— Paths to the packages that should be built, or one standalone.mbtxfile
Options:
-
-g,--debug— Emit debug information -
--release— Compile in release mode -
--strip— Enable stripping debug information -
--no-strip— Disable stripping debug information -
--target <TARGET>— Select output targetPossible values:
wasm,wasm-gc,js,native,llvm,all -
--enable-coverage— Enable coverage instrumentation -
--sort-input— Sort input files -
--output-wat— Output WAT instead of WASM -
-d,--deny-warn— Treat all warnings as errors -
--no-render— Don’t render diagnostics (in raw human-readable format) -
--output-json— Output diagnostics in JSON format -
--warn-list <WARN_LIST>— Warn list config -
-j,--jobs <JOBS>— Set the max number of jobs to run in parallel -
--render-no-loc <MIN_LEVEL>— Render no-location diagnostics starting from a certain levelDefault value:
errorPossible values:
info,warn,error -
--diagnostic-limit <N>— Limit the number of rendered diagnostics -
--frozen— Do not sync dependencies, assuming local dependencies are up-to-date -
-w,--watch— Monitor the file system and automatically build artifacts
moon check
Check the current package, but don’t build object files
A successful check also updates pkg.generated.mbti of the checked local packages whose preferred backend is checked, as moon info does. Pass --no-mbti to skip this.
Usage: moon check [OPTIONS] [PATH]...
Arguments:
<PATH>— Filesystem path to a package directory,.mbt/.mbt.mdselector, or standalone.mbtxfile
Options:
-
-g,--debug— Emit debug information -
--release— Compile in release mode -
--strip— Enable stripping debug information -
--no-strip— Disable stripping debug information -
--target <TARGET>— Select output targetPossible values:
wasm,wasm-gc,js,native,llvm,all -
--enable-coverage— Enable coverage instrumentation -
--sort-input— Sort input files -
--output-wat— Output WAT instead of WASM -
-d,--deny-warn— Treat all warnings as errors -
--no-render— Don’t render diagnostics (in raw human-readable format) -
--output-json— Output diagnostics in JSON format -
--warn-list <WARN_LIST>— Warn list config -
-j,--jobs <JOBS>— Set the max number of jobs to run in parallel -
--render-no-loc <MIN_LEVEL>— Render no-location diagnostics starting from a certain levelDefault value:
errorPossible values:
info,warn,error -
--diagnostic-limit <N>— Limit the number of rendered diagnostics -
--frozen— Do not sync dependencies, assuming local dependencies are up-to-date -
-w,--watch— Monitor the file system and automatically check files -
--patch-file <PATCH_FILE>— The patch file to check. Only valid when the selector resolves to a single package -
--explain— Whether to explain the error code with details -
--fmt— Check whether the code is properly formatted -
--json— Output one complete JSON result to stdout -
--no-mbti— Do not updatepkg.generated.mbtifiles of the checked packages
moon fix
Apply compiler-proposed source fixes (experimental)
Runs the same check as moon check and applies the fixes attached to its diagnostics, but only those that still match the files and pass the fix checks; any other fix is skipped as a whole. A fix is applied only if every target backend that compiles its file proposes it. Pass --verbose to see why a fix was skipped.
Files select only themselves; directories select their package. Declared prebuild outputs and file symlinks are excluded. Writes are atomic per file; a failed run may retain files changed earlier. Exit 0 means the fix workflow completed, even if compiler diagnostics remain. At most four rounds write files, followed by a check of the final contents.
Usage: moon fix [OPTIONS] [PATH]...
Arguments:
<PATH>— Package directory or source file to fix (file paths restrict edits to that file)
Options:
-
--target <TARGET>— Select the target backends to checkPossible values:
wasm,wasm-gc,js,native,llvm,all -
--warn-list <WARN_LIST>— Warn list config (pending deprecation warnings are enabled by default) -
-j,--jobs <JOBS>— Set the max number of jobs to run in parallel -
--frozen— Do not sync dependencies, assuming local dependencies are up-to-date -
--diff— Preview only the first round as a unified diff; later rounds may propose further changes
moon prove
Prove the current package
Set MOON_PROVE_PRELUDE_OVERRIDE to a directory containing moonbit_builtin_prelude.mlw to replace the toolchain’s proof prelude.
Usage: moon prove [OPTIONS] [PATH]
Arguments:
<PATH>— The file-system path to the package or file in package to prove
Options:
-
--why3-config <PATH>— Use a user-supplied Why3 configuration file instead of the generated default -
--frozen— Do not sync dependencies, assuming local dependencies are up-to-date -
-d,--deny-warn— Treat all warnings as errors -
--no-render— Don’t render diagnostics (in raw human-readable format) -
--output-json— Output diagnostics in JSON format -
--warn-list <WARN_LIST>— Warn list config -
-j,--jobs <JOBS>— Set the max number of jobs to run in parallel -
--render-no-loc <MIN_LEVEL>— Render no-location diagnostics starting from a certain levelDefault value:
errorPossible values:
info,warn,error -
--diagnostic-limit <N>— Limit the number of rendered diagnostics
moon run
Run a main package
Usage: moon run [OPTIONS] <PACKAGE_OR_MBT_FILE|-e <SCRIPT>> [ARGS]...
Arguments:
<PACKAGE_OR_MBT_FILE>— The package, .mbt/.mbtx file, or-to read.mbtxsource from stdin<ARGS>— The arguments provided to the program to be run
Options:
-
-e <SCRIPT>— Run.mbtxsource passed in as a string -
-g,--debug— Emit debug information -
--release— Compile in release mode -
--strip— Enable stripping debug information -
--no-strip— Disable stripping debug information -
--target <TARGET>— Select output targetPossible values:
wasm,wasm-gc,js,native,llvm,all -
--enable-coverage— Enable coverage instrumentation -
--sort-input— Sort input files -
--output-wat— Output WAT instead of WASM -
-d,--deny-warn— Treat all warnings as errors -
--no-render— Don’t render diagnostics (in raw human-readable format) -
--output-json— Output diagnostics in JSON format -
--warn-list <WARN_LIST>— Warn list config -
-j,--jobs <JOBS>— Set the max number of jobs to run in parallel -
--render-no-loc <MIN_LEVEL>— Render no-location diagnostics starting from a certain levelDefault value:
errorPossible values:
info,warn,error -
--diagnostic-limit <N>— Limit the number of rendered diagnostics -
--wasm-policy <PATH>— Pass a moonrun JSON policy file to Wasm backends; ignored by other backends -
--frozen— Do not sync dependencies, assuming local dependencies are up-to-date -
--build-only— Only build, do not run the code -
--profile— Profile the native executable using Time Profiler on macOS or perf on Linux
moon test
Test the current package
Test executables run in parallel using the available CPU count by default. Use -j N to set the maximum number of concurrent executables, or --no-parallelize to run them sequentially without limiting build parallelism.
Usage: moon test [OPTIONS] [PATH]...
Arguments:
-
<PATH>— Run tests for package directories, files inside packages, or one standalone.mbtxscript.An explicit
.mbtxpath tests only that script, even inside a project. The script must definefn main, but tests use a generated entrypoint and do not execute the script’s main. Package-wide testing excludes.mbtxscripts. Outside a project, a single.mbtor.mbt.mdfile can also be tested.
Options:
-
-g,--debug— Emit debug information -
--release— Compile in release mode -
--strip— Enable stripping debug information -
--no-strip— Disable stripping debug information -
--target <TARGET>— Select output targetPossible values:
wasm,wasm-gc,js,native,llvm,all -
--enable-coverage— Enable coverage instrumentation -
--sort-input— Sort input files -
--output-wat— Output WAT instead of WASM -
-d,--deny-warn— Treat all warnings as errors -
--no-render— Don’t render diagnostics (in raw human-readable format) -
--output-json— Output diagnostics in JSON format -
--warn-list <WARN_LIST>— Warn list config -
-j,--jobs <JOBS>— Set the max number of jobs to run in parallel -
--render-no-loc <MIN_LEVEL>— Render no-location diagnostics starting from a certain levelDefault value:
errorPossible values:
info,warn,error -
--diagnostic-limit <N>— Limit the number of rendered diagnostics -
--wasm-policy <PATH>— Pass a moonrun JSON policy file to Wasm backends; ignored by other backends -
-p,--package <PACKAGE>— Run test in the specified package -
-i,--index <INDEX>— Run only the index-th test in the file. Accepts a single index or a left-inclusive right-exclusive range like0-2. Only valid when a single file is selected. Implies--include-skipped -
--doc-index <DOC_INDEX>— Run only the index-th doc test in the file. Only valid when a single file is selected. Implies--include-skipped -
-u,--update— Update the test snapshot -
-l,--limit <LIMIT>— Limit of expect test update passes to run, in order to avoid infinite loopsDefault value:
256 -
--frozen— Do not sync dependencies, assuming local dependencies are up-to-date -
--build-only— Only build, do not run the tests -
--profile— Profile native test executables using Time Profiler on macOS or perf on Linux -
--no-parallelize— Run the tests in a target backend sequentially -
--outline— Print the outline of tests to be executed and exit -
--test-failure-json— Print failure message in JSON format -
--patch-file <PATCH_FILE>— Path to the patch file -
--include-skipped— Include skipped tests. Automatically implied when--[doc-]indexis set -
-f,--filter <FILTER>— Run only tests whose name matches the given glob pattern. Supports ‘*’ (matches any sequence) and ‘?’ (matches any single character)
moon testcli
Run CLI tests with the current toolchain’s mooncram
Executes moonrun <toolchain>/bin/mooncram.wasm -- [ARGS]... without loading a MoonBit project. All arguments after testcli, including --help, --version, and --, are forwarded unchanged.
Uses the current toolchain, including MOON_TOOLCHAIN_ROOT and MOONRUN_OVERRIDE. Moon options such as -C must appear before testcli; --trace is not supported before this command.
Usage: moon testcli [ARGS]...
Arguments:
<ARGS>— Arguments forwarded to mooncram
moon clean
Remove local build outputs or configured global caches
Usage: moon clean [OPTIONS]
Options:
--dep-cache— Remove the global dependency-source cache instead of_build--build-cache— Remove the global build-artifact cache instead of_build--registry-cache— Remove cached HTTP registry metadata instead of_build. Uses MOON_REGISTRY_CACHE when set; leaves the Git index, source archives, and credentials intact. This also works outside a project
moon fmt
Format source code
Usage: moon fmt [OPTIONS] [PATH]... [-- <ARGS>...]
Arguments:
-
<PATH>— Paths to packages, files selecting their containing package, or standalone.mbtxscriptsAn explicit
.mbtxpath formats only that script, with or without a surrounding project. Multiple scripts and package paths can be combined. Without paths, standalone scripts are excluded from package formatting.--checkfails if a selected script needs formatting. -
<ARGS>— Extra arguments passed to the formatter (after –)
Options:
--check— Check only and don’t change the source code--sort-input— Sort input files--warn— Warn if code is not properly formatted
moon doc
Generate documentation or searching documentation for a symbol
Usage: moon doc [OPTIONS] [SYMBOL]
Arguments:
<SYMBOL>— [Deprecated] The symbol to query documentation for. Usemoon ide doc <SYMBOL>instead.
Options:
-
--serve— Start a web server to serve the documentation -
-b,--bind <BIND>— The address of the serverDefault value:
127.0.0.1 -
-p,--port <PORT>— The port of the serverDefault value:
3000 -
--frozen— Do not sync dependencies, assuming local dependencies are up-to-date
moon explain
Explain compiler diagnostics and language topics
Usage: moon explain <--diagnostic [<ID_OR_NAME>]|--attribute [<NAME>]>
Resources: Docs: https://docs.moonbitlang.com Skills: https://github.com/moonbitlang/skills
Use `moon explain --diagnostic` to list diagnostic codes and names.
Use `moon explain --attribute` to list attributes.
Options:
--diagnostic <ID_OR_NAME>— Explain diagnostics. Without a query, list diagnostic codes and names--attribute <NAME>— Explain attributes. Without a query, list attribute names
moon info
Generate public interface (.mbti) files for all packages in the module or workspace
By default, moon info writes pkg.generated.mbti from each selected package’s canonical backend: module preferred-backend, then workspace preferred-backend, then wasm.
--target inspects backend-specific interfaces and reports differences, but does not change which backend is written to pkg.generated.mbti.
Usage: moon info [OPTIONS] [PATH]...
Arguments:
-
<PATH>— The file-system path to the package or file in package to emitmbtifiles forConflicts with
--package.
Options:
-
--frozen— Do not sync dependencies, assuming local dependencies are up-to-date -
--target <TARGET>— Inspect one or more target backends without changing the canonicalpkg.generated.mbtioutputPossible values:
wasm,wasm-gc,js,native,llvm,all -
-p,--package <PACKAGE>— The full or subset of name of the package to emitmbtifiles for
moon bench
Run benchmarks in the current package
Usage: moon bench [OPTIONS] [PATH]...
Arguments:
<PATH>— Run benchmarks for a filesystem path.PATHmay point to a package directory or a file inside a package
Options:
-
-g,--debug— Emit debug information -
--release— Compile in release mode -
--strip— Enable stripping debug information -
--no-strip— Disable stripping debug information -
--target <TARGET>— Select output targetPossible values:
wasm,wasm-gc,js,native,llvm,all -
--enable-coverage— Enable coverage instrumentation -
--sort-input— Sort input files -
--output-wat— Output WAT instead of WASM -
-d,--deny-warn— Treat all warnings as errors -
--no-render— Don’t render diagnostics (in raw human-readable format) -
--output-json— Output diagnostics in JSON format -
--warn-list <WARN_LIST>— Warn list config -
-j,--jobs <JOBS>— Set the max number of jobs to run in parallel -
--render-no-loc <MIN_LEVEL>— Render no-location diagnostics starting from a certain levelDefault value:
errorPossible values:
info,warn,error -
--diagnostic-limit <N>— Limit the number of rendered diagnostics -
-p,--package <PACKAGE>— Run benchmarks in the specified package -
-f,--file <FILE>— Run benchmarks in the specified file. Only valid when--packageis also specified -
-i,--index <INDEX>— Run only the index-th benchmark in the file. Accepts a single index or a left-inclusive right-exclusive range like0-2. Only valid when a single file is selected -
--frozen— Do not sync dependencies, assuming local dependencies are up-to-date -
--build-only— Only build, do not bench -
--no-parallelize— Run the benchmarks in a target backend sequentially
moon add
Add a dependency
Usage: moon add [OPTIONS] <MODULE>
Arguments:
<MODULE>— The registry module name to add
Options:
-u,--upgrade— Allow changing the version of an existing dependency--no-update— Do not refresh registry metadata before adding the dependency
moon remove
Remove a dependency
Usage: moon remove <MODULE>
Arguments:
<MODULE>— The registry module name to remove
moon install
Install a binary package globally
Usage: moon install [OPTIONS] [SOURCE] [PATH_IN_REPO]
Examples: moon install user/module/pkg moon install user/module/cmd/… moon install ./cmd/tool moon install ./cmd/… moon install https://github.com/owner/repo/tree/0123456789abcdef0123456789abcdef01234567/cmd/tool moon install https://github.com/owner/repo.git cmd/tool –branch main moon install https://github.com/owner/repo.git cmd/… –tag v1.0.0
Paste a public GitHub directory permalink containing a full 40-character commit SHA to install from its source archive. For branches or tags, use the repository URL, PATH_IN_REPO, and –branch or –tag instead.
Arguments:
-
<SOURCE>— Install source.Interpretation order:
- local path (
./,../,/, Windows drive) - git URL
- registry package path (
user/module/pkg[@version])
Use
/...suffix to install all matching main packages. - local path (
-
<PATH_IN_REPO>— Filesystem path inside the repository source. Used only when SOURCE is a git URL.Use
/...suffix to install all matching main packages under this path prefix.
Options:
--bin <DIR>— Specify installation directory (default: ~/.moon/bin/)--path <PATH>— Install from local path instead of registry--rev <REV>— Git revision to checkout (commit hash, requires git URL)--branch <BRANCH>— Git branch to checkout (requires git URL)--tag <TAG>— Git tag to checkout (requires git URL)
moon tree
Display the dependency tree
Text output expands each dependency once per root. When another path reaches a dependency whose children were already displayed, the dependency remains visible with (*), but its children are omitted. Use --no-dedupe to repeat those subgraphs. Cycles remain marked as (cycle). JSON output represents shared dependencies once and preserves their relationships as edges.
Usage: moon tree [OPTIONS]
Options:
-
--json— Output one complete JSON result to stdout -
--no-dedupe— Repeat dependency subgraphs instead of marking them with(*) -
--package— Show the package-level dependency graph instead of the module-level treeText output expands source imports from every package in the selected module. With
--json, the result contains every non-standard-library package in the resolved project, all import target kinds, and the selected module’s packages inroot. -
--target <TARGET>— Select the backend for the package dependency graphDefaults to the selected module’s preferred target, then wasm. JSON output records the selected backend in
target; all edges belong to it.Possible values:
wasm,wasm-gc,js,native,llvm
moon fetch
Download a package to .repos directory (unstable)
Note: This is an unstable command and may change or be removed in future versions.
Usage: moon fetch [OPTIONS] <MODULE[@VERSION]>
Arguments:
<MODULE[@VERSION]>— The registry module name to fetch in the form of/<module_name>[@ ]
Options:
--no-update— Do not refresh registry metadata before fetching
moon run-postadd
Explicitly run a legacy postadd script (temporary compatibility command)
Dependencies no longer run postadd automatically. This command runs only the selected module’s script, every time it is invoked. It does not download or reinstall sources. Without MODULE, use the current module, including sources selected with moon -C <directory> run-postadd.
Postadd is being retired. If you still need it, please open an issue at https://github.com/moonbitlang/moon/issues describing your use case.
Usage: moon run-postadd [MODULE]
Arguments:
<MODULE>— Installed dependency module name, without a version (defaults to the current module)
moon search
Search modules and package summaries in the registry
Results follow the registry’s ranking, as on mooncakes.io (most downloaded first). Each module includes its version, description, download count, repository link, and matching package excerpts when available. Summaries from older versions are labeled, and a count indicates when only some matching packages are shown.
With –json, the result also preserves the registry’s summary fragments and match markers. Registries without package summaries remain supported.
Usage: moon search [OPTIONS] <KEYWORD>
Arguments:
<KEYWORD>— The keyword to search for
Options:
-
-l,--limit <LIMIT>— Limit the number of search resultsDefault value:
20 -
--json— Print search results as JSON
moon view
View a registry module or a user’s published modules
moon view <username/module[@version]> shows live registry metadata for the latest release or an exact version. Add –versions to list every release, newest first, including deprecated versions and their reasons.
moon view <username> lists all modules on that user’s public registry profile, sorted by name, with their latest versions and deprecation reasons. No login is required. Use moon view --my as a shortcut for your saved username after running moon login.
These commands work outside a project and respect the configured registry. With –json, a versioned report contains a result (module metadata, an array of releases for –versions, or a user profile), status, and messages.
Usage: moon view [OPTIONS] [USER_OR_MODULE]
Arguments:
<USER_OR_MODULE>— Username to list, or username/module[@version] to inspect
Options:
--my— List all modules published under your logged-in username--versions— List all published versions of the module--json— Print the result as JSON
moon work
Workspace maintenance commands
Usage: moon work <COMMAND>
Subcommands:
init— Create a workspace manifestuse— Add modules to the workspace manifestsync— Sync workspace dependency versions into member manifests
moon work init
Create a workspace manifest
Usage: moon work init [PATHS]...
Arguments:
<PATHS>— Module directories to add to the workspace
moon work use
Add modules to the workspace manifest
Usage: moon work use <PATHS>...
Arguments:
<PATHS>— Module directories to add to the workspace
moon work sync
Sync workspace dependency versions into member manifests
Usage: moon work sync
moon login
Log in to your account
Usage: moon login
moon whoami
Show login status and username
Usage: moon whoami
moon register
Register an account at mooncakes.io
Usage: moon register
moon publish
Publish the current module
The optional private field in moon.mod requests restricted access to the module after publication when true. Omission or false requests public visibility.
Publication permissions and visibility are checked by the registry. With –dry-run, validate the publication without creating a release.
Usage: moon publish [OPTIONS]
Options:
--frozen— Do not sync dependencies, assuming local dependencies are up-to-date
moon package
Package the current module
Usage: moon package [OPTIONS]
Options:
--frozen— Do not sync dependencies, assuming local dependencies are up-to-date--list
moon deprecate
Deprecate or restore all existing versions of a published module
Pass --reason <REASON> to deprecate or --undo to restore.
Specify the full module name without a version selector. This command works outside a project and uses the same saved credentials as moon publish. Versions published later start undeprecated. Restoring clears all reasons; it does not recover previous per-version states.
Deprecation does not affect version selection. Commands that resolve dependencies warn about every selected deprecated module, including transitive dependencies, using the local registry index without refreshing it. --quiet hides these warnings.
With --dry-run, fetch the module’s currently published versions and print the intended change for each release without modifying the registry. The preview uses optional API-bound credentials for the read-only lookup.
Usage: moon deprecate [OPTIONS] <MODULE>
Arguments:
<MODULE>— Full module name, without a version selector
Options:
--reason <REASON>— Deprecation reason, replacing any previous reasons--undo— Clear deprecation and reasons on all existing versions
moon update
Refresh registry metadata and report dependency updates
With MOON_REGISTRY_API=1, refresh the selected module or workspace’s exact dependency versions and query each module’s current latest version. Report available updates and deprecation status without changing declarations, downloading sources, or running build hooks. Partial refresh failures return a nonzero exit status; successful refreshes remain cached.
Otherwise, synchronize the Git registry index and symbols as before. This mode also works outside a project.
Usage: moon update
moon coverage
Code coverage utilities
Runs the toolchain’s bin/moon_cove.wasm through moonrun.
Usage: moon coverage <COMMAND>
Subcommands:
analyze— Run test with instrumentation and report coveragereport— Generate code coverage reportclean— Clean up coverage artifacts
moon coverage analyze
Run test with instrumentation and report coverage
Usage: moon coverage analyze [OPTIONS] [-- <EXTRA_FLAGS>...]
Arguments:
<EXTRA_FLAGS>— Extra flags passed directly tomoon_cove
Options:
-p,--package <PACKAGE>— Analyze coverage for a specific package
moon coverage report
Generate code coverage report
Usage: moon coverage report [args]... [COMMAND]
Arguments:
<args>— Arguments to pass to the coverage utility
Options:
-h,--help— Show help for the coverage utility
moon coverage clean
Clean up coverage artifacts
Usage: moon coverage clean
moon generate-build-matrix
Generate build matrix for benchmarking (legacy feature)
Usage: moon generate-build-matrix [OPTIONS] --output-dir <OUT_DIR>
Options:
-n <NUMBER>— Set all ofdrow,dcol,mrow,mcolto the same value--drow <DIR_ROWS>— Number of directory rows--dcol <DIR_COLS>— Number of directory columns--mrow <MOD_ROWS>— Number of module rows--mcol <MOD_COLS>— Number of module columns-o,--output-dir <OUT_DIR>— The output directory
moon upgrade
Upgrade toolchains
Usage: moon upgrade [OPTIONS]
Options:
-f,--force— Force upgrade--dev— Install the latest development version
moon shell-completion
Generate shell completion for bash/elvish/fish/pwsh/zsh to stdout
Usage: moon shell-completion [OPTIONS]
Discussion:
Enable tab completion for Bash, Elvish, Fish, Zsh, or PowerShell
The script is output on stdout, allowing one to re-direct the
output to the file of their choosing. Where you place the file
will depend on which shell, and which operating system you are
using. Your particular configuration may also determine where
these scripts need to be placed.
The completion scripts won’t update itself, so you may need to
periodically run this command to get the latest completions.
Or you may put eval "$(moon shell-completion --shell <SHELL>)"
in your shell’s rc file to always load newest completions on startup.
Although it’s considered not as efficient as having the completions
script installed.
Here are some common set ups for the three supported shells under Unix and similar operating systems (such as GNU/Linux).
Bash:
Completion files are commonly stored in /etc/bash_completion.d/ for
system-wide commands, but can be stored in
~/.local/share/bash-completion/completions for user-specific commands.
Run the command:
$ mkdir -p ~/.local/share/bash-completion/completions
$ moon shell-completion --shell bash >> ~/.local/share/bash-completion/completions/moon
This installs the completion script. You may have to log out and log back in to your shell session for the changes to take effect.
Bash (macOS/Homebrew):
Homebrew stores bash completion files within the Homebrew directory.
With the bash-completion brew formula installed, run the command:
$ mkdir -p $(brew --prefix)/etc/bash_completion.d
$ moon shell-completion --shell bash > $(brew --prefix)/etc/bash_completion.d/moon.bash-completion
Fish:
Fish completion files are commonly stored in
$HOME/.config/fish/completions. Run the command:
$ mkdir -p ~/.config/fish/completions
$ moon shell-completion --shell fish > ~/.config/fish/completions/moon.fish
This installs the completion script. You may have to log out and log back in to your shell session for the changes to take effect.
Elvish:
Elvish completions are commonly stored in a single completers module.
A typical module search path is ~/.config/elvish/lib, and
running the command:
$ moon shell-completion --shell elvish >> ~/.config/elvish/lib/completers.elv
will install the completions script. Note that use >> (append)
instead of > (overwrite) to prevent overwriting the existing completions
for other commands. Then prepend your rc.elv with:
`use completers`
to load the completers module and enable completions.
Zsh:
ZSH completions are commonly stored in any directory listed in
your $fpath variable. To use these completions, you must either
add the generated script to one of those directories, or add your
own to this list.
Adding a custom directory is often the safest bet if you are
unsure of which directory to use. First create the directory; for
this example we’ll create a hidden directory inside our $HOME
directory:
$ mkdir ~/.zfunc
Then add the following lines to your .zshrc just before
compinit:
fpath+=~/.zfunc
Now you can install the completions script using the following command:
$ moon shell-completion --shell zsh > ~/.zfunc/_moon
You must then open a new zsh session, or simply run
$ . ~/.zshrc
for the new completions to take effect.
Custom locations:
Alternatively, you could save these files to the place of your
choosing, such as a custom directory inside your $HOME. Doing so
will require you to add the proper directives, such as sourceing
inside your login script. Consult your shells documentation for
how to add such directives.
PowerShell:
The powershell completion scripts require PowerShell v5.0+ (which comes with Windows 10, but can be downloaded separately for windows 7 or 8.1).
First, check if a profile has already been set
PS C:\> Test-Path $profile
If the above command returns False run the following
PS C:\> New-Item -path $profile -type file -force
Now open the file provided by $profile (if you used the
New-Item command it will be
${env:USERPROFILE}\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
Next, we either save the completions file into our profile, or into a separate file and source it inside our profile. To save the completions into our profile simply use
PS C:\> moon shell-completion --shell powershell >>
${env:USERPROFILE}\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
This discussion is taken from rustup completions command with some changes.
Options:
-
--shell <SHELL>— The shell to generate completion forDefault value:
<your shell>Possible values:
bash,elvish,fish,powershell,zsh
moon version
Print version information and exit
Usage: moon version [OPTIONS]
Options:
--all— Print all version information--json— Print version information in JSON format--no-path— Do not print the path
This document was generated automatically by
clap-markdown.
Package configuration
moon.pkg supports direct declarations for the following package settings.
Each example is an independent setting.
| Declaration | Meaning |
|---|---|
experimental = true | Mark the package as experimental and warn its direct importers. Defaults to false. |
proof_enabled = true | Enable proof workflows for the package. Defaults to false. |
max_concurrent_tests = 4 | Set test concurrency using an unsigned 32-bit integer. |
regex_backend = "table" | Select auto, block, table, or runtime for regex compilation. |
virtual(has_default: true) | Declare a virtual package with a default implementation; use false when it has no default. |
virtual(implement: "user/module/interface") | Implement the given virtual package. |
These declarations preserve the behavior of the corresponding legacy fields in
options(...). Legacy spellings remain accepted there, including proof-enabled,
max-concurrent-tests, regex-backend, and the underscore aliases. Inside
options(...), virtual_pkg is also accepted as a legacy alias of virtual, and
implement corresponds to virtual(implement: ...).
A package declares virtual(...) at most once: it either is a virtual package or
implements one, so has_default and implement cannot be combined.
Declare each setting only once, either directly or in options(...). For
example, do not combine proof_enabled = true with
options("proof-enabled": true): this is an error even when the values agree.
The same rule applies to warnings and warn-list / warn_list,
supported_targets and supported-targets, and dev_build and
pre-build / pre_build. Settings are not merged or overridden between forms.
Multiple import blocks of the same kind still combine in source order, but
cannot be combined with an options(...) import field of that kind. Empty
blocks and empty option lists also count as declarations. Regular, test, and
whitebox imports are independent. Multiple rule and dev_build declarations
remain supported; rule names must be unique.
Each dev_build or legacy pre-build entry must specify exactly one of
command or rule. Supplying both is an error, including in JSON manifests.
In moon.mod, declare each module dependency only once. Repeated module names
in import, or between import and options(deps: ...), are errors even when
the versions agree. Distinct dependencies from the two forms are combined.
Other settings, including overrides, structured
link, native-stub, and per-file targets, still belong in options(...).
These declarations require matching compiler support. Compilers that do not
recognize them report Invalid configuration (E4192); use the legacy
options(...) form with those toolchains. Formatting and JSON-to-DSL migration
are provided by the toolchain’s moonfmt. Older formatter versions may rewrite
direct declarations into their equivalent options(...) form.
Configuration diagnostics
Unknown keys in options(...), JSON manifests, and nested settings produce
warnings. For example, link.native.cc_link_flags warns because the accepted
spelling is cc-link-flags. Warnings do not stop the command and are suppressed
by --quiet; unknown-key warnings in dependencies are suppressed by default.
This applies to both module and package configuration.
The removed module field checksum and package fields bin-name / bin-target
follow this unknown-key policy. Module fields include and exclude are errors
in the current project and workspace members, including empty values, because
ignoring old file filters could package unintended files. Move those filters to
.gitignore or .moonignore; .moonignore overrides .gitignore in the same
directory. These obsolete filters are ignored in dependencies.
The removed package field name follows this unknown-key policy, including
name: "main". Use pkgtype(kind: "executable") to declare an executable.
Module scripts recognizes only the legacy postadd entry for explicit
moon run-postadd execution. Other names, such as prebuild and postbuild,
warn as unknown keys; they do not register build hooks.
In moon.mod, declaring both spellings of warnings / warn-list,
preferred_target / preferred-target, or supported_targets /
supported-targets is an error. This also applies when the values agree or are
empty, or both spellings occur in options(...).
Known fields with incorrect types are errors, including in dependencies and
with --quiet. For example, warnings = 123 is invalid: warnings requires a
string. Compiler-consumed settings such as options("alert-list": "+all")
and the boolean link.wasm-gc.use-ffi-bytes are also recognized and type-checked
by Moon.
Deprecated package settings also warn in the current project and workspace
members, with dependency warnings suppressed. Replace is-main: true with
pkgtype(kind: "executable"), and boolean link: true on a library with
pkgtype(kind: "foreign_library"). Remove false flags and boolean link on
executable packages. Structured link remains backend configuration.
link.*.exports is deprecated in favor of source-level #export_name attributes;
empty export lists also warn. Declare pkgtype(kind: "foreign_library") when
producing a library artifact for a foreign host. These legacy fields are
scheduled for removal.
Module prebuild scripts receive an additional migration notice: their legacy
stdin JSON input will be removed. Read MOON_MOD, MOON_BUILD_DIR, and the other
MOON_* environment variables instead. Stdout JSON remains the result protocol.
This notice is shown for input modules only, even if the current backend does
not run the script; it does not detect stdin reads. --quiet suppresses all
these deprecation warnings.
Experimental packages
Declare experimental = true at the top level of a package’s moon.pkg to
warn packages that directly depend on it. This includes ordinary, whitebox-test,
and blackbox-test imports. Only imports enabled for a requested backend are
checked. Each importing package receives one warning per experimental dependency,
even when several test targets or backends use it. The warning does not make the
command fail, and --quiet suppresses it.
MoonBuild owns this check. Because the compiler also reads moon.pkg, compiling
with this declaration requires a compiler whose manifest parser accepts
experimental; older parsers may report Invalid configuration (E4192).
In the importing package’s moon.pkg, acknowledge specific dependencies by their
full package names:
import { "user/library/unstable" }
options("allow-experimental-packages": ["user/library/unstable"])
Set options("allow-experimental-packages": true) to acknowledge all experimental
dependencies. false, an empty list, or omitting the option acknowledges none.
List entries match full package names exactly, rather than aliases or prefixes.
The option applies only to that package’s direct dependencies; it does not
propagate to other packages. A stable wrapper around an experimental package does
not itself become experimental.
Legacy moon.pkg.json accepts "experimental": true and
"allow-experimental-packages": true (or a string list) as top-level fields.
Lexer and parser generation
Moon no longer automatically runs moonlex or moonyacc for .mbl or .mby
files. Declare an explicit custom rule that produces .mbt files instead. For
example, if 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")
A .mbl or .mby file directly in a package directory must appear in a custom
rule’s declared inputs or outputs (legacy pre-build entries also work).
Otherwise Moon reports a migration error. Include generated .mbt files when
publishing: dependency consumers do not run package prebuild rules.
Conditional imports
Compiling and formatting this syntax also requires a compiler and formatter that support conditional import blocks.
Use #cfg in moon.pkg to select imports for a backend:
#cfg(target = "native")
import {
"example/platform/native" @platform,
}
#cfg(not(target = "native"))
import {
"example/platform/portable" @platform,
}
Both implementations can use the same alias because only one import is active for each backend. Unannotated import blocks apply to every backend.
Supported targets are wasm, wasm-gc, js, native, and llvm. Combine
conditions with all(...), any(...), and not(...), or use true and
false. For example, #cfg(any(target = "native", target = "js")) selects
Native and JavaScript. Conditions also apply to import blocks ending in
for "test" or for "wbtest".
Repeated imports within the same import kind produce a warning when their conditions overlap. They remain valid and keep their declaration order. Imports with disjoint conditions do not produce a duplicate warning.
Inactive imports do not add build dependencies. An active import from another
module still requires a module dependency declaration. Import conditions do
not change the package’s supported_targets setting.
Native build configuration
Backend selection
For --target native, debug builds on macOS AArch64, Linux x86_64, and Windows
x86_64 use the new native backend by default, with moonc emitting object files
directly. Set MOONBIT_NEW_NATIVE=0 to use generated C instead; other values keep
the default. Unsupported hosts and release builds use generated C even when
MOONBIT_NEW_NATIVE=1 is set. If a selected executable package configures
link.native.cc-flags, or MOON_CC selects a compiler for another target, the
invocation also uses generated C.
On Windows, the new native backend requires a cl-compatible MSVC toolchain,
such as cl.exe or clang-cl.exe, to compile the runtime and C stubs and link
the executable.
C compiler caching
Set MOON_CC_WRAPPER to use a compiler cache such as ccache or sccache:
MOON_CC_WRAPPER=ccache moon build --target native --release
MOON_CC=clang MOON_CC_WRAPPER=sccache moon test --target native
The value is one executable name or path, including paths containing spaces; it is not a shell command and cannot include arguments. Unset it or set it to an empty string to disable the wrapper. Custom wrappers receive the selected compiler path followed by its arguments. Configure wrapper options through its environment or a wrapper script.
Moon uses the wrapper for generated C, runtime C, and C stubs, including those in foreign libraries and LLVM builds. Each source is compiled separately to an object before linking or archiving. Compiler discovery, linking, and archiving run without the wrapper. The wrapper does not change compiler selection, backend selection, or the default allocator.
MOON_CC remains a compiler executable name or path; use MOON_CC_WRAPPER
instead of setting MOON_CC="ccache clang". Cache reuse across different
directories also depends on the cache tool’s path and debug-info settings.
Floating-point arithmetic
Native C compilation with GCC/Clang disables floating-point contraction by
default with -ffp-contract=off. This preserves separate rounding of operations
such as multiplication followed by addition. MSVC-compatible compilers retain
their default behavior.
Allocator
MOONBIT_ALLOCATOR selects the allocator used by native runtime builds:
mimalloccompiles the runtime for mimalloc and links the shippedlibmoonbitrun.osupport object.systemcompiles the runtime for the system allocator and does not linklibmoonbitrun.o.
The selected value is defined both when compiling the shipped runtime sources
and when compiling the C emitted by moonc link-core, so the program inlines
the same allocator as the runtime it links against.
When the variable is unset, Moon preserves the platform and toolchain default.
Selecting mimalloc fails when its support object is unavailable, including on
Windows, with TCC, and when cross-compiling.
Cross-compiling
Set MOON_CC (and MOON_AR if needed) to a compiler for another target, for
example a wrapper script that runs zig cc -target x86_64-linux-musl "$@".
Moon runs the compiler with -dumpmachine to find its target. When the
architecture, operating system, or ABI (for example musl on a glibc Linux
host) differs from the host, Moon does not link the
prebuilt objects in the MoonBit lib directory (libmoonbitrun.o, the SIMDUTF
objects, and libbacktrace.a), because they are built for the host. The
runtime then uses the system allocator and its scalar UTF code path, and
panics do not print a backtrace.
Cross-compiling is best effort and works only through the global MOON_CC.
A package-level cc does not change the target of the shared runtime or of the
C stubs of other packages, so it cannot be used to cross-compile. The
platform cfg and the prebuilt core library still follow the host.
Reference cycle collection
Set MOON_COLLECT_REF_CYCLE=1 to enable experimental reference cycle collection:
MOON_COLLECT_REF_CYCLE=1 moon run main --target native
MOON_COLLECT_REF_CYCLE=1 moon test --target wasm
It is off by default. Unset the variable or set it to 0 to disable it;
only the value 1 enables it.
The setting applies to build, run, test, and bench, including standalone
files, in both debug and release builds. Native builds support both generated C
and the machine backend (direct object output), with either native allocator.
Enabling collection preserves the usual backend selection, including
MOONBIT_NEW_NATIVE. Machine builds require a compiler with trial-deletion
support; Wasm builds require one supporting -enable-trial-deletion.
The setting has no effect on WasmGC, JavaScript, or LLVM.
Wasm build configuration
Set MOON_WASM_NEW_ALLOCATOR=1 to enable the MoonBit TLSF allocator:
MOON_WASM_NEW_ALLOCATOR=1 moon build --target wasm
This applies to the wasm backend in moon build, moon run, moon test, and
moon bench, including --output-wat. It passes -allocator tlsf-mbt to
moonc link-core and requires a compiler that supports that option.
When unset or set to any value other than 1, the compiler’s default allocator
is used. Other target backends are unaffected.
Config JSON Schema
moon.mod.json
Supported user configuration formats are the legacy JSON format and the
moon.mod DSL. Legacy JSON keeps its existing field names:
{
"name": "example/app",
"deps": { "example/dep": "1.2.3" },
"warn-list": "+a",
"preferred-target": "js",
"supported-targets": "js"
}
Commands that update a JSON manifest retain this format. moon fmt migrates it
to moon.mod; --check and --warn preserve the input files.
Internal normalized representation
The schema below describes Moon’s internal normalized JSON representation for
maintenance. It is not a schema for user-authored moon.mod.json files and does
not establish a supported input format or a stable JSON export API.