Language basics

Moth uses a compact set of syntax rules across the whole language. Colons open blocks, semicolons close them and square brackets build strings rather than index collections.

These choices keep declarations, supplied values and blocks visually distinct. Start here before moving to bindings, control flow and user-defined types.

Choose the explanation level: Blocks and statements

Blocks and statements

Most Moth blocks have a colon at the start and a semicolon at the end.

greet |name String|:
    io.line([: Hello, [name]])
;

The colon opens the function body. The semicolon closes it.

Semicolons do not end every line. Add one only when the surrounding block is finished. An inline block closes on its opening line. A multiline block closes with the semicolon alone on its own line, or on the line of a terminal else or terminal match arm.

if ready:
    io.line("Ready!")
;

The if opens on its own line, so its semicolon stands alone after the body.

Indentation makes nesting easy to see, but it never decides scope. See Blocks and statements advanced for the full placement contract.

Future compiler-owned blocks use $async: and $checked:; they are deferred and remain distinct from normal control-flow keywords and declared name: regions.

Moth uses explicit block delimiters. A colon opens a block and a semicolon closes it.

Status :: Ready, Busy;

greet |name String| -> Bool: return name is "Priya";

label |ready Bool| -> String:
    if ready:
        return "Rob"
    else return "Emmy";
;

pick |status Status| -> String:
    if status is:
        Ready => return "Emmy"
        else => return "Huw";
;

Contract

  • : opens a function body, if/else or option-capture branch, match, loop, catch handler, value-producing block, trait, declared region or another block-form construct. :: opens a choice declaration.
  • ; closes the active block.
  • A semicolon closes a scope. It never terminates an ordinary statement.
  • Statements inside a block are evaluated in source order unless control flow exits or redirects the block.
  • Child blocks create child scopes.
  • Indentation is for readability. Explicit delimiters define block boundaries, and indentation never decides scope.
  • Blank lines and whitespace inside a block are legal. Empty inline and empty multiline blocks are also legal as source layout.
  • Opening punctuation inside expressions, types or templates is not a scope opener.
  • The language has no general authored lexical-block construct or control-flow labels.
  • Immediate identifier: headers in executable statement position are reserved for declared regions. Full declared-region semantics remain deferred.
  • Normal control-flow keywords remain ordinary language forms. Future compiler-owned directive blocks use $async: and $checked:; both spellings are deferred and are not declared regions.
  • Exact _: is invalid.

Physical placement

  • At most one scope may open on a physical line. A scope opener cannot share a physical line with the opener of an enclosing scope that is still open.
  • A scope closes inline when its opening site and its ; share a physical line.
  • Otherwise it is a multiline scope. Its ; must stand alone on a later line, with only whitespace before it.
  • Only whitespace or a -- comment may follow a closer on its line. No statement, declaration, second ; or other code may follow it.
  • A comment cannot precede a closer on its line because -- consumes the rest of that line.
  • Two independent block-form constructs cannot share a physical line. The first closer ends its line.

Branch exceptions

The terminal else body of an if or the terminal match arm may close on the line that introduces it.

  • The terminal else body may close on the line that begins with else, as in else io.line("waiting");.
  • The terminal match arm may close on the line that contains its =>, as in else => return "busy";.

One final ; closes the whole if/else or match. The exception covers the terminal branch only. A ; after an intermediate then statement or an intermediate match arm is invalid. An intermediate match arm keeps its dedicated match-arm delimiter diagnostic.

Once a valid closer ends an if body, the if is complete. If an else follows that closer, it is outside an if and is rejected as an unexpected else.

Missing and misplaced closers

MOTH-SYNTAX-0041 reports a misplaced opener or closer. It covers a nested opener on one line, a multiline closer after code, code after a closer and a second closer on one line. The diagnostic points at the offending token and labels the opener or closer that explains it.

MOTH-SYNTAX-0042 reports a scope that never closes. It names the construct, labels its opener, asks for the missing ; and labels any visible ; that closed an inner scope instead.

Indentation never decides scope. Recovery follows the authored scope structure, and no suggestion can insert a closer or change which scope a line belongs to.

Coming from statement-terminating semicolons

If you are used to semicolons ending statements, read ; as a closing brace instead. Do not add one at the end of each line inside a block. Add the single ; that finishes a scope once its body has ended. A misplaced ; closes its scope early, so the lines that follow belong outside that scope.

Rejected shapes

Each shape below is invalid on its own.

-- Invalid: a nested opener cannot share the enclosing opener's line.
run ||: if true: io.line("ready");
;
-- Invalid: this `;` closes the function, not the assignment.
compute ||:
    total = 1 + 2;
;
-- Invalid: code follows the `if` closer on its line.
report ||:
    if true: io.line("ready"); io.line("after")
    ;
;
-- Invalid: a second closer follows the `if` closer.
finish ||:
    if true: io.line("ready");;
;

Nested language features may add their own structural rules. Branching, loops, functions, declared regions and template control flow document those forms in detail.

Choose the explanation level: Comments and naming

Comments and naming

In ordinary Moth code, comments begin with two minus signs:

-- This source-code line is ignored by the compiler.
score = 10

Template and moth template bodies are content. Two minus signs inside those bodies are text rather than source comments. To discard template content, use

[$note: ...] as a child of a template body. Use -- for

comments in Moth code. $doc and $todo attach to following source constructs rather than commenting out template bodies.

Use regular_snake_case for values and functions:

player_score = 10

double_score |score I32| -> I32:
    return score * 2
;

Use PascalCase for named types:

PlayerScore = |
    value I32,
|

Clear names beat short names. player_score is easier to understand than ps, especially when the code grows.

Config and spellings differing only by case or leading underscores are reserved by the shared naming rules. export is an ordinary identifier even though $export is a compiler directive.

In ordinary Moth code, -- starts a single-line comment.

-- Explain why this value exists.
retry_count = 3

Everything after -- on that source-code line is comment text.

Template and moth template text

Template bodies are content, not ordinary code-token context.

Inside a template body, -- is ordinary body text. A moth template .mtf file is the body of an implicit compile-time Markdown template, so -- is text there too.

To discard template-authored comment content, use

[$note: ...] as a child of a template body. -- stays

the comment marker for Moth code. $todo annotates the next source statement or declaration and is not a template comment. $doc likewise annotates declarations. See Directives.

Naming conventions

  • Variables and functions use regular_snake_case.
  • Structs, choices, type aliases and generic parameters use PascalCase.
  • Trait names use all-caps identifiers such as DISPLAY_TEXT.
  • Names should describe their role rather than their storage or implementation detail.
retry_count = 3

load_profile |user_id String| -> String:
    return "profile"
;

UserProfile = |
    display_name String,
|

Name collisions

A visible name cannot be redeclared while it remains in scope.

The complete no-shadowing contract is documented by Values and bindings. Dependency aliases and module API names have additional collision rules in the Packages documentation.

Identifier validity and reserved names

Identifiers start with _ or a Unicode alphabetic character and continue with _ or a Unicode alphanumeric character. Exact source-word recognition remains case-sensitive, including this and This. moth-lexical owns one shared source-word inventory and user-name predicate for Moth and MON, including reserved-only names. The predicate strips leading underscores and matches reserved words without regard to ASCII case. It applies no Unicode normalisation or XID substitution. Naming conventions above describe style, not lexical validity: a style mismatch can produce a warning without making an otherwise valid identifier invalid.

The shared policy reserves the numeric names I8, I16, I32, I64, U8, U16, U32, U64, F16, F32, F64 and Byte. It also reserves the Dec family: bare dec and any ASCII-digit suffix match after leading underscores are removed, without regard to case. This includes invalid type spellings such as dec01 and dec257. DecBox remains an ordinary name.

Type recognition stays stricter: only canonical Dec and Dec0 through Dec256 spellings name Dec types. The removed Int, Uint and Float spellings receive no builtin alias or special reservation. uint and UintBox follow ordinary identifier rules.

Any reservation change alters which MON documents and schemas pass, so it is a MON format compatibility change. Such a change updates the shared rule, the cross-parser conformance tests and the release-facing documentation together. See MON format.

The former Number spellings are not reserved. Number, number, Number2 and NumberBox are ordinary user names again, and Number-family spellings no longer name builtin types. Without a matching user declaration, Number or Number2 in a type position reports an unknown-type diagnostic. There is no legacy Number type alias.

Configuration names

Source directives use the $ marker. $export marks public declarations and direct-selection re-exports in @mod.moth and @package.moth. $config marks typed build inputs, $doc records declaration documentation and $todo annotates source statements or declarations. They can share one line or occupy consecutive lines before the same target, but duplicate names are invalid. Project and active-builder settings remain ordinary named records, so $project, $builder and $html_builder are not directives.

Directive spellings do not reserve ordinary identifiers. Names such as export, project, html_builder and entry are available outside directive syntax. The reserved build-only filename @config.moth and the dependency root @project retain their separate path and package semantics.

The shared identifier rules reserve Config, including case-insensitive spellings and leading-underscore variants. This also applies to MON names.

import is not a keyword. Import is an ordinary valid PascalCase user name:

Import = |
    source String,
|

Ordinary dependency clauses do not use an import keyword.

block, group and region are not keywords. They follow ordinary identifier policy. In executable statement position, each corresponding name: header has the same reserved declared-region shape as any other valid identifier.

Choose the explanation level: Core values

Core values

Moth can usually work out a value's type from its initializer.

enabled = true
count = 42
ratio = 0.5
letter = '🦋'
name = "Moth"

You can write a type when it helps the reader or gives the compiler needed context:

count I32 = 42
ratio F64 = 0.5
name String = "Moth"

Direct typed receiving contexts can give raw numeric literals an exact type. Later direct exact uses in the same function body can also constrain a retained numeric literal origin. Copies and writes connect to that same origin. This doesn't infer arbitrary values from later uses or work backwards through named arithmetic.

Without an exact constraint, whole-number literals default to I32 and decimal/exponent literals default to F64. See Numeric literals for the receiving contexts and Numbers for the numeric types.

The core types include:

  • Bool for true and false
  • the exact signed and unsigned integer types
  • the exact binary-float types
  • Char for one character
  • String for text

Collections, structs, choices and options build larger values from these ideas.

Values have a semantic type. A binding may infer that type from its initializer or state it explicitly.

enabled = true
count I32 = 42
ratio F64 = 0.5
letter Char = '🦋'
label String = "Moth"

Core forms

  • true and false are Bool values.
  • Whole-number and decimal/exponent literals receive exact numeric types through the bounded receiving contexts described at Numeric literals.
  • Single-quoted literals create Char values.
  • Quoted slices and string templates use the String type.
  • none requires an optional T? receiving context.

Numeric types

  • Exact signed integers are I8, I16, I32 and I64.
  • Exact unsigned integers are U8, U16, U32 and U64.
  • Exact binary floats are F16, F32 and F64.
  • Byte is a one-byte octet value with equality and unsigned-octet ordering. It takes no part in numeric arithmetic.
  • Dec is an arbitrary-precision integer at scale zero, Dec1 through Dec256 are arbitrary-precision scaled integers, and Dec0 is another spelling of Dec's scale-zero identity.

Numbers owns the complete type family, exact numeric grammar, literal inference, operators and conversions. The standard defaults do not set a minimum arithmetic width. Current implementation and backend support are recorded by Progress.

The Strings and characters section owns the implemented string source forms. Options are documented with Errors and options.

Composite values

Collections use braces. String templates use square brackets.

names = {"Priya", "Rob"}

message = [:
    Hello from a template.
]

Structs, choices, collections, maps and generic instances add richer value shapes without changing the basic annotation form.

Binding mutability and access mode are separate from semantic type identity. See Values and bindings for that contract.

Choose the explanation level: Strings and characters

Strings and characters

Use double quotes for normal text:

greeting = "Hello"

Expression-position backtick strings aren't implemented. Use an ordinary string with escapes when the text contains backslashes:

windows_path = "C:\\docs\\site"

Use single quotes for one Unicode scalar value:

seedling = '🦋'

Char follows scalar values rather than UTF-16 code units. A user-perceived character made from more than one scalar value needs a String.

Use a template when text needs values or a larger structure:

name = "Priya"

greeting = [:
    Hello, [name]
]

Joining strings

Use templates to join strings together. Put the parts inside square brackets:

first = "Hello, "
second = "world"
message = [first, second]

Don't use + to join strings. + is for numbers only. Use templates to concatenate strings.

Read-only strings

A quoted string like "Hello" is read-only content. You can reassign a mutable binding to point at a different string, but you can't change the string itself.

Square brackets belong to templates. Collections use curly braces instead.

Moth has two string source forms and one character form. Both string forms share one semantic String type at ordinary typed boundaries.

escaped_slice = "Hello\nworld"
letter = '🦋'

name = "Priya"
message = [:
    Hello, [name]
]

Quoted string slices

Double quotes create escaped string slices. They support exactly these escapes:

  • \\ for a backslash
  • \" for a double quote
  • \n for a newline
  • \r for a carriage return
  • \t for a tab

Every other escape is invalid. A backslash can't continue a quoted string across a physical newline.

MON string boundary

Source quoted slices keep exactly the five escapes listed above; source widening is deferred. MON literal data uses its own bounded decoder, which additionally accepts \u{H...} with 1–6 ASCII hex digits; no source escape implementation is shared. This does not change source availability. MON accepts only quoted strings and characters; raw template syntax is not a MON string literal, while a folded or runtime-evaluated template result is an ordinary serialisable String. See MON format.

A quoted string slice is read-only content. It has no character or substring mutation surface and isn't concatenated with +. A slice may be read, compared, passed, returned, stored and inserted into templates. A mutable binding that currently holds a slice may be reassigned. That doesn't make the slice contents mutable.

name ~= "Priya"
~name = "Rob"  -- reassigns the mutable binding, doesn't mutate the slice

Characters

Single quotes create Char values.

Template strings

Square brackets create string templates. Templates produce owned string values and may fold at compile time or lower to runtime string construction.

Templates are the idiomatic and canonical way to:

  • concatenate strings
  • interpolate values
  • build runtime or compile-time text
  • produce strings that need full template composition
first = "Hello, "
second = "world"
message = [first, second]

name = "Priya"
greeting = [: Hello, [name]]

Use [left, right] for concatenation. Don't use +:

-- VALID: template concatenation
joined = [left, right]

-- INVALID: + is a numeric operator only
joined = left + right

Source String + String is invalid because + is a numeric operator only. Runtime equality compares content for every String origin, and String map keys use the same content rule. Non-JS map lowering remains target-gated. See Progress matrix for current target support.

One semantic String type

Quoted slices and template-produced strings share one String type at ordinary typed boundaries. They share:

  • parameter and return compatibility
  • equality
  • choice payload equality
  • collection and map value use
  • String map-key use
  • casts
  • IO and external StringContent boundaries
  • template insertion
  • aliases and generic use where String is concrete

Construction origin doesn't create hidden equality, hashing, map-key or call-compatibility rules.

Equality

String supports is and is not. String doesn't support ordering operators (<, <=, >, >=).

slice = "hello"
template = [: hello]

-- VALID: equality across both forms
same = slice is template

-- INVALID: ordering is not supported
-- ordered = slice < template

Binding reassignment versus content mutation

A mutable binding that holds a string can be reassigned. Quoted slices are immutable. Templates produce owned String values. The current source surface does not yet expose in-place string mutation operations.

text ~= "initial"
~text = "replacement"  -- valid: reassigns the binding

-- No mutation API exists:
-- text.append("more")  -- invalid
-- text[0] = 'X'        -- invalid

Templates

Templates own interpolation, formatting, slots, wrappers and structured content. See Templates for the complete system.

Quoted slices and templates both participate in the language's String surface. Expression-position raw backtick slices aren't implemented. Inside a template body, backticks, backslashes and physical newlines are ordinary body text available to the active formatter.

Choose the explanation level: MON syntax

MON syntax

MON means Moth Object Notation. MON syntax gives supplied arguments and record values a common notation. Pipes declare fields or parameters. Parentheses supply values or group an expression.

Size = |
    width I32,
    height I32,
|

size = Size(width = 1280, height = 720)

settings #= (
    title = "Strategy",
    window = (width = 1280, height = 720),
)

Every anonymous field has a name and a value. Records can nest directly. #= requires all their values to be known during compilation.

(value) groups an expression. (name = value) constructs a one-field record. Commas separate entries, and a final comma is optional. Moth has no tuple values. The label and = share one logical line. The value may start on the next line.

Named types still need their constructors. An anonymous record with matching fields does not become a Size.

Moth MON source syntax allows ordinary expressions according to the receiving Moth context. MON serialised data is self-contained literal data only, and a MON reader never evaluates Moth expressions, including foldable ones.

MON format owns the serialised literal-data contract. This page owns the shared notation only.

MON syntax alone does not turn a record into serialised text or make every Moth value serialisable.

MON means Moth Object Notation. MON syntax names Moth's shared parenthesised argument and value-construction notation. The MON format is the separate serialised-data profile with its own supported values and serialisation rules. Using MON syntax does not make a value serialisable or turn a call into a data document.

This reference owns the shared notation and the distinction between grouping, supplied arguments and anonymous construction. Calls, constructors, directives and const or runtime records retain their own semantic contracts.

Declarations and supplied values

Pipes enclose declared parameters and typed nominal fields. Parentheses supply values or group an expression.

Size = |
    width I32,
    height I32,
|

size = Size(width = 1280, height = 720)

A nominal value uses its named constructor. Matching field names do not make an anonymous record a Size. MON syntax adds no implicit nominal construction, structural typing, argument spreading or tuple values.

Declaration lists remain flat. A legal default expression may contain nested value construction without introducing a nested type declaration. Defaults still need the type and compile-time evidence their receiving declaration requires.

Grouping and records

A single unnamed expression in parentheses is grouping. A named initializer selects anonymous record construction, including a record with one field.

total #= (1 + 2)
label #= (name = "Moth")
labels #= (first = "Priya", second = "Rob",)
empty #= ()

A comma separates entries. It does not create a tuple or infer a field name. (value,), (first, second) and (,) are invalid value constructions. Expression-position () is an empty const record when the receiving context requires a compile-time value. Empty runtime records are outside the initial runtime surface. Neither case introduces a unit type.

(calculate(x = 1, y = 2)) groups a call. Names and commas inside that inner call do not classify the outer parentheses. Grouping preserves ordinary precedence, place access, postfix operations and immediate cast-target rules.

Entries and layout

Every anonymous entry has a unique identifier and an explicit label = expression entry. It requires at least one horizontal whitespace character before = and whitespace immediately after it. Its type is inferred from the expression. Entries have no type annotation, declaration qualifier, default, omitted value or field-level mutable declaration. There are no positional anonymous fields or implicit name shorthands.

Use commas between entries. One trailing comma is allowed. Blank lines and comments may separate entries. The label and = must share one logical line. LF and CR are the only line breaks, with CRLF counting as one break; every other Unicode whitespace character is horizontal whitespace and may separate them. At least one whitespace character must immediately follow =, and it may be a line break, so the value can start on the next line. The same named-entry boundary applies to MON, including implicit and explicit roots, nested records and qualified payloads. Newlines do not replace commas or join an incomplete label to a later assignment.

Map entry = also requires whitespace on both sides. MON's {=} empty-map spelling is the exception because it is not a non-empty map entry.

A field label does not bind a local name. Every initializer resolves names in the surrounding scope. Earlier fields are not bare names visible to later fields.

title #= "Strategy"
panel #= (
    title = title,
    details = (title = "Overview"),
)

The two title labels belong to different records and do not conflict. Duplicate labels within the same record are invalid.

Each initializer supplies one value. Multiple return slots cannot become a tuple field or expand into several entries. A field label supplies no expected type for an otherwise untyped none, empty container or cast. Use an earlier typed value when its type cannot be inferred. The existing expression rules decide which empty literals can infer their own type.

Recursive construction

Anonymous values nest directly. Named nominal children still use their constructors.

Size = |
    width I32,
    height I32,
|

settings #= (
    window = (
        title = "Strategy",
        size = Size(width = 1280, height = 720),
    ),
)

width #= settings.window.size.width

#= requires the complete value to fold, including every nested field. It does not grant new compile-time execution capabilities. A runtime receiving context selects the separate runtime-record contract even when all fields look constant.

Const records owns folded fields and runtime-use restrictions. Runtime anonymous records owns hidden nominal identity, local composition and escape restrictions.

Context determines argument policy

Calls, constructors and directives share MON list syntax without sharing every permitted argument or value category.

  • User calls and named constructors keep positional-then-named signature routing.
  • Host calls and builtin members keep their positional-only contracts.
  • Anonymous records require named entries and establish their own fields.
  • Directive arguments require compile-time values and their registered categories.

A known signature supplies parameter names, types and defaults. An anonymous record has no callee signature or omitted default slots. Shared syntax changes neither evaluation order nor the ordinary access, coercion and error rules.

consume(x = 1) supplies the argument named x. consume((x = 1)) supplies one record expression, whose legality still depends on record and parameter rules. There is no automatic record-to-argument expansion.

Ordinary f() is a zero-argument call. The accepted directive contract uses bare $name when no arguments are supplied and rejects $name(). Template labels, indices and helper wrappers retain their specialised meanings.

Shared construction parity

For a supported common literal form in the same language and format revision, equivalent exact receiving types or schemas require both parsers to accept the form and produce the same typed value. Source and MON keep independent parsers: compiler-local owners parse calls and declarations, while moth-mon parses literal data. Both consume identifier, reserved-word and numeric text facts from moth-lexical. The real-source conformance suite at src/compiler_tests/mon_syntax_parity/ checks each expected outcome before comparing typed values.

Nominal constructor names and choice variant names take a payload only when ( follows on the same logical line with only horizontal whitespace between. LF, CR or a line comment between the head and ( means there is no payload; the following input fails through ordinary parsing. Source and MON share this head rule. Newlines inside argument lists and after = remain valid, and the existing adjacency restriction between :: and its variant name is unchanged.

Common invalid forms must fail in both parsers for the expected reason. Intentional data/source differences include:

  • MON frames one root record, including implicit and empty roots. Source receivers also accept expression fragments.
  • A MON schema supplies field and nominal shape. Source infers anonymous records and requires explicit nominal constructors.
  • MON contains literal values only. Expressions, bindings, imports, mutable access and declarations remain source syntax.
  • MON preserves raw quoted text and uses its own bounded escapes. Source quoted slices have separate escape and line-ending rules.
  • MON applies codec text, nesting, node and materialisation budgets. These are not source grammar limits.

This contract does not make an arbitrary MON document pasteable anywhere in Moth. Document framing, supplied schema information and legal source receiving contexts still matter. An anonymous source record does not implicitly construct a nominal struct just because a MON schema can receive that record as struct data.

MON format boundary

Moth MON source syntax allows ordinary expressions according to the receiving Moth context. MON serialised data is self-contained literal data only. A MON reader never evaluates Moth expressions, including foldable ones.

MON format owns the serialised literal-data contract: one root record, literal-only values, strict numeric conversion, qualifiers, defaults and bounded first errors. This reference owns the shared notation and the distinction between grouping, supplied arguments and anonymous construction.

The standalone moth_mon codec serves independent Rust callers. Compiler clients can use the same API and Rust types through the convenience re-export moth::mon. The engine or application supplies its own data schema.

Full compile-time Moth authoring expressions and the self-contained serialised representation are distinct surfaces.

Templates remain ordinary strings. MON syntax adds no automatic record printing, implicit live bindings, stored Wire capabilities or executable Route values.