Project structure

A Moth project combines directory-scoped modules, an optional build-only @config.moth at the selected root and a builder that selects the final artefacts.

A module recognises three optional root files: @mod.moth publishes the normal API, @package.moth publishes a scoped support API and @entry.moth owns page runtime work. Any subset is valid. $export marks each public declaration or selected re-export in a facade. The HTML builder emits one directory-derived page for each @entry.moth. No root-purpose directive exists.

Choose the explanation level: Project layout

Project layout

A Moth project is the directory you select. That directory is both the build root and the source root. There is no implicit src/ folder.

Starter config

@config.moth uses two ordinary named records:

project #= (
    name = "my_site",
)

html #= ()

name is optional and falls back to the selected folder name. There are no $project or $html_builder directives.

Where things live

  • @config.moth at the selected root is optional and controls build settings. It is not module source, and a helper named config.moth is ordinary source.
  • Everything below the selected root is source unless it is excluded or is generated output.
  • _dev/ and _release/ are generated output. Do not edit them.
  • A folder name starting with _ is excluded from the build unless you select it directly.

Up to three root files per module folder

Each source folder can contain @mod.moth, @package.moth and @entry.moth. Any subset works. They form one module with shared helper files and separate root scopes.

  • @mod.moth exports the normal API.
  • @package.moth exports a scoped support API, or the project package API at the project root.
  • @entry.moth holds page code and document metadata.

A page appears for every folder with @entry.moth. The file can be empty, hold only metadata or hold runtime code:

[$in title:Welcome]

That metadata-only entry still produces a page. No other filename creates a page.

Shared scoped packages

An @package.moth root creates a scoped support surface. For example, shared/@package.moth creates @shared. Its owner module, normal sibling modules and their descendants may depend on it. Other support packages in the same scope and the package's private implementation subtree cannot.

When a folder has both an @mod.moth and an @package.moth, helpers are shared while each root keeps its own declarations and public interface. A project-root @package.moth is the external project package surface. Internal modules cannot import it.

Outputs are generated

The build command creates hidden output folders. They are not source. The builder cleans up stale artefacts automatically.

A Moth project is a directory tree rooted at the directory selected by the command. That directory is both the build root and the source root. There is no implicit src/ entry directory, and a nested @config.moth never applies to an enclosing build.

Starter shape

The optional project config uses ordinary named compile-time records:

project #= (
    name = "my_site",
)

html #= ()

The project record and its name field are optional. An omitted name uses the selected directory name. The active builder section follows its own required or optional presence rule. HTML permits an omitted section and applies its defaults.

A configurable value uses $config before one explicitly typed top-level # binding. project and html stay ordinary record values. No $project, $builder or $html_builder directive exists.

Project root contents

website/
├── @config.moth        # optional
├── @entry.moth
├── @package.moth         # optional external package surface
├── shared/
│   └── @package.moth
├── pages/
│   └── @mod.moth
├── _dev/
│   └── .moth_manifest
├── _release/
│   └── .moth_manifest
└── .gitignore

Directory roles

  • The selected directory is the build root and the top of the discoverable source tree.
  • @config.moth is optional. When present, only the one at the selected root applies. It is not module source. A helper named config.moth is ordinary source and @config resolves it.
  • A directory named src/ is ordinary source content. There is no configured entry directory or entry_root.
  • _dev/ and _release/ are hidden generated output folders, not source folders. The build system manages them through manifests.
  • .moth_manifest files are build-system metadata used for safe stale-output cleanup. They are not source.
  • A directory component below the selected root whose name starts with _ is excluded from that build. Select it directly to compile it.

Reserved package namespace roots

@core and @builder are reserved package namespace roots. Compiler-shipped Core packages register below @core/, such as @core/html, @core/css and @core/math, and Builder packages below @builder/, such as @builder/web/site. Neither root alone names an importable package.

A project-local import name whose first path component claims core or builder, in any ASCII case, is rejected. This covers normal and support facades, importable helpers and aliases. A directory name alone claims nothing, so entry-only modules, their private helpers, folders that contain only entries and plain asset directories below core/ or builder/ stay legal.

A project folder whose full path matches a registered source package path, such as core/html/ or builder/web/site/, collides whichever module owns it, even when the folder holds no importable surface. Comparison ignores ASCII case. A binding-backed package has no source module, so an asset folder at builder/web/canvas/ stays legal. An ancestor folder such as core/ alone stays legal, and so do unrelated project folders named html/, css/, styles/ or web/. @project remains a separate reserved interface for project globals.

Root files inside source directories

A source directory recognises exactly three optional root files: @mod.moth, @package.moth and @entry.moth. The directory may contain any present subset. One directory forms one structural module with shared helper files. @config.moth is the reserved build-only filename, not a fourth root, and a nested copy stays inert.

@mod.moth publishes a normal API facade. @package.moth publishes a scoped support facade, or the external project package surface when it sits at the selected project root. @entry.moth owns executable page or application work. Only entry roots may hold top-level runtime code, page fragments and direct builder slots.

Apart from the reserved @config.moth, any other @*.moth or +*.moth spelling, such as @page.moth, is rejected as a structure error. The exact filename is the role. See Module roots for the full vocabulary and visibility rules.

A project produces an HTML page for each @entry.moth directory. Entry eligibility comes from file presence, not from the amount of authored activity:

[$in title:Welcome]

This metadata-only entry still produces a complete document. An empty @entry.moth is also eligible.

Helpers in ordinary files stay inside the surrounding module. They never become entries on their own.

Structural packages

Project-local source-backed packages use @package.moth. An @package.moth file marks its directory as a scoped support package root named by that directory.

In the example above, shared/@package.moth creates the scoped @shared support package. It is visible to its normal-position owner module, normal sibling modules and their descendants. It is not dependency-bound from its own private implementation subtree or from another support package in the same scope.

A project-root @package.moth is the external project package surface. Internal project modules cannot import it. It is an ordinary support surface, not a separate graph node.

No folder gains package meaning without an @package.moth root. Ordinary directories do not automatically become packages.

Copying a compiler-shipped source package folder, one with @package.moth such as packages/core/html, to a non-colliding project path gives an ordinary project-local support package. It never gains Core or Builder identity, capabilities or registration. Copying a binding asset folder, such as packages/builder/web/canvas/, creates no package, registers none of the original symbols and gains no namespace identity.

A directory may contain both an @mod.moth normal root and an @package.moth support root. They are two isolated surfaces of one structural module. Helpers are shared, roots cannot import each other and both interfaces publish only from one successful semantic transaction.

For the full package contract see Project-local packages.

Project scaffold

moth new html creates an @config.moth with an explicit valid project name, a root-level @entry.moth and a .gitignore containing /_dev and /_release. The generated config is:

project #= (
    name = "my_site",
)
html #= ()

The generated entry contributes document metadata and a starter page through direct root inserts. Deleting the generated config is valid when the directory name is a valid project identifier.

Source versus output

Developers own source directories. The builder generates hidden output folders and owns their stale-output cleanup. Treat generated artefacts as output, not source. A visible directory named release remains ordinary source.

Builder-neutral frontend versus builder-owned output

The compiler frontend discovers modules, resolves dependencies, checks types, lowers code and validates borrowing. A project builder then decides how compiled modules become real output files. The HTML project builder uses this frontend.

This separation lets the same frontend feed other builders. The frontend does not decide which modules produce artefacts. The builder owns that decision.

Only @config.moth has config semantics

Only the selected project's root-level @config.moth defines its settings. A nested @config.moth does not configure the enclosing build. An ordinary config.moth helper never gains config meaning, and @config resolves that helper. Invalid special root filenames are rejected during source discovery.

Concepts related to project layout

Choose the explanation level: Project config

Project config

Project and builder settings use top-level compile-time constants in the optional @config.moth. $config marks typed external inputs, not the settings records.

@config.moth is optional at the selected build root and is one self-contained compile-time source with no source dependencies. A nested @config.moth has no effect on its enclosing build. The filename is reserved but is not a module root or importable module. A helper named config.moth is ordinary source, and @config resolves that helper.

Project and builder settings

project #= (
    name = "my_site",
    version = "1.0.0",
)

html #= ()

The project record is optional. Omitting name uses the selected directory name and omitting version means unversioned. The HTML builder section is also optional and uses defaults when omitted. The command selects the builder; these records never select one. There is no entry_root setting.

Typed configuration inputs

$config
version #String = "1.0.0"

project #= (
    version = version,
)

html #= ()

$config marks one explicitly typed top-level compile-time # binding as a build input. The binding name is the input key, the declared type is the receiving contract and the initializer is the missing-input fallback. Only a marked binding may omit its initializer. The other bindings in @config.moth remain ordinary compile-time constants.

See Project config, Build configuration values and Directives.

Project and builder settings are ordinary top-level compile-time constants in an optional @config.moth at the selected build root. The project and selected builder records hold settings. $config separately marks typed external inputs those constants can use.

@config.moth is one self-contained compile-time source at the selected project root. It has no source dependencies, package resolution or authored file-value paths. A nested @config.moth is inert to an enclosing build.

@config.moth is a reserved compiler filename, not a module root. It has no normal or support facade, entry, export surface or importable namespace. Selecting it for single-file compilation is rejected. Case variants such as @Config.moth are invalid. An ordinary helper named config.moth keeps ordinary source rules, so a dependency path such as @config resolves that helper and never the build-only file.

Named project and builder records

project #= (
    name = "my_site",
    version = "1.0.0",
)

html #= ()

The project record is optional. An omitted name uses the selected directory name, and an omitted version means the project is unversioned. The active builder section follows its existing required/optional presence rule; HTML permits an omitted html record and applies its defaults. The selected directory is the source root.

Use an earlier $config input to provide a configurable value. A field is not itself an input declaration.

Project record

The optional project #= (...) constant accepts these named fields:

Parameter

Type

Default

Configurable value permitted

name

String

The selected directory name

No

version

String?

none

Yes

author

String?

none

Yes

license

String?

none

Yes

template_const_loop_iteration_limit

I32

The existing compiler-owned default

No

const_work_limit

I32

1000000

No

const_memory_limit_mb

I32

16

No

max_errors_per_module

I32?

5

No

max_errors_per_project

I32?

30

No

The record's recognised settings schema is closed. Arbitrary fields, misspelled standard fields and metadata = ... are rejected. @project publishes name, version, author, license and an explicitly configured template_const_loop_iteration_limit. It does not publish the const-execution controls or the diagnostic limits; those are compiler controls.

name, template_const_loop_iteration_limit, const_work_limit, const_memory_limit_mb, max_errors_per_module and max_errors_per_project remain fixed-only, including through helper constants. An omitted name defaults to the selected directory name and is validated as a Moth project identifier; it is never silently rewritten. Omitted version means unversioned.

Diagnostic limits

max_errors_per_module is a strict allowance of primary errors retained for each module. File preparation keeps the first errors in source order up to the allowance. Ordinary-body diagnostic recovery admits a further eligible body after the first failed one only while the retained primary error count stays below the allowance. Check-only files attributed to one module share that module's allowance.

max_errors_per_project is a soft scheduling threshold for the whole command. Once the returned primary errors reach it, the compiler starts no further modules, source packages or check-only files. Work already running finishes and keeps its errors, so the project total may exceed the threshold. It is not a maximum result count. Skipped work is reported as not checked and never counts as successful.

A present value must be an I32 from 1 to 2147483647. Zero, negative values and other types are rejected. Omitting a setting uses its default. An explicit none disables that one count and leaves the other unchanged. Warnings, notes and related labels never count. Neither setting disables the compiler's fixed recovery-work guard or changes program meaning.

HTML builder settings record

An HTML directory project may use the named html #= (...) compile-time record. The command selects the builder first; this record never selects a backend or platform. Omitting the record applies its schema defaults.

The recognised setting names and defaults are:

Parameter

Type

Default

dev_output

String

"_dev"

release_output

String

"_release"

origin

String

"/"

page_url_style

String

"trailing_slash"

redirect_index_html

Bool

true

html_lang

String

"en"

html_title_prefix

String

""

html_title_postfix

String

""

html_favicon

String?

none

html_inject_charset

Bool

true

html_inject_viewport

Bool

true

html_inject_color_scheme

Bool

true

html_inject_core_css

Bool

true

html_body_style

String

""

page_url_style accepts trailing_slash, no_trailing_slash or ignore. html_favicon accepts a compile-time String containing an untracked URL, not necessarily a string literal. Tracked file resources belong in a direct root builder slot because @config.moth rejects authored file-value paths.

Names other than the selected builder's recognised settings section remain ordinary config constants; they do not implicitly configure another builder. The active settings record is checked against the selected builder's existing schema. Synthetic single-file operations without authored @config.moth keep their explicit synthetic path and do not invent source settings.

Example with typed inputs

A project can use typed external inputs alongside its top-level settings constants:

$config
version #String = "0.1.0"
project_error_limit #I32? = none

project #= (
    name = "moth_docs",
    version = version,
    max_errors_per_module = 5,
    max_errors_per_project = project_error_limit,
)

html #= ()

The project record may omit name or version. HTML settings are also optional and use the builder defaults.

The diagnostic limits use fixed-only I32? values. Use a typed constant for none because the record does not infer a type for an absent value. See Diagnostic limits above for bounds, defaults and scheduling rules.

Concepts related to project config

Choose the explanation level: Module roots

Module roots

Every folder can hold one module. A module can have up to three special root files, and each one has one job.

Three jobs, three files

  • @mod.moth publishes the folder's normal API.
  • @package.moth publishes the folder's support API. At the project root it publishes the project's external package API.
  • @entry.moth runs the page or application code.

A folder may have one, two or all three files. A folder with only @entry.moth is a normal module that has no API to import.

Other helper files in the folder hold shared code. All roots can bind that shared code.

The names are fixed

Only those three names work as roots. Apart from the reserved @config.moth, the compiler rejects any other .moth name that starts with @, + or #. The error names the invalid file and lists the three accepted root files.

@config.moth is the one extra reserved filename. It holds build settings at the selected project root, but it is not a root, it cannot be imported and a nested copy does nothing. A helper named config.moth is ordinary source and resolves as @config. Case variants such as @Config.moth are invalid.

A + prefix is not a root marker in another source file. An ordinary supported file such as +notes.mtf can be bound like any other helper source.

Roots keep their declarations private

A root file can read its own top-level declarations and shared helper declarations. It cannot read a declaration written in another root file. Helper files cannot read declarations written in a root file either.

site/
├── @mod.moth
├── @package.moth
├── @entry.moth
└── shared.moth

All three roots may bind shared.moth. None of them can read another root's private declarations. Move shared declarations into shared.moth instead.

What each root allows

@mod.moth and @package.moth hold declarations and functions. They may export an API. They cannot hold page runtime code, page fragments or builder metadata.

@entry.moth holds page runtime code, page fragments and builder metadata. It also owns the page's entry point. It cannot export an API.

An imported module never runs its entry. The build command runs only selected entries.

Names come from folders

A root filename never becomes an import name. pages/@mod.moth is imported as @pages, not @mod.

@pages page_heading

The filename is a role marker, not a dependency path.

Concepts related to module roots

Every rooted directory forms one structural module. Three optional authored root files give that module its roles. @mod.moth publishes the normal API facade, @package.moth publishes the scoped support facade or the external project package surface, and @entry.moth owns executable entry work.

The build-only @config.moth is a reserved compiler filename outside those roles. It never becomes a module root, an importable name or a project global.

The three root files

Root file

Structural role

Publishes API

Implicit start

Top-level runtime and fragments

@mod.moth

Normal public facade

Yes

No

Rejected

@package.moth

Scoped support or external project package facade

Yes

No

Rejected

@entry.moth

Executable entry root

No

Yes

Permitted

The filenames are exact and case-sensitive. A directory may contain any present subset, including all three files. @Entry.moth is not an entry root. An entry-only directory is a valid module even though it publishes no importable API.

Ordinary .moth files hold shared implementation. They never own a facade, a start function or an entry.

One structural module per directory

A rooted directory has one ModuleId, one compilation and one atomic publish-or-diagnose outcome. Its @mod.moth, @package.moth and @entry.moth, when present, are three root-local views of that one module. They are not three modules.

A directory containing only @config.moth is not rooted. @config.moth remains the optional build-only project config and stays outside the module graph. It publishes no API and cannot be imported. A nested @config.moth is inert.

A root marker may be a symlink, but every root must resolve to a distinct physical file owned by its module. The visible symlink name decides the role. Two markers cannot alias one file, and a root cannot resolve into another structural module.

The root vocabulary is closed

Apart from the reserved @config.moth, only @mod.moth, @package.moth and @entry.moth are authored root files. Any other .moth filename whose stem starts with @, + or # is a Stage 0 structure error:

@page.moth          rejected
@home.moth          rejected
@api.moth           rejected
@Entry.moth         rejected
+package.moth       rejected
#package.moth       rejected
@Config.moth        rejected

The diagnostic is MOTH-CONFIG-0001 (InvalidModuleRootFileName). It names the invalid filename and lists the three accepted root files. It does not guess whether the author meant an entry, a normal facade or a support facade.

@config.moth is the one exact @-prefixed .moth filename outside the three roots. It configures the selected build root only, carries no module role and never enters the source graph. Case variants such as @Config.moth stay invalid.

The rejected spellings are never reclassified as ordinary helper files. An ordinary config.moth helper keeps ordinary source rules and resolves through the dependency path @config, which never selects the build-only config file. Non-.moth files with an @ prefix, such as @theme.css, remain ordinary resources.

A + prefix is not a root marker in a non-.moth filename. An ordinary supported source such as +notes.mtf resolves through the same dependency path and visibility rules as any other helper source.

Root-local declarations stay in their root

Each root file is its own declaration and visibility scope. A top-level declaration in one root is visible only in that file:

  • another root cannot resolve it
  • ordinary helper files cannot resolve it
  • re-exporting it through another root is rejected
  • naming the root file in a dependency path is rejected

The rejection keeps the root-local declaration site as a related location. Ordinary helpers still supply the shared implementation that every root may bind.

Shared helper declarations are prepared once and carry one shared origin. A root imports them through ordinary dependency clauses. Helpers obey ordinary same-module declaration ordering and cannot depend on any root-local declaration.

Same-spelling declarations in disjoint roots stay independent. A name that conflicts with a shared helper already in scope is an ordinary visible-name collision.

site/
├── @mod.moth          public facade
├── @package.moth      support facade
├── @entry.moth        executable entry
└── shared.moth        helper bound by all three roots

In this layout shared.moth can expose site_label to every root, but no root can read either sibling root's private declarations.

What each root may contain

@mod.moth and @package.moth carry declarations and function bodies. They use $export before each declaration or direct-selection dependency clause they publish. They reject top-level runtime statements, direct const fragments, runtime fragments and builder-slot contributions. A rejected top-level runtime body reports MOTH-RULE-0023. Functions declared inside a facade remain ordinary callable functions when reachable through the API.

@entry.moth carries private declarations, top-level runtime statements, direct compile-time and runtime fragments and registered direct builder slots. It owns the module's implicit start. It rejects $export because entry roots have no public surface.

An API facade has no implicit start, route metadata or entry lifecycle. An entry root publishes no importable interface. Only the two facades publish APIs.

Root identity and dependency names

The authored root filename never supplies a dependency name. Names come from the containing directory or the registered package identity.

@entry.moth
pages/
├── @mod.moth
└── article.moth

Valid dependency from a sibling module:

@pages page_heading

Invalid dependency spellings:

@@pages
@@mod

Do not concatenate the filesystem @ with the dependency @. The exact root filename is the role, not a dependency name. Direct dependency clauses on a root file are rejected. Depend on the module directory instead.

Entry eligibility follows presence

A module is entry-eligible when @entry.moth exists. Presence alone decides eligibility. An empty file, a file with only static content and a file with only builder metadata all count. No activity heuristic selects an HTML route.

Compiling or importing a module never activates its entry. Only the selected build command activates a compiled entry, and a project-local @entry.moth is the only project entry source. Separately compiled source packages and dependency entries never activate.

Publishing a public API

Only @mod.moth and @package.moth accept $export. Place it above each eligible public declaration or direct-selection re-export. A facade with no marked items exposes an empty API. Root-local declarations remain isolated from sibling roots.

See Public API for eligible targets and Module visibility for consumer access.

Concepts related to module roots

Choose the explanation level: Public API

Public API

Declarations are private by default. In @mod.moth and @package.moth, place $export before each public declaration or direct-selection re-export.

Exporting declarations

private_helper || -> String:
    return "private"
;

$export
public_name #= "Moth"

$export
render || -> String:
    return private_helper()
;

$export applies only to the next eligible item. It occupies its own line and a blank line breaks attachment. A # binding is compile-time, not automatically public.

Re-exporting helpers

$export
@components/card CardData as Card, render_card

This publishes Card and render_card. CardData is not also exported under its original name.

Files within a module can bind shared helpers. Other modules see only the matching facade's exported API. Declarations in separate root files remain isolated. Public signatures cannot expose private types or trait evidence, and public callables require closed error contracts.

See Public API and Module visibility.

Declarations are private to their module by default. In @mod.moth and @package.moth, place $export on its own line before a declaration to include it in that facade's public API.

Exporting declarations

-- @mod.moth
private_helper || -> String:
    return "private"
;

$export
public_name #= "Moth"

$export
render || -> String:
    return private_helper()
;

public_name and render are visible through the module's normal facade. private_helper remains private. An unmarked facade exports nothing.

$export applies to the next eligible top-level item only. It must occupy its own line, with no operands. Comment-only lines may intervene, but a blank line breaks attachment. It is valid only in the two facade files, including when both exist in one directory. It does not apply in @entry.moth, ordinary helper files or the build-only @config.moth, which has no export surface.

The directive can mark a function, struct, choice, transparent type alias, trait or compile-time # constant. The # marker controls when a constant is evaluated, not whether it is public.

Runtime bindings, mutable bindings, executable statements, templates, page fragments, trait conformances and incompatibilities cannot be exported. Receiver methods are exposed through their public receiver type, not exported independently.

Re-exporting dependencies

A facade may publish selected declarations defined in another file without moving them into the facade:

$export
@components/card CardData as Card, render_card

$export
@core/math PI, sin

One $export publishes every selected name in its dependency clause. The alias Card is the public name. CardData is not also published unless selected separately. Bare namespaces and namespace aliases cannot be re-exported.

An ordinary dependency clause without $export binds names for the facade's own use but does not publish them. See Public re-exports for selection and alias rules.

Visibility boundaries

Files in one module can bind shared helper declarations through ordinary dependencies. Declarations authored directly in any root file remain local to that root. Other roots and helper files cannot read them, even if the roots share a directory.

Consumers in another module can bind only the applicable facade's explicitly exported names. A normal module publishes through @mod.moth. A scoped support or external project package publishes through @package.moth. Resolution never falls back between facades or bypasses one with a filesystem path.

See Module roots for file roles and Module visibility for the complete access rules.

Public API contracts

An exported signature must not expose private types, inaccessible trait requirements or project-private context. Exported functions and public receiver methods also need closed error contracts: implicit built-in failures must be handled or delivered through an explicit built-in Error! result. A custom error result needs local recovery or explicit mapping. The same rules apply to re-exports.

See Returns and multiple values and Error propagation for error handling.

Related references

Choose the explanation level: Entry runtime and fragments

Entry runtime and fragments

@entry.moth is the page root. The file's presence makes the folder a page. @mod.moth and @package.moth hold APIs and never become pages. Dependencies never run their entries.

Entry code

Top-level runtime code in @entry.moth becomes a dormant entry. It runs once when that module becomes a page entry. Helper files provide declarations and never own an entry.

The entry has built-in Error!. Checked numeric failure and compatible top-level postfix ! can propagate to the generated terminal handler. Custom errors still need explicit recovery.

An empty entry file produces the builder's default page. A metadata-only entry produces a complete document too:

[$in title:Welcome]

A nested or aliased insert remains ordinary template composition.

$doc attaches documentation to a following declaration, and $todo annotates a declaration or executable statement. Both take compile-time String operands and are source directives. As a child of a template body, $note discards comment content without producing output. A note outside a template body is rejected.

Page fragments

Direct top-level templates in @entry.moth become fragments:

  • Bare [...] must fold and becomes static HTML.
  • Explicit ~[...] runs through the entry, even if its content can fold.

The removed #[...] spelling is invalid. A nonconstant bare entry fragment is an error instead of an implicit runtime fragment.

The builder keeps static and runtime fragments in source order. Assigned or returned templates are ordinary values. Helpers cannot create page fragments.

Runtime fragments publish only after that startup invocation succeeds. Failure leaves static HTML in place and publishes none of the invocation's runtime fragments. Other side effects do not roll back. The generated terminal handler shows a generic safe release notice rather than the application's Error message as HTML. Development presentation belongs to the build and dev docs.

Imported entries stay dormant

Importing a module exposes only its API. It never runs that module's entry or adds its page fragments. An entry-only child has no API to import.

@entry.moth is the executable entry root. Its presence makes the directory entry-eligible. Top-level runtime work in that file becomes a dormant compiler-owned entry, which entry assembly activates exactly once for a selected page. @mod.moth and @package.moth are API-only facades with no start function and no fragments, and a dependency never activates its entry.

Entry ownership

Every selected module compiles into an immutable module artefact. Only a module with @entry.moth owns dormant root runtime, direct page fragments and an implicit start. An API facade may declare functions and constants but rejects top-level runtime statements, direct fragments and builder slots.

The entry still has its built-in Error! contract. Checked numeric failure propagates to that contract, and compatible top-level postfix ! is legal. Custom typed errors still need explicit recovery. A generated terminal handler closes the entry boundary, so an unhandled built-in failure does not become an implicit panic. See Progress for compiler support.

Entry eligibility and activation

Eligibility follows file presence. An empty @entry.moth, a static-only entry and a metadata-only entry all count. No activity heuristic selects a page.

Entry assembly activates the selected module-owned entry exactly once. Loading a module, binding its API or importing a package exposes declarations without activating root work. A project-local @entry.moth is the only project entry source. Dependency entries and separately compiled source-package entries never activate.

Only a direct top-level const $in on the entry reaches the builder. A nested or aliased insert remains ordinary template composition, and runtime top-level templates still contribute only to the default body lane. Runtime named builder slots are not supported.

Documentation and comments

$doc value attaches a compile-time String to a following declaration as documentation metadata. $todo value annotates a following declaration or executable statement and is validated without generating runtime work. Both are source directives, not template fragments. $note is the sole template comment directive and is valid only as a child of a template body. A

[$note: ...] child discards its balanced body and

contributes no output or runtime slot, unlike an ordinary template that emits an empty String. Source-root [$note: ...] and runtime

~[$note: ...] fragments are rejected.

Assigned or returned template values remain ordinary values, not direct output. Their containing runtime code follows normal entry placement rules. See Directives for source attachment and stacking.

Entry-activated root runtime

The entry file's top-level runtime code becomes a dormant compiler-owned entry. Entry assembly activates it exactly once. This includes top-level bindings, function calls and other runtime statements. Helper files define reusable declarations and never own an entry or public facade.

Page fragments

Two forms of direct top-level template in @entry.moth become page fragments:

  • A bare direct [...] is a const-required fragment. It must fold and is emitted as static HTML; runtime-dependent content is an error, not a fallback.
  • An explicitly marked direct ~[...] is a runtime body fragment. It reserves a runtime slot even when its content happens to fold. The entry evaluates it on activation, then publishes it only on success.

~ [...] may include horizontal space after ~, but no newline may separate

its marker from [. The old direct #[...] syntax is removed. These fragment rules apply only to direct top-level entry templates, not ordinary expression or nested templates. Runtime named $in destinations are unsupported.

Each direct fragment ends its physical line. A comment may follow it, but any other code on that line, including a second fragment, a binding or a call, is rejected with guidance to move that code to the next line. Fragments on separate lines still join in source order.

The builder preserves source order between static and runtime fragments. Static fragments remain in the document even when startup fails. Runtime fragments use generated slots, and the entry boundary fills those slots only after successful startup. Failure publishes none of that invocation's runtime fragments. This is not rewind: other side effects do not roll back.

The generated terminal handler presents a generic safe release notice, not the application's Error message as HTML. Development presentation, including the three startup categories and invocation-local reporting, is owned by docs/build-system-design.md > Development entry-error reports and summarised at HTML assembly.

Metadata-only and empty pages

An entry with only direct const builder slot contributions still produces a complete document. A page containing only resource-bearing metadata also emits the resources it uses without non-empty executable HIR, an artificial fragment or generated runtime code.

An empty @entry.moth produces the builder's ordinary default document for its route. The route exists because the entry file exists.

Dependency entries

An imported module never activates its entry. When a module is bound for its public API, its entry runtime, entry body and page fragments remain dormant. Only exported declarations remain available.

A consumer cannot make a dependency's root work or fragments part of its own entry, and imported entries do not contribute named builder slots to the consumer. An entry-only child publishes no normal API, so a dependency that requests one receives a missing-surface diagnostic. Valid dependency access and check remain non-activating.

Do not put page fragments in helper files

Helper files define reusable declarations. The entry file binds and uses them. Top-level page templates and builder slots belong in @entry.moth only. An ordinary file cannot become a page or contribute a fragment by containing a template.

Concepts related to entry runtime

Choose the explanation level: HTML routing and artefacts

HTML routing and artefacts

HTML pages come from folders that contain @entry.moth. Routes come from the folder's position. No homepage is required.

Directory routes

@entry.moth          -> index.html
about/@entry.moth    -> about/index.html

The root filename is fixed. Ordinary filenames such as index.moth have no page meaning. @mod.moth and @package.moth publish APIs and emit no page.

Entry rules

A folder becomes a page when it contains @entry.moth. An empty file or a metadata-only file still counts:

[$in title:Welcome]

Imported modules never run their entries.

check accepts a project with no entries. HTML build and dev need an entry somewhere below the selected project root, not necessarily at its root.

Single files

When you select one file directly, an ordinary .moth file or @entry.moth becomes a page:

moth build page.moth     -> page.html
moth build @entry.moth   -> index.html
moth build index.moth    -> index.html

A selected @mod.moth or @package.moth stays an API facade. check validates it. build reports that the project has no entry.

Launch page

Development tooling opens the real homepage when the project has one. Otherwise it opens the first route in alphabetical order. It never invents a homepage. Requests to an empty site root stay missing.

The builder does not invent a homepage or scan arbitrary .moth files. Generated _dev/ and _release/ folders remain output, not source.

The HTML builder emits one route for each @entry.moth directory. The directory position determines the output path. No homepage is required.

Directory-based routes

@entry.moth              -> index.html
docs/@entry.moth         -> docs/index.html
docs/basics/@entry.moth  -> docs/basics/index.html

The root module maps to the project index. A nested directory maps to a nested index route. Only the directory position matters. The root filename and ordinary filenames such as index.moth have no route significance.

@mod.moth and @package.moth directories emit no route of their own. They publish APIs only. An ordinary file cannot supply an entry. The builder adds no route override, filename-derived route, page alias or new redirect. Existing page_url_style and redirect_index_html policies stay unchanged.

Entry selection

A directory becomes an HTML entry when it contains @entry.moth. An empty file, a static-only file and a metadata-only file all count. A direct named builder contribution is a direct const fragment, so this entry still produces a complete document:

[$in title:Welcome]

One entry directory produces at most one directory-derived route. @mod.moth and @package.moth never become entries. Imported entries stay dormant.

Command policy

  • Directory-project check accepts a valid project with no entries.
  • HTML application build and dev require at least one @entry.moth anywhere below the selected project root, not necessarily a homepage.
  • Single-file HTML output classifies the explicitly selected root as described below.

The builder does not invent a homepage to satisfy development tooling. Development launch uses the real homepage when one exists, otherwise the lexicographically first normalised entry route. That choice creates no redirect or route alias. Requests to an absent site root retain ordinary missing-route behaviour.

Single-file entries

A command that explicitly selects one ordinary .moth file or one @entry.moth compiles it as a synthetic entry:

moth build page.moth        -> page.html
moth build @entry.moth      -> index.html
moth build index.moth       -> index.html

A selected @mod.moth or @package.moth keeps its facade role. check validates it as an API facade, while an application build reports the no-entry outcome instead of manufacturing a page. Other special root filenames are rejected during source discovery.

The synthetic unit uses the same source identity, module service and error-reporting rules as a directory project. It never creates a filesystem-backed module API.

Builder ownership

The HTML builder owns route and artefact policy. The frontend remains builder-neutral. The builder decides:

  • which @entry directories produce HTML artefacts
  • how routes are derived
  • how output files are organised
  • whether to reject unsupported reachable features

Source stays target agnostic. The HTML builder may choose JavaScript, Wasm or mixed output, but source cannot query or branch on that choice. Builder packages expose stable capabilities rather than target identity.

Output folders

The builder generates output folders and manages them through manifests. Builder settings in @config.moth own output paths. HTML defaults to _dev for development and _release for release builds. Every directory output root must be hidden from source discovery. Treat generated folders as build artefacts, not source.

Release versus development output

The default build writes to the hidden dev folder. The --release flag writes to the hidden release output folder. The dev server serves from the dev folder.

HTML-Wasm output

With --html-wasm, the builder can emit a route folder containing index.html, page.js and page.wasm instead of a single HTML file with embedded JavaScript.

Concepts related to HTML routing and artefacts

Choose the explanation level: Build configuration values

Build configuration values

Build configuration values let a project or source module receive typed primitive values before its modules are compiled.

CLI numeric spelling stays raw until the exact contract selects its type. $config inputs use these exact numeric rules. See Progress for implementation status.

$config declarations

$config
analytics #Bool = false

if analytics:
    send_analytics()
;

The name is the input name, the type is the contract and = is the fallback. A required non-optional input may omit the initializer and then reports a missing-input diagnostic when no value is supplied. An optional input with no initializer or with = none resolves to absence. Ordinary constants still need one.

Only $config declarations create explicit-only contracts. A project record field named version does not supply a source input named version.

Command examples

moth build . --input enabled=true
moth build . --input retries=4
moth build . --input api_url=https://example.com

Raw CLI numeric spelling keeps its category until the exact input contract is known. A whole literal can materialise directly as U64 or F32. Decimal/exponent spelling cannot satisfy an integer contract, and every numeric value must fit its destination's range or finite precision. Already typed programmatic inputs keep their exact type: an I32 value cannot satisfy I64 or F64. Inputs accept all eleven fixed numeric types, but not Byte or Dec. See Numeric types for the exact inventory.

Build configuration cannot inspect operating-system, architecture, backend or target identity.

CLI numeric inputs retain their raw spelling until an exact contract selects the destination. $config contracts use the same exact numeric input rules. See Progress for implementation status.

Build configuration values are typed primitive values resolved before module AST execution semantics are finalised. They can represent schema-approved settings and similar stable semantic configuration. They do not represent project identity, source-discovery settings, operating-system, architecture, backend or target identity.

$config declarations

$config marks exactly one explicitly typed top-level # binding in @config.moth or a selected source module. The name is the input name, the type is the contract and = is the fallback.

$config
analytics #Bool = false

$config
max_retries #I32 = 3

$config
api_url #String

$config
label #String? = none

Declaration

Missing external input

Non-optional type, no initializer

Required-input diagnostic

Non-optional type with initializer

Use the validated fallback

Optional type with no initializer or = none

Resolve to absence

Optional type with a present initializer

Use that present fallback

Ordinary constants still require initializers. Only a marked configuration contract may omit one. Reject inferred #= configuration contracts, runtime or mutable bindings, multi-bind targets, parameters, fields, function-local declarations and type-position or value-position directives.

The accepted input types are String, Bool, Char, all fixed-width integers (I8, I16, I32, I64, U8, U16, U32, U64), all fixed binary floats (F16, F32, F64) and one optional layer around those types. Byte and Dec remain excluded. This exact numeric input contract applies to $config input declarations.

Numeric types and Numeric literals own the exact ranges, direct rounding and source defaults. Build inputs use explicit contracts rather than unconstrained source defaults. Builders and physical build profiles never select numeric semantics.

Explicit-only providers

Only $config declarations create explicit-only input contracts.

  • project #= (version = "1.0") is project metadata, not a version input provider.
  • An ordinary version #String = "1.0" is a helper constant, not an input provider.
  • Using version = release_version inside project #= (...) does not rename the input contract.
  • @project publishes only predefined project fields.

Matching declarations within one compilation boundary agree on name, primitive type, optionality, required or default state and normalised default value. Each project or package boundary owns its own namespace.

Bootstrap versus source defaults

In @config.moth, a fallback may use earlier visible helper values on the allowed single-file compile-time surface. Same-file forward references remain errors.

In source modules, defaults remain self-contained primitive literals or none. Names, projections, expressions, templates, calls, casts, collections, records and references to other configuration values remain invalid defaults.

Bootstrap contracts resolve from explicit input, a compatible builder primitive global, the fallback or a required-input diagnostic. Source contracts resolve from a matching bootstrap contract, explicit source-only input, a compatible builder global, the common source fallback or a required-input diagnostic.

Inputs in @config.moth

In @config.moth, the $config declaration sits at the top level and the grouped project field carries only name = expression; for example:

$config
version #String = "0.1.0"

project #= (
    version = version,
)

The version binding declares the input and project #= passes its resolved value. Only $config declarations create explicit-only providers.

Command build-input parsing and resolution

The command accepts repeated --input name=value arguments. It splits at the first = and preserves all later = characters. Names must be lower_snake_case. The command retains each numeric category and its exact spelling until the corresponding input contract supplies a destination. It does not first materialise whole-number input as I32 or decimal/exponent input as F64.

  1. exact lowercase true or false -> Bool
  2. a complete valid whole-number literal -> retain whole-number category and spelling
  3. a complete valid decimal-point or exponent literal -> retain binary-float category and spelling
  4. a complete valid single-quoted character literal -> Char
  5. a complete valid double-quoted string literal -> String
  6. every other value -> String

Numeric destination examples:

--input count=4_294_967_296 -> accepted by U64
--input ratio=1 -> accepted by F32
--input count=1.0 -> rejected by an integer contract
--input count=256 -> rejected by U8
moth build . --input analytics=true
moth build . --input retries=4
moth build . --input ratio=0.75
moth build . --input api_url=https://example.com
moth build . --input 'label="true"'
moth build . --input "separator=':'"

Anything else, including empty text after name=, falls back to String. A value beginning with a quote must be a complete valid quoted literal; malformed quoted text is a command-input diagnostic rather than a String fallback. Bare none is String text. To force an ambiguous String such as true or 42, use explicit double-quoted Moth String syntax. A Char requires explicit single-quoted syntax and never infers from an unquoted character.

Omitting an input lets optional absence resolve to none through the contract or default. A raw CLI numeric value materialises directly as the exact contract type, including an optional's inner type, with destination range and finite-result checks. An already typed programmatic input must have the exact contract type. A concrete T may satisfy a matching T? as a present value. Typed values receive no implicit numeric conversion: a typed I32 cannot satisfy I64 or F64, even when its value fits. The raw CLI spelling 1 can satisfy either contract because it has not yet acquired a numeric type.

Programmatic inputs and builder globals retain their exact types and are not reparsed to match a receiver. Contract identity and effective-value fingerprints include the resolved exact type and canonical value. Resolution origin and source location remain diagnostic provenance, not semantic fingerprint inputs. The existing bootstrap/source ordering and conflict checks remain unchanged.

Ordinary static if

Ordinary if is the only conditional source form. There is no $config if.

$config
analytics #Bool = false

if analytics:
    send_analytics()
;

Both branches remain valid Moth source and complete frontend validation, including unknown directives. A known Bool selects the executable branch before HIR. This does not condition imports, declarations, exports or package topology. Future $feature is a separate pre-graph structural-selection contract.

Platform boundary

Moth source cannot inspect or branch on operating system, architecture, backend, target or runtime-platform identity. Builders own physical target decisions and map stable source semantics and capabilities to JavaScript, Wasm or other platform-specific artefacts.

Concepts related to build inputs

Choose the explanation level: Entry metadata and builder slots

Entry metadata and builder slots

@project supplies project fields and HTML builder slots supply entry metadata. @entry.moth is selected by file presence. See Progress for implemented syntax and runtime io.set_title status.

Using @project

Bind @project to read predefined project fields:

@project version

footer #= [: v[version]]

@project is never implicitly injected.

HTML metadata

Bare direct const inserts in @entry.moth set document metadata, without a # prefix:

[$in title:About]
[$in stylesheets:[@assets/site.css]]
[: <main>About this site</main>]

HTML also accepts description, lang, favicon, body_style and head. Repeated scalar contributions concatenate. A supplied empty value differs from an absent slot. An absent title uses the route and then the project name with the configured prefix and postfix. Absent description emits nothing and the other values use builder defaults. The builder escapes title text and attribute values. Each stylesheet insert needs one tracked CSS resource. The builder keeps the first contribution for each resource origin and renders its URL relative to the output page.

head inserts raw HTML after built-in head content. Identical complete head contributions render once. Old page_* constants have no implicit metadata effect. JavaScript and HTML-Wasm documents use the same slot plan.

A metadata-only entry still produces a page. Explicit ~[...] runtime top-level templates contribute only to the body; bare direct [...] must fold. Runtime named builder slots are not supported. Only direct inserts in @entry.moth reach the builder. API facades, helper files and imported modules cannot contribute.

Entry selection

A folder becomes an entry when it contains @entry.moth. An empty or metadata-only file still counts. @mod.moth and @package.moth never become entries.

check works with no entries. HTML build and dev need at least one entry somewhere below the selected project root. No homepage is required.

Concepts related to entry basics

An HTML page's entry root is @entry.moth. Entry eligibility follows the file's presence, not the amount of authored runtime work. Direct const root inserts on the entry supply document metadata.

This page describes entry metadata and its relationship to project configuration.

The @project namespace

@project is an explicitly bound immutable namespace. The named project configuration record supplies its predefined fields. The grouped-record configuration remains the accepted model.

@project version

footer #= [: v[version]]

Normal project modules and eligible project-owned support packages may bind it. It is never implicitly injected or directly re-exported. Project-package exposure restrictions and field provenance still apply. Config helper and input bindings do not become project metadata merely because they exist.

See Project configuration for the field contract and Build configuration values for independent input resolution.

HTML builder slots

Use bare direct top-level [$in name: ...] inserts in @entry.moth to supply document metadata. These templates are const-required without a # prefix:

[$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 builder registers title, description, lang, favicon, body_style, stylesheets and head. Ordinary top-level const and runtime fragments render into the body. A nested or aliased $in remains a template composition helper, not a builder message. Helper files, API facades and imported modules do not contribute to the selected entry.

An entry with only these direct const contributions still produces a complete document. Only explicitly marked ~[...] entry templates contribute runtime body fragments. Unmarked direct output must fold, while ordinary assigned or nested templates retain their usual rules. Runtime named builder slots are not supported.

The compiler accepts the active builder's read-only destination schema. It validates that a direct root insert targets a registered name and folds the contribution to a structural value, but it does not know HTML slot meaning. The builder validates slot-specific content and assembles the document. Both the JavaScript and HTML-Wasm paths consume the same builder slot plan, so metadata fallbacks, stylesheet order and body output remain equivalent.

Repeated title, description, lang, favicon and body_style contributions concatenate in source order. Template body whitespace remains part of each value, including a space immediately after :. A supplied empty value counts as present. An absent title uses the route, then project name, with the configured title prefix and postfix. An absent description emits no description element. Absent language, favicon and body style use the HTML builder defaults.

The builder escapes title text and attribute values. It inserts head as raw HTML after its dedicated head content. It removes only repeated complete head contributions that render identically in the page's URL context. It does not rewrite duplicates inside one contribution.

Each stylesheets contribution must contain exactly one tracked CSS resource and optional formatting whitespace. Plain paths, external URLs, site-root values, non-CSS resources and combined resources are invalid. The builder deduplicates by stable resource origin, keeps the first occurrence and renders the URL relative to each output page. Use head for an external stylesheet.

Resource and site-root pieces retain their identity through folding and output planning. Named contributions keep their tracked resources live, including on metadata-only pages. The builder does not scan rendered HTML for paths. The former page_title, page_description, page_lang, page_favicon, page_body_style and page_head names are ordinary constants with no implicit document effect.

Entry selection

@entry.moth is the only project entry source. A directory that contains the file is entry-eligible whether the file is empty, static-only, metadata-only or full of runtime work.

@mod.moth and @package.moth are API-only facades. They never become entries, own no start function and emit no route. An entry-only module publishes no importable API.

Importing a module or binding a package never activates its entry. Only a build or development command activates selected compiled entries. Separately compiled dependency entries stay dormant.

HTML build and dev require at least one @entry.moth anywhere below the selected project directory. No homepage is required. check accepts a project with no entries.

Concepts related to entry metadata

Choose the explanation level: Project package facade

Project package facade

A project publishes an external package API through @package.moth at the selected project root. Each public declaration or direct-selection re-export uses $export.

The project can also contain @mod.moth, @entry.moth and @config.moth. Roots share ordinary helpers but keep separate declaration scopes. The package facade never falls back to the normal facade.

The support facade rejects runtime statements, page fragments and builder slots. Without a project-root @package.moth, the project has no external Moth package surface.

Exported signatures and reachable implementations cannot depend on project-private @project values. Consumer configuration does not implicitly supply a dependency package's $config inputs.

Registered Moth-source packages publish through their own directly contained @package.moth. A @mod.moth alone does not register one.

See Project package facade and Module roots.

The project package facade exposes a project's public API to external consumers. It is the @package.moth file at the selected project root. That file is an ordinary support root of the project's structural module, not a separate facade node.

The package surface

One optional @package.moth at the selected project directory is the external project package surface. Package assembly selects that support interface. It never falls back to the normal @mod.moth facade.

The directory may also contain @mod.moth, @entry.moth and @config.moth. The project can be an application and a package at the same time.

The support root may publish functions, structs, choices, type aliases, traits, compile-time constants and direct-selection re-exports with $export. Helpers are shared with the other roots, but no root can import another root's local declarations.

Facade restrictions

The facade:

  • publishes only declarations marked with $export
  • is invisible to internal project modules
  • cannot depend on @project
  • cannot expose a semantic fact that depends on project-private context
  • rejects top-level runtime work, direct fragments and builder-slot contributions
  • has no implicit start and no route
  • never becomes an application entry

Support roots and the project package facade reject root runtime and page fragments rather than merely staying inactive. The facade has no entry lifecycle to activate.

Project package assembly

The compiler produces one immutable module artefact with optional normal and support interfaces. ProjectPackageAssembly is a separate link plan over:

  • the selected support interface
  • selected descendant public interfaces
  • reachable generated functions
  • package runtime requirements permitted by the target

Assembly never recompiles or mutates the facade.

Without a project-root @package.moth, the project has no externally consumable Moth package surface, even when it has @mod.moth.

The facade package identity comes from the project record's name field.

External package eligibility

The build system rejects any declaration whose public semantic facts or reachable executable implementation directly or transitively depend on private @project. This includes an exported function that calls a private project-dependent helper.

The validator does not treat implementation-only dependence as a reusable package specialisation mechanism.

Registered package surfaces

Every registered Moth-source package publishes its external API through a directly contained @package.moth. A @mod.moth alone never satisfies registration, though it may still own a separate internal normal-position scope. The external project package follows the same facade rule. Binding-backed packages have no source facade.

For example, packages/core/html/@package.moth, packages/core/css/@package.moth and packages/builder/web/site/@package.moth publish their package surfaces. A compiler-shipped set that has lost a required facade is damaged and reports an infrastructure failure. A malformed third-party registered package reports a structure diagnostic naming @package.moth.

Importing a package never activates its entry. A builder that registers a source package publishes that package's declared API surface, not a project facade.

Dependency package facades

A dependency package exposes its facade and immutable artefacts to consumers. Consumers never see the dependency's private @project.

No declaration exposed through a dependency package facade may directly or transitively depend on that dependency's private @project. Private declarations may use the dependency's own @project only when no external package export can reach or expose them.

Configuration namespaces are scoped to one project or package compilation boundary. A consuming command's unqualified CLI or programmatic inputs do not implicitly satisfy a dependency's $config contracts.

Concepts related to the project package facade