Skip to content

Instantly share code, notes, and snippets.

@mizchi
Created June 23, 2025 08:50
Show Gist options
  • Save mizchi/6baf1c679adc45ba13c16742fe0b41db to your computer and use it in GitHub Desktop.
Save mizchi/6baf1c679adc45ba13c16742fe0b41db to your computer and use it in GitHub Desktop.

MoonBit Knowledge Base for LLMs (Claude Code)

This document contains essential MoonBit knowledge that LLMs cannot know without external environment access. Last updated: December 2024.

Language Version and Status

Current Status: Beta (as of December 2024)

  • Version 1.0 planned for 2026
  • Core language features are now stable
  • Breaking changes will follow RFC process

Actual Project Structure

# Create new project
moon new project-name

# Generated structure:
project-name/
├── moon.mod.json       # Project manifest
├── lib/                # Library package
│   ├── moon.pkg.json   # Package config
│   ├── lib.mbt         # Implementation
│   └── lib_test.mbt    # Tests
└── main/               # Main package
    ├── moon.pkg.json
    └── main.mbt        # Entry point

moon.mod.json Example

{
  "name": "username/project-name",
  "version": "0.1.0",
  "deps": {},
  "readme": "README.md",
  "repository": "https://github.com/username/project-name",
  "license": "MIT"
}

moon.pkg.json Example

{
  "import": ["lib"],
  "test_import": ["@test"]
}

Actual CLI Commands

# Project management
moon new <name>           # Create new project
moon init                 # Initialize in existing directory
moon version             # Show moon version

# Development
moon check               # Type check only
moon build               # Build project
moon run main [args]     # Run main package
moon test                # Run all tests
moon clean               # Clean build artifacts

# Package management
moon add <package>       # Add dependency
moon remove <package>    # Remove dependency
moon update              # Update dependencies
moon publish             # Publish to mooncakes.io

# Documentation
moon doc                 # Generate documentation
moon info                # Show project info

# Formatting
moon fmt                 # Format code
moon fmt --check         # Check formatting

# Coverage
moon test --coverage     # Run tests with coverage
moon coverage report     # Show coverage report

Real File Extensions

  • .mbt - MoonBit source files
  • .mbt.md - Markdown-oriented programming files (new feature)
  • _test.mbt - Test files
  • .mbti - Interface files (for virtual packages)

Actual Import Syntax

// Import from standard library
fn main {
  let list = @list.of([1, 2, 3])
  let map = @map.Map::new()
  println(@json.stringify(data))
}

// Import from local package
// If lib package exports process_data function
fn main {
  let result = @lib.process_data(input)
}

// No explicit import statements - use @ prefix

Standard Library Modules (Actual)

// Core types
@int, @int64, @uint, @uint64
@double, @float
@string, @char, @byte, @bytes
@bool, @unit

// Collections
@array.Array[T]
@list.List[T]
@map.Map[K, V]
@hashmap.HashMap[K, V]
@set.Set[T]
@queue.Queue[T]

// Utilities
@option.Option[T]
@result.Result[T, E]
@ref.Ref[T]
@lazy.Lazy[T]

// I/O and System
@io
@fs
@env
@time

// Serialization
@json
@serde

// Testing
@test
@assertion

// Math
@math
@random

// Algorithms
@sort
@search

Actual Syntax Features (2024)

1. String Interpolation

let name = "Alice"
let age = 30
println("Hello, \{name}! You are \{age} years old.")
// Note: Uses \{} not ${} or {}

2. Array Syntax

// Array literal
let arr = [1, 2, 3, 4, 5]

// Array methods
arr.push(6)
arr.pop()
arr.length()
arr.map(fn(x) { x * 2 })
arr.filter(fn(x) { x % 2 == 0 })
arr.fold(0, fn(acc, x) { acc + x })

3. Pattern Matching

// Must be exhaustive
match value {
  Some(x) => x
  None => 0
}

// Guard clauses
match x {
  n if n > 0 => "positive"
  0 => "zero"
  _ => "negative"
}

4. Error Handling Operators

// Option
let value = some_option.or(default_value)
let mapped = some_option.map(fn(x) { x + 1 })

// Result
let result = operation()
  .map_err(fn(e) { "Error: " + e.to_string() })
  .and_then(fn(x) { another_operation(x) })

5. Struct Update Syntax

type Person { name: String; age: Int }
let p1 = { name: "Alice", age: 30 }
let p2 = { ..p1, age: 31 }  // Spread syntax

6. Method Definition

// Methods use :: syntax
fn Array::sum(self : Array[Int]) -> Int {
  self.fold(0, fn(acc, x) { acc + x })
}

// Call with dot notation
let total = [1, 2, 3].sum()

7. Async Functions (Experimental)

async fn fetch_data() -> String! {
  let response = http_get!(url)  // Note: ! suffix for async calls
  response.text!()
}

// No await keyword needed

8. Type Constraints

fn sort[T : Compare](arr : Array[T]) -> Array[T] {
  // T must implement Compare trait
}

fn debug[T : Show + Eq](value : T) {
  // Multiple constraints with +
}

Common Error Messages and Solutions

1. "Type annotation needed"

// Error
let empty = []

// Fix
let empty : Array[Int] = []

2. "Cannot assign to immutable variable"

// Error
let x = 5
x = 6

// Fix
let mut x = 5
x = 6

3. "Non-exhaustive pattern match"

// Error
match option {
  Some(x) => x
  // Missing None case
}

// Fix
match option {
  Some(x) => x
  None => default
}

4. "Package not found"

// Error in moon.pkg.json
{
  "import": ["nonexistent"]
}

// Fix: Add to moon.mod.json deps first
{
  "deps": {
    "package-name": "0.1.0"
  }
}

WebAssembly Integration

Build for WebAssembly

moon build --target wasm
# Outputs to target/wasm/release/build/main/main.wasm

JavaScript Bindings

// Export to JavaScript
pub fn add(a : Int, b : Int) -> Int {
  a + b
}

// Use extern for importing
extern fn console_log(s : String) = "console" "log"

Optimization Flags

moon build --target wasm --release  # Optimized build
moon build --target wasm -g         # Debug build

Testing Patterns

Basic Test

test "addition works" {
  assert_eq(1 + 1, 2)
  assert_ne(1 + 1, 3)
  assert(1 < 2, "1 should be less than 2")
}

Test with Errors

test "error handling" {
  match risky_operation() {
    Ok(value) => assert_eq(value, expected)
    Err(e) => assert(false, "Should not error: \{e}")
  }
}

Property-based Testing

test "reverse twice equals original" {
  @quickcheck.check(fn(arr : Array[Int]) {
    arr.reverse().reverse() == arr
  })
}

Package Management

Publishing to mooncakes.io

# 1. Update moon.mod.json with your username
{
  "name": "yourusername/package-name",
  "version": "0.1.0"
}

# 2. Login (first time)
moon login

# 3. Publish
moon publish

Using Published Packages

// moon.mod.json
{
  "deps": {
    "username/package": "0.1.0"
  }
}

Virtual Packages (New Feature)

Define Virtual Package

// virtual-pkg/moon.pkg.json
{
  "virtual": true,
  "has-default": true
}

Interface File (.mbti)

// logger.mbti
fn log(String) -> Unit
fn error(String) -> Unit

Implementation Selection

// main/moon.pkg.json
{
  "import": ["virtual-logger"],
  "overrides": {
    "virtual-logger": "my-logger-impl"
  }
}

Build Targets

  • wasm - WebAssembly (default)
  • wasm-gc - WebAssembly with GC proposal
  • js - JavaScript (ES6+)
  • native - Native code via LLVM
  • riscv - RISC-V assembly

Environment Variables

// Access command line arguments
let args = @env.get_args()

// Note: Full environment variable access may be limited
// depending on target platform

Performance Considerations

  1. Arrays are mutable and efficient

    • Random access: O(1)
    • Append: O(1) amortized
  2. Prefer iterators over intermediate arrays

    // Good
    arr.filter(pred).map(transform).fold(init, combine)
    
    // Better (if available)
    arr.filter_map(fn(x) { ... })
  3. String concatenation

    // Inefficient for many concatenations
    let s = s1 + s2 + s3 + s4
    
    // Better: Use StringBuilder when available
    let sb = @string.StringBuilder::new()
    sb.append(s1)
    sb.append(s2)
    sb.to_string()

Debugging

Print Debugging

println("Debug: \{variable}")
debug(value)  // Pretty-prints complex types

Assertions

assert(condition, "Error message")
debug_assert(condition)  // Only in debug builds

Common Pitfalls

  1. Forgetting mut for mutable variables
  2. Not handling all enum cases in match
  3. Type inference limitations with empty collections
  4. Async function calls need ! suffix
  5. No null/nil - use Option[T]
  6. Strings are immutable
  7. No implicit type conversions

Integration with Editors

VS Code

  • Official extension: "MoonBit"
  • Features: syntax highlighting, code completion, inline errors, formatting

Command Line

moon lsp  # Start language server

Recent Changes (2024)

  1. Markdown-oriented programming (.mbt.md files)
  2. Virtual packages for dependency injection
  3. Async/await with ! syntax (experimental)
  4. Native backend via LLVM
  5. Open-sourced compiler
  6. Python interop (in development)

This document should be updated as MoonBit evolves. Check official sources for the latest information.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment