Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

移动至 https://docs.moonbitlang.com/zh-cn/latest/toolchain/

本页面只保留命令行文档、后端构建配置与配置 JSON Schema。

Command-Line Help for moon

This document contains the help content for the moon command-line program.

Command Overview:

moon

Usage: moon <COMMAND>

Subcommands:
  • new — Create a new MoonBit module
  • build — Build the current package
  • check — Check the current package, but don’t build object files
  • prove — Prove the current package
  • run — Run a main package
  • runwasm — Deprecated: use moon run –target wasm locally or moonx for registry packages
  • test — Test the current package
  • clean — Remove local build outputs or configured global caches
  • fmt — Format source code
  • doc — Generate documentation or searching documentation for a symbol
  • explain — Explain compiler diagnostics and language topics
  • info — Generate public interface (.mbti) files for all packages in the module or workspace
  • bench — Run benchmarks in the current package
  • add — Add a dependency
  • remove — Remove a dependency
  • install — Install a binary package globally
  • tree — Display the dependency tree
  • fetch — Download a package to .repos directory (unstable)
  • search — Search modules and package summaries in the registry
  • view — View a registry module or a user’s published modules
  • work — Workspace maintenance commands
  • login — Log in to your account
  • whoami — Show login status and username
  • register — Register an account at mooncakes.io
  • publish — Publish the current module
  • package — Package the current module
  • deprecate — Deprecate or restore all existing versions of a published module
  • update — Update the package registry index
  • coverage — Code coverage utilities
  • generate-build-matrix — Generate build matrix for benchmarking (legacy feature)
  • upgrade — Upgrade toolchains
  • shell-completion — Generate shell completion for bash/elvish/fish/pwsh/zsh to stdout
  • version — 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 .mbtx file
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 target

    Possible 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 level

    Default value: error

    Possible 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.md selector, or standalone .mbtx file
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 target

    Possible 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 level

    Default value: error

    Possible 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 update pkg.generated.mbti files of the checked packages

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 level

    Default value: error

    Possible 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 .mbtx source from stdin
  • <ARGS> — The arguments provided to the program to be run
Options:
  • -e <SCRIPT> — Run .mbtx source 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 target

    Possible 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 level

    Default value: error

    Possible 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 runwasm

Deprecated: Local packages: use moon run <LOCAL_PACKAGE> --target wasm. Registry packages: use moonx <PACKAGE[@VERSION]>.

Run a local package as WebAssembly or a prebuilt WebAssembly binary published as a Mooncakes asset.

Local package inputs are handled like moon run --target wasm: moon runwasm main moon runwasm ./main

Experimental moonrun policy forwarding: moon runwasm –experimental-policy moonrun-policy.json main

Accepted Mooncakes coordinate forms: moon runwasm moonbitlang/parser/cmd/moonfmt@0.3.3 moon runwasm moonbitlang/parser/cmd/moonfmt@latest moon runwasm moonbitlang/parser/cmd/moonfmt

Pinned coordinates use the given version directly. @latest refreshes the registry index before resolving the latest version. Unpinned coordinates use the latest version already in the local index, updating it only when the module is absent. Fetched wasm files are cached under $MOON_HOME/registry/cache/assets and reused on later runs.

Usage: moon runwasm [OPTIONS] <LOCAL_PACKAGE|PACKAGE[@VERSION]> [ARGS]...

Arguments:
  • <LOCAL_PACKAGE|PACKAGE[@VERSION]> — Local package path or Mooncakes package coordinate of the prebuilt wasm binary
  • <ARGS> — The arguments provided to the wasm program
Options:
  • --experimental-policy <PATH> — Experimental: pass a moonrun JSON policy file for moonbitlang/async runtime access.

    The policy applies to moonbitlang/async and moonrun-owned unstable FFI; WASI is not covered.

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 .mbtx script.

    An explicit .mbtx path tests only that script, even inside a project. The script must define fn main, but tests use a generated entrypoint and do not execute the script’s main. Package-wide testing excludes .mbtx scripts. Outside a project, a single .mbt or .mbt.md file 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 target

    Possible 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 level

    Default value: error

    Possible 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 like 0-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 loops

    Default 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-]index is set

  • -f, --filter <FILTER> — Run only tests whose name matches the given glob pattern. Supports ‘*’ (matches any sequence) and ‘?’ (matches any single character)

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

moon fmt

Format source code

Usage: moon fmt [OPTIONS] [PATH]... [-- <ARGS>...]

Arguments:
  • <PATH> — Paths to packages, files selecting their containing package, or standalone .mbtx scripts

    An explicit .mbtx path 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. --check fails 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. Use moon ide doc <SYMBOL> instead.
Options:
  • --serve — Start a web server to serve the documentation

  • -b, --bind <BIND> — The address of the server

    Default value: 127.0.0.1

  • -p, --port <PORT> — The port of the server

    Default 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 emit mbti files for

    Conflicts 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 canonical pkg.generated.mbti output

    Possible values: wasm, wasm-gc, js, native, llvm, all

  • -p, --package <PACKAGE> — The full or subset of name of the package to emit mbti files for

moon bench

Run benchmarks in the current package

Usage: moon bench [OPTIONS] [PATH]...

Arguments:
  • <PATH> — Run benchmarks for a filesystem path. PATH may 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 target

    Possible 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 level

    Default value: error

    Possible 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 --package is 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 like 0-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 — Upgrade an existing dependency
  • --no-update — Do not update the registry index 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:

    1. local path (./, ../, /, Windows drive)
    2. git URL
    3. registry package path (user/module/pkg[@version])

    Use /... suffix to install all matching main packages.

  • <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 tree

    Text 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 in root.

  • --target <TARGET> — Select the backend for the package dependency graph

    Defaults 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 update the registry index before fetching

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 results

    Default 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 manifest
  • use — Add modules to the workspace manifest
  • sync — 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 (or moon.mod.json) requests restricted access to the module after publication when true. Omission or false requests public visibility.

Publishing with private visibility is not supported yet, so private modules are currently rejected, including with –dry-run. Local building, testing, and packaging remain available.

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

Update the package registry index

Usage: moon update

moon coverage

Code coverage utilities

Runs the toolchain’s bin/moon_cove.wasm through moonrun by default. Set MOON_COVE_REPORT_ENABLED=0 (or false) to use the legacy moon_cove_report instead.

Usage: moon coverage <COMMAND>

Subcommands:
  • analyze — Run test with instrumentation and report coverage
  • report — Generate code coverage report
  • clean — 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 to the selected coverage reporter
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 of drow, dcol, mrow, mcol to 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 for

    Default 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.

包配置

moon.pkg 支持直接声明以下包配置。表中的示例是独立配置。

声明含义
proof_enabled = true为包启用证明流程,默认值为 false。
max_concurrent_tests = 4设置测试并发数,取值为 32 位无符号整数。
regex_backend = "table"选择正则表达式编译后端,可选 auto、block、table 或 runtime。
virtual(has_default: true)声明带默认实现的虚包;没有默认实现时使用 false。
virtual(implement: "user/module/interface")实现指定的虚包。

这些声明与 options(...) 中对应配置的行为一致。options(...) 仍然支持 proof-enabled、max-concurrent-tests、regex-backend 及其下划线别名, 也支持以 virtual_pkg 作为 virtual 的旧别名;其中的 implement 对应 virtual(implement: ...)。

每个包最多声明一次 virtual(...):包要么本身是虚包,要么实现一个虚包, 因此 has_default 和 implement 不能同时使用。

每项配置只需声明一次,直接声明或写在 options(...) 中均可。例如,不要同时使用 proof_enabled = true 和 options("proof-enabled": true)。

其他配置,包括 bin-name、bin-target、overrides、结构化的 link、 native-stub 和按文件配置的 targets,仍需写在 options(...) 中。

这些声明需要配套的编译器支持。不识别这些声明的编译器会报告 Invalid configuration(E4192);使用这些工具链时,请继续使用旧的 options(...) 形式。格式化和 JSON 到 DSL 的迁移由工具链中的 moonfmt 提供。较旧的格式化工具可能会把直接声明改写成等价的 options(...) 形式。

词法和语法分析器生成

Moon 不再根据 .mbl 或 .mby 文件自动运行 moonlex 或 moonyacc。 请显式声明生成 .mbt 文件的自定义规则。例如,假设 my-lexer 命令可用:

rule(name: "lexer", command: "my-lexer $input -o $output")
dev_build(rule: "lexer", input: "lexer.mbl", output: "lexer.mbt")

直接位于包目录中的 .mbl 或 .mby 文件必须声明为自定义规则的输入或输出, 旧的 pre-build 配置也可以使用。否则 Moon 会报告迁移错误。 发布包时应包含生成的 .mbt 文件,因为依赖该包的项目不会运行其包级预构建规则。

条件导入

编译和格式化这种语法还需要编译器和格式化工具支持条件导入块。

在 moon.pkg 中使用 #cfg,为不同后端选择导入:

#cfg(target = "native")
import {
  "example/platform/native" @platform,
}

#cfg(not(target = "native"))
import {
  "example/platform/portable" @platform,
}

每个后端只启用其中一个导入,因此两个实现可以使用相同的别名。 没有 #cfg 的导入块对所有后端生效。

支持的目标包括 wasm、wasm-gc、js、native 和 llvm。 可以使用 all(...)、any(...)、not(...) 组合条件,也可以使用 true 和 false。例如,#cfg(any(target = "native", target = "js")) 表示对 Native 和 JavaScript 生效。条件也适用于以 for "test" 或 for "wbtest" 结尾的测试导入块。

同一导入类型中,重复导入同一个包且条件重叠时会产生警告,导入仍然有效并保留声明顺序。 条件互不重叠时不会产生重复导入警告。

未启用的导入不会添加构建依赖。启用的跨模块导入仍需声明相应的模块依赖。 导入条件不会改变包的 supported_targets 设置。

原生构建配置

后端选择

对于 --target native,macOS AArch64、Linux x86_64 和 Windows x86_64 的 debug 构建默认使用新 native 后端,由 moonc 直接生成目标文件。设置 MOONBIT_NEW_NATIVE=0 可切换到生成 C 代码的后端;其他值保持默认行为。 其他平台以及 release 构建使用 C 后端,即使设置 MOONBIT_NEW_NATIVE=1 也不例外。 如果选中的可执行包配置了 link.native.cc-flags,或 MOON_CC 指定了面向其他 目标的编译器,本次构建也会使用 C 后端。

Windows 的新 native 后端要求兼容 cl 的 MSVC 工具链,例如 cl.exe 或 clang-cl.exe,用于编译运行时、C stub 和链接可执行文件。

浮点运算

使用 GCC/Clang 的 Native C 编译默认通过 -ffp-contract=off 禁止浮点运算收缩, 保留乘法、加法等各步运算独立舍入的语义。MSVC 兼容编译器保持默认行为。

内存分配器

MOONBIT_ALLOCATOR 用于选择原生运行时构建所使用的内存分配器:

  • mimalloc:按 mimalloc 配置编译运行时,并链接工具链提供的 libmoonbitrun.o 支持目标文件。
  • system:按系统分配器配置编译运行时,不链接 libmoonbitrun.o。

编译工具链自带的运行时源码和 moonc link-core 生成的 C 代码时都会定义该宏, 以保证程序内联的分配器与其链接的运行时一致。

未设置该变量时,Moon 保留当前平台和工具链的默认行为。如果所选平台或 工具链不提供相应的支持目标文件(包括 Windows、TCC 以及交叉编译),选择 mimalloc 将在构建规划阶段报错。

交叉编译

将 MOON_CC(以及按需设置的 MOON_AR)设为面向其他目标的编译器,例如执行 zig cc -target x86_64-linux-musl "$@" 的包装脚本。Moon 会以 -dumpmachine 运行该编译器以确定其目标。当目标的架构、操作系统或 ABI(例如 glibc Linux 主机上的 musl)与主机不同时,Moon 不会链接 MoonBit lib 目录中的预编译目标文件(libmoonbitrun.o、SIMDUTF 目标文件以及 libbacktrace.a),因为它们是为主机构建的。此时运行时使用系统分配器和标量 UTF 代码路径,且 panic 时不打印调用栈。

交叉编译仅为尽力支持,且只能通过全局的 MOON_CC 进行。包级别的 cc 不会改变 共享运行时或其他包的 C stub 的目标,因此不能用于交叉编译。platform cfg 以及预编译的 core 库仍然跟随主机。

引用环回收

设置 MOON_COLLECT_REF_CYCLE=1 可启用实验性的引用环回收:

MOON_COLLECT_REF_CYCLE=1 moon run main --target native
MOON_COLLECT_REF_CYCLE=1 moon test --target wasm

该功能默认关闭。取消设置该变量或将其设为 0 即可关闭;只有值 1 会启用。

该设置适用于 build、run、test 和 bench,包括单文件模式以及 debug 和 release 构建。原生构建的生成 C 代码后端和机器码后端(直接输出目标文件)均支持 引用环回收,也都支持两种原生内存分配器。启用回收不会改变原有的后端选择规则, 包括 MOONBIT_NEW_NATIVE 的设置。机器码构建需要支持 trial deletion 的编译器。 Wasm 构建需要支持 -enable-trial-deletion 的编译器。 该设置不影响 WasmGC、JavaScript 和 LLVM。

Wasm 构建配置

设置 MOON_WASM_NEW_ALLOCATOR=1 可启用 MoonBit 实现的 TLSF 内存分配器:

MOON_WASM_NEW_ALLOCATOR=1 moon build --target wasm

此设置适用于 moon build、moon run、moon test 和 moon bench 的 wasm 后端,包括 --output-wat 输出。Moon 会向 moonc link-core 传递 -allocator tlsf-mbt,因此需要编译器支持该选项。

未设置此变量或值不为 1 时,使用编译器的默认分配器。其他后端不受影响。

Config JSON Schema

moon.mod.json

moon.pkg.json