iTranslated by AI
Understanding the Template Generated by 'moon new' in MoonBit
This is Day 1 of the Moonbit Advent Calendar.
For those who want to get started, I would like to explain the parts I found tricky or difficult to understand by walking through the moon new boilerplate. There is a lot to learn just from this template.
If you are interested, feel free to read this article and then join any open slots. Otherwise, I will have to fill them all by myself.
Installation from Scratch
Install the extension in VS Code:
Linux or Mac:
$ curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash
# Configure PATH in ~/.bashrc / ~/.zshrc
export PATH="$HOME/moon/bin:$PATH"
Setting up a Project with the Moon Command
The basic commands are similar to cargo:
❯ moon -h
The build system and package manager for MoonBit.
Usage: moon [OPTIONS] <COMMAND>
Commands:
new Create a new MoonBit module
build Build the current package
check Check the current package, but don't build object files
run Run a main package
test Test the current package
clean Remove the target directory
fmt Format source code
...
Generate the boilerplate with moon new:
$ moon new myapp
Initialized empty Git repository in /Users/mizchi/sandbox/myapp/.git/
Created mizchi/myapp at myapp
(You might be asked for a username if this is your first time generating.)
In the initial state, the following template is generated:
❯ tree .
.
├── AGENTS.md
├── cmd
│ └── main
│ ├── main.mbt
│ └── moon.pkg.json
├── LICENSE
├── moon.mod.json
├── moon.pkg.json
├── myapp_test.mbt
├── myapp.mbt
├── README.mbt.md
└── README.md -> README.mbt.md
The myapp part corresponds to the directory name when it was generated.
Before running it, let's check what kind of code has been generated.
moon.mod.json
This is the project configuration file that exists once in the project.
{
"name": "mizchi/myapp",
"version": "0.1.0",
"readme": "README.mbt.md",
"repository": "",
"license": "Apache-2.0",
"keywords": [],
"description": ""
}
-
name: Must have a username namespace, in the formatusername/pkg. -
readme: The README file displayed at the top when publishing a package to mooncakes.
There are various fields, but it will work with at least {"name": "user/pkg"} written.
There is a peculiar extension called .mbt.md. This is an executable markdown format, which is convenient and will be explained later.
myapp.mbt
///|
pub fn fib(n : Int) -> Int64 {
loop (n, 0L, 1L) {
(0, _, b) => b
(i, a, b) => continue (i - 1, b, a + b)
}
}
///|
/// data is a labelled argument without default value having type Array[Int]
/// start is an optional labelled argument with default value 0 having type Int
/// length is an optional labelled argument without default value having type Option[Int]
pub fn sum(data~ : Array[Int], start? : Int = 0, length? : Option[Int]) -> Int {
let end = if length is Some(length) { start + length } else { data.length() }
for i = start, sum = 0; i < end; i = i + 1, sum = sum + data[i] {
} else {
sum
}
}
This is sample code for calculating Fibonacci numbers.
-
loopis a loop construct that recurses via pattern matching on the result ofcontinue.- Don't worry, there are regular
forloops andarray.mapas well. - https://tour.moonbitlang.com/basics/loop/index.html
- Don't worry, there are regular
- The type argument syntax is
Array[T]. Note that it is notArray<T>. -
data~:is a labelled argument.- On the calling side, it becomes
sum(data=1).
- On the calling side, it becomes
-
start?:is an optional labelled argument.- On the calling side, it becomes the
sum(data=1, start=2)format.
- On the calling side, it becomes the
- The return type syntax is
-> T.- Unlike TypeScript, it cannot be omitted in top-level
fnstatements. - For lambda expressions
fn(){}or arrow functions() => ..., it can be omitted if type inference is possible.
- Unlike TypeScript, it cannot be omitted in top-level
.mbt files in a directory containing moon.pkg.json belong to the same namespace. (As a slight exception, *_test.mbt has its own namespace.)
///| may look strange at first, but consider the unit separated by this as a single file, regardless of the filename. It is inserted at the top-level statement unit by moon fmt formatting.
cmd/main/main.mbt
///|
fn main {
println(@lib.fib(10))
}
An fn main {} without arguments is a special form of an entry point function, and when combined with "is-main": true in moon.pkg.json, it indicates that the package is executable.
That is all for the source code; the rest are configuration files, so let's try running it first.
❯ moon run cmd/main/main.mbt
89
The result of @lib.fib(10) is displayed using the built-in println function.
You can see why it can be referenced by @lib.fib by looking at moon.pkg.json.
cmd/main/moon.pkg.json
{
"is-main": true,
"import": [
{
"path": "mizchi/myapp",
"alias": "lib"
}
]
}
is-main enables the use of fn main, and import allows importing myapp(.mbt).
"path" specifies a relative path from moon.mod.json. Since myapp.mbt is in the root directory, it is named mizchi/myapp. Incidentally, the namespace of the package executing this main is mizchi/myapp/cmd/main. (Since it is main, it cannot be imported by others.)
By adding @ to the name specified in alias, you can call it in the form of @lib.
Implicitly, if you write it as follows, it becomes @myapp.fib():
"import": [
"mizchi/myapp"
]
It is good to remember that the terminal path becomes the namespace. Remember that this rule also applies to third-party libraries and built-in libraries (moonbitlang/core).
Core libraries can be called from the beginning with namespaces like @json., and types such as Array, Map, Option, and Result are simply automatically inserted into the import from ~/.moon/lib/core/prelude/prelude.mbt. You can also remove them with the --nostd option.
Built-in functions
There are not many built-in functions introduced at the top level. You can get by just remembering these few:
println-
ignore: A function that takes an argument and discards it as aUnittype. -
fail: Throws an exception. -
panic: Terminates the program forcibly. assert_eqassert_not_eqassert_trueassert_false-
inspect: A function with an inline snapshot.
My impression is that while MoonBit has many features in the syntax itself, the built-in library is quite concise.
You can check the details by running cat ~/.moon/lib/core/prelude/prelude.mbt.
As I will introduce later, inspect is extremely convenient.
Output directory
The output is generated under target. By default, it uses --wasm-gc, so target/wasm-gc/release/build/cmd/main/main.wasm is produced.
./target/
└── wasm-gc
└── release
└── build
├── build.moon_db
├── build.output
├── cmd
│ └── main
│ ├── main.core
│ ├── main.mi
│ └── main.wasm
├── moon.db
├── myapp.core
└── myapp.mi
If you run moon build --target all, all outputs for js, native, wasm, and wasm-gc will be generated.
./target/
├── js
│ └── release
│ └── build
│ ├── cmd
│ │ └── main
│ │ ├── main.d.ts
│ │ ├── main.js
│ │ └── moonbit.d.ts
├── native
│ └── release
│ └── build
│ ├── cmd
│ │ └── main
│ │ ├── main.c
│ │ ├── main.exe
├── wasm
│ └── release
│ └── build
│ ├── cmd
│ │ └── main
│ │ └── main.wasm
└── wasm-gc
└── release
└── build
├── cmd
│ └── main
│ └── main.wasm
While you cannot output for a specific environment if it includes extern bindings tailored to that environment, you can generate code/binaries that run on js, native, and wasm(-gc) if you use pure MoonBit implementations. The fact that it provides type definitions for TypeScript is also a welcome feature.
Builds are also quite fast. Even for my own project with 50,000 lines of code, it takes about 10 seconds initially, and incremental builds are instantaneous.
test
❯ moon test
Total tests: 2, passed: 2, failed: 0.
These two tests are executed from myapp_test.mbt.
❯ cat ./myapp_test.mbt
///|
test "fib" {
let array = [1, 2, 3, 4, 5].map(fib)
// `inspect` is used to check the output of the function
// Just write `inspect(value)` and execute `moon test --update`
// to update the expected output, and verify them afterwards
inspect(array, content="[1, 2, 3, 5, 8]")
}
///|
test "sum" {
let array = [1, 2, 3, 4, 5]
inspect(sum(data=array), content="15")
inspect(sum(data=array, start=1), content="14")
inspect(sum(data=array, length=3), content="6")
let length = None
// Use `?` for punning
inspect(sum(data=array, length?), content="15")
}
-
testis a built-in testing syntax. - In
*_test.mbt, you can access the namespace of functions/types exposed with thepubmodifier.- You can also access them with a namespace, such as
@myapp.fib.
- You can also access them with a namespace, such as
-
param?is used to pass an optional value while keeping it optional (it's a bit hard to explain).
What's interesting is that the content of inspect serves as an inline snapshot.
Let's try deleting content="15" and running moon test.
[mizchi/myapp] test myapp_test.mbt:12 ("sum") failed
expect test failed at /Users/mizchi/sandbox/myapp/myapp_test.mbt:19:3-19:36
Diff: (- expected, + actual)
----
+15
----
This causes the test to fail (as expected).
If you run moon test --update, the content= attribute will be automatically inserted.
❯ moon test -u
Auto updating expect tests and retesting ...
Total tests: 2, passed: 2, failed: 0.
Agents.md
This provides instructions for AI agents. It is also convenient for humans to quickly grasp the project structure.
README.mbt.md
This is Markdown where code blocks are executable. If you write code here, it will be type-checked by moon check and executed by moon test.
For example, if you write it like this:
# mizchi/myapp
```moonbit
test {
assert_eq(1, 1)
}
```
it will be executed with moon test.
❯ moon test
Total tests: 3, passed: 3, failed: 0.
If you are using VS Code, it is also checked by the LSP.
Since Markdown often tends to become outdated, it is great that you can maintain it here.
Pitfalls during environment setup
- In a VS Code workspace where multiple
moon.mod.jsonfiles exist (including subdirectories), the LSP may lose consistency. - If you see warnings related to
externin VS Code, follow these steps:- Specify your preferred target in
moon.mod.json, such as"preferred-target": "js". - Delete the
targetdirectory usingrm -r target(there is behavior where the LSP might cache the results of the last build). - Switch the backend via the command palette in VS Code:
Moonbit: Select Backend->js.
- Specify your preferred target in
If "preferred-target" is not specified, it defaults to the equivalent of --target wasm-gc.
If you have a dependency that cannot be built with wasm-gc, you will encounter issues.
Good luck!
If you know this much, you should be able to at least get started.
If you're unsure how to write something, I recommend searching the core library implementations under ~/.moon/lib/core.
Discussion