Constants and compile-time behaviour

A constant tells the compiler to finish a value before runtime. Unlike a read-only runtime binding, a Moth constant can depend only on other compile-time values and must fold completely.

The same rule covers scalar values, const records and templates. Direct const fragments can contribute finished content to an HTML page.

Choose the explanation level: Constant bindings

Constant bindings

Add # when a value must be known during compilation.

site_name #= "Moth"
version #I32 = 1

Constants cannot change.

They can be used by other compile-time values:

full_name #= [: [site_name] v[version]]

Use a normal binding when the value belongs to runtime code.

Ordinary constants always need an initializer. A marked $config input may omit one; required non-optional inputs then report missing input and optional inputs resolve to absence. See Build configuration values.

# marks a compile-time constant. $config marks an explicitly typed top-level constant as a build input, without changing ordinary constant syntax. See Build configuration values.

For example:

$config
api_url #String

Only a marked $config input can omit an initializer: a required non-optional input then reports a missing-input error, while an optional input resolves to absence.

site_name #= "Moth"
major_version #I32 = 1
names #{String} = {"Priya", "Rob"}
maybe_name #String? = none

Declaration forms

name #= value
name #Type = value

Every ordinary constant must have an initializer.

  • A $config-marked required, non-optional input may omit its initializer and reports a missing-input error when no value is supplied.
  • A $config-marked optional input may omit its initializer and resolves to absence.
  • A $config-marked input with an initializer uses that initializer as its fallback.
  • A constant is immutable.
  • A mutable marker cannot be combined with #.
  • Without an annotation, the initializer supplies the type.
  • An explicit annotation supplies a compile-time receiving type.
  • The initializer must fully fold.
  • A constant may reference only compile-time values.

# controls compile-time evaluation. It does not control visibility.

Top-level constants follow ordinary module and public-surface visibility rules.

Body-local constant declarations remain local to their scope.

A top-level runtime binding without # belongs to entry-selected runtime code rather than the dependency-bindable constant surface.

Each constant resolves at its declaration-owned compile-time boundary. A later runtime consumer cannot retype a named constant. Choose its exact type at the declaration or use the defaults defined by Numeric literals.

Choose the explanation level: Constant folding

Constant folding

The compiler must finish a constant before runtime code begins.

base #I32 = 4
larger #I32 = base + 2

A constant can use another constant that is already available.

It cannot use a runtime variable or call a runtime function.

When a constant expression is invalid, the compiler reports it during the build instead of leaving the failure for runtime.

A compile-time-known Bool, including one provided through $config, can select an ordinary if branch:

$config
enabled #Bool = false

if enabled:
    perform_optional_work()
;

$config before a typed # binding feeds the same ordinary if and cannot remove declarations or dependencies. Future structural selection belongs to $feature.

A constant initializer must fully evaluate during AST construction.

base #I32 = 4
larger #I32 = base + 2
label #= [: size [larger]]

Allowed dependency shape

A constant may depend on:

  • literals
  • earlier same-file constants
  • imported constants
  • foldable operators
  • foldable casts
  • foldable struct construction
  • foldable templates
  • other compile-time values

It may not depend on:

  • runtime bindings
  • runtime function calls
  • host calls
  • runtime-only template content
  • mutable state

Ordering

Same-file constant evaluation follows source order.

A same-file forward reference is invalid.

Cross-file constant dependencies are represented in the top-level dependency graph and evaluated in dependency order. A direct .mtf or .md file value creates one of these without a top-level clause, because it consumes that file's content constant.

Circular constant dependencies are compilation errors. That includes a cycle formed through content-file values.

Structural values fold without final text

A folded String is not always plain text. A file path, and the bare site root @/, fold to a String that carries a structural anchor rather than characters, because the final URL depends on output placement the frontend has not chosen yet.

logo #= @assets/logo.svg
image #= [: <img src="[logo]">]

Both are complete constants. The compiler knows the whole semantic value, so composition, storage, export and template insertion all fold normally.

What cannot fold is an operation that needs the final characters while an anchor is unresolved, such as comparing one of these strings against a literal URL. That is diagnosed rather than folded against a guessed path. The restriction is about placement being undecided, not about the value being a file: once a builder resolves each anchor, ordinary runtime string behaviour applies.

See File values.

Compile-time and runtime agreement

Folding must preserve runtime language semantics.

Examples:

  • a statically known checked-numeric failure is a compile-time diagnostic
  • String -> I32, String -> U32 and F64 -> I32 enforce the complete source and target conversion rules.
  • Fixed-width numeric targets enforce their own declared ranges and precision.
  • String -> F64 rejects non-finite materialisation.
  • F64 -> String uses Moth's stable formatter.
  • Compile-time and runtime template interpolation use the same F64 formatting.

The compiler must not accept one result during folding and produce another at runtime.

Advisory const facts

The compiler may discover private const facts for optimisation.

Those facts do not:

  • change source semantics
  • create dependency-bindable declarations
  • participate in header dependency sorting
  • turn a runtime binding into a source constant

Static Bool control flow

An ordinary if condition may fold to a known Bool. A $config-marked Bool input is one source of that folded value. $config does not add a separate conditional form.

Both branches first parse, resolve and type-check as normal source. Stage 4 then selects one branch, preserving the selected branch's lexical scope; inactive executable work does not reach HIR or later analysis. Runtime conditions remain runtime branches.

This is not target conditional compilation. Ordinary $config values and static if cannot remove declarations or dependencies. Future structural source selection waits for $feature; advisory const facts do not create source constants or structural conditional compilation.

Stage 4 performs this selection after final constant values and full branch validation, then derives terminality and executable facts from the selected AST.

Release optimisation of ordinary functions

In a release build, the compiler may replace a call to an ordinary function with its folded result when the function's entire transitive body is const-safe and every argument is a compile-time constant. Parameters must be immutable ordinary values, the function must produce one infallible success slot, and calls with handling or error channels are ineligible. Assignments and collection mutations must target body-local bindings.

Release optimisation never changes observable work it cannot prove. Parameter-dependent calls, host effects, mutable-reference calls, recursive candidate graphs and unrepresentable result shapes stay in the runtime program. A refused candidate is left unchanged.

Const execution is bounded by typed project settings:

  • const_work_limit limits evaluation steps for one call. The aggregate module allowance is eight times this value.
  • const_memory_limit_mb limits retained folded value and text allocation in MiB for one call, with the same aggregate multiplier.

A configured value above the compiler maximum for either setting is rejected as a project configuration error. A release call that exhausts a budget remains at runtime and produces a deduplicated Note naming the effective limit and, for a configurable limit, the setting to raise. Required const evaluation reports an error instead.

Choose the explanation level: Const records

Const records

A constant can hold a fully known struct value.

Defaults = |
    title String,
    year I32,
|

defaults #= Defaults("Moth", 2026)

Read its fields during compilation or use an ordinary field in runtime code:

site_title #= defaults.title
io.line(defaults.title)

The complete const record is not an ordinary runtime object. Use its fields instead. A field that is itself a const record keeps the same restriction.

Anonymous records

Anonymous construction uses MON syntax and requires all fields to fold.

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

width #= settings.window.width

Every field needs a name and a value. Anonymous construction creates a value, not a named type. Use an explicit constructor for a named struct.

A fully folded struct instance stored in a constant may become a const record.

Defaults = |
    title String,
    year I32,
|

defaults #= Defaults("Moth", 2026)
site_title #= defaults.title

Contract

A const record is a data-only compile-time member group. Every supplied value must fold. Field projection may participate in another constant expression.

The complete record is unavailable as an ordinary runtime value. It cannot be assigned to a runtime binding, passed as a runtime argument, returned from a runtime function, stored in a collection or map or used through a runtime receiver method.

Use a folded field when runtime code needs its ordinary value:

io.line(defaults.title)

A projection whose result is another const record retains the same restriction. Project further to an ordinary value before runtime use.

Struct-backed const records preserve their named struct's fields and types. Anonymous const records retain named folded fields without declaring a constructable type or introducing structural runtime typing. Their existing folded export and provenance rules remain in force.

Anonymous const records

Anonymous construction uses the named-only form of MON syntax:

labels #= (
    first = "Priya",
    second = "Rob",
)

single #= (name = "Moth")
empty #= ()

Every field has a unique name and an explicit initializer. Types are inferred from those values. Labels create fields, not local declarations or parameters. #= imposes the compile-time requirement. Ordinary = does not become a const record merely because its fields could fold.

Nested values

A field may contain an inline anonymous const record, an already declared const record or an explicitly constructed nominal value that satisfies constant rules.

Size = |
    width I32,
    height I32,
|

settings #= (
    window = (
        size = Size(width = 8, height = 4),
        title = "Strategy",
    ),
)

width #= settings.window.size.width

All nested initializers must fold. Initializers use the surrounding scope, not names introduced by earlier fields. Nesting introduces neither arbitrary compile-time execution nor implicit construction of a named type.

Input contracts belong to declarations rather than record entries. Exact configuration placement and processing rules are owned by Build configuration values. The MON format's serialisation domain is an accepted Rust-only contract owned by MON format; its moth::mon codec is implemented, and it does not change const-record evaluation or source syntax.

Choose the explanation level: Const templates

Const templates

A constant template is finished during compilation.

title #= "Moth"

heading #= [$md:
    # [title]
]

A bare direct [...] in @entry.moth must fold at compile time. An explicit ~[...] instead creates a runtime body fragment, even if foldable. The removed direct #[...] spelling is invalid. The entry file's presence selects the page. A direct const root $in insert supplies builder metadata, while an ordinary const fragment renders into the body.

[$in title:About]
[$in stylesheets:[@assets/site.css]]

[$md:
    # Compile-time heading
]

Only a direct root insert reaches builder routing. Nested and stored inserts remain ordinary template composition. Scalar builder values concatenate, and each stylesheet insert needs one tracked CSS resource. The HTML builder deduplicates stylesheets by resource origin.

Runtime top-level named builder inserts are not supported.

Assigned or returned templates remain ordinary values, not direct page fragments.

Const template loops have an iteration limit so an accidental build-time loop cannot run forever.

HTML pages come from directories that contain @entry.moth. Direct const root inserts supply builder metadata.

A template can be required to finish during compilation.

Named const templates

A normal constant binding can hold a folded template string.

site_name #= "Moth"

heading #= [$md:
    # [site_name]
]

This creates a compile-time String value. A template assigned to a binding or returned from a function remains a value and does not become a page fragment by itself.

Direct top-level const fragments

Every bare direct [...] fragment in @entry.moth is const-required by default. It must fold even if an ordinary template expression in the same position would be runtime-dependent. Use direct ~[...] to request a runtime body fragment. The file's presence makes its directory entry-eligible, so metadata-only pages remain valid. The removed direct #[...] spelling has no compatibility alias.

[$md:
    # Compile-time heading
]

The bare direct form in the entry file:

  • is valid only as top-level entry fragment syntax
  • must fully fold, reporting a constant-required diagnostic for runtime dependence
  • records its position relative to explicit ~[...] runtime fragments
  • is handed to the project builder
  • never becomes HIR runtime code

Builder slot contributions

A builder can register named destinations for direct top-level const inserts. The HTML builder registers title, description, lang, favicon, body_style, stylesheets and head. Ordinary direct const fragments still render into the body. A metadata-only @entry.moth still produces a complete page.

[$in title:Moth]
[$in description:A language for creating reliable software]
[$in lang:en]
[$in favicon:[@assets/favicon.svg]]
[$in stylesheets:[@assets/site.css]]
[$in head:<meta name="theme-color" content="#ffffff">]

[:<main>Hello Moth</main>]

The HTML destinations are:

  • title: escaped title text, with the builder's route then project-name fallback
  • description: escaped meta description text, omitted when absent
  • lang: escaped <html lang> value, with the builder default when absent
  • favicon: escaped icon URL from a tracked resource or a permitted String
  • body_style: escaped body style attribute, with the builder default when absent
  • stylesheets: one tracked local CSS resource per insert, linked in first-origin order
  • head: raw additional head HTML, appended after the builder's dedicated head content
  • the implicit default destination: ordered body fragments

A direct named insert must fold to a compile-time value. ~[$in name: ...] is not a runtime named builder contribution. A nonconstant contribution and a name the builder has not registered are diagnosed at their authored source. Nested, stored and aliased inserts remain ordinary template composition and never become builder messages. Ordinary template slots are owned by Template slots. Helper files, imported roots and API-only roots cannot contribute to the selected entry.

The builder interprets each registered destination. Scalar metadata contributions concatenate in source order and a supplied empty value stays present, even for title. There is no scalar cardinality error. Template body whitespace remains part of each value, including a space immediately after the body colon. A missing value uses the builder fallback, which is separate from an ordinary slot occurrence default. An absent title uses the route then project name with the configured prefix and postfix. An absent description emits no element. Other absent scalar values use the builder defaults. The builder escapes scalar metadata and never treats it as raw HTML.

Each stylesheets contribution must contain exactly one tracked local CSS resource. Plain paths, external URLs, site-root values, non-CSS files and combined resources are invalid. Use head for an external stylesheet. The builder keeps the first contribution for each stable resource origin and renders the link relative to each output page. head is raw HTML emitted after the builder's dedicated head content and deduplicated only when complete contributions render identically in the page URL context. It never replaces or bypasses scalar escaping. The full HTML contract is owned by Entry metadata and builder slots.

Named contributions keep their structural resources live, including on a page with no runtime work. Ordinary constants alone do not create builder metadata.

Const template if

[if show_heading:
    Visible heading
]

A const template if conditionally includes one body when its Bool condition is true. It can also test an option with is |name|, making the captured value available only inside the selected body. A false condition or absent option produces structural no-output. Template if has no else or else if form.

The selector and body must be compile-time evaluable even when the body is not selected. A runtime expression in an inactive body is rejected. Only a selected body contributes output.

Const template loops

[loop items |item|:
    [item]
]

Const collection and range loops expand their body for each visited iteration until the ordinary loop header ends. Template loops have no break or continue controls. Their body must fold on every expansion.

Const loops follow the ordinary loop header contract. An explicit step must be compile-time known. A runtime-only step is rejected with MOTH-SYNTAX-0022 (invalid_template_structure.template_loop_step_not_const). The step's sign selects direction, a negative collection step starts at the last source item and a collection loop's second binding is the actual source index.

The project config field template_const_loop_iteration_limit guards expansion:

template_const_loop_iteration_limit

The default is 10_000.

The maximum accepted configured value is 1_000_000.

The configured value must be a positive folded I32. Zero, negative values and values above 1_000_000 are rejected.

The limit counts visited iterations, not source positions. A literal zero step is rejected by the loop header with MOTH-SYNTAX-0029. A step that folds to zero is rejected with MOTH-SYNTAX-0022 (invalid_template_structure.template_loop_step_is_zero), even when the source is empty or the range would visit nothing. A const float range step that rounds back to the current counter is rejected with MOTH-SYNTAX-0022 (invalid_template_structure.template_loop_step_no_progress).

A const conditional loop folds to no-output only when its condition is compile-time false.

A compile-time true condition and a runtime or unknown condition are rejected because the compiler does not prove loop termination.

Runtime template control flow remains owned by Template control flow.

MON data boundary

A folded const template is an ordinary String that an encoder can quote. An unevaluated template is not a serialisable value. Compile time versus runtime concerns the producer and never changes document validity. The MON data format is independent of the producer and its runtime environment. See MON format.