MoonBit Documentation

repository·main·Indexed 25 days ago

https://github.com/moonbitlang/moonbit-docs

Official documentation for the MoonBit programming language, featuring an interactive language tour, technical guides, and static language documentation. Includes resources on language basics such as variables, functions with labeled and optional arguments, block scoping, tuples, and control flow, as well as implementation examples for lambda expressions and segment trees.

Tokens
114K
Snippets
161
Records
771
Agent score
81%

What's inside MoonBit Docs

  1. Overview of the MoonBit Language

    main

    MoonBit is an AI-native programming language toolchain designed for cloud and edge computing. It is optimized for high performance and small binary sizes, making it suitable for environments where resource efficiency is critical.

    Target Backends

    MoonBit supports multiple backends within a single module, allowing for mixed-backend projects:

    • wasm
    • wasm-gc
    • js
    • native

    Key Characteristics

    • Small WASM Output: Generates significantly smaller WASM binaries compared to existing solutions.
    • High Performance: Offers fast runtime performance and state-of-the-art compile-time performance.
    • Design Philosophy: Uses a simple, practical, and data-oriented language design.
    • Current Status: Currently in beta-preview. While suitable for production, users should expect a fast-moving ecosystem and potential backwards-incompatible changes.
  2. Overview of MoonBit Agent IDE (`moon ide`)

    main
    The moon ide CLI toolset is designed for semantic-aware navigation and exploration of MoonBit codebases. Unlike text-based tools like grep, moon ide uses the compiler's semantic analysis to provide precise code discovery, making it more reliable for understanding project structures and symbol relationships.
  3. Explore MoonBit toolchains

    main

    MoonBit provides several specialized toolchains for different development workflows:

    • moon Build System: The core build system for managing MoonBit projects.
    • moon ide (Agent IDE): A specialized agentic IDE for MoonBit development.
    • VSCode Plugin: An extension for the Visual Studio Code editor to provide MoonBit support.
    • WebAssembly (Wasm) Toolchain: Tools and instructions for using MoonBit with WebAssembly.
  4. Explore MoonBit tutorials and transition guides

    main

    The MoonBit tutorial repository provides several paths for learning depending on your current experience level:

    For Beginners

    • Tour for Beginners: A structured introduction to the language.
    • Native CLI Quickstart: Instructions for setting up and using the MoonBit Command Line Interface.
    • Fullstack in One MoonBit Project: A guide on building complete fullstack applications using a single MoonBit project.

    For Experienced Developers

    • MoonBit for Go Programmers: A transition guide specifically designed for developers moving from Go to MoonBit.
  5. Understand MoonBit FFI Backends

    main

    MoonBit's Foreign Function Interface (FFI) behavior depends on the target backend. Because the 'world' (runtime, memory model, and host environment) differs between targets, FFI declarations must be understood in the context of the backend being used.

    Supported Backends

    • Wasm: WebAssembly with post-MVP proposals (bulk-memory-operations, multi-value, reference-types). The init function is compiled as a start function, and main is exported as _start.
    • Wasm GC: WebAssembly with the Garbage Collection proposal. Uses reference types (struct, array) instead of linear memory by default. Supports multi-value and JS string builtins. Like standard Wasm, init is the start function and main is exported as _start.
    • JavaScript: Generates a JavaScript file (CommonJS, ES module, or IIFE depending on configuration).
    • C: Generates a C file. The toolchain compiles this into an executable based on configuration.
    • LLVM (experimental): Generates an object file. Note: This backend does not support FFIs.

    Portability Warning for Wasm

    Functions interacting with the outside world in Wasm/Wasm GC rely on host functions. For example, println imports spectest.print_char. Using the env package or specific moonbitlang/x packages may rely on host functions specific to the MoonBit runtime. Avoid these if you require portable Wasm modules.

  6. MoonBit Runtime and Memory Management

    main

    MoonBit can target multiple runtimes:

    • WebAssembly: For web and edge computing.
    • JavaScript: For Node.js integration.
    • C: For native performance.
    • LLVM: Experimental native backend.

    Memory Management Strategies:

    • Wasm/C backends: Uses reference counting without cycle detection.
    • Wasm GC/JavaScript backends: Leverages the host runtime's garbage collector.
  7. What is a Segment Tree?

    main

    A Segment Tree is a data structure used to solve range query problems (such as range sums, minimums, or maximums) efficiently. It works by recursively dividing a linear sequence into segments until reaching segments of length one.

    Key Characteristics:

    • Complexity: For a sequence of length $N$, any range query can be answered by querying at most $\log N$ segments, ensuring $O(\log N)$ complexity.
    • Structure: It is a tree where each node represents a segment of the original sequence. Internal nodes store aggregated data (like the sum) of their children, and leaf nodes represent individual elements.
    • Query Logic: To query a range, the tree is traversed from top to bottom. The algorithm selects the minimum number of pre-computed segments that collectively cover the target range.
  8. Customize integer values of constant enums

    main

    In all MoonBit backends, constant enums (enums where all constructors have no payload) are translated to integers. You can customize the integer value of each constructor by adding = <integer literal> after the declaration. This is particularly useful for binding C library flags.

    If a value is not specified, it defaults to one plus the value of the previous constructor (or zero for the first).

    enum SpecialNumbers {
      Zero = 0
      One
      Two
      Three
      Ten = 10
      FourtyTwo = 42
    }
  9. How the MoonBit method system works

    main

    In MoonBit, a method is a top-level function associated with a type constructor. Unlike traditional object-oriented languages, methods are not contained within a class body but are defined as standalone functions using a specific naming convention.

    Defining Methods

    To define a method for a type T, prepend T:: to the function name: fn T::method_name(...).

    Inside the method signature, you can use the keyword Self to refer to the type being defined.

    WARNING

    MoonBit currently supports a shorthand syntax where if the first parameter is named self, the function is automatically treated as a method for that parameter's type. This syntax is subject to deprecation and is not recommended for new code.

    Calling Methods

    You can invoke methods using two styles:

    1. Qualified Syntax: T::method_name(..)
    2. Dot Syntax: x.method(...) (where x is an instance of type T). MoonBit automatically resolves the correct method based on the type of x.
  10. Use Or Patterns in pattern matching

    main

    Or patterns allow you to combine multiple cases in a pattern match if they share the same logic or data structure. This reduces verbosity when different enum variants should be handled identically.

    Rules for Or Patterns:

    • You can combine sub-patterns using the | operator.
    • If sub-patterns introduce new variables, those variables must have the same name and the same type across all sub-patterns. This ensures the variable can be used uniformly in the match arm's body.
  11. Implement lazy lists with NConstr graph nodes

    main

    In the G-Machine implementation, data structures like lazy lists are represented using NConstr graph nodes. An NConstr node consists of:

    • A tag identifying the constructor (e.g., 0 for Nil, 1 for Cons).
    • A list of addresses for storing substructures (the length corresponds to the constructor's arity).

    To support these, the VM requires the following instructions:

    • Split: To deconstruct a list.
    • Pack: To construct a list.
    • CaseJump: To implement case expressions for pattern matching.
    • Print: To recursively evaluate and print NConstr nodes and their substructures.