Mesh

Complete Reference ​

This page is the index of features implemented on the current Mesh 14 branch. It distinguishes supported syntax from reserved words, source-level APIs from runtime-only symbols, and built-in modules from optional packages.

For examples and explanation, follow the linked guides. Use this page when you need to answer “does Mesh support this?” or find the owning reference.

Source files and modules ​

Mesh source files use the .mpl extension. main.mpl is the default executable entrypoint; [package].entrypoint can select another source file.

mesh
module Billing do
  pub fn total(items :: List<Int>) -> Int do
    List.reduce(items, 0, fn acc, item -> acc + item end)
  end
end
FormMeaning
foo/bar_baz.mplA file module named Foo.BarBaz: each path segment in PascalCase
module Name do ... endDeclare a module named exactly Name inside a file; import it to use it, from that file only
pub module Name do ... endDeclare a module any file may import
import Foo.BarImport a module for qualified access through its last segment: Bar.run()
from Foo.Bar import one, twoImport selected public symbols
pubExport a function, module, struct, interface, supervisor, sum type, alias, or resource

Standard-library modules need no import. A module block may not share its name with a file module. Qualified names work in calls, type annotations (p :: Geo.Point), struct literals (Geo.Point { x: 1, y: 2 }), constructors and constructor patterns (Shapes.Circle(r)), and impl headers (impl Geo.Describe for Geo.Point).

Selective imports may be parenthesized. Only the parenthesized form may span lines; an unparenthesized import list ends at the newline. Glob imports are not supported.

Comments, literals, and separators ​

SurfaceSyntax and behavior
Line comment# comment
Documentation comment## item documentation
Module documentation##! module documentation
Nested block comment#= outer #= inner =# outer =#
StatementsA newline ends a statement, unless the line ends in = or an infix operator or the next line starts with one (other than - and %); two statements on one line need ; between them
IdentifierStarts with _ or a Unicode alphabetic code point; later characters may be _ or a Unicode alphanumeric code point
IntegerDecimal, 0x hexadecimal, 0b binary, or 0o octal (prefixes may be uppercase); _ separators are accepted; at most 9223372036854775807 in any radix, and -9223372036854775808 may be written
FloatDecimal and scientific notation; any literal with an exponent, such as 1e3, is a Float
Booleantrue, false
Unitnil or ()
String"text", with interpolation and the escapes \n \t \r \0 \\ \", \$ and \# (a literal ${ or #{), and \u{1F389} (1 to 6 hex digits); any other escape is an error
Heredoc"""multiline text"""; dedented to the closing """, with escapes and interpolation as in strings
Atom:name; the first character after : is a lowercase ASCII letter or _, later ones may be _ or any Unicode letter or digit
Regex~r/pattern/ims; the pattern may span physical source lines until an unescaped /; supported flags are i, m, and s
List[one, two]
Tuple(one, two)
Map%{key => value}
JSON objectjson { bare_key: expression }
StructPoint { x: 1, y: 2 }
Struct update`%{point

Both "#{expression}" and "${expression}" interpolate. The #{...} form is preferred in new code.

The compiler rejects malformed numeric literals, a digit outside the radix (0b102), an integer literal beyond the Int range (0xffffffffffffffff), and a float literal that overflows (1e999).

A heredoc drops the newline after its opening """ and the final line holding only the closing indentation, removes that indentation from every line, and turns source \r\n line endings into \n. In a run of more than three quotes, the last three close it: """say "hi"""" is say "hi". A heredoc may also be a pattern. See Heredoc Strings.

Reserved keywords are exact ASCII identifiers: let is a keyword, but letπ is a valid ordinary identifier.

json { ... } has static type Json. It is implicitly compatible with String at APIs that consume encoded JSON, but structured access remains available through Json.parse, Json.object_get, Json.array_get, and the typed scalar accessors.

Core types ​

TypeNotes
IntSigned runtime integer used by ordinary numeric literals and operators
FloatFloating-point value
BoolBoolean value
StringUTF-8 text
BytesBinary-safe byte sequence
U64, U128, I128Opaque checked wide integers; use their module functions
JsonStructured JSON value with implicit String compatibility
AtomNamed atom such as :ok; has Eq, Display, Debug, and Hash, and matches as a literal pattern
RegexCompiled regular expression
()Unit
Option<T> / T?Some(T) or None; a tuple takes the shorthand too: (Int, String)?
Result<T, E> / T!EOk(T) or Err(E); for example (Int, Int)!String
List<T>Immutable list
Map<K, V>Immutable map
Set<T>Immutable set of unique values
Queue<T>Immutable first-in, first-out queue
RangeEnd-exclusive integer range
(A, B)Tuple type
Fun(A, B) -> RFunction type
Pid<M>Process identifier whose mailbox accepts M
PidUntyped process-identifier escape hatch

Additional opaque types are introduced by their modules, including database connections, pools, HTTP values, WebSocket messages, dates, jobs, iterators, and cluster bootstrap records.

The built-in algebraic types also include Ordering, whose constructors are Less, Equal, and Greater.

Bindings and functions ​

mesh
let inferred = 42
let explicit :: Int = 42

fn identity<T>(value :: T) -> T do
  value
end

fn join_display<A, B>(left :: A, right :: B) -> String where A: Display, B: Display do
  left.to_string() <> right.to_string()
end
FormSupport
let name = expressionImmutable inferred binding
let name :: Type = expressionAnnotated binding
let (a, b) = pairTuple destructuring binding
fn name(...) ...Named function
def name(...) ...Synonym for fn
fn name(...) = expressionOne-expression function
Multiple same-name clausesPattern and guard dispatch; clauses must be consecutive
Different aritiesSupported as separate overloads
<T, U>Explicit generic parameters
where T: TraitGeneric interface bound; multiple bounds are comma-separated
when guardClause guard
return expressionExplicit early return
returnEarly Unit return

The final expression of a function or block is its value. Named functions are registered before their bodies are inferred, so mutual recursion is supported. A non-exhaustive function-clause group warns; a non-exhaustive case or match is an error.

Function parameters may be patterns: literals, constructors, tuples, lists (len([])), cons (len(_ :: rest)), and or-patterns (small(1 | 2)). In a parameter, :: Type after a name or a pattern is an annotation (0 :: Int); a lowercase name, _, or a list pattern after :: makes a cons pattern. A clause may use = expression or a do ... end body. The first clause owns the public, generic, return-type, and where metadata for a same-name/arity clause group. Put a catch-all clause last. A function clause's when guard may be any Bool expression.

Direct calls to the current function in tail position are lowered to a loop, including tail positions reached through blocks, let continuations, if branches, case/match arms, explicit return, and actor receive arms or timeouts. This does not eliminate mutual recursion, calls wrapped in another operation, or any other non-tail call.

Closures and calls ​

Supported closure forms include:

mesh
fn(x, y) -> x + y end
fn x, y -> x + y end
fn -> 42 end
fn do
  let value = compute()
  value
end
fn value do
  transform(value)
end
fn 0 -> "zero" | n when n > 0 -> "positive" | _ -> "negative" end

Closures capture lexical bindings. Calls support:

  • positional arguments;
  • keyword arguments, which become one final map argument;
  • a trailing do |x| ... end closure after the argument list, which becomes the last argument of a call, method call, or pipe step;
  • field and method chaining;
  • postfix ? on Option and Result.

Positional arguments cannot follow keyword arguments. The heads of if, while, case, and for do not take a trailing closure, so their do always opens the body.

On a String, List, Map, Set, or Range value, a method call falls back to that module's function: xs.contains(x) is List.contains(xs, x), m.put(k, v) is Map.put(m, k, v), and "s".length() is String.length("s"). An interface method of the same name is preferred.

Built-in functions ​

These functions need no module prefix and no import:

FunctionBehavior
println(text), print(text)Write a String to standard output, with or without a newline; interpolate other values
panic(message)String -> Never; end the current actor, or the program from main
default()The Default value of the type the context expects
compare(a, b)An Ordering (Less, Equal, or Greater) through Ord
map, filter, reduce, head, tailThe List functions of the same names
spawn, send, self, linkActor operations; see Actors
test, describe, setup, teardown, assert, assert_eq, assert_ne, assert_raisesThe test DSL; see Testing

inspect(value) and to_string(value) call the Debug and Display methods as functions, the same as value.inspect() and value.to_string().

Pattern matching ​

case and match are synonyms:

mesh
match value do
  Some(head :: tail) when head > 0 -> do
    use(head, tail)
  end
  None -> "missing"
  Some(items) -> inspect(items)
end

Supported patterns are:

  • wildcard _;
  • variable binding;
  • integer, float, string, atom, boolean, and nil literals;
  • negative numeric literals;
  • tuple patterns;
  • struct patterns such as Point { x: 0, y } and Geo.Point { x }: field: pattern matches a field, a field alone binds a variable of its name, and omitted fields match anything;
  • qualified and unqualified constructors;
  • constructor payload destructuring;
  • cons patterns such as head :: tail;
  • list patterns such as [] and [a, b], which match exactly that length;
  • or-patterns such as one | two;
  • alias patterns such as pattern as whole;
  • optional when guards on function, closure, receive, and match arms.

Both sides of an or-pattern must bind the same names. A heredoc literal is also a pattern. let and for take any pattern that matches every value: names, _, and tuple and struct patterns of them.

An arm body is one expression, a -> do ... end block, or statements starting on the next line and indented under the arm. return is an expression, so None -> return -1 leaves the function.

A guard on a case, match, or receive arm, a function clause, or a multi-clause closure may be any Bool expression.

A case or match arm with no -> is its pattern alone and passes the matched value through, rebuilt: Ok(value) means Ok(value) -> Ok(value). The rebuilt value takes the type of the whole case, so another arm may change the rest of it, as Err(e) -> Err(wrap(e)) changes the error type. The pattern must name a whole value: names, literals, constructors, and nullary constructors such as None; _ and a bare Ok are rejected (E0056).

Control flow ​

FormResult
if condition do ... else ... endUnified branch type
if a do ... else if b do ... else ... endelse if chain closed by one end
if condition do ... end()
case value do ... endUnified arm type; exhaustiveness checked
match value do ... endSynonym for case
for value in iterable [when guard] do ... endList<body type>
while condition do ... endUnit
breakExit the enclosing loop
continueContinue the enclosing loop

for supports ranges, lists, maps, sets, and user implementations of Iterable/Iterator. Ranges are end-exclusive: 0..5 yields 0 through 4, and a..b is a Range value anywhere, not only in a for head. A map loop binds each entry with {key, value} or a tuple pattern (key, value).

An if without else has type (), so use it only for its effects.

Pipes and operators ​

Operators are listed from lower to higher precedence:

Precedence groupOperators
Pipe|>, |N>
Boolean ORor, ||
Boolean ANDand, &&
Equality==, !=
Ordering<, >, <=, >=
Range..
Concatenation<>, ++
Additive+, -
Multiplicative*, /, %
Prefix-, not, !
Postfixcall, field, ?

|> supplies the left value as the first argument. |N> supplies it as argument position N; N begins at 2. Leading and trailing multiline pipe forms are both supported.

Arithmetic and comparisons dispatch through built-in interfaces. <> and ++ are interchangeable: either joins two strings or two lists of the same type.

Int division truncates toward zero (-7 / 2 is -3), and % takes the dividend's sign (7 % -2 is 1). Integer division or remainder by zero panics; -9223372036854775808 / -1 wraps. Float follows IEEE 754, so NaN is unequal to itself. Float.to_int, Math.floor, Math.ceil, and Math.round saturate at the Int bounds and turn NaN into 0.

Structs, sum types, and aliases ​

mesh
pub struct Box<T> do
  value :: T
end deriving(Eq, Debug, Json)

pub type Either<A, B> do
  Left(A)
  Right(value :: B)
end deriving(Eq, Debug, Json)

pub type Pair<A, B> = (A, B)
  • Structs are product types with named fields.
  • Sum types may have nullary, positional, or named-payload variants.
  • Aliases are transparent and may be generic.
  • Struct and sum constructors can be used qualified or unqualified.
  • ORM schema metadata may be declared inside structs; see Databases.

Interfaces and implementations ​

mesh
pub interface Container<T> do
  type Item
  fn first(self) -> Self.Item
  fn label(self) -> String do
    "container"
  end
end

struct IntBox do
  value :: Int
end

impl Container<Int> for IntBox do
  type Item = Int
  fn first(self) -> Int do
    self.value
  end
end

Interfaces support:

  • generic parameters;
  • required methods;
  • methods with default bodies;
  • instance and static methods;
  • associated types;
  • generic where constraints.

Implementations must provide required methods and associated types with matching signatures. Extra associated types, duplicate structural implementations, and ambiguous method resolution are rejected.

The declaration keyword is interface; trait is reserved but is not a supported declaration form.

Built-in interfaces ​

GroupInterfaces
ArithmeticAdd, Sub, Mul, Div, Mod, each with Output; Neg with Output
Comparison and logicEq, Ord, Not
Presentation and identityDisplay, Debug, Hash, Default
IterationIterator with Item; Iterable with Item and Iter
ConversionFrom, Into, TryFrom, TryInto
Generated serializationToJson, FromJson, FromRow, and schema metadata behind derives

Implementing From<Source> synthesizes the matching Into<Target>. Implementing TryFrom<Source> synthesizes TryInto<Target>. Result propagation may use From to convert an error into the enclosing function's error type.

Deriving ​

An explicit deriving(...) clause is selective, and deriving() selects nothing. For backward compatibility, omitting the clause derives Debug, Eq, Ord, and Hash for a struct, and Debug, Eq, and Ord for a sum type. Display, Json, Row, and Schema are never enabled by omission.

Type kindSupported derivesConstraints
StructEq, Ord, Display, Debug, Hash, Json, Row, SchemaOrd requires Eq; Row and Schema are struct-only
Sum typeEq, Ord, Display, Debug, Hash, JsonOrd requires Eq; Schema is rejected

Json generates encoding and decoding. Row generates database row conversion for supported scalar/optional fields. Schema generates ORM schema metadata. See Type System for field rules.

Errors and propagation ​

mesh
fn load() -> Account!AppError do
  let raw = File.read("account.json")?
  let value = Json.parse(raw)?
  decode_account(value)
end
  • T? is shorthand for Option<T>.
  • T!E is shorthand for Result<T, E>.
  • ? unwraps Some/Ok.
  • ? returns None/Err early.
  • A Result error may be converted through From.
  • Use case/match for explicit handling.
  • panic(message) (String -> Never) prints Mesh panic: message and ends the current actor, which a supervisor can restart, or ends the program with exit status 101 when called from main.
  • Runtime errors are panics: List.get out of range, Map.get of a missing key, a call no function clause matches, and integer division by zero.
  • Recursion deeper than the stack ends the whole program with error: stack overflow.

See Panics.

Actors and concurrent processes ​

SurfacePurpose
actor name(args) do ... endDefine an actor
spawn(function, args...)Start an actor and return Pid<M>
send(pid, message)Type-check and enqueue a message, returning an observable Int status
receive do ... endWait for the next mailbox message
after timeout -> ...Receive timeout arm
self()Current actor PID; actor context only
link(pid)Bidirectional failure link
terminate do ... endOne actor cleanup callback
Process.monitor / Process.demonitorOne-way process observation: a message of the watching actor's type when the process ends; actor context required
serviceStateful call/cast actor with generated client functions
supervisorChild restart tree
JobShort-lived async result
TimerSleep and delayed message delivery
ChannelBounded, nonblocking queues between actors

Actor definitions accept arguments. Receive arms match the next message like case arms: patterns, guards, and multi-line bodies are allowed, and the arms must cover the whole message type. An actor that calls itself continues with new arguments; in tail position that call is a loop. See Concurrency for service syntax, supervisor strategies, channel policies, jobs, registries, and graceful shutdown.

Cluster declarations ​

mesh
@cluster
pub fn read_model() -> String do
  "ready"
end

@cluster(3)
pub fn replicated_read() -> String do
  "ready"
end

@cluster and @cluster(N) may decorate fn or def. The target must resolve to one uniquely named public work function. The omitted replication count is currently 2.

HTTP.clustered(...) adapts declared work to an HTTP route. It does not make an arbitrary private closure remotely executable. Runtime bootstrap, continuity, identity, admission, routing, and capacity policy are documented under Distributed Actors and Autonomous Clusters.

The removed clustered(work) declaration form is rejected; use the decorator.

Native declarations ​

mesh
@native("mesh_math_add")
pub fn add(left :: Int, right :: Int) -> Int

A native declaration must be:

  • in a manifest-listed bindings file;
  • pub;
  • bodyless;
  • fully annotated, including an explicit return type;
  • concrete, without generic parameters, where, or guards;
  • bound to one literal C identifier.

ABI 1 value types are Int, Float, Bool, String, Bytes, U64, U128, and I128. A return may additionally be Option<T> or Result<T, E> when every payload is an ABI value. User structs, collections, tuples, closures, actors, and generic native functions do not have ABI 1 layouts.

See Native Packages for manifests, archive verification, ownership, errors, and target selection.

Exported functions ​

mesh
@export("mesh_mobile_echo")
pub fn echo(request :: Bytes) -> Bytes!String do
  Ok(request)
end

@export("c_symbol") exposes a function under a C symbol when the project is built with meshc build --artifact staticlib or --artifact cdylib. The function must be pub, the symbol a C identifier, and the signature exactly (Bytes) -> Bytes!String, without generic parameters, where, or a guard; anything else is error E0055. An export marked @display (before or after @export) may use Plaintext<Bytes> for either Bytes, and only such an export may carry plaintext (E0093); see Plaintext. See Library Builds.

Standard-library module index ​

This table lists every compiler-recognized built-in module on the current branch.

AreaModulesDetailed guide
Text and collectionsString, List, Map, Set, Tuple, Range, Queue, Iter, RegexStandard Library, Iterators
Binary and numbersBytes, BytesBuilder, U64, U128, I128, Checked, Math, Int, FloatStandard Library
Encoding and JSONJSON, Json, Base64, HexWeb, Standard Library
System and timeIO, Env, File, DateTime, Monotonic, Duration, Random, CryptoStandard Library
Secrets and keysSecret, SecretMap, StorageKey, X25519PrivateKey, SigningPrivateKey, MlKemPrivateKey, BlindRsaSecretKeyStandard Library
Message contentPlaintextType System
Host callbacksHostStandard Library, Library Builds
Concurrent runtimeJob, Timer, Channel, Process, TestConcurrency, Testing
Web and socketsHTTP, Request, Ws, Http, WsClientWeb
DatabasesSqlite, Pg, Pool, Orm, Expr, Query, Repo, Changeset, MigrationDatabases
DistributionNode, Global, Continuity, ClusterDistributed Actors, Autonomous Clusters

JSON and Json address the same module family; Json is the conventional name in new examples.

Official packages ​

PackageCurrent scope
mesh-borshBounded Borsh readers and writers backed by a native archive
mesh-anchorPure-Mesh Anchor discriminator, owner, and versioned-layout validation
mesh-solana 0.2Typed RPC, account decoders, subscriptions, SPL/Jito helpers, instruction inspection, legacy/v0 unsigned messages, and bounded unsigned simulation

See Packages and Registry for public functions, installation, provenance, and explicit non-goals.

Toolchain index ​

CommandPurpose
meshc buildCompile and link a project as an executable, static library, or dynamic library
meshc initGenerate hello, clustered, or Todo API starters
meshc depsResolve git and path dependencies and fetch git checkouts
meshc fmtFormat or check .mpl files
meshc lintReport deep nesting and other lint findings in .mpl files
meshc testRun .test.mpl tests
meshc replStart the LLVM-backed REPL
meshc lspRun the language server over stdio
meshc migrateGenerate, inspect, apply, or roll back migrations
meshc clusterInspect or control a cluster
meshc proofRun repository-owned proof scenarios
meshc updateRefresh an installer-managed toolchain
meshpkg loginStore a registry token
meshpkg searchSearch the registry
meshpkg installInstall the latest release of one package, or the manifest's exact registry dependencies
meshpkg publishPublish an immutable package version
meshpkg updateRefresh the toolchain

See Developer Tools for arguments, output paths, supported targets, editor integration, and limitations, Library Builds for --artifact staticlib|cdylib, and Environment Variables for the variables the tools and runtime read.

Keywords ​

These words are reserved and cannot name a variable or function:

actor, after, and, break, call, case, cast, continue, def, do, else, end, false, fn, for, if, impl, import, in, interface, json, let, link, match, module, nil, not, or, pub, receive, return, self, send, service, spawn, struct, supervisor, terminate, true, type, when, where, while.

Some words have a meaning only in one position and remain ordinary names elsewhere:

WordPosition
fromfrom Module import name
asAfter a pattern: pattern as whole
derivingAfter a struct or sum type's end
resourceBefore a type declaration: resource Name, resource struct Name do ... end
borrow, consumeParameter ownership after ::: handle :: borrow Handle
table, primary_key, timestamps, belongs_to, has_many, has_oneORM schema metadata inside a struct
strategy, max_restarts, max_seconds, child, start, restart, shutdownFields of a supervisor block and its child blocks
cluster, native, exportDecorator names after @

Words from other languages ​

alias, cond, trait, trap, with, and monitor are ordinary names in Mesh. For what they do elsewhere, use:

  • import or from ... import instead of alias;
  • if, case, or match instead of cond;
  • interface instead of trait;
  • Result, supervision, links, and monitors for the corresponding error and process flows;
  • Process.monitor and Node.monitor, or from Process import monitor, to monitor a process.

Current intentional limits ​

  • Variables and collections are immutable.
  • There are no module-level bindings: a let outside a function is error E0080 in a build. Use a function, such as fn limit() -> Int do 10 end. The REPL keeps its let bindings between inputs.
  • A program runs main and what it calls: an expression outside every function, such as println("hi") at the top of a file, would never run, and is error E0087 in a build. The REPL runs each one it is given.
  • Functions, types, imports and other definitions go at the top level of a module; inside a function, only let binds, and a definition there is error E0084. Bind a closure instead: let helper = fn x -> x + 1 end.
  • There is no bracket indexing: an index expression is error E0078. Use module functions such as List.get, Map.get, Tuple.nth, and Json.array_get.
  • Methods are not generic: an impl method, or an interface's default method, is compiled once for each type implementing the interface, so each parameter needs a type, from an annotation in the interface or the impl, or from how the body uses it. A parameter nothing fixes is error E0082. A top-level function with an unannotated parameter is generic and compiled for each argument type. Likewise, calling value.method() needs the method's return type: when neither an annotation nor the body fixes it ([], whose elements nothing names), the call is error E0088.
  • Wide integers use checked module functions instead of ordinary literal operators.
  • Random is deterministic, not cryptographic.
  • Inbound WebSocket TLS is not exposed at the Mesh source API.
  • SQLite is a local/single-node application database.
  • Native packages supply prebuilt, exact-target static archives.
  • meshc test --coverage is explicitly unsupported.
  • mesh-solana does not sign or submit transactions.

These are boundaries of the current public surface, not implied future commitments.

Edit this page on GitHub
v0.1.8 Last updated: October 8, 2026