
<!-- path: toolchain/index.md -->
# Toolchains

- [MoonBit's Build System](moon/index.md): full manual of `moon` build system.
- [MoonBit's Agent IDE](moonide/index.md): full manual of `moon ide`, the agent ide.
- [MoonBit's VSCode Plugin](vscode/index.md): hint on VSCode plugin.

**Other toolchains**

- [WebAssembly Toolchain](wasm/index.md): how to use Wasm with MoonBit.
- ...

# Contents:

* [Moon Build System](moon/index.md)
  * [MoonBit's Build System Tutorial](moon/tutorial.md)
  * [Running `.mbtx` Scripts](moon/script-mode.md)
  * [Use and publish packages](moon/package-manage-tour.md)
  * [Workspace Support](moon/workspace.md)
  * [Command-Line Help for `moon`](moon/commands.md)
  * [Module Configuration](moon/module.md)
  * [Package Configuration](moon/package.md)
  * [Measuring code coverage](moon/coverage.md)
* [MoonBit Agent IDE](moonide/index.md)
  * [Overview](moonide/index.md#overview)
  * [Symbol Syntax](moonide/index.md#symbol-syntax)
  * [`moon ide peek-def` - View Symbol Definitions](moonide/index.md#moon-ide-peek-def-view-symbol-definitions)
  * [`moon ide find-references` - Track All Usages](moonide/index.md#moon-ide-find-references-track-all-usages)
  * [`moon ide outline` - Get Structural Overview](moonide/index.md#moon-ide-outline-get-structural-overview)
  * [`moon ide doc` - Discover and Explore APIs](moonide/index.md#moon-ide-doc-discover-and-explore-apis)
* [MoonBit VSCode Plugin](vscode/index.md)
  * [Commands](vscode/index.md#commands)
  * [Actions](vscode/index.md#actions)
  * [Code Lens](vscode/index.md#code-lens)
* [WebAssembly Integration](wasm/index.md)
  * [Component Model](wasm/index.md#component-model)
  * [Custom Export and Import](wasm/index.md#custom-export-and-import)
  * [Q&A](wasm/index.md#q-a)

<!-- path: toolchain/moon/index.md -->
## Moon Build System

## Contents:

* [MoonBit's Build System Tutorial](tutorial.md)
  * [Prerequisites](tutorial.md#prerequisites)
  * [Creating a New Module](tutorial.md#creating-a-new-module)
  * [Understanding the Module Directory Structure](tutorial.md#understanding-the-module-directory-structure)
  * [Working with Packages](tutorial.md#working-with-packages)
  * [Choosing a Target](tutorial.md#choosing-a-target)
  * [Package Importing](tutorial.md#package-importing)
  * [Creating and Using a New Package](tutorial.md#creating-and-using-a-new-package)
  * [Adding Tests](tutorial.md#adding-tests)
* [Running `.mbtx` Scripts](script-mode.md)
  * [Run a `.mbtx` file](script-mode.md#run-a-mbtx-file)
  * [Run a `.mbtx` script from stdin](script-mode.md#run-a-mbtx-script-from-stdin)
* [Use and publish packages](package-manage-tour.md)
  * [Setup mooncakes.io account](package-manage-tour.md#setup-mooncakes-io-account)
  * [Setup MoonBit project](package-manage-tour.md#setup-moonbit-project)
  * [Add dependencies](package-manage-tour.md#add-dependencies)
  * [Import packages from module](package-manage-tour.md#import-packages-from-module)
  * [Remove dependencies](package-manage-tour.md#remove-dependencies)
  * [Publish your module](package-manage-tour.md#publish-your-module)
* [Workspace Support](workspace.md)
  * [Initialize a workspace](workspace.md#initialize-a-workspace)
  * [Add members](workspace.md#add-members)
  * [Work at workspace root](workspace.md#work-at-workspace-root)
  * [Sync member versions](workspace.md#sync-member-versions)
* [Command-Line Help for `moon`](commands.md)
  * [`moon`](commands.md#moon)
  * [`moon new`](commands.md#moon-new)
  * [`moon build`](commands.md#moon-build)
  * [`moon check`](commands.md#moon-check)
  * [`moon run`](commands.md#moon-run)
  * [`moon test`](commands.md#moon-test)
  * [`moon clean`](commands.md#moon-clean)
  * [`moon fmt`](commands.md#moon-fmt)
  * [`moon doc`](commands.md#moon-doc)
  * [`moon info`](commands.md#moon-info)
  * [`moon bench`](commands.md#moon-bench)
  * [`moon add`](commands.md#moon-add)
  * [`moon remove`](commands.md#moon-remove)
  * [`moon install`](commands.md#moon-install)
  * [`moon tree`](commands.md#moon-tree)
  * [`moon login`](commands.md#moon-login)
  * [`moon register`](commands.md#moon-register)
  * [`moon publish`](commands.md#moon-publish)
  * [`moon package`](commands.md#moon-package)
  * [`moon update`](commands.md#moon-update)
  * [`moon coverage`](commands.md#moon-coverage)
  * [`moon coverage analyze`](commands.md#moon-coverage-analyze)
  * [`moon coverage report`](commands.md#moon-coverage-report)
  * [`moon coverage clean`](commands.md#moon-coverage-clean)
  * [`moon generate-build-matrix`](commands.md#moon-generate-build-matrix)
  * [`moon upgrade`](commands.md#moon-upgrade)
  * [`moon shell-completion`](commands.md#moon-shell-completion)
  * [`moon version`](commands.md#moon-version)
* [Module Configuration](module.md)
  * [Name](module.md#name)
  * [Version](module.md#version)
  * [Dependency Management](module.md#dependency-management)
  * [Meta Information](module.md#meta-information)
  * [Include and Exclude](module.md#include-and-exclude)
  * [Preferred Target](module.md#preferred-target)
  * [Supported Targets](module.md#supported-targets)
  * [Source directory](module.md#source-directory)
  * [Warning List](module.md#warning-list)
  * [Scripts](module.md#scripts)
* [Package Configuration](package.md)
  * [New format (`moon.pkg`)](package.md#new-format-moon-pkg)
  * [Name](package.md#name)
  * [Formatter](package.md#formatter)
  * [is-main](package.md#is-main)
  * [Importing dependencies](package.md#importing-dependencies)
  * [Maximum Concurrent Tests](package.md#maximum-concurrent-tests)
  * [Conditional Compilation](package.md#conditional-compilation)
  * [Supported Targets](package.md#supported-targets)
  * [Native Stub Files](package.md#native-stub-files)
  * [Link Options](package.md#link-options)
  * [Pre-build](package.md#pre-build)
  * [Warnings List](package.md#warnings-list)
  * [Virtual Package](package.md#virtual-package)
* [Measuring code coverage](coverage.md)
  * [Running code coverage in tests](coverage.md#running-code-coverage-in-tests)
  * [Visualizing the coverage results](coverage.md#visualizing-the-coverage-results)
  * [Skipping coverage](coverage.md#skipping-coverage)

<!-- path: toolchain/moonide/index.md -->
## MoonBit Agent IDE

### Overview

`moon ide` is a specialized CLI toolset for navigating, understanding, and exploring MoonBit codebases. It provides semantic-aware tools for code discovery using the compiler's knowledge of your project structure.

These commands use semantic analysis rather than text matching, making them more precise than grep-based searching for code navigation tasks.

#### Available Commands

- **`moon ide peek-def`**: Locate symbol definitions with inline context
- **`moon ide find-references`**: Locate all usages of a symbol across the project
- **`moon ide outline`**: Get a structural overview of files or packages
- **`moon ide doc`**: Discover and explore APIs with documentation

### Symbol Syntax

All `moon ide` subcommands accept a `<symbol>` argument using these patterns:

**Basic symbols:**

- `[@pkg.]symbol` - Symbol in a package (e.g. `parse_int`, `Array`)
- If `@pkg.` is omitted, searches current package and prelude

**Type members:**

- `[@pkg.]Type::member` - Type methods, struct fields, enum variants, trait methods
- Examples: `Array::length`, `@http.Request::new`, `Option::None`

Package prefix `@pkg.` is optional for symbols in the current package and standard library.

### `moon ide peek-def` - View Symbol Definitions

Quickly locate symbol definitions with surrounding context. This is faster and more precise than grepping for declarations.

#### Usage

```bash
moon ide peek-def <symbol> [-loc filename:line[:col]]
```

**Two modes:**

1. **Global search** (no `-loc`): Searches the entire project using the symbol syntax described above
2. **Contextual search** (`-loc` provided): Matches `<symbol>` as a substring at the specified location
   - Line number must be precise; column is optional (used as a hint)
   - The `<symbol>` argument is matched as plain text, not parsed as symbol syntax
   - Useful when a symbol name is ambiguous or appears in multiple contexts

#### Examples

```bash
$ moon ide peek-def Agent
Found 1 symbols matching 'Agent':

`pub (all) struct Agent` in package moonbitlang/maria/agent at ./agent/agent.mbt:17-47

17 | ///|
   | /// Represents an AI agent that interacts with language models and executes tools.
...|
   | pub(all) struct Agent {
...|
...| }
```

```bash
$ moon ide peek-def Agent -loc ./maria.mbt:7
Definition found at file ./maria/agent/agent.mbt
   | ///
   | /// The `Agent` struct encapsulates the complete state and behavior of an AI agent,
...|
24 | pub(all) struct Agent {
   |                 ^^^^^
   |   /// UUID generator for creating unique identifiers.
...|
```

### `moon ide find-references` - Track All Usages

Discover where and how a symbol is used throughout your codebase.

#### Usage

```bash
moon ide find-references <symbol>
```

Note: The `-loc` argument is not yet supported. Always searches globally.

#### Example

```bash
$ moon ide find-references Agent
`pub (all) struct Agent` in package moonbitlang/maria/agent at ./agent/agent.mbt:17-47
17 | ///|
   | /// Represents an AI agent that interacts with language models and executes tools.
...|
   | pub(all) struct Agent {
...|
...| }
Found 98 references of this symbol:
./agent/agent_tool.mbt:41:8-41:13:
   | /// * `agent` : The agent instance whose tools will be enabled or disabled.
   | /// * `tool_names` : A set containing the names of tools that should be enabled.
   | ///   Tools not in this set will be disabled.
41 | pub fn Agent::set_enabled_tools(
   |        ^^^^^
   |   agent : Agent,
   |   tool_names : Set[String],
...
```

### `moon ide outline` - Get Structural Overview

Quickly scan the structure of a file or package to understand its organization.

#### Usage

```bash
moon ide outline <path/to/file_or_directory>
```

Two modes:

- `moon ide outline path/to/file.mbt` - Outline a specific file
- `moon ide outline path/to/directory` - Outline all `.mbt` files in the package

#### Examples

**Package outline** - See all files and their top-level symbols:

```bash
moon ide outline .
maria.mbt:
 L05 | pub struct Maria {
       ...
 L71 | pub fn Maria::close(self : Maria) -> Unit {
       ...
 L84 | pub async fn Maria::start(self : Maria, prompt? : String) -> Unit {
```

**File outline** - Detailed view of a single file:

```bash
$ moon ide outline ./internal/readline/readline.mbt
 L0002 | priv struct Edit {
         ...
 L0008 | pub enum KeyName {
         ...
 L0045 | pub struct Key {
         ...
 L1369 | pub async fn Interface::start(self : Interface) -> Unit {
         ...
 L1383 | pub async fn Interface::read_line(self : Interface) -> String {
         ...
 L1390 | pub async fn Interface::read_key(self : Interface) -> Key {
         ...
```

### `moon ide doc` - Discover and Explore APIs

Query documentation and discover available symbols, packages, and APIs.

#### Usage

```bash
moon ide doc '<query>'
```

#### Query Syntax

The query syntax is specialized for symbol and package discovery:

**Empty query** - List available packages or symbols:

- `moon ide doc ''`
  - In a module: Shows all available packages (including dependencies and `moonbitlang/core`)
  - In a package: Shows all symbols in current package
  - Outside package: Shows all available packages

**Lookup by name:**

- `moon ide doc "[@pkg.]function_name"` - Find functions or values
- `moon ide doc "[@pkg.]TypeName"` - Find types (builtin types don't need prefix)
- `moon ide doc "[@pkg.]Type::member"` - Find type methods or fields
- `moon ide doc "[@pkg.]Type::member"` - Find type methods or fields

**Package exploration:**

- `moon ide doc "@pkg"` - List all exported symbols in a package
- `moon ide doc "@encoding/utf8"` - Works with nested packages
- Examples: `moon ide doc "@json"`, `moon ide doc "@buffer"`

**Globbing** - Use `*` wildcard for partial matches:

- `moon ide doc "String::*rev*"` - Find all String methods containing "rev"
- `moon ide doc "*parse*"` - Find all symbols with "parse" in the name

#### Examples

**Search for type methods:**

```bash
## Search for String methods in standard library:
$ moon ide doc "String"

type String

  pub fn String::add(String, String) -> String
  # ... more methods omitted ...
```

**Explore a package:**

```bash
$ moon ide doc "@buffer"
moonbitlang/core/buffer

fn from_array(ArrayView[Byte]) -> Buffer
## ... omitted ...
```

**Query a specific function:**

```bash
$ moon ide doc "@buffer.new"
package "moonbitlang/core/buffer"

pub fn new(size_hint? : Int) -> Buffer
  Creates ... omitted ...
```

**Use globbing to find related functions:**

```bash
$ moon ide doc "String::*rev*"
package "moonbitlang/core/string"

pub fn String::rev(String) -> String
  Returns ... omitted ...
  # ... more

pub fn String::rev_find(String, StringView) -> Int?
  Returns ... omitted ...
```

<!-- path: toolchain/vscode/index.md -->
## MoonBit VSCode Plugin

MoonBit provides a plugin for Visual Studio Code, available in the
[Visual Studio MarketPlace](https://marketplace.visualstudio.com/items?itemName=moonbit.moonbit-lang)
and [Open VSX Registry](https://open-vsx.org/extension/moonbit/moonbit-lang).

### Commands

The plugin provides several commands, available through
[command palettes](https://code.visualstudio.com/docs/getstarted/userinterface#_command-palette)

- Select backend: It allows you to switch between several backends
- Restart MoonBit language server: It allows you to restart the language server,
  in case it's unresponsive or has some stale state.
- Install MoonBit toolchain: Manually triggers the installation process. The
  extension will check if the installed MoonBit toolchain matches the
  extension's version.
- Get lsp's compiler version: It will display the MoonBit compiler version used
  by the extension.
- Toggle multiline string: It can help switching the chosen text between a plain
  text and the MoonBit's
  [multiline string syntax](../../language/fundamentals.md#string)

### Actions

The plugin also provides several actions, available through
[quick fix](https://code.visualstudio.com/docs/editing/refactoring#_code-actions-quick-fixes-and-refactorings)

- Add missing arms: It allows you to fill up the branches of a `match`
  expression when encountering [Error 0011](../../language/error_codes/E0011.md)

### Code Lens

The plugin provides code lens for each top-level code block, especially test
blocks.

The provided functionalities are:

- Format: format the code block
- Test / Bench: test or bench the test block
- Debug (JavaScript backend only): test the test block with debugger
- Update: update the [snapshot tests](../../language/tests.md#snapshot-tests) in the
  code block
- Trace: turn on/off the tracing of the test block where each assignment will
  have the value rendered next to it

<!-- path: toolchain/wasm/index.md -->
## WebAssembly Integration

MoonBit is a programming language that provides first-class support for
WebAssembly.

### Component Model

Check out [this tutorial](component-model-tutorial.md) on how to work with
[component model](https://component-model.bytecodealliance.org/) in MoonBit.

### Custom Export and Import

Check out [FFI](../../language/ffi.md) section on how to import or export functions.

### Q&A

1. Q: What is `spectest.print_char`

   A: It's how MoonBit prints. It prints a UTF-16 unicode code at a time. For
   portability, avoid using `println`. If this does occur in the final result,
   consider using [`wasm-merge`](https://github.com/WebAssembly/binaryen) or
   similar tools.
