Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

简体中文

Puddi is a statically typed, expression-oriented language that compiles to WebAssembly. One source language targets the browser, WASI runtimes (servers, edge functions, command-line tools) and plugin hosts. Programs use the WebAssembly engine’s garbage collector (WasmGC) and talk to their host through the Component Model.

@derive(Eq, Show)
struct Todo {
    title: Str
    var done: Bool
}

fn main() {
    let todos = [Todo { title: "spec", done: true }, Todo { title: "compiler", done: false }]
    let pending = todos.filter(|t| !t.done)
    print("{pending.len()} of {todos.len()} left")
}
1 of 2 left

At a glance

TopicPuddi
OutputWebAssembly only; JavaScript appears only as loader glue
Hostsbrowser, wasi (WASI 0.3), plugin (any Component Model host)
MemoryWasmGC, no manual memory management
Typesstatic, with local type inference
Polymorphismgenerics, nominal traits, dyn Trait
Missing values and errorsno null: Option, Result, ?, AnyErr; panics trap
Mutabilitylet and var bindings, mutability declared per field
NumbersInt is 32-bit and overflow traps; lossless widening is implicit
Concurrencyasync fn, .await, structured task scopes, isolated workers
Toolchainone pud command, a pud.toml manifest, git-based packages

How this book is organized

  • Getting started installs pud and walks through a first program and a first package.
  • Language guide introduces the language one topic at a time. Every complete example in it is compiled, and the ones with output are run, against the released toolchain.
  • Toolchain and Host interop cover building for each target and talking to hosts.
  • Standard library lists the prelude and the std modules.
  • Reference holds the language specification, which is the normative definition of Puddi, and the conformance suite that checks the toolchain against it.

This book documents Puddi 0.1, the first release. The language is a draft and may still change between 0.x releases; the changelog records what changed.

Choose a path

I want toStart here
Run a command-line programHello, Puddi and the bundled examples
Put a program on a web pageThe browser
Write a plugin for an existing hostPlugins and WIT imports
Understand a compiler errorTroubleshooting and the implementation status
Work on the compilerCompiler development and contributing

Getting help

Installation

简体中文

pud is a single executable that contains the compiler, the formatter, the package manager and a WebAssembly runtime for the wasi target.

Install script

macOS and Linux, on x86_64 or arm64:

curl -fsSL https://raw.githubusercontent.com/puddi-lang/puddi/main/install.sh | sh

Windows, in PowerShell:

irm https://raw.githubusercontent.com/puddi-lang/puddi/main/install.ps1 | iex

The script downloads the latest release, checks its SHA-256 checksum, installs pud into ~/.pud/bin and adds that directory to your PATH (through ~/.profile, ~/.bashrc, ~/.zshrc and fish’s conf.d on Unix, or the user PATH on Windows). Open a new terminal afterwards, or follow the command the script prints.

VariableEffect
PUD_VERSIONinstall a specific release, for example v0.1.2 (default: latest)
PUD_INSTALLinstall into this directory instead of ~/.pud
PUD_NO_MODIFY_PATHset to 1 to leave shell profiles and PATH alone
curl -fsSL https://raw.githubusercontent.com/puddi-lang/puddi/main/install.sh | PUD_VERSION=v0.1.2 sh

Run the script again to upgrade. To uninstall, remove the installed executable and remove the path entry the script added to your shell profile or Windows user PATH. If you used PUD_INSTALL, look under that directory instead of ~/.pud.

Release archives

Every release has archives for these targets, each with a .sha256 file, plus a combined SHA256SUMS:

ArchivePlatform
pud-x86_64-unknown-linux-gnu.tar.gzLinux x86_64 (glibc 2.35 or newer)
pud-aarch64-unknown-linux-gnu.tar.gzLinux arm64 (glibc 2.35 or newer)
pud-x86_64-apple-darwin.tar.gzmacOS Intel
pud-aarch64-apple-darwin.tar.gzmacOS Apple silicon
pud-x86_64-pc-windows-msvc.zipWindows x64 (also used on Windows arm64)

Unpack the archive and put pud (or pud.exe) anywhere on your PATH.

From source

With a current stable Rust toolchain:

cargo install --locked --git https://github.com/puddi-lang/puddi --tag v0.1.2

cargo install --no-default-features builds pud without the embedded runtime. It compiles much faster, but pud run then needs an external WASI 0.3 host (see Targets).

Node.js

pud test and the browser target run code on a JavaScript host and need Node.js 22 or newer. Async code under Node.js needs JSPI, which is enabled by default from Node.js 24. The embedded WASI and plugin runners do not need Node.js. See Troubleshooting if the JS host reports a missing WebAssembly feature.

Check the installation

pud --version

Hello, Puddi

简体中文

A single file

pud can run one file without any project setup. Save this as hello.pud:

fn main() {
    let name = "Puddi"
    print("Hello, {name}!")
}
Hello, Puddi!

and run it:

pud run hello.pud

pud run compiles the file to a WASI component and runs it in the embedded WebAssembly runtime. There is no separate build step to remember: the compiler is fast enough to run on every invocation.

A few things to notice:

  • fn main() is the entry point of a program.
  • let introduces a binding. Its type, Str, is inferred.
  • Strings interpolate any expression in braces: "{name}", "{1 + 2}".
  • Statements end at the end of a line. Semicolons are optional.

Arguments and exit status

Command-line arguments come from std.env, and main can return a Result: when it returns Err, the error is printed and the program exits with a failure status.

import std.env

fn main() -> Result<(), Str> {
    let args = env.args()
    let Some(who) = args.get(1) else {
        return Err("usage: greet <name>")
    }
    print("Hello, {who}!")
    Ok(())
}
pud run greet.pud -- Ada

Everything after -- is passed to the program; env.args() starts with the program name.

Checking without running

pud check hello.pud     # type-check only
pud fmt hello.pud       # format in the official style

Next, turn the file into a package.

Packages

简体中文

A package is a directory with a pud.toml manifest and a src/ directory.

pud new hello
cd hello
pud run

pud new creates:

hello/
├── pud.toml
└── src/
    └── main.pud

with this manifest:

[package]
name = "hello"
version = "0.1.0"
puddi = "0.1"

Inside a package, pud commands work on the whole package and look for pud.toml in the current directory or a parent directory, so pud run, pud test and pud build need no arguments.

Modules

Each file is a module, named after its path under src/. src/main.pud is the root of a program (src/lib.pud for a library), src/geometry.pud is the module geometry and src/net/url.pud is net.url.

// src/geometry.pud
pub struct Point {
    pub x: Float
    pub y: Float
}

pub fn distance(a: Point, b: Point) -> Float {
    ((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)).sqrt()
}
// src/main.pud
import geometry
import geometry.{Point}

fn main() {
    let d = geometry.distance(Point { x: 0.0, y: 0.0 }, Point { x: 3.0, y: 4.0 })
    print("{d}")
}

Items are private to their module unless they are marked pub. See Modules for the details.

Building

pud build                     # target/wasi/hello.wasm
pud build --target browser    # target/browser/hello.wasm and puddi.mjs
pud run --target browser      # build and serve on http://127.0.0.1:8000

The build output is a WebAssembly component in target/<target>/. The generated .gitignore already excludes target/. See the target matrix for the files each build produces.

Dependencies

pud add github.com/someone/lib@1.2

adds the dependency to pud.toml and records its exact commit in pud.lock, which belongs in version control. See Dependencies.

Tests

test blocks can sit next to the code they test, in any file:

fn add(a: Int, b: Int) -> Int { a + b }

test "addition" {
    assert_eq(add(2, 2), 4)
}

pud test compiles and runs them, each in a fresh instance. See Testing.

Bundled examples

简体中文

The compiler repository includes four small packages. Install pud first, then clone the compiler repository. The commands below run from the repository root.

PackageWhat it demonstratesCommand
todoRead data from JSON and handle errorscd examples/todo then pud run
wordfreqRead standard input and count tokens with a mapprintf 'a b a\n' | pud run examples/wordfreq
pluginImplement exports for a custom WIT worldpud build examples/plugin --target plugin
plugin-hostUse several host capabilities in one componentpud build examples/plugin-host --target plugin

todo reads todos.json from the current working directory and reports 2 of 4 left. wordfreq prints two lines, with count 2 for a and count 1 for b. The plugin builds produce target/plugin/plug.wasm and target/plugin/plugin-host.wasm under their respective package directories.

For a plugin invocation you can reproduce end to end, follow Plugins. The greet export in the plugin example calls the custom demo:host/log interface, which the embedded runner cannot provide. The classify export does not call that interface.

Bindings and values

简体中文

let and var

let declares a binding that cannot be reassigned. var declares one that can.

fn main() {
    let greeting = "hello"
    var count = 0
    count += 1
    count = count * 10
    print("{greeting} {count}")
}
hello 10

Types of local bindings are inferred. Write a type after the name when you want to state it or when there is nothing to infer it from:

fn main() {
    let ratio: Float = 1
    let names: List<Str> = []
    print("{ratio} {names}")
}
1.0 []

Assigning to a let binding is a compile error:

fn main() {
    let total = 1
    total = 2
}

Values are references

Structs, enums and collections are reference values. Assigning one or passing it to a function shares the same object; nothing is copied.

fn main() {
    let a = [1, 2]
    let b = a
    b.push(3)
    print("{a}")
    print("{same(a, b)}")
}
[1, 2, 3]
true

let only stops the binding from changing. Whether the object itself can change is decided by its type: a List can grow, and a struct field can be assigned only if it is declared var (see Structs and enums).

== compares values through the Eq trait; same(a, b) checks whether two references point to the same object.

Expressions everywhere

Blocks, if, match and loop are expressions. The last expression in a block is its value:

fn main() {
    let x = 7
    let size = {
        let doubled = x * 2
        if doubled > 10 { "big" } else { "small" }
    }
    print(size)
}
big

Statements and lines

A newline ends a statement, and ; can separate statements on one line. A line continues onto the next when it ends with a binary operator or a comma, when a ( or [ is still open, or when the next line starts with .:

fn main() {
    let price = 3
    let count = 4
    let total = price * count +
        2
    let words = ["a", "bb", "ccc"]
        .map(|w| w.to_upper())
    print("{total} {words}"); print("done")
}
14 ["A", "BB", "CCC"]
done

Comments

// a line comment
/* a block comment /* which may nest */ */
/// a doc comment, attached to the next declaration and read by `pud doc`

Naming

Types, traits and enum variants are UpperCamelCase. Functions, variables, fields and modules are snake_case. Constants are SCREAMING_SNAKE_CASE:

const MAX_RETRIES: Int = 3

fn main() {
    print("up to {MAX_RETRIES} retries")
}
up to 3 retries

A constant’s initializer must be a constant expression: literals, other constants, arithmetic and comparisons on them, and struct, tuple and enum construction.

Numbers

简体中文

TypeMeaning
Int32-bit signed integer, the same type as I32
I8 I16 I32 I64signed integers
U8 U16 U32 U64unsigned integers
Float64-bit float, the same type as F64
F32 F64floats

Integer literals default to Int and float literals to Float, unless the context asks for another type. Literals can use _ as a separator and 0x, 0b and 0o prefixes. A literal that does not fit its type is a compile error.

fn main() {
    let a = 1_000
    let mask: U8 = 0xFF
    let big: I64 = 3_000_000_000
    let f = 2.5e-3
    print("{a} {mask} {big} {f}")
}
1000 255 3000000000 0.0025

Overflow and division

Integer overflow is not silent: it traps (see panics). So does integer division or remainder by zero. / on integers truncates toward zero, and % takes the sign of the dividend.

fn main() {
    print("{-7 / 2} {-7 % 2}")
    let x: U8 = 250
    print("{x.wrapping_add(10)} {x.saturating_add(10)} {x.checked_add(10)}")
}
-3 -1
4 255 None

wrapping_*, saturating_* and checked_* methods exist for the arithmetic operators when you want a different behavior.

Widening is implicit

A conversion that can never lose information happens on its own, wherever the expected type is known: in annotated bindings, arguments, return values, fields and collection elements.

fn average(total: Float, n: Float) -> Float { total / n }

fn main() {
    let n: Int = 4
    let wide: I64 = n
    let small: U8 = 200
    print("{average(10, n)} {wide + 1} {small + n}")
}
2.5 5 204

For a binary operator with two different numeric types, both sides widen to the narrowest type that holds both. U8 + Int is Int. When no such type exists, as for I64 and U64 or I64 and Float, it is a compile error. I64 and U64 never widen to a float, since F64 cannot represent every 64-bit integer.

FromWidens to
I8I16 I32 I64 F32 F64
I16I32 I64 F32 F64
I32I64 F64
U8U16 U32 U64 I16 I32 I64 F32 F64
U16U32 U64 I32 I64 F32 F64
U32U64 I64 F64
F32F64

Narrowing is explicit

A conversion that might lose information is always a method call. to_<type>() returns an Option that is None when the value does not fit; methods such as truncate_to_int() and round_to_int() say how they lose information.

fn main() {
    let big: I64 = 5_000_000_000
    let fits: I64 = 42
    print("{big.to_int()} {fits.to_int()}")
    print("{3.7.truncate_to_int()} {3.7.round_to_int()}")
}
None Some(42)
3 4

Floats

Floats have the usual methods: sqrt, pow, abs, floor, ceil, round, sin, cos, ln and more, and std.math has the same as functions plus constants such as math.PI. Floats print with the shortest digits that read back as the same value, and a float with no fractional part keeps its .0.

fn main() {
    let x = 2.0
    print("{x.sqrt()} {0.1 + 0.2} {x.pow(10.0)}")
}
1.4142135623730951 0.30000000000000004 1024.0

Parsing

fn main() {
    print("{"42".parse_int()} {"x".parse_int()} {"1.5".parse_float()}")
}
Some(42) None Some(1.5)

Strings and characters

简体中文

Str

Str is an immutable Unicode string. String literals use double quotes and interpolate expressions in braces; the expression’s type must implement Show. A literal brace is written \{ or \}.

fn main() {
    let name = "Ada"
    let unread = 2
    print("hi {name}, you have {unread + 1} messages")
    print("a literal \{brace\}")
    print("tab\tnewline\\n quote\" smile \u{1F600}")
}
hi Ada, you have 3 messages
a literal {brace}
tab	newline\n quote" smile 😀

Escapes are \n \r \t \0 \\ \" \' \{ \} and \u{...}.

No integer indexing

A Str cannot be indexed by an integer and has no len(), because “the length of a string” means different things: bytes, code points or user-visible characters. Ask for the one you mean:

fn main() {
    let s = "héllo👋🏽"
    print("{s.utf8_len()} bytes")
    print("{s.chars().count()} code points")
    print("{s.graphemes().count()} graphemes")
}
14 bytes
7 code points
6 graphemes

chars() iterates code points as Char values, and graphemes() iterates grapheme clusters (what a reader sees as one character) as Str values.

Searching and slicing

Positions in a string are StrIndex values. They come from searching (find, rfind), from start() and end(), or from moving an index by code points with advance(i, n) and next_index(i), and they are only valid for the string that produced them.

fn main() {
    let line = "key=value"
    match line.find("=") {
        Some(i) -> {
            print(line.slice_to(i))
            let after = line.advance(i, 1).unwrap()
            print(line.slice_from(after))
        }
        None -> print("no =")
    }
    if let Some((k, v)) = line.split_once("=") {
        print("{k} -> {v}")
    }
}
key
value
key -> value

Common methods

fn main() {
    let s = "  Hello, World  "
    let t = s.trim()
    print(t.to_lower())
    print("{t.contains("World")} {t.starts_with("He")} {t.ends_with("!")}")
    print(t.replace("World", "Puddi"))
    print("{"a,b,,c".split(",")}")
    print("{"one two  three".split_whitespace()}")
    print(["x", "y", "z"].join("-"))
    print("ab".repeat(3))
}
hello, world
true true false
Hello, Puddi
["a", "b", "", "c"]
["one", "two", "three"]
x-y-z
ababab

Other methods include lines, trim_start, trim_end, rfind, slice, is_empty, parse_int, parse_float and to_bytes. + concatenates two strings.

Building strings

Use StrBuilder to assemble a string piece by piece:

fn main() {
    let b = StrBuilder.new()
    for i in 0..3 {
        b.push("item {i};")
    }
    b.push_char('!')
    print(b.to_str())
}
item 0;item 1;item 2;!

Char

A Char is a Unicode scalar value, written in single quotes: 'a', '\n', '\u{1F600}'.

fn main() {
    let c = 'q'
    print("{c.is_alpha()} {c.to_upper()} {c.to_u32()} {'7'.to_digit(10)}")
}
true Q 113 Some(7)

Case mapping covers ASCII only in Puddi 0.1.

Collections

简体中文

TypeLiteralNotes
List<T>[1, 2, 3]growable array
Map<K, V>["a": 1, "b": 2], empty [:]keys need Eq + Hash; keeps insertion order
Set<T>Set.from([1, 2, 3])elements need Eq + Hash; keeps insertion order

Lists

fn main() {
    let xs = [3, 1, 2]
    xs.push(5)
    print("{xs} has {xs.len()} items, first {xs[0]}")
    print("{xs.get(10)} {xs.first()} {xs.pop()}")
    xs[1] = 10
    print("{xs.sorted()} {xs.contains(10)} {xs.index_of(2)}")
}
[3, 1, 2, 5] has 4 items, first 3
None Some(3) Some(5)
[2, 3, 10] true Some(2)

xs[i] traps when i is out of bounds; xs.get(i) returns an Option instead.

Lists have the usual functional methods, which return new lists:

fn main() {
    let words = ["apple", "fig", "banana", "kiwi"]
    let short = words.filter(|w| w.chars().count() <= 4)
    let shout = short.map(|w| w.to_upper())
    let total = words.fold(0, |acc, w| acc + w.chars().count())
    print("{short} {shout} {total}")
    print("{words.any(|w| w.starts_with("b"))} {words.find(|w| w.ends_with("i"))}")
    print("{[1, 2, 3].sum()} {[4, 9, 2].max()}")
    for (i, w) in words.enumerate() {
        if i < 2 { print("{i}: {w}") }
    }
}
["fig", "kiwi"] ["FIG", "KIWI"] 18
true Some("kiwi")
6 Some(9)
0: apple
1: fig

Sorting in place uses sort, sort_by and sort_by_key; sorted and reversed return a sorted or reversed copy.

Maps

fn main() {
    let ages = ["ada": 36, "alan": 41]
    ages["grace"] = 85
    ages.insert("ada", 37)
    print("{ages["ada"]} {ages.get("bob")} {ages.get_or("bob", 0)}")
    print("{ages.contains_key("alan")} {ages.len()}")
    for (name, age) in ages {
        print("{name} is {age}")
    }
    ages.remove("alan")
    print("{ages.keys()}")
}
37 None 0
true 3
ada is 37
alan is 41
grace is 85
["ada", "grace"]

m[k] traps when the key is missing; m.get(k) returns an Option. Iterating a map yields (key, value) tuples in insertion order.

Sets

fn main() {
    let a = Set.from([1, 2, 3])
    let b = Set.from([2, 3, 4])
    a.insert(3)
    print("{a.len()} {a.contains(2)}")
    print("{a.union(b).to_list()} {a.intersection(b).to_list()} {a.difference(b).to_list()}")
}
3 true
[1, 2, 3, 4] [2, 3] [1]

Read-only views

Every collection is mutable through its own type. When a function should only read, take a view: ListView<T>, MapView<K, V> or SetView<T>. A collection converts to its view implicitly, and a view has no methods that modify.

fn count_long(words: ListView<Str>) -> Int {
    words.filter(|w| w.chars().count() > 3).len()
}

fn main() {
    let words = ["tea", "coffee", "water"]
    print("{count_long(words)}")
}
2

Ranges and iterators

a..b is a half-open range and a..=b an inclusive one. Ranges, lists, maps and sets can all be used in for loops. .iter() gives a lazy iterator with map, filter, take, skip, zip, chain, enumerate and collect:

fn main() {
    let squares = (1..=10).iter().map(|n| n * n).filter(|n| n % 2 == 0).take(3).to_list()
    print("{squares}")
    print("{(0..5).count()} {(0..5).contains(5)}")
}
[4, 16, 36]
5 false

Control flow

简体中文

if

if is an expression. Both branches must have the same type when the value is used; an if without else has type ().

fn sign(x: Int) -> Int {
    if x > 0 { 1 } else if x < 0 { -1 } else { 0 }
}

fn main() {
    print("{sign(-4)} {sign(0)} {sign(9)}")
}
-1 0 1

match

match compares a value against patterns, top to bottom, and must cover every possible value. Arms are written pattern -> expression.

fn label(code: Int) -> Str {
    match code {
        200 -> "ok"
        404 -> "not found"
        500..=599 -> "server error"
        _ -> "other"
    }
}

fn main() {
    print("{label(200)} {label(503)} {label(302)}")
}
ok server error other

Patterns are covered in detail in Pattern matching.

Loops

fn main() {
    for i in 0..3 { print("for {i}") }

    var n = 3
    while n > 0 {
        n -= 1
        if n == 1 { continue }
        print("while {n}")
    }

    let stack = [1, 2, 3]
    while let Some(top) = stack.pop() {
        print("popped {top}")
    }
}
for 0
for 1
for 2
while 2
while 0
popped 3
popped 2
popped 1

for x in e works for anything that implements Iterable: ranges, lists, maps, sets and iterators. for and while have type ().

loop repeats until break, and break can carry a value out as the value of the loop:

fn main() {
    var x = 1
    let first_big = loop {
        x *= 3
        if x > 100 { break x }
    }
    print("{first_big}")
}
243

Struct literals in conditions

In the condition of if, while and match (and the iterated expression of for), a struct literal must be wrapped in parentheses, so that its { is not mistaken for the start of the body:

struct Point { x: Int, y: Int }

fn main() {
    let p = Point { x: 1, y: 2 }
    if same(p, p) && (Point { x: 1, y: 2 }).x == p.x {
        print("same x")
    }
}
same x

Early exit

return leaves a function with a value. break and continue work in all loops. Each of them, like panic, has a type that fits anywhere, so they can appear in any branch:

fn first_negative(xs: List<Int>) -> Option<Int> {
    for x in xs {
        if x < 0 { return Some(x) }
    }
    None
}

fn main() {
    print("{first_negative([3, -1, -5])} {first_negative([1])}")
}
Some(-1) None

Functions and closures

简体中文

Functions

Parameters and the return type of a top-level function are always written out. A missing return type means (). The last expression of the body is the return value; return exits early.

fn area(w: Int, h: Int) -> Int {
    let s = w * h
    s
}

fn report(name: Str, value: Int) {
    print("{name}: {value}")
}

fn main() {
    report("area", area(3, 4))
}
area: 12

Methods

Methods are declared in an impl block and take self as the first parameter. Functions in an impl block without self are associated functions, called through the type name. . is the only path separator: there is no ::.

struct Counter {
    var count: Int
}

impl Counter {
    fn new() -> Counter { Counter { count: 0 } }
    fn bump(self, by: Int) { self.count += by }
    fn get(self) -> Int { self.count }
}

fn main() {
    let c = Counter.new()
    c.bump(2)
    c.bump(3)
    print("{c.get()}")
}
5

There is no separate mutable receiver: values are references, so a method changes the object by assigning its var fields.

Closures

Closures are written |params| body. Parameter types can usually be inferred from where the closure is used; annotate them when the closure is stored before it is used.

fn apply_twice(f: fn(Int) -> Int, x: Int) -> Int {
    f(f(x))
}

fn main() {
    let add = |a: Int, b: Int| -> Int { a + b }
    print("{add(2, 3)}")
    print("{apply_twice(|x| x * 10, 3)}")
    print("{[1, 2, 3].map(|x| x + 1)}")
}
5
300
[2, 3, 4]

Function types are written fn(A, B) -> R. Named functions and closures both convert to them:

fn double(x: Int) -> Int { x * 2 }

fn main() {
    let ops: List<fn(Int) -> Int> = [double, |x: Int| x + 1]
    for op in ops { print("{op(10)}") }
}
20
11

Closures capture variables by reference. A closure that captures a var sees later assignments to it, and can make them:

fn main() {
    var total = 0
    let add = |x: Int| { total += x }
    add(5)
    add(7)
    print("{total}")
}
12

Generic functions

Type parameters go in angle brackets, with bounds after :. They are usually inferred at the call site, and can be written explicitly:

fn largest<T: Ord>(xs: List<T>) -> Option<T> {
    var best: Option<T> = None
    for x in xs {
        best = match best {
            Some(b) if b >= x -> Some(b)
            _ -> Some(x)
        }
    }
    best
}

fn main() {
    print("{largest([3, 9, 2])} {largest(["b", "a"])} {largest<Int>([])}")
}
Some(9) Some("b") None

See Traits and generics for bounds and traits.

Structs and enums

简体中文

Structs

@derive(Show)
struct Point {
    x: Int
    var y: Int
}

fn main() {
    let p = Point { x: 1, y: 2 }
    p.y = 5
    let x = 10
    let y = 20
    let q = Point { x, y }
    let r = Point { x: 7, ..p }
    print("{p} {q} {r}")
}
Point { x: 1, y: 5 } Point { x: 10, y: 20 } Point { x: 7, y: 5 }
  • Fields are separated by newlines or commas.
  • A field can be assigned after construction only if it is declared var. The others are fixed when the struct is built, which maps directly onto WasmGC immutable fields.
  • Point { x, y } is shorthand for Point { x: x, y: y }, and ..p copies the remaining fields from p.
  • Fields are private to the module unless marked pub.

Assigning a field that is not var is a compile error:

struct Point {
    x: Int
    var y: Int
}

fn main() {
    let p = Point { x: 1, y: 2 }
    p.x = 5
}

Structs can be generic:

struct Pair<A, B> { a: A, b: B }

fn main() {
    let p = Pair { a: 1, b: "one" }
    print("{p.a} {p.b}")
}
1 one

Enums

Enums are algebraic data types. A variant can be bare, tuple-like or record-like, and variants are named through the enum: Shape.Circle.

enum Shape {
    Circle(Float)
    Rect { w: Float, h: Float }
    Empty
}

fn area(s: Shape) -> Float {
    match s {
        Shape.Circle(r) -> 3.14 * r * r
        Shape.Rect { w, h } -> w * h
        Shape.Empty -> 0.0
    }
}

fn main() {
    let shapes = [Shape.Circle(1.0), Shape.Rect { w: 2.0, h: 3.0 }, Shape.Empty]
    for s in shapes { print("{area(s)}") }
}
3.14
6.0
0.0

Option and Result are ordinary enums. Their variants Some, None, Ok and Err are in the prelude and are written without a path.

Tuples and unit

Tuples group values without naming them: (Int, Str), built with (1, "a") and read with .0, .1. The unit type () has one value, also written ().

fn min_max(xs: List<Int>) -> (Int, Int) {
    (xs.min().unwrap(), xs.max().unwrap())
}

fn main() {
    let t = min_max([4, 1, 7])
    let (lo, hi) = t
    print("{t.0} {t.1} {lo} {hi}")
}
1 7 1 7

Deriving traits

@derive generates implementations of built-in traits: Eq, Ord, Hash, Show and Transfer.

@derive(Eq, Ord, Hash, Show)
struct Version { major: Int, minor: Int }

fn main() {
    let a = Version { major: 1, minor: 2 }
    let b = Version { major: 1, minor: 10 }
    print("{a < b} {a == b} {[b, a].sorted()}")
    let seen = Set.from([a, b, a])
    print("{seen.len()}")
}
true false [Version { major: 1, minor: 2 }, Version { major: 1, minor: 10 }]
2

Ord compares fields in declaration order. Transfer lets a value be sent to a worker.

Type aliases

type UserId = Int
type Callback<T> = fn(T) -> ()

fn notify(id: UserId, cb: Callback<UserId>) { cb(id) }

fn main() {
    notify(7, |id| print("user {id}"))
}
user 7

An alias is another name for the same type, not a new type.

Pattern matching

简体中文

Patterns destructure values. They appear in match, let, var, for, if let, while let and let ... else.

PatternExample
Wildcard_
Bindingx
Literal42, "hi", 'a', true
Range1..=9, 'a'..='z'
Tuple(a, _, c)
StructPoint { x, y: 0 }, Point { x, .. }
Enum variantSome(v), Shape.Rect { w, h }
OrA | B
List[first, ..rest], []

match

enum Shape {
    Circle(Float)
    Rect { w: Float, h: Float }
    Empty
}

fn describe(s: Shape) -> Str {
    match s {
        Shape.Circle(r) if r > 10.0 -> "big circle"
        Shape.Circle(_) -> "circle"
        Shape.Rect { w, h } if w == h -> "square {w}"
        Shape.Rect { w, h } -> "rect {w}x{h}"
        Shape.Empty -> "nothing"
    }
}

fn main() {
    print(describe(Shape.Circle(20.0)))
    print(describe(Shape.Rect { w: 2.0, h: 2.0 }))
    print(describe(Shape.Rect { w: 2.0, h: 3.0 }))
}
big circle
square 2.0
rect 2.0x3.0

An arm can have an if guard. The compiler checks that the arms cover every value; a missing case is an error that names an example of what is not covered:

enum Light { Red, Yellow, Green }

fn next(l: Light) -> Light {
    match l {
        Light.Red -> Light.Green
        Light.Green -> Light.Yellow
    }
}

fn main() {}

Literals, ranges and or-patterns

fn kind(c: Char) -> Str {
    match c {
        'a' | 'e' | 'i' | 'o' | 'u' -> "vowel"
        'a'..='z' -> "consonant"
        '0'..='9' -> "digit"
        _ -> "other"
    }
}

fn main() {
    print("{kind('e')} {kind('k')} {kind('4')} {kind('?')}")
}
vowel consonant digit other

Lists

List patterns match on length and bind the rest of the list with ..name:

fn summary(xs: List<Int>) -> Str {
    match xs {
        [] -> "empty"
        [x] -> "just {x}"
        [first, ..rest] -> "{first} and {rest.len()} more"
    }
}

fn main() {
    print(summary([]))
    print(summary([5]))
    print(summary([1, 2, 3]))
}
empty
just 5
1 and 2 more

Destructuring bindings

struct Point { x: Int, y: Int }

fn main() {
    let (a, b) = (1, "two")
    let Point { x, .. } = Point { x: 3, y: 4 }
    for (i, name) in ["ann", "bo"].enumerate() {
        print("{i} {name}")
    }
    print("{a} {b} {x}")
}
0 ann
1 bo
1 two 3

if let, while let and let ... else

if let runs a block when one pattern matches. let ... else binds the pattern or runs an else block that must leave the current scope (return, break, continue or panic):

fn parse_pair(s: Str) -> Option<(Int, Int)> {
    let Some((a, b)) = s.split_once(",") else {
        return None
    }
    let Some(x) = a.trim().parse_int() else { return None }
    let Some(y) = b.trim().parse_int() else { return None }
    Some((x, y))
}

fn main() {
    if let Some((x, y)) = parse_pair("3, 4") {
        print("{x + y}")
    }
    print("{parse_pair("nope")}")
}
7
None

Traits and generics

简体中文

Traits

A trait is a set of methods that a type can implement. Traits are nominal: a type implements a trait only through an explicit impl block.

trait Shape {
    fn area(self) -> Float
    fn name(self) -> Str { "shape" }
}

struct Square { side: Float }
struct Circle { r: Float }

impl Shape for Square {
    fn area(self) -> Float { self.side * self.side }
    fn name(self) -> Str { "square" }
}

impl Shape for Circle {
    fn area(self) -> Float { 3.0 * self.r * self.r }
}

fn main() {
    let s = Square { side: 2.0 }
    let c = Circle { r: 1.0 }
    print("{s.name()} {s.area()}")
    print("{c.name()} {c.area()}")
}
square 4.0
shape 3.0

Methods with a body are default methods; an impl can override them.

Bounds

A generic function states what it needs from its type parameters with bounds, combined with +:

fn describe<T: Show + Eq>(a: T, b: T) -> Str {
    if a == b { "{a} twice" } else { "{a} and {b}" }
}

fn main() {
    print(describe(1, 1))
    print(describe("x", "y"))
}
1 twice
x and y

Generic code is monomorphized: each instantiation is compiled separately, so generics have no runtime cost.

Implementing standard traits

Show controls how a value appears in string interpolation. Implement it by hand when @derive(Show) is not what you want:

struct Money { cents: Int }

impl Show for Money {
    fn show(self) -> Str {
        let rest = self.cents % 100
        let pad = if rest < 10 { "0" } else { "" }
        "${self.cents / 100}.{pad}{rest}"
    }
}

fn main() {
    print("total: {Money { cents: 1205 }}")
}
total: $12.05

Operator traits

Operators call trait methods, so implementing the trait gives a type the operator:

OperatorTrait
+ - * / %Add Sub Mul Div Rem
unary - !Neg Not
== !=Eq
< <= > >=Ord
a[i]Index
for x in aIterable
"{a}"Show
@derive(Show)
struct V2 { x: Int, y: Int }

impl Add for V2 {
    fn add(self, other: V2) -> V2 { V2 { x: self.x + other.x, y: self.y + other.y } }
}

fn main() {
    print("{V2 { x: 1, y: 2 } + V2 { x: 10, y: 20 }}")
}
V2 { x: 11, y: 22 }

Associated types and supertraits

A trait can declare associated types, written Self.Name, and require other traits:

trait Container {
    type Item
    fn items(self) -> List<Self.Item>
}

trait Named: Show {
    fn title(self) -> Str { "<{self.show()}>" }
}

struct Bag { xs: List<Int> }

impl Container for Bag {
    type Item = Int
    fn items(self) -> List<Int> { self.xs }
}

impl Show for Bag {
    fn show(self) -> Str { "bag of {self.xs.len()}" }
}

impl Named for Bag {}

fn main() {
    let b = Bag { xs: [1, 2] }
    print("{b.items()} {b.title()}")
}
[1, 2] <bag of 2>

Generic impls and coherence

An impl can itself be generic, with bounds:

trait Describe {
    fn describe(self) -> Str
}

impl<T: Show> Describe for List<T> {
    fn describe(self) -> Str { "{self.len()} items: {self}" }
}

fn main() {
    print([1, 2, 3].describe())
}
3 items: [1, 2, 3]

An impl Trait for Type is allowed only in the package that defines the trait or the package that defines the type, and at most one impl may apply to a type.

Trait objects

dyn Trait is a type for any value that implements the trait. Calls go through a vtable at runtime, so values of different types can live in one list:

fn main() {
    let items: List<dyn Show> = [1, "two", 3.5, [4]]
    for it in items { print(it.show()) }
}
1
two
3.5
[4]

A value converts to dyn Trait wherever that type is expected. A trait can be used this way only if none of its methods has its own type parameters or mentions Self outside the receiver, and associated types must be fixed, as in dyn Iterator<Item = Int>.

Error handling

简体中文

Puddi has no null and no exceptions. A value that may be missing is an Option<T>; an operation that may fail returns a Result<T, E>. Bugs that a program cannot recover from are panics.

Option and Result

fn find_user(id: Int) -> Option<Str> {
    if id == 1 { Some("ada") } else { None }
}

fn parse_port(s: Str) -> Result<Int, Str> {
    match s.parse_int() {
        Some(n) if n > 0 && n < 65536 -> Ok(n)
        _ -> Err("bad port: {s}")
    }
}

fn main() {
    print("{find_user(1)} {find_user(2).unwrap_or("nobody")}")
    print("{parse_port("8080")} {parse_port("x")}")
    print("{parse_port("80").map(|p| p + 1)} {find_user(1).is_some()}")
}
Some("ada") nobody
Ok(8080) Err("bad port: x")
Ok(81) true

Both have the familiar combinators: map, and_then, unwrap_or, unwrap_or_else, ok_or, map_err, is_some, is_ok and so on. unwrap and expect panic on None or Err.

The ? operator

Postfix ? unwraps Some or Ok, or returns the None or Err from the enclosing function:

fn add_strings(a: Str, b: Str) -> Option<Int> {
    let x = a.parse_int()?
    let y = b.parse_int()?
    Some(x + y)
}

fn main() {
    print("{add_strings("2", "3")} {add_strings("2", "z")}")
}
Some(5) None

? on an Option works only in a function that returns Option. On a Result, when the error type differs from the function’s error type, ? converts it with the From trait:

enum AppErr {
    BadNumber(Str)
    TooBig(Int)
}

impl Show for AppErr {
    fn show(self) -> Str {
        match self {
            AppErr.BadNumber(s) -> "not a number: {s}"
            AppErr.TooBig(n) -> "{n} is too big"
        }
    }
}

struct ParseErr { input: Str }

impl From<ParseErr> for AppErr {
    fn from(e: ParseErr) -> AppErr { AppErr.BadNumber(e.input) }
}

fn parse(s: Str) -> Result<Int, ParseErr> {
    s.parse_int().ok_or(ParseErr { input: s })
}

fn check(s: Str) -> Result<Int, AppErr> {
    let n = parse(s)?
    if n > 100 { return Err(AppErr.TooBig(n)) }
    Ok(n)
}

fn main() {
    for s in ["42", "abc", "500"] {
        match check(s) {
            Ok(n) -> print("ok {n}")
            Err(e) -> print("error: {e}")
        }
    }
}
ok 42
error: not a number: abc
error: 500 is too big

Error and AnyErr

Error types should implement the Error trait, which requires Show and has an optional source method for error chains. AnyErr holds any value that implements Error, and since every Error converts into it, ? works with any error type in a function that returns Result<T, AnyErr>. Libraries should define their own error types; applications can use AnyErr and skip writing From impls.

import std.json

struct ConfigErr { msg: Str }

impl Show for ConfigErr {
    fn show(self) -> Str { "config: {self.msg}" }
}

impl Error for ConfigErr {}

fn port(text: Str) -> Result<Int, AnyErr> {
    let v = json.parse(text)?
    let Some(p) = v.get("port").and_then(|p| p.as_int()) else {
        return Err(AnyErr.new(ConfigErr { msg: "no port" }))
    }
    Ok(p)
}

fn main() {
    print("{port("\{\"port\": 8080\}")}")
    match port("\{\}") {
        Ok(_) -> {}
        Err(e) -> {
            print("{e}")
            if let Some(c) = e.downcast<ConfigErr>() { print("message: {c.msg}") }
        }
    }
    match port("nonsense") {
        Ok(_) -> {}
        Err(e) -> print("{e}")
    }
}
Ok(8080)
config: no port
message: no port
invalid JSON at byte 0: unexpected character

e.downcast<E>() gets the original error back as an Option<E>.

Errors from main

main can return Result<(), E> for any E: Show. When it returns Err, the error is printed; a wasi program then exits with a failure status, and in a browser the error goes to the console.

Panics

panic(msg) stops the program with an unrecoverable error. So do a failed assert, integer overflow, division by zero, indexing out of bounds and unwrap on None or Err. A panic traps the WebAssembly instance and cannot be caught inside Puddi. A plugin’s host sees the trap and keeps running; a wasi program exits with status 101.

fn main() {
    let xs = [1, 2, 3]
    print("{xs[5]}")       // traps: index out of bounds
}

Use panics for bugs, and Result for failures a caller might handle.

Modules

简体中文

One file is one module. Module paths follow the file layout under src/:

FileModule
src/main.pudthe root of a program
src/lib.pudthe root of a library
src/parser.pudparser
src/net/http.pudnet.http

Imports

import net.http                   // use as http.get(...)
import net.http.{get, Request}    // import specific names
import net.http as h              // alias
import json                       // a dependency named in pud.toml
import std.fs                     // a standard library module
import wasi:clocks/system-clock   // a WIT interface, see Host interop

An imported module is used through its last path segment (http.get) or its alias. Imports between modules of one package may form cycles; dependencies between packages may not.

Visibility

Declarations and struct fields are private to their module by default. pub makes them visible to other modules and to other packages:

// src/account.pud
pub struct Account {
    pub owner: Str
    var balance: Int          // private: only this module can read or set it
}

impl Account {
    pub fn open(owner: Str) -> Account { Account { owner, balance: 0 } }
    pub fn deposit(self, amount: Int) { self.balance += amount }
    pub fn balance(self) -> Int { self.balance }
}
// src/main.pud
import account.{Account}

fn main() {
    let a = Account.open("ada")
    a.deposit(10)
    print("{a.owner} has {a.balance()}")
    // a.balance = 99 would not compile: the field is private
}

export is separate from pub: it marks functions that become exports of the compiled component (see Plugins).

Code for one target

@target keeps a declaration only when building for the listed targets:

@target(wasi)
fn home() -> Str { "terminal" }

@target(browser, plugin)
fn home() -> Str { "embedded" }

The standard library

std modules are imported like any other module. Which ones exist depends on the target; importing a module the target does not provide is a compile error. See Modules by target.

Testing

简体中文

test blocks can appear in any file, next to the code they test. They are compiled only by pud test, which runs every test in a fresh instance, so tests cannot affect each other.

fn fizz(n: Int) -> Str {
    match (n % 3, n % 5) {
        (0, 0) -> "FizzBuzz"
        (0, _) -> "Fizz"
        (_, 0) -> "Buzz"
        _ -> "{n}"
    }
}

test "multiples of three" {
    assert_eq(fizz(9), "Fizz")
}

test "multiples of both" {
    assert_eq(fizz(30), "FizzBuzz")
    assert(fizz(7) == "7")
}
pud test                 # all tests in the package
pud test fizz.pud        # tests in one file
pud test . "multiples"   # tests in the package whose name contains "multiples"

A test fails when it panics, which includes a failed assert, assert_eq, assert_ne or assert_msg. assert_eq prints both values when they differ.

Async tests

Test bodies may use .await:

import std.time

async fn slow_double(x: Int) -> Int {
    time.sleep(1).await
    x * 2
}

test "async code" {
    assert_eq(slow_double(21).await, 42)
}

Where tests run

pud test runs tests on the JavaScript host and needs Node.js 22 or newer. Async tests need a Node.js runtime with JSPI. Node.js 24 enables it by default. Tests cannot call WIT imports on this host. Put code that talks to WIT interfaces behind a function you can replace in tests, or cover it with a small program run by pud run.

Async and tasks

简体中文

Async functions

Code that waits (for a timer, the network, another task) is written as an async fn and awaited with postfix .await. Async functions are colored: only async functions, async closures and test bodies can use .await. main can be async.

import std.time

async fn slow_square(x: Int) -> Int {
    time.sleep(10).await
    x * x
}

async fn main() {
    let a = slow_square(3).await
    let b = slow_square(4).await
    print("{a + b}")
}
25

.await binds as tightly as a method call, so fetch(url).await? awaits and then applies ?.

Structured concurrency

Tasks run concurrently only inside a scope. task.scope takes an async closure that receives the scope; s.spawn(future) starts a child task and returns a handle to await. The scope finishes only when all its children have finished, so no task outlives the code that started it. There is no free-standing spawn.

import std.time

async fn job(name: Str, ms: Int) -> Str {
    time.sleep(ms).await
    print("{name} done")
    name
}

async fn main() {
    let names = task.scope(async |s| {
        let slow = s.spawn(job("slow", 200))
        let fast = s.spawn(job("fast", 10))
        [slow.await, fast.await]
    }).await
    print("{names}")
}
fast done
slow done
["slow", "fast"]

Both jobs sleep at the same time: the fast one finishes first even though it was started second.

Cancellation

If a child fails, or the scope’s body finishes early (by returning, or with ? on an error), the remaining children are cancelled. Cancellation is cooperative: a cancelled task stops at its next .await and does not resume after it. A long synchronous loop can check task.is_cancelled() itself.

import std.time

async fn step(n: Int) -> Result<Int, Str> {
    time.sleep(n * 50).await
    if n == 2 { return Err("step {n} failed") }
    print("step {n} ok")
    Ok(n)
}

async fn run() -> Result<Int, Str> {
    task.scope(async |s| {
        let a = s.spawn(step(1))
        let b = s.spawn(step(2))
        let c = s.spawn(step(5))
        Ok(a.await? + b.await? + c.await?)
    }).await
}

async fn main() {
    print("{run().await}")
}
step 1 ok
Err("step 2 failed")

step(5) never prints: when b.await? returns the error, the scope ends and cancels it while it sleeps.

Async closures and methods

Closures can be async (async |url| { fetch(url).await }), and trait methods can be async fn, including methods called through dyn Trait. The type of an async function value is written async fn(Int) -> Str.

How it runs

On the wasi target, every spawned task runs on its own Component Model thread, and a blocking WASI call suspends only the task that made it. On the JavaScript host (browser, Node.js and pud test), tasks are scheduled with JSPI. Either way, tasks in one instance share its heap but never run Puddi code at the same moment; use workers for parallelism.

Workers

简体中文

Puddi has no shared-memory threads, since WasmGC objects cannot yet be shared between threads. Parallel work runs in workers instead: each worker is a separate WebAssembly instance with its own heap, and it talks to its parent only through messages.

import std.worker

@derive(Transfer)
struct Job {
    id: Int
    data: List<Int>
}

async fn summer(port: worker.Port<Job, Int>) {
    while let Some(job) = port.recv().await {
        port.send(job.data.sum())
    }
}

async fn main() {
    task.scope(async |s| {
        let w = s.worker(summer)
        w.send(Job { id: 1, data: [1, 2, 3] })
        w.send(Job { id: 2, data: [10, 20] })
        print("{w.recv().await} {w.recv().await}")
    }).await
}
Some(6) Some(30)
  • A worker is started with s.worker(f) inside a task scope and is terminated when the scope ends.
  • f must be a top-level async function, not a closure, since a closure cannot leave its instance. It receives a worker.Port<In, Out>, which receives In and sends Out.
  • The handle returned by s.worker(f) is the other end: it sends In and receives Out. recv() returns None once the other side is gone.

Transfer

Messages are deep-copied between instances, so a message type must implement Transfer. It is implemented for numbers, Bool, Char, Str, tuples, Option, Result and collections of Transfer types, and can be derived with @derive(Transfer) for structs and enums whose fields are all Transfer. Functions, closures and dyn values are never Transfer.

Where workers run

TargetWorkers
browserWeb Workers (worker threads under Node.js)
wasiinstances of the same component on other OS threads, through the bundled puddi:runtime worker interfaces
pluginavailable when the host world includes the puddi:runtime worker interfaces

The embedded runner of pud run implements the puddi:runtime interfaces. Other WASI hosts can run a program that uses workers only if they implement them too; see Targets.

The pud command

简体中文

All tooling goes through one command.

CommandPurpose
pud new <name>create a package
pud build [path] [--target t] [--emit-wat] [-o dir]build a component for wasi (default), browser or plugin
pud run [path|file.pud] [-- args]build and run
pud test [path|file.pud] [filter]run test blocks
pud check [path|file.pud]type-check without generating code
pud fmt [files] [--check]format sources in the official style
pud doc [path]write Markdown docs for public items
pud add <repo@version|path> [--name n]add a dependency
pud versionprint the version

For build, run, test, check and doc, path can be a package directory, the package’s pud.toml or a single source file. An omitted path starts manifest discovery in the current directory and searches its parents. To treat a source file as part of a package, pass the package path.

Single-file mode

Any .pud file can be checked, run or tested without a package. It may import the standard library and WIT interfaces, but not dependencies.

pud run script.pud -- input.txt

pud build

Compiles the package to a WebAssembly component in target/<target>/<name>.wasm.

  • --target wasi|browser|plugin (or -t) picks the target.
  • --emit-wat also writes the core module as WebAssembly text, which is useful when you work on the compiler.
  • -o dir or --out dir writes the build output to a different directory.

pud run

Builds and runs. What running means depends on the target:

Targetpud run
wasiruns main in the embedded Wasmtime; arguments after -- go to the program
browserserves the page on loopback and prints the URL to open
pluginpud run --target plugin -- <export> [args] calls one export and prints the result

PUD_HOST=node pud run runs a wasi program’s core module with Node.js instead of the embedded runtime.

pud test

Compiles the package with its test blocks and runs each test in a fresh instance on Node.js. The optional filter, after the path, runs only the tests whose name contains it:

pud test . parser

pud fmt

Formats sources in the single official style. There are no options to configure. --check changes nothing and exits with status 1 if a file would change, which suits CI.

pud doc

Collects /// doc comments of public items into target/doc/<name>.md for a package. For a single file it writes <name>.md in the current directory.

/// Splits a line into words, dropping empty ones.
pub fn words(line: Str) -> List<Str> { line.split_whitespace() }

pud add

pud add github.com/someone/lib@1.2     # a git dependency
pud add ../shared --name shared         # a local path dependency

Adds the entry to [deps] in pud.toml and updates pud.lock. See Dependencies.

Environment variables

VariableEffect
PUD_HOST=noderun the wasi core module with Node.js and its JavaScript host shims
PUD_PORTfirst port to try for the browser dev server; defaults to 8000

For options introduced on the compiler’s main branch, see Compiler development.

The manifest

简体中文

pud.toml sits at the root of a package.

[package]
name = "hello"
version = "0.1.0"
puddi = "0.1"

[deps]
json = "github.com/someone/puddi-json@1.2"
util = { path = "../util" }

[target.wasi]
world = "wasi:cli/command"

[target.plugin]
world = "wit/host.wit#plugin"

[package]

KeyMeaning
namepackage name, used for build outputs and by packages that depend on this one
versionthe package version, in semver form
puddithe language version the package is written for

[deps]

Each entry names a dependency and says where it comes from: a git repository with a minimum version, or a local path. The key is the name used to import it. See Dependencies.

[target.wasi]

KeyMeaning
worldthe WIT world the component targets; default wasi:cli/command

[target.plugin]

KeyMeaning
worldrequired: the host’s world, written <file>#<world> relative to the package, for example wit/host.wit#plugin

Package layout

my-package/
├── pud.toml
├── pud.lock          # written by pud; commit it
├── src/
│   ├── main.pud      # or lib.pud for a library
│   └── ...
├── wit/              # WIT files of your own, if any
└── target/           # build output; do not commit

WIT interfaces in the package’s wit/ directory can be imported alongside the bundled WASI and puddi:runtime interfaces (see WIT imports).

Dependencies

简体中文

A dependency is either a git repository with semver tags or a directory on disk.

[deps]
json = "github.com/someone/puddi-json@1.2"
util = { path = "../util" }

The key (json, util) is the name the dependency is imported by. Modules of a dependency are imported through that name: import json for its root module, import json.parser for others. Only pub items are visible.

Git dependencies

The version after @ is a minimum. Releases of a package are git tags such as v1.2.0 in its repository. pud add writes the entry and resolves it:

pud add github.com/someone/puddi-json@1.2

Minimal version selection

Versions are chosen with minimal version selection: every dependency gets the lowest version that satisfies every requirement on it in the whole dependency graph. A build therefore never picks up a release that nobody asked for, and the result is the same with or without a lock file.

Different major versions of one package are different packages and can be used side by side.

pud.lock

The lock file records the exact commit of every tag that was resolved, so a tag that is moved later does not change your build. Commit pud.lock to version control.

Path dependencies

[deps]
util = { path = "../util" }

A path dependency is a package directory, relative to the manifest. It is useful in a repository with several packages, or while you work on a library and an application together.

Rules

  • Dependencies between packages must not form a cycle. Modules inside one package may import each other in cycles.
  • Single-file programs (pud run file.pud) cannot have dependencies.
  • An impl Trait for Type must live in the package that defines the trait or the one that defines the type.

Targets

简体中文

Every target is built from the same source language. @target(...) keeps a declaration only for some targets, and importing a standard module that a target does not provide is a compile error (see Modules by target).

TargetOutputEntry point
wasi (default)a WASI 0.3 component for the world in [target.wasi], default wasi:cli/commandfn main() or async fn main(); export fn for other worlds
browsera component plus a JavaScript loader, puddi.mjsfn main(), async fn main() and export fn
plugina component for the host world in [target.plugin]the exports the world requires

wasi

The output is a component of the wasi:cli/command@0.3.2 world, or the world named in [target.wasi]. The runtime talks to WASI directly:

  • standard input and output go through WASI streams, and files through wasi:filesystem preopens;
  • time and randomness come from wasi:clocks and wasi:random;
  • std.http uses wasi:http/client;
  • run is lifted with the async ABI and every spawned task runs on its own Component Model thread, so a blocking WASI call suspends only its task.

There is no WASI 0.2 output.

pud run runs the component in the Wasmtime runtime embedded in pud. To run it elsewhere you need a host with WASI 0.3, component-model async and threading, GC and exceptions enabled. A program that uses workers also needs the puddi:runtime worker interfaces, which the embedded runner provides.

For a pud built with --no-default-features, build the component with pud build and invoke a compatible runtime separately. For programs that work with the JavaScript host shims, PUD_HOST=node pud run is another option.

browser

pud build --target browser writes the component and puddi.mjs, and pud run --target browser serves them with a page on http://127.0.0.1:8000. Browsers cannot instantiate components yet, so the loader does what jco transpile does: it takes the core module out of the component and instantiates it with the host functions the component imports. The page needs a browser with WebAssembly GC, and JSPI for async code. See The browser.

plugin

A plugin is a component for a world defined by its host, such as an editor, a game or a server that loads extensions. The world is set in the manifest:

[target.plugin]
world = "wit/host.wit#plugin"

export fn items implement the world’s exports, and the compiler checks that every required export exists with a matching signature. See Plugins.

Output format

All targets use WasmGC: structs and enums are GC structs, generics are monomorphized, and closures and trait objects are GC structs holding function references. Components are encoded with wit-component.

Troubleshooting

简体中文

Installation and package discovery

  • pud is not found. Open a new terminal after running the installer. With the default install, check that ~/.pud/bin is on PATH and run pud version.
  • could not find pud.toml. Change to the package directory or pass its path. Pass an existing .pud file explicitly for single-file mode. A single file does not load sibling modules or a package dependency graph.
  • A Git dependency cannot be resolved. Check the repository URL, Git availability, and whether the remote publishes a semver tag that satisfies your minimum. Commit pud.lock with pud.toml. See Dependencies.

Choosing the host

SymptomWhat to check
pud test cannot start Node.jsVerify node --version in the same terminal and install Node.js 22 or newer
An async example reports missing JSPIUse Node.js 24 for tests or a browser with JSPI for the browser target
std.dom is unavailableCheck or build with --target browser
std.fs, std.io or std.env is unavailableUse the wasi target
The browser cannot fetch the Wasm fileUse the URL printed by pud run --target browser or serve every generated file over HTTP
An external runtime rejects a componentCheck its WasmGC, exception, WASI 0.3 and Component Model async/threading support
A plugin export has the wrong signatureCompare the Puddi types against the WIT type mapping
An imported plugin function trapsRun it in a host that supplies the imported WIT interface

Reporting a problem

Include pud version, your operating system, the command and target, the exact diagnostic, and the smallest program that reproduces it. If the program uses WIT, include the manifest’s world setting and the relevant WIT declarations. Check the known gaps, then file a compiler issue or ask in Discussions.

WIT imports

简体中文

The Component Model describes host interfaces in WIT. Importing an interface by its WIT name generates typed Puddi bindings for it and adds it to the component’s world:

import wasi:clocks/system-clock as clock

fn main() {
    let now = clock.now()
    print("{now.seconds > 0}")
}
true

The pud toolchain bundles the WASI 0.3 interfaces (wasi:cli, wasi:clocks, wasi:filesystem, wasi:http, wasi:logging, wasi:random, wasi:sockets) and puddi:runtime. Interfaces from WIT files in the package’s own wit/ directory can be imported the same way.

Type mapping

WITPuddi
boolBool
s8 s16 s32 s64I8 I16 I32 I64
u8 u16 u32 u64U8 U16 U32 U64
f32 f64F32 F64
charChar
stringStr
list<T>List<T>
option<T>Option<T>
result<T, E>Result<T, E>
tuple<...>tuple
recordstruct
variant, enumenum
flagsa generated struct of Bool fields
resourcea handle struct with methods and drop()

Names are converted to Puddi conventions: a WIT record entry becomes the struct Entry, the enum case info becomes the variant Level.Info, and functions and fields keep snake_case. Types are reached through the interface’s import name, as in log.Entry.

How bindings work

The bindings, including the canonical ABI lowering and lifting of every value, are generated as Puddi code and compiled with the rest of the program, so there is no separate binding generator to run. pud check type-checks calls into WIT interfaces like any other call.

Exports

export fn declares a function that the component exports. On the plugin target the exports must match the host’s world; on wasi, exports are used with worlds other than wasi:cli/command. See Plugins.

The world can use records, variants, enums and flags from an interface in its export signatures.

Limits

  • pud test runs on the JavaScript host, so tests cannot call WIT imports.
  • pud run on the plugin target provides the WASI interfaces listed in Plugins; calls to other host imports trap.

Plugins

简体中文

The plugin target builds a component for a world that a host application defines. The host decides what the plugin can call (its imports) and what the plugin must provide (its exports).

A plugin from start to finish

The host publishes a WIT world:

// wit/host.wit
package demo:host;

interface log {
  enum level { info, warn }
  record entry { level: level, message: string }
  write: func(e: entry);
}

world plugin {
  import log;
  export greet: func(name: string, times: u32) -> list<string>;
  export classify: func(n: s64) -> result<string, option<u8>>;
}

The plugin’s manifest points at the world:

[package]
name = "greeter"
version = "0.1.0"
puddi = "0.1"

[target.plugin]
world = "wit/host.wit#plugin"

and export fn implements each export:

// src/main.pud
import demo:host/log

export fn greet(name: Str, times: U32) -> List<Str> {
    log.write(log.Entry { level: log.Level.Info, message: "greeting {name}" })
    let out: List<Str> = []
    for i in 0..times.to_int().unwrap_or(0) {
        out.push("hi {name} {i}")
    }
    out
}

export fn classify(n: I64) -> Result<Str, Option<U8>> {
    if n > 0 { Ok("positive {n}") } else if n == 0 { Err(None) } else { Err(Some(7)) }
}
pud build --target plugin       # target/plugin/greeter.wasm
pud run --target plugin -- classify 5
ok("positive 5")

A missing export, or one whose signature does not match the world, is a compile error. Use export async fn for an async func export; it may spawn tasks and await.

Host capabilities

A plugin gets the standard modules its world provides:

ModuleNeeds these imports in the world
std.timewasi:clocks/monotonic-clock, wasi:clocks/system-clock
std.randomwasi:random/random
std.httpwasi:http/types, wasi:http/client
std.workerpuddi:runtime/workers, puddi:runtime/port
std.log, printwasi:logging/logging (otherwise they do nothing)

pud run --target plugin -- <export> [args] calls one export in the embedded runtime. The runtime provides the interfaces in the table above; other host imports, like demo:host/log here, trap when called, so test those code paths in the real host.

Panics in plugins

A panic traps the plugin instance. The host sees the trap as an error from the call and keeps running.

The puddi repository has two complete examples: examples/plugin and examples/plugin-host, which uses every host capability.

The browser

简体中文

The browser target builds a component plus puddi.mjs, a loader that instantiates it in the page. Programs get std.dom for the document, std.http backed by fetch, and std.worker backed by Web Workers.

import std.dom

fn main() {
    dom.set_title("Counter")
    let label = dom.create("p")
    label.set_text("clicked 0 times")
    let button = dom.create("button")
    button.set_text("click me")
    var clicks = 0
    button.on("click", |e| {
        clicks += 1
        label.set_text("clicked {clicks} times")
    })
    dom.body().append(label)
    dom.body().append(button)
}
pud run --target browser    # serves the page on http://127.0.0.1:8000
pud build --target browser  # writes target/browser/<name>.wasm and puddi.mjs

Deploying

pud build --target browser writes everything a page needs to target/browser/: the component <name>.wasm, the loader puddi.mjs and an index.html that runs the program. The files are static and can be served by any web server; serve .wasm files with the application/wasm content type.

To embed the program in a page of your own, import the loader as a module:

<script type="module">
  import { load } from "./puddi.mjs";
  const app = await load("./counter.wasm", {
    output(fd, line) { (fd === 2 ? console.error : console.log)(line) }
  });
  await app.run();      // runs main and resolves to the exit code
</script>

load returns { instance, exports, run }. output receives each line the program prints, with fd 1 for standard output and 2 for errors and panics; without it, lines go to the console.

Requirements

The page needs a browser with WebAssembly GC. Async code also needs JSPI (JavaScript Promise Integration). Use a recent Chromium-based browser for the async examples, or check whether your browser provides WebAssembly.Suspending and WebAssembly.promising.

How the loader works

Browsers cannot instantiate components yet. The loader does what jco transpile does: it takes the core module out of the component and instantiates it with the host functions that the component’s world imports.

See std.dom for the DOM API.

Raw core-wasm

简体中文

The Component Model is the main way to talk to hosts. For hosts that only understand plain core WebAssembly, @extern and @export declare raw imports and exports.

@extern("env", "log")
fn log(msg: Str)

@export("run")
fn run() { log("hi") }
  • @extern(module, name) declares a function without a body that the host provides as the core import module.name.
  • @export(name) exports a function from the core module under name.
  • Only numeric types and Str may cross the boundary. Anything else has to be marshaled by hand.

Prefer WIT imports and export fn whenever the host supports components: they carry full types and the compiler checks them.

Prelude

简体中文

The prelude is available in every module without an import.

KindNames
TypesBool, Int, Float and the sized numeric types, Char, Str, StrBuilder, List, Map, Set, ListView, MapView, SetView, Option, Result, AnyErr
VariantsSome, None, Ok, Err
TraitsEq, Ord, Hash, Show, From, Error, Transfer, Add, Sub, Mul, Div, Rem, Neg, Not, Index, Iterable, Iterator
Functionsprint, eprint, panic, assert, assert_msg, assert_eq, assert_ne, same, min, max, todo
Valuestask, for task scopes

The prelude is written in Puddi: see src/prelude.pud in the compiler repository.

Functions

FunctionMeaning
print(x)write x and a newline to standard output (wasi), the console (browser) or the log (plugin)
eprint(x)the same, to standard error
panic(msg)stop with an unrecoverable error
assert(cond), assert_msg(cond, msg)panic when cond is false
assert_eq(a, b), assert_ne(a, b)panic, showing both values, when a != b (or a == b)
same(a, b)whether two references point to the same object
min(a, b), max(a, b)the smaller or larger of two Ord values
todo()panic with “not yet implemented”; fits any type

Methods by type

The lists below name the methods; the language guide shows them in use.

Option<T>: is_some is_none unwrap expect unwrap_or unwrap_or_else map and_then or or_else filter ok_or ok_or_else to_list

Result<T, E>: is_ok is_err ok err unwrap unwrap_err expect unwrap_or unwrap_or_else map map_err and_then

Str: utf8_len is_empty chars graphemes start end find rfind contains starts_with ends_with slice slice_from slice_to next_index advance split_once split split_whitespace lines trim trim_start trim_end to_upper to_lower replace repeat parse_int parse_i64 parse_float to_bytes, and Str.from_chars, Str.from_utf8

Char: to_u32 is_digit is_alpha is_alphanumeric is_whitespace is_upper is_lower is_ascii to_upper to_lower to_digit to_str, and Char.from_u32

StrBuilder: new reserve push push_char push_byte len to_str

List<T>: new with_capacity filled len is_empty push pop get set first last insert remove clear truncate swap extend concat copy slice take skip view enumerate map filter flat_map filter_map for_each fold any all count find position zip reverse reversed sort sort_by sort_by_key sorted contains index_of min max dedup; join on List<Str>; sum on lists of Int, I64 and Float

Map<K, V>: new len is_empty insert get get_or contains_key remove clear keys values entries view

Set<T>: new from len is_empty insert contains remove clear to_list union intersection difference view

Views (ListView, MapView, SetView): the reading methods of their collection

Ranges (a..b, a..=b): start end contains to_list map filter for_each fold any all count rev

Iterator: next map filter enumerate take skip zip chain collect to_list count fold for_each any all find position last min max

AnyErr: AnyErr.new(e) msg downcast inner

Numbers: arithmetic with wrapping_*, saturating_* and checked_* variants, to_<type>() narrowing conversions, truncate_to_int, round_to_int and friends, and on floats sqrt cbrt pow exp ln log2 log10 sin cos tan asin acos atan atan2 hypot floor ceil round abs. See Numbers.

Modules by target

简体中文

Standard modules are imported with import std.<name>. A module the build target does not provide is a compile error to import.

ModulePurposebrowserwasiplugin
std.jsonJSON values, parsing and outputyesyesyes
std.logleveled loggingyesyesyes
std.mathconstants and functionsyesyesyes
std.bytesbyte-order conversions and bounded binary readsyesyesyes
std.collectionsdeques, priority queues, grouping and countingyesyesyes
std.csvdelimited text with CSV quoting rulesyesyesyes
std.dateGregorian dates, UTC timestamps and Unix epoch conversionsyesyesyes
std.encodinghex, Base64, Base64url and percent encodingyesyesyes
std.fmtvalue formatting and integer base conversionyesyesyes
std.iterlazy iterator sourcesyesyesyes
std.pathlexical operations on slash-separated pathsyesyesyes
std.statssummaries, variance, standard deviation and medianyesyesyes
std.textUnicode scalar based truncation and padding, prefix and suffix removalyesyesyes
std.timeclocks, sleepingyesyeshost
std.randomrandom numbersyesyeshost
std.httpHTTP clientyesyeshost
std.workerparallel workersyeshosthost
std.iostandard input and output-yes-
std.fsfiles and directories-yes-
std.envarguments, environment, exit-yes-
std.domthe browser documentyes--

“host” means the module is available only when the target world includes the interfaces it needs; Plugins lists them. On wasi, std.worker uses the puddi:runtime interfaces that pud run provides. On plugin, std.log writes to the host’s logging interface if the world has one and does nothing otherwise.

See the portable module API reference and the standard library source.

std.json

简体中文

JSON values, parsing and serialization. Available on every target.

import std.json
import std.json.{Json}

fn main() {
    let v = json.parse("\{\"name\": \"ada\", \"langs\": [\"en\", \"fr\"], \"age\": 36\}").unwrap()
    print("{v.get("name").and_then(|n| n.as_str())}")
    print("{v.get("langs").and_then(|l| l.at(1))}")
    print("{v.get("age").and_then(|a| a.as_int())} {v.get("missing").is_none()}")

    let out = Json.Object(["ok": Json.Bool(true), "items": Json.Array([Json.Number(1.0), Json.Null])])
    print(json.stringify(out))
}
Some("ada")
Some("fr")
Some(36) true
{"ok":true,"items":[1,null]}

Json

pub enum Json {
    Null
    Bool(Bool)
    Number(Float)
    String(Str)
    Array(List<Json>)
    Object(Map<Str, Json>)
}

Objects keep their keys in insertion order. A Json value shows as JSON text, so "{v}" and print(v) print it in the same form as stringify.

MethodReturns
get(key)the member of an object, or None
at(i)the element of an array, or None
is_null()whether the value is null
as_bool(), as_float(), as_int(), as_str()the value, if it has that type (as_int needs an integral number in range)
as_list(), as_map()the elements or members of an array or object

Functions

FunctionMeaning
parse(text) -> Result<Json, ParseErr>parse JSON text; decode is the same
stringify(v) -> Strcompact JSON text; encode is the same

ParseErr has public fields msg and pos (a byte offset) and implements Show and Error, so ? converts it to AnyErr.

std.http

简体中文

An HTTP client. Available on browser (through fetch), on wasi (through wasi:http/client) and on plugin when the world imports wasi:http/types and wasi:http/client.

import std.http

async fn main() -> Result<(), http.HttpErr> {
    let res = http.get("https://example.com/").await?
    print("{res.status} {res.ok()} {res.header("content-type")}")
    let body = res.text().await?
    print("{body.utf8_len()} bytes")
    Ok(())
}

Requests

http.get(url) and http.post(url, body) cover the common cases. For anything else build a Request:

import std.http

async fn main() -> Result<(), http.HttpErr> {
    let res = http.Request.new("PUT", "https://example.com/items/1")
        .header("content-type", "application/json")
        .with_body("\{\"done\": true\}")
        .send()
        .await?
    print("{res.status}")
    Ok(())
}
Function or methodMeaning
get(url), post(url, body)send a request, return Result<Response, HttpErr>
request(req)send a Request
Request.new(method, url)a request with no headers and an empty body
req.header(name, value)a copy of the request with a header added
req.with_body(body)a copy with a body
req.send()send it

All sending functions are async.

Responses

Response has the public fields status (an Int) and headers (a List<(Str, Str)> of name and value pairs). Read the body with text() or json().

MethodMeaning
ok()whether the status is in 200-299
header(name)the first header with this name, compared case-insensitively
text()the body as a string
json()the body parsed as Json

Errors

HttpErr implements Show and Error:

VariantMeaning
HttpErr.Network(msg)the request could not be sent or no response arrived
HttpErr.InvalidUrl(msg)the URL could not be parsed
HttpErr.Body(msg)the body was not what the caller asked for, such as invalid JSON from json()

std.io, std.fs and std.env

简体中文

These modules give a wasi program access to its process: standard streams, files and the environment. They exist only on the wasi target.

std.io

FunctionMeaning
read_line() -> Option<Str>one line of standard input without its line ending; None at the end of input
read_all() -> Strall remaining standard input
write(s)write to standard output without a newline
ewrite(s)write to standard error without a newline
import std.io

fn main() {
    var lines = 0
    var words = 0
    while let Some(line) = io.read_line() {
        lines += 1
        words += line.split_whitespace().len()
    }
    io.write("{lines} lines, {words} words\n")
}

std.fs

Paths are resolved against the directories the host makes available. The embedded pud run runner preopens the current working directory and / with read/write access and inherits the environment from the calling process. Run programs you trust, and use a host with narrower preopens and environment settings when you need tighter isolation.

FunctionMeaning
read(path) -> Result<Str, IoErr>the whole file as a string
write(path, content) -> Result<(), IoErr>create or replace a file
append(path, content) -> Result<(), IoErr>append to a file, creating it if needed
exists(path) -> Boolwhether the path exists
is_dir(path) -> Boolwhether the path is a directory
remove(path) -> Result<(), IoErr>delete a file or an empty directory
list_dir(path) -> Result<List<Str>, IoErr>the names in a directory
create_dir(path) -> Result<(), IoErr>create a directory
import std.fs

fn main() -> Result<(), AnyErr> {
    fs.write("notes.txt", "first\n")?
    fs.append("notes.txt", "second\n")?
    let text = fs.read("notes.txt")?
    print("{text.lines()}")
    fs.remove("notes.txt")?
    print("{fs.exists("notes.txt")}")
    match fs.read("missing.txt") {
        Ok(_) -> print("found it")
        Err(fs.IoErr.NotFound(_)) -> print("missing.txt does not exist")
        Err(e) -> print("{e}")
    }
    Ok(())
}
["first", "second"]
false
missing.txt does not exist

IoErr implements Show and Error, and has the variants NotFound, PermissionDenied, AlreadyExists and Other, each carrying a message.

std.env

FunctionMeaning
args() -> List<Str>command-line arguments; the first is the program name
get(name) -> Option<Str>an environment variable
exit(code)exit immediately with a status code
import std.env

fn main() {
    let args = env.args()
    if args.len() < 2 {
        print("usage: {args[0]} <file>")
        env.exit(2)
    }
    print("home is {env.get("HOME").unwrap_or("unknown")}")
}

std.time and std.random

简体中文

Both modules are available on browser and wasi, and on plugin when the world imports the WASI clocks or random interfaces.

std.time

ItemMeaning
now_ms() -> Floatmilliseconds since the Unix epoch
monotonic_ms() -> Floatmilliseconds from an arbitrary fixed point; only differences are meaningful
utc_offset_minutes() -> Intthe local time zone’s offset from UTC
Instant.now(), instant.elapsed_ms()measure a duration
sleep(ms)async: suspend the current task for at least ms milliseconds
yield_now()async: let other tasks run before continuing
import std.time

async fn main() {
    let start = time.Instant.now()
    time.sleep(20).await
    print("{start.elapsed_ms() >= 20.0}")
    print("{time.now_ms() > 1_700_000_000_000.0}")
}
true
true

std.random

ItemMeaning
float() -> Floata random float in [0, 1)
int(lo, hi) -> Inta random integer in [lo, hi)
bool() -> Boola random boolean
choice(xs) -> Option<T>a random element, or None for an empty list
shuffle(xs)shuffle a list in place
Rng.new(seed)a small deterministic generator (xorshift64*) with next_u64, float and int

The module functions draw from the host’s random source. Use Rng when a run must be reproducible:

import std.random

fn main() {
    let roll = random.int(1, 7)
    print("{roll >= 1 && roll <= 6}")
    let a = random.Rng.new(42)
    let b = random.Rng.new(42)
    print("{a.int(0, 100) == b.int(0, 100)}")
}
true
true

std.math and std.log

简体中文

std.math

Constants and functions on Float, plus integer helpers. Available on every target.

ItemMeaning
PI, E, TAUconstants
sqrt cbrt pow exp ln log2 log10powers and logarithms
sin cos tan asin acos atan atan2 hypottrigonometry
floor ceil round absrounding
gcd(a, b), lcm(a, b)greatest common divisor and least common multiple of Ints

The Float functions are also methods: math.sqrt(x) is x.sqrt().

import std.math

fn main() {
    let r = 2.0
    print("{math.PI * r * r}")
    print("{math.hypot(3.0, 4.0)} {math.gcd(12, 18)} {math.lcm(4, 6)}")
}
12.566370614359172
5.0 6 12

std.log

Leveled logging: debug, info, warn and error, each taking a Str. Messages go to standard error on wasi, to the console in browsers, and to wasi:logging/logging on plugin when the world imports it (otherwise they are dropped).

import std.log

fn main() {
    log.info("starting")
    log.warn("disk almost full")
}

std.dom

简体中文

The browser document. Available only on the browser target.

import std.dom

fn main() {
    let input = dom.create("input")
    input.set_attr("placeholder", "type something")
    let echo = dom.create("p")
    input.on("input", |e| echo.set_text(e.value()))
    let app = dom.query("#app").unwrap_or(dom.body())
    app.append(input)
    app.append(echo)
}

Functions

FunctionMeaning
query(selector) -> Option<Element>the first element matching a CSS selector
query_all(selector) -> List<Element>all elements matching a CSS selector
create(tag) -> Elementa new, detached element
body() -> Elementthe document body
set_title(title)set the document title

Element

MethodMeaning
text(), set_text(s)the text content
set_html(s)replace the content with HTML
attr(name) -> Option<Str>, set_attr(name, value)attributes
value(), set_value(s)the value of an input, select or textarea
add_class(c), remove_class(c), toggle_class(c)CSS classes
set_style(property, value)an inline style property
append(child), remove()change the tree
query(selector) -> Option<Element>the first matching descendant
on(event, f)call f with an Event each time the event happens

Event

MethodMeaning
kind()the event type, such as click
target()the element the event happened on
key()the key for keyboard events, or ""
value()the target’s value for input events, or ""
prevent_default()cancel the browser’s default action

Puddi Language Specification

简体中文

This page is the specification as of Puddi v0.1.2, copied from SPEC.md in the compiler repository. Section numbers match the ones cited by the conformance suite.

Version: draft 0.1 Status: complete draft. Section 14 lists what is deferred past v1.

1. Overview

Puddi is a statically typed, expression-oriented language that compiles to WebAssembly. It targets the browser, WASI runtimes (server, edge, CLI) and plugin hosts from a single source language, uses the WASM engine’s garbage collector (WasmGC), and talks to hosts through the Component Model.

TopicDecision
Compile targetWASM only; any JS is loader glue only
Host environmentsbrowser, wasi (server / edge / CLI, WASI 0.3), plugin
Memory managementWasmGC
Type systemStatic, local type inference
PolymorphismGenerics + nominal traits, dyn Trait for dynamic dispatch
Null / errorsNo null; Option<T>, Result<T, E>, ? with From conversion; std Error trait and AnyErr; panic traps
Mutabilitylet / var bindings; field mutability declared per field; values are shared references
NumbersInt = 32-bit signed, overflow traps; lossless widening is implicit
StringsOpaque Str, no integer indexing
Asyncasync fn + postfix .await, structured concurrency
ParallelismNo shared-memory threads; isolated workers with message passing
Host interopComponent Model (WIT) as the main path, raw @extern / @export as the escape hatch
MetaprogrammingNone in v1, except the compiler’s built-in @derive
SyntaxBraces, optional semicolons, expression-oriented semantics
Toolchainpud command, pud.toml manifest, git-based packages
Source filesUTF-8, extension .pud

2. Lexical Structure

2.1 Source text

Source files are UTF-8 with the extension .pud. Identifiers follow Unicode UAX #31 (XID_Start followed by XID_Continue); _ alone is the wildcard and is not an identifier.

2.2 Comments

// line comment
/* block comment, may nest */
/// doc comment, attached to the next declaration

2.3 Keywords

as      async   await   break   const   continue  dyn     else
enum    export  false   fn      for     if        impl    import
in      let     loop    match   pub     return    self    Self
struct  test    trait   true    type    var       while

2.4 Naming conventions

Types, traits and enum variants use UpperCamelCase. Functions, variables, fields and modules use snake_case. Constants use SCREAMING_SNAKE_CASE. pud fmt does not rename, but the compiler warns on violations.

2.5 Statement termination

A newline ends a statement. A semicolon is optional and can separate several statements on one line. A semicolon is only a separator: it never changes the meaning of an expression.

A newline does not end a statement when:

  1. it is inside an unclosed ( or [;
  2. the line ends with a binary operator or a comma;
  3. the next line starts with ..
let total = price * count +
    shipping                    // continues: line ends with +

let names = users
    .filter(|u| u.active)       // continues: next line starts with .
    .map(|u| u.name)

Inside struct, enum, trait and match bodies, members are separated by newlines or commas.

2.6 Numeric literals

42    1_000    0xFF    0b1010    0o17
3.14  1e9      2.5e-3

An integer literal takes its type from context and defaults to Int. A float literal takes its type from context and defaults to Float. A literal that does not fit its type is a compile error.

2.7 Character literals

Char is a Unicode scalar value, written with single quotes: 'a', '\n', '\u{1F600}'.

2.8 String literals

String literals use double quotes and support interpolation with {expr}. The interpolated expression must implement Show. A literal brace is written \{ or \}.

let s = "hi {name}, you have {count + 1} messages"
let t = "a literal \{brace\}"

Escapes: \n \r \t \0 \\ \" \' \{ \} \u{...}.

3. Types

3.1 Type inference

Inference is local. Top-level function signatures (parameter types and return type) must be written out; a missing return type means (). Types of local bindings, closures and expressions inside function bodies are inferred.

fn area(w: Int, h: Int) -> Int {
    let s = w * h      // inferred Int
    s
}

3.2 Built-in types

CategoryTypes
BooleanBool
IntegersInt (= I32), I8 I16 I32 I64 U8 U16 U32 U64
FloatsFloat (= F64), F32 F64
TextChar, Str
Unit()
Tuples(A, B, ...)
Functionsfn(A, B) -> R
CollectionsList<T>, Map<K, V>, Set<T>
Core enumsOption<T>, Result<T, E>

3.3 Structs

struct Point {
    x: Int
    var y: Int
}

struct Pair<A, B> { a: A, b: B }

Fields are private to the module unless marked pub. A field marked var can be assigned after construction; other fields cannot (see 4.1).

Construction uses field names, with shorthand and update syntax:

let p = Point { x: 1, y: 2 }
let q = Point { x, y }          // shorthand for x: x, y: y
let r = Point { x: 5, ..p }     // copy remaining fields from p

3.4 Enums

Enums are algebraic data types. Variants can be bare, tuple-like or record-like.

enum Shape {
    Circle(Float)
    Rect { w: Float, h: Float }
    Empty
}

let s = Shape.Circle(2.0)

match on an enum must be exhaustive.

3.5 Tuples and unit

Tuples are written (Int, Str) and constructed with (1, "a"). Fields are accessed as t.0, t.1. The unit type and its only value are both written ().

3.6 Function types and closures

Function values have types written fn(Int, Int) -> Int. Named functions and closures both convert to function types. Async functions have types written async fn(Int) -> Str.

3.7 Numeric types

Int maps to WASM i32, I64 / U64 to i64, Float to f64, F32 to f32. I8 I16 U8 U16 U32 are stored as i32 and kept in range by the compiler.

Integer overflow traps. Integer division or remainder by zero traps. / on integers truncates toward zero, and % takes the sign of the dividend. Wrapping, saturating and checked arithmetic are available as explicit methods (wrapping_add, saturating_add, checked_add, and so on).

Widening. A conversion that can never lose information happens implicitly:

FromImplicitly widens to
I8I16 I32 I64 F32 F64
I16I32 I64 F32 F64
I32I64 F64
U8U16 U32 U64 I16 I32 I64 F32 F64
U16U32 U64 I32 I64 F32 F64
U32U64 I64 F64
F32F64

I64 and U64 never widen to a float type, since F64 cannot represent every 64-bit integer.

Widening applies wherever an expected type is known (annotated bindings, function arguments, return values, field initializers, collection elements). For a binary operator with operands of two different numeric types, both operands widen to the narrowest type that can hold both losslessly; if none exists (for example I64 and U64, or I64 and Float) it is a compile error.

Narrowing. Lossy conversions are always explicit. to_<type>() returns Option and yields None when the value does not fit. Explicit lossy methods such as truncate_to_int(), round_to_int() and wrap_to_u8() are also available.

let a: Int = 5
let b: I64 = a              // ok, widening
let c: Int = b.to_int()?    // narrowing, returns Option<Int>

3.8 Strings and characters

Str is an immutable, opaque Unicode string. It has no integer indexing. Text is accessed by:

  • iterating code points: s.chars() yields Char;
  • iterating grapheme clusters: s.graphemes() yields Str;
  • search and slicing: s.find("x") returns Option<StrIndex>, and s.slice(start, end) takes StrIndex values. StrIndex is opaque and only valid for the string that produced it.

s.len() is not provided, since its meaning would depend on the representation. Use s.chars().count(), s.graphemes().count() or s.utf8_len() explicitly.

The implementation may choose any internal representation, including the host’s native strings.

3.9 Collections

TypeLiteralNotes
List<T>[1, 2, 3]growable array
Map<K, V>["a": 1, "b": 2], empty [:]K: Eq + Hash, insertion order preserved
Set<T>Set.from([1, 2, 3])T: Eq + Hash, insertion order preserved

xs[i] on a List takes an Int and traps when out of bounds; xs.get(i) returns Option<T>. m[k] on a Map traps when the key is missing; m.get(k) returns Option<V>.

Collections are references like any other object. Whether a collection can be modified is decided by its type: List, Map and Set are mutable (push, insert, remove); their read-only views ListView, MapView and SetView expose only reading methods, and a mutable collection converts to its view implicitly.

3.10 Option and Result

Puddi has no null. A missing value is Option<T> (Some(v) / None) and a fallible result is Result<T, E> (Ok(v) / Err(e)). Both are ordinary enums. Their variants are in the prelude and can be written without a path. See 6 for ?.

3.11 Generics

Type parameters use angle brackets. Bounds use : and are combined with +.

fn largest<T: Ord>(xs: List<T>) -> Option<T> { ... }
fn dump<T: Show + Hash>(x: T) { ... }

struct Stack<T> { var items: List<T> }

Type arguments are inferred at call sites and can be written explicitly as parse<Int>(s).

3.12 Traits

Traits are nominal. A type implements a trait only through an explicit impl block. Traits can have default methods, associated types and supertraits. Self refers to the implementing type.

trait Show {
    fn show(self) -> Str
}

trait Iterator {
    type Item
    fn next(self) -> Option<Self.Item>
}

trait Shape: Show {
    fn area(self) -> Float
    fn describe(self) -> Str { "{self.show()} with area {self.area()}" }
}

impl Show for Point {
    fn show(self) -> Str { "({self.x}, {self.y})" }
}

impl<T: Show> Show for List<T> {
    fn show(self) -> Str { ... }
}

Coherence. An impl Trait for Type is allowed only in the package that defines Trait or the package that defines Type. At most one impl may apply to a given type.

Async methods. Trait methods can be async fn.

Operator traits. Operators are overloaded by implementing standard traits:

OperatorTrait
+ - * / %Add Sub Mul Div Rem
unary - !Neg Not
== !=Eq
< <= > >=Ord
a[i]Index
for x in aIterable
"{a}"Show

3.13 Derive

@derive asks the compiler to generate standard trait impls. Only built-in traits can be derived; there are no user-defined derives in v1.

@derive(Eq, Ord, Hash, Show)
struct Point { x: Int, y: Int }

Derivable traits: Eq, Ord, Hash, Show, Transfer (see 9.4).

3.14 Trait objects

dyn Trait is a type for any value whose type implements Trait. Calls on it are dispatched at runtime through a vtable. A value converts to dyn Trait implicitly wherever the expected type is dyn Trait.

let items: List<dyn Show> = [Point.new(1, 2), "hi", 42]
for it in items { print(it.show()) }

A trait can be used as dyn Trait only if none of its methods has its own type parameters or mentions Self outside the receiver. Associated types must be fixed: dyn Iterator<Item = Int>.

Async methods are allowed on dyn Trait. Calling one through a trait object returns a heap-allocated future; since WasmGC objects already live on the heap, this adds little cost beyond the dynamic dispatch itself.

3.15 Type aliases

type UserId = Int
type Callback<T> = fn(T) -> ()

An alias is another name for its target type. Aliases can refer to later declarations and must expand without cycles.

4. Expressions and Statements

Puddi is expression-oriented. Blocks, if, match and loop produce values. The last expression in a block is the block’s value. When a block’s expected type is (), the value of its last expression is discarded.

Assignment (=, +=, …) is an expression of type ().

4.1 Bindings and mutability

let declares a binding that cannot be reassigned and var declares one that can. Both take a pattern. Binding mutability only controls reassignment.

Field mutability is declared on the type: only fields marked var can be assigned after construction. This maps directly onto WasmGC mutable and immutable struct fields.

Struct, enum and collection values are references: assignment and argument passing share the same object rather than copying it.

struct Point {
    x: Int        // immutable
    var y: Int    // mutable
}

let p = Point { x: 1, y: 2 }
p.y = 5        // ok, y is var
p.x = 5        // error: x is immutable
p = Point { x: 0, y: 0 }   // error: p is let

let q = p      // q and p refer to the same object

== compares through Eq. Reference identity is checked with same(a, b) from the prelude.

4.2 Operators and precedence

From highest to lowest:

LevelOperatorsAssociativity
1.field .method() f() a[i] ? .awaitleft
2unary - !prefix
3* / %left
4+ -left
5<< >>left
6&left
7^left
8|left
9== != < <= > >=none
10&&left
11||left
12.. ..=none
13= += -= *= /= %= &= |= ^= <<= >>=right

&& and || short-circuit. a..b is a half-open range and a..=b is inclusive.

4.3 Blocks and control flow

let sign = if x > 0 { 1 } else if x < 0 { -1 } else { 0 }

let label = match code {
    200 -> "ok"
    404 -> "not found"
    500..=599 -> "server error"
    _ -> "other"
}

An if without else has type (). In the condition of if, while and match, a struct literal must be wrapped in parentheses.

4.4 Patterns

Patterns can destructure tuples, structs and enum variants, and can appear in let, var, match, for, if let, while let and let ... else.

PatternExample
Wildcard_
Bindingx
Literal42, "hi", 'a', true
Range1..=9, 'a'..='z'
Tuple(a, _, c)
StructPoint { x, y: 0 }, Point { x, .. }
Enum variantSome(v), Shape.Rect { w, h }
OrA | B
List[first, ..rest], []

match arms can have if guards.

let (a, b) = pair

match shape {
    Shape.Circle(r) if r > 10.0 -> "big circle"
    Shape.Circle(_) -> "circle"
    Shape.Rect { w, h } -> "rect {w}x{h}"
    Shape.Empty -> "nothing"
}

if let Some(user) = find(id) { greet(user) }

let Some(cfg) = load() else { return }

The else block of let ... else must diverge (return, break, continue or panic).

4.5 Loops

for x in xs { ... }
for (i, x) in xs.enumerate() { ... }
for i in 0..10 { ... }
while cond { ... }
while let Some(job) = queue.pop() { ... }

let found = loop {
    if done() { break value }
}

break can carry a value out of loop, which becomes the value of the loop expression. for and while have type (). for x in e works for any e whose type implements Iterable.

4.6 Closures

let inc = |x| x + 1
let add = |a: Int, b: Int| -> Int { a + b }
let fetch = async |url| { http.get(url).await }

Closures capture variables by reference: a closure that captures a var binding sees and can make later assignments to it.

4.7 Paths

. is the only path separator, for module members, enum variants and associated functions alike: io.read, Shape.Circle, Point.new(1, 2). There is no ::.

5. Declarations

5.1 Functions

fn add(a: Int, b: Int) -> Int { a + b }
async fn load(url: Str) -> Result<Str, HttpErr> { ... }

return exits early with a value. A function’s body block provides its value otherwise.

5.2 Methods

Inherent methods are declared in an impl block. Methods take self as the first parameter; functions without self are associated functions. Since values are references and field mutability is declared per field, there is no separate mutable receiver.

impl Point {
    fn new(x: Int, y: Int) -> Point { Point { x, y } }
    fn len(self) -> Float { ... }
    fn move_down(self, dy: Int) { self.y += dy }
}

let p = Point.new(1, 2)
p.len()

5.3 Constants

const MAX_USERS: Int = 1_000
const GREETING: Str = "hi"

A constant’s initializer must be a constant expression: literals, other constants, arithmetic and comparison on them, and struct, tuple and enum construction from constant expressions. Names in an initializer resolve in the module that declares the constant.

5.4 Visibility

Declarations and struct fields are private to their module by default. pub makes them visible to other modules and packages. export (see 8) is separate and marks component exports.

5.5 Attributes

Attributes start with @ and apply to the next declaration.

AttributeMeaning
@derive(...)generate standard trait impls (3.13)
@target(t)include the declaration only when building for target t; t is browser, wasi or plugin, combinable as @target(wasi, plugin)
@extern(module, name)raw core-wasm import (8.4)
@export(name)raw core-wasm export (8.4)
@deprecated(msg)warn on use

5.6 Tests

test blocks can appear in any file. They are compiled only by pud test, which runs each test in a fresh instance. A test fails if it panics or a failed assertion traps. Test bodies may use .await.

test "addition works" {
    assert_eq(add(2, 2), 4)
}

6. Error Handling

6.1 The ? operator

Postfix ? unwraps Ok / Some, or returns early from the enclosing function with the Err / None. On Result, when the error type differs from the function’s error type, ? converts it through From.

enum AppErr {
    Io(IoErr)
    Bad
}

impl From<IoErr> for AppErr {
    fn from(e: IoErr) -> AppErr { AppErr.Io(e) }
}

fn load(path: Str) -> Result<Config, AppErr> {
    let text = fs.read(path)?         // IoErr converted to AppErr
    parse(text).ok_or(AppErr.Bad)
}

? on Option is allowed only in functions returning Option.

6.2 Panics

panic(msg) signals an unrecoverable error. So do failed assert, integer overflow, division by zero, and out-of-bounds indexing. A panic traps the WASM instance and cannot be caught inside Puddi. In a plugin, the host sees the trap and the host process keeps running.

6.3 The Error trait and AnyErr

Error types should implement Error:

trait Error: Show {
    fn source(self) -> Option<dyn Error> { None }
}

source returns the underlying error, if any, so error chains can be walked and printed.

AnyErr wraps any value that implements Error. Since std provides impl<E: Error> From<E> for AnyErr, ? converts any error into AnyErr automatically. Libraries should return their own error types; applications can use AnyErr and skip writing From impls.

fn main() -> Result<(), AnyErr> {
    let s = fs.read(path)?        // IoErr -> AnyErr
    let v = json.decode(s)?       // ParseErr -> AnyErr
    ...
}

e.downcast<E>() returns Option<E> to recover the original error type. AnyErr implements Error by delegating to the wrapped value.

6.4 Errors from main

main may return Result<(), E> where E: Show. If it returns Err, the error is printed; on wasi the program then exits with a failure status, and on browser it is reported to the console.

7. Modules and Packages

7.1 Modules

One file is one module. Module paths follow the file layout under src/: src/net/http.pud is the module net.http. src/main.pud (or src/lib.pud for libraries) is the root.

import net.http                   // use as http.get(...)
import net.http.{get, Request}    // import specific names
import net.http as h              // alias
import json                       // dependency named in pud.toml
import std.fs                     // standard library

Imports between modules of one package may form cycles. Dependencies between packages must be acyclic.

7.2 Manifest

[package]
name = "hello"
version = "0.1.0"
puddi = "0.1"

[deps]
json = "github.com/someone/puddi-json@1.2"

[target.wasi]
world = "wasi:cli/command"

[target.plugin]
world = "wit/host.wit#plugin"

pud.lock records the exact commit of every dependency and is committed to version control.

7.3 Dependencies

A dependency is a git repository plus a semver tag (v1.2.0). The version in pud.toml is a minimum. Versions are resolved with minimal version selection: each dependency gets the lowest version that meets every requirement, so builds stay the same without a lock file. Different major versions of one package are distinct packages and can coexist.

7.4 Toolchain

All tooling goes through the pud command.

CommandPurpose
pud new <name>create a package
pud build [--target t]build for browser, wasi or plugin
pud runbuild and run (wasi: in a WASI runtime; browser: dev server)
pud testrun test blocks
pud fmtformat with the single official style, no configuration
pud docgenerate documentation from /// comments
pud add <dep>add a dependency

8. Host Interop

8.1 Targets

TargetOutputEntry
browsercomponent plus generated JS loader gluefn main() / async fn main() and/or export fn
wasiWASI 0.3 component for the world in [target.wasi], default wasi:cli/commandfn main() / async fn main() for commands, export fn for other worlds
plugincomponent for the host world in [target.plugin]the exports that the host world requires

The compiler checks that every export required by the target world is provided with a matching signature.

The wasi target requires WASI 0.3 and uses its native async. There is no WASI 0.2 output.

8.2 Component Model

The Component Model is the main interop path. Importing a WIT interface generates typed bindings, and export fn makes a component export.

import wasi:cli/stdout
import wasi:http/outgoing-handler

export fn run() -> Result<(), AppErr> { ... }

8.3 WIT type mapping

WITPuddi
boolBool
s8 s16 s32 s64I8 I16 I32 I64
u8 u16 u32 u64U8 U16 U32 U64
f32 f64F32 F64
charChar
stringStr
list<T>List<T>
option<T>Option<T>
result<T, E>Result<T, E>
tuple<...>tuple
recordstruct
variant / enumenum
flagsgenerated struct of Bool fields
resourceopaque handle type with methods

8.4 Raw core-wasm interop

Raw imports and exports are the low-level escape hatch. Only numeric types and Str may cross; marshaling beyond that is manual.

@extern("env", "log")
fn log(msg: Str)

@export("run")
fn run() { log("hi") }

9. Concurrency

9.1 Async functions

Async uses explicit async fn and postfix .await. Async functions are colored: only async functions, async closures and test bodies can await.

async fn fetch_user(id: Int) -> Result<User, HttpErr> {
    let res = http.get("/u/{id}").await?
    res.json().await
}

9.2 Structured concurrency

Concurrent child tasks are started inside a scope and cannot outlive it. The scope completes only when all its children have completed. If a child fails or the scope exits early, the remaining children are cancelled.

async fn load_all() -> Result<(A, B), AppErr> {
    task.scope(async |s| {
        let a = s.spawn(load_a())
        let b = s.spawn(load_b())
        (a.await?, b.await?)
    }).await
}

There is no free-standing spawn.

9.3 Cancellation

Cancellation is cooperative. A cancelled task stops at its next .await, which returns early without resuming the task’s code after that point. task.is_cancelled() lets long synchronous loops check for cancellation themselves.

9.4 Workers

Puddi has no shared-memory threads, since WasmGC objects cannot yet be shared across threads. Parallelism uses workers: each worker runs in its own WASM instance with its own heap and communicates only by message passing.

A worker is started from a task scope and runs a top-level async function (not a closure, since closures cannot leave their instance). The worker is terminated when the scope ends. Inside the worker, a worker.Port<In, Out> receives In and sends Out; outside, the handle returned by s.worker(f) sends In and receives Out.

import std.worker

@derive(Transfer)
struct Job { id: Int, data: List<Int> }

async fn summer(port: worker.Port<Job, Int>) {
    while let Some(job) = port.recv().await {
        port.send(job.data.sum())
    }
}

async fn main() {
    task.scope(async |s| {
        let w = s.worker(summer)
        w.send(Job { id: 1, data: [1, 2, 3] })
        let total = w.recv().await     // Option<Int>
        print("{total}")
    }).await
}

Messages are deep-copied between instances. A message type must implement Transfer. It is implemented for numbers, Bool, Char, Str, tuples, Option, Result and collections of Transfer types, and can be derived for structs and enums whose fields are all Transfer. Function values, closures and dyn values are never Transfer.

std.worker is available on browser (Web Workers), and on other targets only when the target world provides a worker interface.

10. Standard Library

10.1 Prelude

Available in every module without import:

  • types: Bool Int Float sized numeric types, Char Str List Map Set Option Result AnyErr
  • variants: Some None Ok Err
  • traits: Eq Ord Hash Show From Error Transfer Add Sub Mul Div Rem Neg Not Index Iterable Iterator
  • functions: print panic assert assert_eq same

print writes a line to stdout on wasi, to the console on browser, and to std.log on plugin.

10.2 Modules by target

A module that the build target does not provide is a compile error to import.

Modulebrowserwasiplugin
core (prelude and built-in collections)yesyesyes
std.bytes, std.collections, std.csv, std.date, std.encoding, std.fmt, std.iter, std.math, std.path, std.stats, std.textyesyesyes
std.jsonyesyesyes
std.logyesyesyes
std.timeyesyeshost
std.randomyesyeshost
std.httpyesyeshost
std.workeryeshosthost
std.io-yes-
std.fs-yes-
std.env-yes-
std.domyes--

“host” means available only if the target world includes the corresponding interface. On plugin, std.log uses the host’s logging interface if the world has one and does nothing otherwise.

10.3 Portable modules

Import portable modules by name, for example import std.csv to use csv.parse.

ModuleAPIBehavior
std.bytesEndian.Big, Endian.Little, pack_u16, pack_u32, pack_u64, ReaderThe reader snapshots the bytes at construction. It supports read, read_u8, typed reads with explicit byte order, skip, position, and remaining. Failed reads and skips preserve the position.
std.collectionsDeque<T>, PriorityQueue<T>, count_by, group_byThe deque supports amortized constant-time insertion and removal at either end. The priority queue pops the smallest value in logarithmic time. Grouping preserves input order within each group.
std.csvparse, stringify, Format.newReads comma-separated rows with quoted fields, doubled quotes, and LF, CRLF, or CR endings. It accepts rows of varying lengths. A Format can parse and write using a tab or a printable ASCII separator other than a double quote. Serialization uses CRLF and writes a zero-field row as one empty field. Parse errors carry a zero-based byte offset.
std.dateDate, DateTime, days_in_month, is_leap_yearUses the Gregorian calendar throughout years 0001 through 9999. Dates parse and display as YYYY-MM-DD and can convert to days since 1970-01-01. Timestamps parse and display as YYYY-MM-DDTHH:MM:SSZ and can convert to Unix seconds. Invalid or out-of-range values return None.
std.encodinghex_encode, hex_decode, base64_encode, base64_decode, base64url_encode, base64url_decode, percent_encode, percent_decodeHex accepts either case and writes lowercase. Base64 uses canonical padding, and Base64url uses the URL-safe alphabet without padding. Percent encoding preserves ASCII letters, digits, -, ., _, and ~. Percent decoding preserves literal plus signs. Decoders return bytes or an error with a zero-based byte offset.
std.fmtjoin, int_radix, uint_radix, parse_int_radix, parse_uint_radixJoins values using Show. Radix formatting and parsing support bases 2 through 36. Output uses lowercase digits. Parsing accepts either letter case, and signed parsing accepts an optional leading sign. Invalid input and overflow return None.
std.iteronce, repeat, from_fn, unfoldCreates lazy iterators from values, callbacks, or state transitions. repeat is infinite. Callback-based sources end at their first None.
std.jsonparse, stringify, pretty, Json.at_pointerWrites compact or two-space-indented JSON. A pointer traverses object keys and array indices with slash-separated segments. ~0 represents a tilde, ~1 represents a slash, and the empty pointer selects the root value. Invalid pointers and missing values return None.
std.pathis_absolute, normalize, join, parent, file_name, stem, extensionHandles slash-separated paths lexically. A leading slash denotes the root, and an absolute right operand replaces the left operand in join. Normalizing an empty relative path gives ..
std.statssummarize, medianSummaries include count, mean, extrema, and population and sample variance and standard deviation. Empty samples and non-finite values return None. Summary overflow and sample variance with fewer than two observations also return None.
std.textstrip_prefix, strip_suffix, truncate, pad_start, pad_endTruncation lengths and padding widths count Unicode scalars. Prefix and suffix matching is exact.
import std.collections
import std.csv

fn main() {
    let rows = csv.parse("fruit,red\nfruit,green\nvegetable,green").unwrap()
    let colors = collections.count_by(rows, |row| row[1])
    print(colors["green"])
}

11. Grammar Summary

Informal EBNF. sep is a newline, ; or , as allowed by 2.5.

file          = { import } { item } ;
import        = "import" mod_path [ "." "{" ident { "," ident } "}" ] [ "as" ident ]
              | "import" wit_name ;

item          = { attribute } [ "pub" | "export" ]
                ( fn_decl | struct_decl | enum_decl | trait_decl | impl_decl
                | type_alias | const_decl | test_decl ) ;
attribute     = "@" ident [ "(" [ attr_arg { "," attr_arg } ] ")" ] ;

fn_decl       = fn_sig [ block ] ;                       (* no block only with @extern *)
fn_sig        = [ "async" ] "fn" ident [ generics ] "(" [ params ] ")" [ "->" type ] ;
params        = param { "," param } [ "," ] ;
param         = "self" | ident ":" type ;
generics      = "<" gparam { "," gparam } ">" ;
gparam        = ident [ ":" bound { "+" bound } ] ;

struct_decl   = "struct" ident [ generics ] "{" { field sep } "}" ;
field         = [ "pub" ] [ "var" ] ident ":" type ;
enum_decl     = "enum" ident [ generics ] "{" { variant sep } "}" ;
variant       = ident [ "(" type { "," type } ")" | "{" { field sep } "}" ] ;
trait_decl    = "trait" ident [ generics ] [ ":" bound { "+" bound } ]
                "{" { ( "type" ident | fn_decl ) sep } "}" ;
impl_decl     = "impl" [ generics ] [ type_path "for" ] type
                "{" { ( fn_decl | "type" ident "=" type ) sep } "}" ;
type_alias    = "type" ident [ generics ] "=" type ;
const_decl    = "const" ident ":" type "=" expr ;
test_decl     = "test" string_lit block ;

type          = type_path | "dyn" type_path | "Self"
              | "(" [ type { "," type } ] ")"
              | [ "async" ] "fn" "(" [ type { "," type } ] ")" [ "->" type ] ;
type_path     = path [ "<" type_arg { "," type_arg } ">" ] ;
type_arg      = type | ident "=" type ;

block         = "{" { stmt sep } [ expr ] "}" ;
stmt          = ( "let" | "var" ) pattern [ ":" type ] "=" expr [ "else" block ]
              | expr ;

expr          = (* operators per 4.2 *) unary { binop unary } ;
unary         = { "-" | "!" } postfix ;
postfix       = primary { "." ident [ call_args ] | "." int_lit | call_args
                        | "[" expr "]" | "?" | ".await" } ;
call_args     = [ "<" type { "," type } ">" ] "(" [ expr { "," expr } [ "," ] ] ")" ;
primary       = literal | path | block | "(" expr ")" | tuple
              | list_lit | map_lit | struct_lit
              | if_expr | match_expr | loop_expr | while_expr | for_expr | closure
              | "return" [ expr ] | "break" [ expr ] | "continue" ;

if_expr       = "if" cond block [ "else" ( if_expr | block ) ] ;
cond          = expr | "let" pattern "=" expr ;
match_expr    = "match" expr "{" { pattern [ "if" expr ] "->" expr sep } "}" ;
loop_expr     = "loop" block ;
while_expr    = "while" cond block ;
for_expr      = "for" pattern "in" expr block ;
closure       = [ "async" ] "|" [ cparam { "," cparam } ] "|" [ "->" type ] expr ;
cparam        = pattern [ ":" type ] ;

list_lit      = "[" [ expr { "," expr } [ "," ] ] "]" ;
map_lit       = "[" ":" "]" | "[" expr ":" expr { "," expr ":" expr } [ "," ] "]" ;
struct_lit    = path "{" [ field_init { "," field_init } ] [ "," ".." expr ] "}" ;
field_init    = ident [ ":" expr ] ;

pattern       = pat_atom { "|" pat_atom } ;
pat_atom      = "_" | literal | literal ( ".." | "..=" ) literal | ident
              | path [ "(" [ pattern { "," pattern } ] ")"
                     | "{" [ fpat { "," fpat } ] [ "," ".." ] "}" ]
              | "(" [ pattern { "," pattern } ] ")"
              | "[" [ pattern { "," pattern } ] [ "," ".." ident ] "]" ;
fpat          = ident [ ":" pattern ] ;

12. Implementation Notes (non-normative)

  • Generics are monomorphized.
  • Structs map to WasmGC structs; var fields are mutable, all others immutable.
  • Enums map to a WasmGC base struct with one subtype per variant; match compiles to br_on_cast chains or a tag switch.
  • Trait objects are a pair of a vtable reference and a data reference.
  • Closures are structs holding a function reference and the captured environment; a captured var is boxed.
  • Strings may use JS String Builtins in the browser and UTF-8 GC arrays elsewhere.
  • Async builds on JSPI in the browser and native async in WASI 0.3.
  • Workers map to Web Workers in the browser, each running its own instance of the module.
  • Overflow checks compile to the native op plus an overflow test and a trap.

13. Example

// src/main.pud, built with: pud build --target wasi
import std.fs
import json

@derive(Eq, Show)
struct Todo {
    title: Str
    var done: Bool
}

enum AppErr {
    Io(fs.IoErr)
    Parse(json.ParseErr)
}

impl From<fs.IoErr> for AppErr {
    fn from(e: fs.IoErr) -> AppErr { AppErr.Io(e) }
}

impl From<json.ParseErr> for AppErr {
    fn from(e: json.ParseErr) -> AppErr { AppErr.Parse(e) }
}

fn load(path: Str) -> Result<List<Todo>, AppErr> {
    let text = fs.read(path)?
    let todos: List<Todo> = json.decode(text)?
    Ok(todos)
}

fn main() {
    let todos = match load("todos.json") {
        Ok(t) -> t
        Err(e) -> {
            print("could not load: {e}")
            return
        }
    }

    let pending = todos.filter(|t| !t.done)
    print("{pending.len()} of {todos.len()} left")

    for t in pending {
        print(" - {t.title}")
    }
}

test "empty list has nothing pending" {
    let todos: List<Todo> = []
    assert_eq(todos.filter(|t| !t.done).len(), 0)
}

14. Deferred Past v1

  • Shared-memory threads, once WasmGC can share objects across threads
  • where clauses
  • Const generics
  • User-defined derives and compile-time execution

Conformance suite

简体中文

The language specification is the normative definition of Puddi. The conformance suite, in conformance/ of the compiler repository, checks a pud binary against it from the outside:

  • every case names the spec sections it verifies;
  • every normative section (chapters 2 to 10) has at least one passing case, and CI fails if one does not;
  • cases marked xfail record where the compiler still differs from the spec. A known gap that gets fixed makes the run fail until the marker is removed, so the list stays accurate.

Every normative section has passing coverage in v0.1.2. The release workflow runs the suite on every native release binary before publishing.

Running it

The suite needs Node.js 22 or newer and runs against any pud, including an installed release:

git clone https://github.com/puddi-lang/puddi
cd puddi
node conformance/run.mjs --pud ~/.pud/bin/pud --coverage
OptionEffect
--pud <path>the binary to test (default: target/release/pud, then target/debug/pud, then pud)
--filter <text>only cases for a section such as 3.7, or whose path contains the text
--coverageprint a per-section report
--strict-coveragefail when a normative section has no passing case
--json <file>write a machine-readable report
--listlist the cases without running them
--jobs <n>limit the number of cases running at once
--timeout <seconds>set the time limit per case

Known gaps in 0.1

The following gaps apply to v0.1.0 and v0.1.1. Their conformance cases pass in v0.1.2.

SectionGap
2.4no warnings for naming-convention violations
2.4struct literals need an uppercase type name
3.7U8 + 0.5 does not default the literal to Float
3.12Self.Item does not resolve inside an impl
3.12a duplicate impl is accepted
4.6let inc = |x| x + 1 needs a parameter annotation
8.3exports that use WIT records, variants, enums or flags fail to compile

Writing cases

A case is a .pud file (or a small package) with a header of // comments that names the sections it covers and how to run it, and //> lines with the expected output. The format is described in the suite’s README. A change to the specification’s normative text should come with cases for it; see Contributing.

Implementation status

简体中文

The conformance suite checks the pud compiler against the draft 0.1 language specification.

Language

Structs, enums, tuples, generics with bounds (monomorphized), traits with default methods, associated types and supertraits, dyn Trait, operator traits, closures that capture by reference, pattern matching with exhaustiveness checking (guards, ranges, or-patterns, list patterns, let ... else, if let, while let), ? with From conversion, AnyErr with downcast, @derive(Eq, Ord, Hash, Show, Transfer), constants, type aliases, async fn and .await, task.scope with structured cancellation, workers, implicit numeric widening, checked integer overflow, modules and imports, WIT imports, test blocks, @target, @extern, @export, export fn and @deprecated.

Standard library

See the prelude and the standard library modules available on each target.

Known limitations

  • std.io, std.fs and std.env exist only on wasi, and std.dom only on browser, as the specification says.
  • Other WASI hosts can run wasi components that use workers only if they implement the puddi:runtime worker interfaces.
  • The embedded runner links WASI 0.3.0 from Wasmtime, which satisfies the 0.3.2 imports through semver matching.
  • pud test runs tests on the JavaScript host, so tests cannot call WIT imports.
  • Grapheme segmentation is an approximation (combining marks, variation selectors, ZWJ sequences), and case mapping covers ASCII only.

Deferred past version 1

The specification defers these on purpose:

  • shared-memory threads, until WasmGC can share objects across threads
  • where clauses
  • const generics
  • user-defined derives and compile-time execution

Compiler development

简体中文

Puddi compiles source and WIT bindings to WebAssembly. The compiler architecture describes the current main branch in detail.

StageWhat it doesStarting point
SourcesDiscovers modules, loads dependencies and generates WIT bindingssrc/main.rs, src/deps.rs, src/wit.rs
Front endLexes and parses source, expands derives and resolves namessrc/lexer.rs, src/parser.rs, src/derive.rs, src/program.rs
ElaborationChecks types and patterns, monomorphizes generics and lowers to typed IRsrc/elab.rs, src/exhaust.rs, src/ir.rs
WebAssemblyLowers WasmGC types and instructions, encodes the module and wraps it as a componentsrc/codegen.rs, src/wit.rs
HostingRuns the component in Wasmtime or extracts the core module for a JavaScript hostsrc/runner.rs, src/runtime.mjs

Optimization and diagnostics

Puddi v0.1.1 includes an IR optimization pass, a built-in WebAssembly assembler, parallel parsing and code generation, and caches for builds and Wasmtime machine code. See the v0.1.1 release notes for details.

Environment variableWhat it does
PUD_TIME=1Print elapsed time at compiler phases
PUD_NO_CACHE=1Disable the build and Wasmtime caches
PUD_NO_OPT=1Skip the IR optimizer
PUD_WAT=1Use the wat crate instead of the built-in assembler
PUD_ASM_CHECK=1Assemble with both implementations and compare their output
PUD_SERIAL_CODEGEN=1Generate WebAssembly text on one thread

Finding the right test

Add a conformance case when a change affects a rule in the specification. Use the compiler repository’s tests/run for a runtime regression and tests/fail for a rejected program. The contribution guide explains the fixture formats.

Changelog

简体中文

Copied from CHANGELOG.md at Puddi v0.1.2.

All notable changes to Puddi are recorded here. The format follows Keep a Changelog, and versions follow Semantic Versioning as described in docs/releasing.md.

[Unreleased]

0.1.2 - 2026-11-21

Added

  • Nine portable standard library modules for browser, WASI and plugins. They provide deques and priority queues, lazy iterator sources, Unicode text helpers, radix formatting, binary readers, hex and Base64 codecs, percent encoding, lexical paths, CSV and descriptive statistics.
  • std.date adds Gregorian dates, UTC timestamps, Unix epoch conversions and checked arithmetic. CSV supports configurable delimiters, JSON supports pretty printing and pointer lookup, and std.fmt parses signed and unsigned integers in bases 2 through 36.

Fixed

  • JSON parsing rejects malformed surrogate escape pairs.
  • Float literals can be used on either side of a binary operator with a fixed-width integer when a lossless common type exists.
  • Trait implementations resolve Self.Item and other associated types from the current impl in method signatures and local annotations.
  • Naming conventions produce warnings. Struct literals and patterns accept lowercase type names.
  • The compiler rejects overlapping trait implementation headers and cyclic supertraits.
  • Recursive constant initializers are diagnosed instead of overflowing the compiler stack.
  • Type aliases resolve in dependency order, preserve their target types in generic bounds, and report cycles.
  • Constant initializers resolve names in their declaring module and reject references to ordinary functions.
  • Numeric operands can constrain unannotated closure parameters.
  • WIT exports can use records, variants, enums and flags aliased from an interface.
  • pud fmt preserves trailing spaces inside multiline strings. #4
  • Str.from_utf8 rejects overlong encodings, surrogate code points and values above the Unicode range.

Documentation

0.1.1 - 2026-11-21

This release improves the Puddi toolchain for the draft 0.1 language specification.

Fixed

  • pud rejects unknown and empty targets in the --target=<value> form, matching --target <value> and -t <value> (#6).

Performance

Measured with the programs in bench/ against Rust and MoonBit; see bench/README.md.

  • pud run uses Wasmtime’s copying garbage collector instead of deferred reference counting and starts with a 16 MiB GC heap: up to 20x faster on allocation-heavy code
  • Compiled machine code is cached per component in the user cache directory, so running an unchanged program again skips Cranelift (PUD_NO_CACHE=1 turns this off)
  • Payload-less enum variants (None, Ordering.Less, …) are shared instead of allocated on every use
  • Integer overflow checks for Int addition and subtraction are emitted inline, and left out where the operands’ ranges show they cannot overflow (for example i += 1 inside while i < n)
  • list[i] compiles to a single unsigned bounds check and an array access instead of calls through Index; for x in list walks the list by index without allocating an Option per element
  • Iterator adapters implement fold by internal iteration, so chains ending in fold, count, collect or for_each allocate nothing per element
  • List.sort compares with < directly instead of through a closure and merges without branches; lists of integers of 256 or more elements are sorted by radix; List.filled and StrBuilder.push copy in bulk
  • A new IR optimizer inlines closures passed to higher-order functions, tiny functions, matches on constructors returned by small functions and one level of small recursive functions: iterator chains run 45x faster on Wasmtime, and Option results of Map.get or to_int are no longer allocated when unwrapped at once (PUD_NO_OPT=1 turns it off)
  • Map.insert finds the key or a free slot in one probe
  • PUD_HOST=node pud run starts Node.js with --no-liftoff: V8 cannot move a running wasm loop to optimized code, so loops in main stayed in the baseline tier
  • pud run compiles faster (parallel parsing, shared declarations, only the platform operations a program uses) and starts Wasmtime on another thread while compiling; PUD_TIME=1 prints the time of each phase
  • pud build and pud run reuse the previous build when the sources, WIT files, target and compiler are unchanged: running an unchanged hello takes 25 ms instead of 160 ms
  • Wasmtime keeps compiled machine code per function, so after an edit only the changed functions are compiled again; Cranelift’s own inliner is off, which makes compiling 1.7x faster at the same speed
  • Large source files are lexed and parsed in pieces on several threads
  • The generated WebAssembly text is assembled by src/asm.rs on several threads instead of the wat crate, 10x faster with byte-identical code (PUD_WAT=1 uses wat, PUD_ASM_CHECK=1 compares both); functions are also turned into WebAssembly text on several threads, with the same result as on one; a 2,000-function program builds in 250 ms instead of 570 ms
  • bench/compile.mjs compares the edit-compile-run loop with cargo and moon

Documentation

  • Documentation site at https://puddi-lang.github.io/puddi-docs/ with a language guide, toolchain and standard library pages, built from puddi-lang/puddi-docs
  • Complete Simplified Chinese documentation
  • Contributing guide, code of conduct, security policy, compiler architecture and release process documents
  • Draft governance model in GOVERNANCE.md, not yet in effect

Known gaps

The known conformance gaps in 0.1.0 still apply to this release.

0.1.0 - 2026-11-18

First release of Puddi and its pud toolchain, implementing the draft 0.1 language specification.

Language

  • Structs, enums, tuples, generics with bounds, traits with default methods, associated types and supertraits, dyn Trait, operator traits and closures
  • Pattern matching with exhaustiveness checking, if let, while let and let ... else
  • ? with From conversion, the Error trait and AnyErr
  • @derive(Eq, Ord, Hash, Show, Transfer), constants, type aliases, modules and imports
  • async fn and .await, task.scope with structured cancellation, and workers
  • WIT imports, export fn, @extern and @export, @target, @deprecated and test blocks

Toolchain

  • pud new, build, run, test, check, fmt, doc and add
  • browser, wasi (WASI 0.3) and plugin targets, all emitted as WebAssembly components on WasmGC
  • An embedded Wasmtime runtime for pud run
  • Git dependencies with minimal version selection and pud.lock, plus local path dependencies

Testing and distribution

  • A conformance suite in conformance/ with cases for every normative section of SPEC.md
  • CI on Linux, macOS and Windows
  • Prebuilt binaries for Linux (x86_64, arm64), macOS (x86_64, arm64) and Windows (x86_64), with install scripts for each

Known gaps

The conformance suite marks these differences from the spec as expected failures:

  • no warnings for naming-convention violations, and struct literals need an uppercase type name (2.4)
  • a float literal next to an unsigned integer does not default to Float (3.7)
  • Self.Item does not resolve inside an impl block, and a duplicate impl is accepted (3.12)
  • unannotated closure parameters are not inferred from the body or later calls (4.6)
  • plugin exports that use WIT records, variants, enums or flags fail to compile (8.3)

Contributing

简体中文

Puddi is developed in the open on GitHub and contributions are welcome: bug reports, conformance cases, compiler fixes, standard library work, examples and documentation.

RepositoryWhat lives there
puddi-lang/puddithe specification, the pud toolchain, the standard library and the conformance suite
puddi-lang/puddi-docsthis book

The compiler repository’s CONTRIBUTING.md explains how to build and test the toolchain, and docs/architecture.md walks through the compiler.

Ways to help

  • Report a bug. Open an issue with the smallest program that shows it, the pud version output and what you expected.
  • Add a conformance case. If you find a place where the compiler and the specification disagree, a failing case (marked xfail until it is fixed) is often the most useful contribution.
  • Fix a known gap. The known gaps each have a case that will tell you when you are done.
  • Find a first task. Browse good first issues or ask in Discussions.
  • Improve this book. Every chapter has an edit button. CI checks complete examples in both languages. When changing a technical explanation or example, update the corresponding page in src/ and src-zh-CN/.

Changing the language

The specification is the definition of the language, so a change to its normative text is a language change. For now, open an issue that describes the problem, the proposed text and its effect on existing programs, and discuss it there before sending a pull request. A spec change is merged together with conformance cases for it and, when it is not already implemented, an xfail marker. A more formal RFC process is drafted in the governance document for when the community grows.

Working on the book

git clone https://github.com/puddi-lang/puddi-docs
cd puddi-docs
tools/build.sh                       # build English and Simplified Chinese
python3 -m http.server --directory book 8000
node tools/check-examples.mjs       # compile and run every example with pud

The book needs mdBook 0.5 and an installed pud of the version in PUDDI_VERSION. A ```puddi block that declares fn main or test is compiled by the example checker; a ```text,output block right after it is the expected output of pud run. Mark a complete example that cannot be checked in isolation with ```puddi,ignore, one that must be rejected with puddi,fail, and one for the browser with puddi,browser.

All contributions are dual licensed under the MIT and Apache 2.0 licenses, as described in each repository’s README.

Governance

简体中文

Puddi is a young project with a small community, and it is run informally for now: the maintainers of the puddi-lang organization review changes and make decisions in the open, in issues and pull requests.

A fuller governance model is written down in GOVERNANCE.md in the compiler repository. It is a draft that is not in effect. It describes:

  • the roles of contributors, reviewers and maintainers, and how people move between them;
  • how decisions are made, by lazy consensus with a vote as the fallback;
  • an RFC process for changes to the language specification and the standard library;
  • the release, stability and security policies;
  • how the code of conduct is enforced;
  • the conditions under which the model takes effect.

Until then, the interim rules in that document apply: discuss significant changes in an issue first, and change the specification only together with conformance cases.

Code of conduct

简体中文

Everyone who takes part in the Puddi project, in its repositories, issues, pull requests and any other project space, is expected to follow the code of conduct.

In short: be respectful and patient, assume good intent, give and accept technical criticism graciously, and do not harass anyone. The full text explains what is not acceptable, how to report a problem privately and how reports are handled.