モジュール設定#

moon は、モジュールファイルを使ってモジュールを識別し、説明します。従来の形式は moon.mod.json で、新しい形式は moon.mod です。完全な JSON スキーマは moon のリポジトリを参照してください。

moon.mod の完全な構文は次のとおりです:

moon_mod ::= statement*
statement ::= import | assign | apply

import ::= "import" "{" (import_item ",")* import_item? "}" import_kind?
import_item ::= STRING

assign ::= LIDENT "=" expr

apply ::= LIDENT "(" (argument ",")* argument? ")"
argument ::= LIDENT ":" expr | STRING ":" expr  

expr ::= array | object | apply | STRING | INT | "true" | "false"
array ::= "[" (expr ",")* expr? "]"
object ::= "{" (field ",")* field? "}"

名前#

name フィールドはモジュール名を指定するために使います。このフィールドは必須です。

name = "user/example"
{
  "name": "user/example"
  // ...
}

モジュール名には、英字、数字、_-/ を含めることができます。

mooncakes.io に公開するモジュールでは、モジュール名をユーザー名で始める必要があります。

バージョン#

version フィールドはモジュールのバージョンを指定するために使います。

このフィールドは任意です。mooncakes.io に公開するモジュールでは、バージョン番号は Semantic Versioning 2.0.0 仕様に従う必要があります。

version = "0.1.0"
{
  "version": "0.1.0"
}

依存関係管理#

deps フィールドはモジュールの依存関係を指定するために使います。

moon addmoon remove などのコマンドによって自動的に管理されます。

name = "username/hello"
import {
  "moonbitlang/x@0.4.6"
}
{
  "name": "username/hello",
  "deps": {
    "moonbitlang/x": "0.4.6"
  }
}

モジュールにはローカル依存関係も使用できます。

新しい moon.mod 形式では、ローカル依存関係の設定は非推奨です。ローカル依存関係を使う推奨方法は、moon.work で設定することです。

例えば、moon.work を使って user/module1user/module2 を管理する場合:

// in moon.work
members = [
  "source/to/module1",
  "source/to/module2",
]

そして user/module1user/module2 を依存関係として使う場合:

// in source/to/module1/moon.mod
import {
  "user/module2@0.1.0"
}

@version の部分は無視され、user/module2 は mooncakes.io ではなくローカルソースから解決されます。

{
  "name": "username/hello",
  "deps": {
    "username/other": {
      "path": "../other"
    }
  }
}

メタ情報#

README#

readme フィールドは、モジュールの README ファイルへのパスを指定するために使います。

readme = "README.md"
{
  "readme": "README.md"
}

リポジトリ#

repository フィールドは、モジュールのリポジトリ URL を指定するために使います。

repository = "link/to/your/repo"
{
  "repository": "link/to/your/repo"
}

ライセンス#

license フィールドはモジュールのライセンスを指定するために使います。ライセンス種別は SPDX License List に準拠している必要があります。

license = "MIT"
{
  "license": "MIT"
}

キーワード#

keywords フィールドはモジュールのキーワードを指定するために使います。

keywords = ["example", "test"]
{
  "keywords": ["example", "test"]
}

説明#

description フィールドはモジュールの説明を指定するために使います。

description = "This is a description of the module."
{
  "description": "This is a description of the module."
}

include と exclude#

includeexclude フィールドは、公開処理中に特定のディレクトリやファイルを含める、または除外するために使います。

gitignore 構文に従い、include は exclude の後に適用されます。例えば、次の設定では build/assets を含めますが、build ディレクトリ内のその他の内容は除外します。

options(
  exclude: ["build"],
  "include": ["build/assets"],
)
{
  "exclude": ["build"],
  "include": ["build/assets"]
}

パッケージ結果が期待どおりかどうかは、moon package --list を使って確認できます。

優先ターゲット#

preferred-target フィールドは、moon と言語サーバーにデフォルトターゲットとして使うべきターゲットを知らせます。これにより、Wasm GC 以外のバックエンドを対象とするプロジェクトを開発するときに --target を書く必要を避けられます。

preferred_target = "js"
{
  "preferred-target": "js"
}

サポート対象ターゲット#

supported-targets フィールドは、このモジュールがサポートする想定のバックエンドを宣言します。preferred-target とは異なり、コマンドのデフォルトターゲットは選択しません。モジュールの互換バックエンド範囲をメタデータに記録するために使います。

supported-targets はコンパクトなターゲット集合構文を使います:

  • js は単一のバックエンドを表します

  • +js+wasm-gc はバックエンドの明示的な集合を表します

  • +all-jsjs 以外のすべてのバックエンドを表します

例えば:

supported_targets = "+js+wasm-gc"
{
  "supported-targets": "+js+wasm-gc"
}

互換性のために、従来の配列構文も引き続き受け付けられます:

supported_targets = ["js", "wasm-gc"]
{
  "supported-targets": ["js", "native"]
}

preferred-targetsupported-targets はよく一緒に使われます:

  • preferred-target は、moon がデフォルトで使うべきバックエンドを示します

  • supported-targets は、モジュールがサポートすると宣言するバックエンドを示します

パッケージも supported-targets を定義している場合、実際に有効なバックエンド集合はモジュールレベルとパッケージレベルの宣言の共通部分になります。

パッケージ内でファイルごとの条件付きコンパイルを行う場合は、代わりに moon.pkg / moon.pkg.jsontargets を使ってください。

ソースディレクトリ#

source フィールドはモジュールのソースディレクトリを指定するために使います。

moon.mod.json ファイルがあるディレクトリのサブディレクトリであり、相対パスである必要があります。

moon new コマンドでモジュールを作成すると、src ディレクトリが自動的に生成され、source フィールドのデフォルト値は src になります。

options(
  source: "src"
)
{
  "source": "src"
}

source フィールドが存在しない場合、または値が空文字列 "" の場合、"source": "." を設定した場合と同等です。これは、ソースディレクトリが moon.mod.json ファイルのあるディレクトリと同じであることを意味します。

options(
  "source": ""
)
options(
  "source": "."
)
{
  "source": ""
}
{
  "source": "."
}

null は上記の場合と同等です:

{
  "source": null
}

警告リスト#

これは、特定のプリセットコンパイラ警告番号を無効化するために使います。

例えば、次の設定では -2 によって警告番号 2(未使用の変数)を無効化します。

warnings = "-2"
{
  "warn-list": "-2"
}

複数の警告を無効化する必要がある場合は、それらをそのまま連結して組み合わせることができます。

warnings = "-2-4"
{
  "warn-list": "-2-4"
}

もともと禁止されていた特定の警告を有効化する必要がある場合は、プラス記号を使います。

warnings = "+31"
{
  "warn-list": "+31"
}

moonc check -warn-help を使うと、プリセットコンパイラ警告番号の一覧を確認できます。以下の出力では、mnemonic は警告リストで使われる記号名で、id は同じ警告の数値形式です。

$ moonc check -warn-help
Available warnings: 
mnemonic                   description                                                     id state
unused_value               Unused variable or function.                                     1 warn
unused_value               Unused variable.                                                 2 warn
unused_type_declaration    Unused type declaration.                                         3 warn
missing_priv               Unused abstract type.                                            4 warn
unused_type_variable       Unused type variable.                                            5 warn
unused_constructor         Unused constructor.                                              6 warn
unused_field               Unused field or constructor argument.                            7 warn
redundant_modifier         Redundant modifier.                                              8 warn
struct_never_constructed   Struct never constructed.                                        9 warn
unused_pattern             Unused pattern.                                                 10 warn
partial_match              Partial pattern matching.                                       11 error
unreachable_code           Unreachable code.                                               12 warn
unresolved_type_variable   Unresolved type variable.                                       13 warn
alert or alert_<category>  All alerts or alerts with specific category.                    14 warn
unused_mut                 Unused mutability.                                              15 error
parser_inconsistency       Parser inconsistency check.                                     16 warn
ambiguous_loop_argument    Ambiguous usage of loop argument.                               17 warn
useless_loop               Useless loop expression.                                        18 warn
deprecated                 Deprecated API usage.                                           20 warn
missing_pattern_arguments  Some arguments of constructor are omitted in pattern.           21 warn
ambiguous_block            Ambiguous block.                                                22 warn
unused_try                 Useless try expression.                                         23 warn
unused_error_type          Useless error type.                                             24 warn
test_unqualified_package   Using implicitly imported API in test.                          25 off
unused_catch_all           Useless catch all.                                              26 warn
deprecated_syntax          Deprecated syntax.                                              27 warn
todo                       Todo                                                            28 warn
unused_package             Unused package.                                                 29 warn
missing_package_alias      Empty package alias.                                            30 warn
unused_optional_argument   Optional argument never supplied.                               31 off
unused_default_value       Default value of optional argument never used.                  32 off
text_segment_excceed       Text segment exceed the line or column limits.                  33 warn
implicit_use_builtin       Implicit use of definitions from `moonbitlang/core/builtin`.    34 warn
reserved_keyword           Reserved keyword.                                               35 warn
loop_label_shadowing       Loop label shadows another label.                               36 warn
unused_loop_label          Unused loop label.                                              37 warn
missing_invariant          For-loop is missing an invariant.                               38 off
missing_reasoning          For-loop is missing a proof_reasoning.                          39 off
multiline_string_escape    Deprecated escape sequence in multiline string.                 40 error
missing_rest_mark          Missing `..` in map pattern.                                    41 warn
invalid_attribute          Invalid attribute.                                              42 warn
unused_attribute           Unused attribute.                                               43 warn
invalid_inline_wasm        Invalid inline-wasm.                                            44 error
unused_rest_mark           Useless `..` in pattern                                         46 warn
invalid_mbti               Invalid mbti file                                               47 warn
missing_definition         Unused pub definition because it does not exist in mbti file.   49 warn
method_shadowing           Local method shadows upstream method                            50 warn
ambiguous_precedence       Ambiguous operator precedence                                   51 warn
unused_loop_variable       Loop variable not updated in loop                               52 warn
unused_trait_bound         Unused trait bound                                              53 warn
ambiguous_range_direction  Ambiguous looping direction for range e1..=e2                   54 off
unannotated_ffi            Unannotated FFI param type                                      55 error
missing_pattern_field      Missing field in struct pattern                                 56 warn
missing_pattern_payload    Constructor pattern expect payload                              57 warn
unaligned_byte_access      Unaligned byte access in bits pattern                           59 warn
unused_struct_update       Unused struct update                                            60 warn
duplicate_test             Duplicate test name                                             61 warn
invalid_cascade            Calling method with non-unit return type via `..`               62 warn
syntax_lint                Syntax lint warning                                             63 warn
unannotated_toplevel_array Unannotated toplevel array                                      64 warn
prefer_readonly_array      Suggest ReadOnlyArray for read-only array literal               65 off
prefer_fixed_array         Suggest FixedArray for mutated array literal                    66 off
unused_async               Useless `async` annotation                                      67 warn
declaration_unimplemented  Declaration is unimplemented                                    68 warn
declaration_implemented    Declaration is already implemented                              69 off
deprecated_for_in_method   using `iterator()` method for `for .. in` loop.                 70 off
core_package_not_imported  Packages in `moonbitlang/core` need to be explicitly imported.  71 warn
unqualified_local_using    unqualified local using                                         72 off
unnecessary_annotation     unnecessary type annotation                                     73 off
missing_doc                Missing documentation for public definition                     74 off
A                          all warnings
state: warn = enabled, error = promoted to error, off = disabled
note: default alert exceptions: alert_unsafe=off

rule#

モジュールレベルの rule エントリは、モジュール内のすべての moon.pkg から参照できる再利用可能な事前ビルドコマンドを宣言します。モジュールレベルの rule はそれ自体では実行されません。パッケージをビルドする前に使用するには、moon.pkg にパッケージレベルの dev_build エントリを追加します。パッケージレベルの設定については、パッケージ設定 の「ruledev_build」セクションを参照してください。

rule(name: "...", command: "...") を使用します。ここで name はその rule を識別し、command はシェルコマンド文字列です。このコマンドは $input$output を参照できます。これらは、その rule を使用するパッケージレベルの dev_build エントリから提供されます。モジュールは複数のモジュールレベル rule エントリを宣言できます。

rule(name: "tool", command: "tool $input -o $output")

この機能は moon.mod.json ではサポートされていません。

スクリプト#

scripts フィールドは、モジュールに関連付けるカスタムスクリプトを定義するために使います。

postadd スクリプト#

postadd スクリプトは、モジュールが追加された後に自動的に実行されます。実行時、スクリプトの現在の作業ディレクトリ(cwd)は moon.mod.json ファイルがあるディレクトリに設定されます。

options(
  scripts: {
    "postadd": "python3 build.py",
  },
)
{
  "scripts": {
    "postadd": "python3 build.py"
  }
}

[実験的] 事前ビルド設定スクリプト#

警告

この機能は非常に実験的であり、API はいつでも変更される可能性があります。このドキュメントは 2025-06-03 時点の実装を反映しています。

重要

この機能を使うと、コンピュータ上で任意のコードが実行される可能性があります。注意して使用し、信頼できる依存関係に対してのみ使ってください。

事前ビルド設定スクリプトは、native ターゲット向けプログラミングを支援するために追加されました。このようなスクリプトを使うには、moon.mod.json にスクリプトを追加します:

options(
  "--moonbit-unstable-prebuild": "<path/to/build-script>",
)
{
  "--moonbit-unstable-prebuild": "<path/to/build-script>"
}

パスはプロジェクトルートからの相対パスです。スクリプトには、node で実行される JavaScript スクリプト(拡張子 .js.cjs.mjs)か、python3 または python で実行される Python スクリプト(拡張子 .py)を指定できます。

入力#

スクリプトには、標準入力ストリーム(stdin)から BuildScriptEnvironment 構造の JSON が渡されます:

/** Represents the environment a build script receives */
interface BuildScriptEnvironment {
  env: Record<string, string>
  paths: Paths
}

interface BuildInfo {
  /** The target info for the build script currently being run. */
  host: TargetInfo
  /** The target info for the module being built. */
  target: TargetInfo
}

interface TargetInfo {
  /** The actual backend we're using, e.g. `wasm32`, `wasmgc`, `js`, `c`, `llvm` */
  kind: string // TargetBackend
}

出力#

スクリプトは、標準出力ストリーム(stdout)に BuildScriptOutput 構造の JSON 文字列を出力することが期待されます:

interface BuildScriptOutput {
  /** Build variables */
  vars?: Record<string, string>
  /** Configurations to linking */
  link_configs?: LinkConfig[]
}

interface LinkConfig {
  /** The name of the package to configure */
  package: string

  /** Link flags that needs to be propagated to dependents
   *
   * Reference: `cargo::rustc-link-arg=FLAG` */
  link_flags?: string

  /** Libraries that need linking, propagated to dependents
   *
   * Reference: `cargo::rustc-link-lib=LIB` */
  link_libs?: string[]

  /** Paths that needs to be searched during linking, propagated to dependents
   *
   * Reference: `cargo::rustc-link-search=[KIND=]PATH` */
  link_search_paths?: string[]
}

ビルド変数#

vars フィールドに出力された変数は、moon.pkg の native リンク引数内で ${build.<var_name>} として使用できます。

例えば、ビルドスクリプトが次を出力する場合:

{ "vars": { "CC": "gcc" } }

そして moon.pkg が次のような構成の場合:

moon.pkg#
options(
  link: {
    "native": {
      "cc": "${build.CC}",
    },
  },
)

次のように変換されます

{
  "link": {
    "native": {
      "cc": "gcc"
    }
  }
}