10. Organizing a larger program
<!-- coax-release:current:start --> Current compiler: coax0 0.52.0. Status inventory schema: 1. <!-- coax-release:current:end --> The small programs in the first half of this book fit in one file. A world, a compiler and an app do not. They need boundaries: who owns a type, what crosses a boundary, and which parts a build is allowed to replace together.
Load another source unit
Run this example from the repository root:
coax/bin/coax run coax/book/examples/ch10_sources.coaxIt prints 42. The entry file imports printing and loads a source unit:
#import "Basic";#load "lib/ch10_numbers.coax";#test "a loaded type has one identity" { #assert cells_total(Cell.{value=20},Cell.{value=22})==42; }main :: () { print("%\n",cells_total(Cell.{value=20},Cell.{value=22})); }That unit loads a shared type next to itself:
#load "ch10_types.coax";#test "negative and positive cells" { #assert cells_total(Cell.{value= -2},Cell.{value=3})==1; }cells_total :: (a: Cell, b: Cell) -> int { return a.value+b.value; }The final file declares Cell. It is the same declaration in both files, not two structurally similar types that happen to have the same spelling. Procedure and type names can refer forward across the graph. In this unannotated example the loaded units share the legacy namespace, so a second unrelated Cell still conflicts. Explicit logical modules and qualified lookup, introduced below, let independent declarations keep the same local spelling.
Paths are literal, nonempty, NUL-free strings, resolved beside the file containing the directive. Absolute paths are also explicit inputs. There is no search path, environment expansion, network download or package version selection. A source load is a file-level declaration, not an interpreted operation that #run can perform.
One graph, with explicit limits
The compiler reads the entry unit first, then visits its loads depth first in written order. It parses the composed program after loading the graph. Declarations resolve across units regardless of their textual position. Checks retain that deterministic source-unit order too.
Canonical file paths establish source identity. A completed dependency loads once when another load resolves to that same canonical path, including dot paths and symlinks. Distinct hard-link names remain distinct units. Loading an active ancestor is a cycle and reports E0602 at the directive that closes it. This is source identity, not a guarantee that a filesystem cannot change during a build.
Each compilation admits at most 4096 distinct units, 32 active units, 64 MiB of source bytes and 512 load directives per unit, and a unit exports at most 512 names. Budget exhaustion is E0603 (E0613 for exports). A build above three quarters of any of these gets a note, such as coax: note[E0603]: source units: 3100 of 4096 used (75%), ..., so the limit can be raised before the build fails. Reads are checked against the byte budget before allocation and as the file is read. These bounds do not make the whole compiler a hostile process sandbox: token, syntax-tree and native toolchain work have their own costs.
Every physical unit is checked with the Coax grammar before composition. It must contain complete declarations and balance its own delimiters within depth 128. A brace or semicolon in another file cannot complete its procedure or constant. Comments and string contents never become directives. Unreadable or nonregular source inputs report E0601; invalid load syntax is E0600; unbalanced composed units are E0604.
Authority belongs to the authored unit
An #authority directive applies to procedures authored in that physical file. Loading an unmarked utility does not silently mark the utility, and loading an authority file does not discard its requirements. Checks from another unit can exercise its procedures.
If any unit is authoritative, ordinary compilation runs the graph's checks and verifies actual execution of its authority procedures. The checks of a library, described next, already ran when the library was checked on its own. Dead references and a folded #run still do not satisfy execution coverage. Tests remain pure; moving a test to another file does not permit native effects in it.
coax test entry.coax runs checks throughout the graph. A source unit with no program main is taken as a library; --library says so explicitly and is never required. coax mutate mutates reachable code, including dependency helpers reached by the checks; its unchecked-procedure gate covers the entry file and authority units. An unused non-authority dependency need not be covered by its importer. For a reusable dependency, run its own checks and mutation gate separately. coax mutate entry.coax --root-only selects only entry-source procedure mutation sites while still running all baseline checks and enforcing the same authority coverage. It reports an explicit scoped result; it does not repeat or replace a dependency's mutation gate. Every shard and its merge must use the same scope.
This makes Chapter 24's composition possible: a protocol adapter can load a pure authority policy without requiring checks to execute every unused accessor in a generated descriptor closure. Importing a descriptor directly inside the authority unit still places its generated declarations under that unit's obligations. Do not remove the directive to avoid those checks.
These are source-level verification rules, not runtime permissions. An author can still edit the files and directives. Chapter 23 explains the review and trust boundary.
Check a library once
A library's checks belong to the library. When you compile a program, the compiler first checks each loaded unit on its own, in the unit's own #load closure. If the unit passes, it's a library for this compile: the compiler leaves its #test and #forall declarations out of your program. Your compile doesn't check them again, and the C has none of the generic instances or helpers that only those checks reach. Loading coax/lib/bounded.coax, whose checks instantiate Bounded over int, u8, string and a record, adds only the instance your program uses.
A unit whose checks need helpers, fixtures or an oracle keeps them in a file of their own and loads it with #test: #load "hud-checks.coax" #test;. That is a check load. The file is checked with the unit, its #test and #forall bodies run wherever the unit is compiled, and they count toward the unit's #authority coverage. No compile emits its procedures, so a page that loads the unit ships none of them. A procedure that calls into a check unit is a check's helper, and is left out with it. main and exported procedures are always emitted, so they can't reach a check unit (E0616).
The result is cached in ~/.cache/coax-check/, or in $COAX_CHECK_CACHE when you set it. Its key is the compiler binary's SHA-256, the options that change checking, and every unit in the library's closure. Edit the library, or any unit it loads, and the next compile checks it again. A cached result gives the same C as a fresh check. To see what a compile reused, read library_checks in its timing report:
coax/bin/coax c psionic/lib/shadow.coax --library --timings /tmp/shadow.json > /dev/nullgrep -o '"library_checks":{[^}]*}' /tmp/shadow.jsonSome units stay in place:
- The entry file's own checks.
- A part that uses names its loader declares, so it can't be checked on its own. Your program checks it as before, and reports its errors at the part's lines.
- A unit whose closure has an
#authorityunit, because its checks may count toward that unit's coverage, or an#import_proto.
When your program has an #authority unit, every compile runs the checks, so a library qualifies only if its checks also pass when run on their own. coax test and coax mutate still run every check in the graph.
Inspect the inputs and failures
coax/bin/coax deps coax/book/examples/ch10_sources.coaxdeps prints JSON with schema_version: 1, an ordered sources array of canonical source paths and a descriptors array of resolved descriptor inputs. It checks the program first and exits unsuccessfully for missing inputs, cycles or failed authority checks. Descriptor paths are explicit inputs; no guessed placeholders are emitted.
This is an input inventory, not a lockfile or cache key. It does not hash contents or enumerate native compiler, SDK, linker or environment inputs. A reproducible build must record those separately. #load and deps need no Python, external preprocessor or protoc process.
Parser, checker and evaluator diagnostics point at the original physical file and line. Mutation reports do too. Native traps in composed C output map their joined source lines back to the original unit. Native source line maps and optional debugger name presentation also exist; Chapter 12 explains the limits for optimized values, generated code and target tools.
A protobuf import in a loaded file resolves its descriptor beside that file. An error in generated declarations points to that import directive. Use distinct prefixes for imports combined in one declaration scope. A source alias does not version a protobuf package or change its published message and field identities.
See it in actual builds
The compiler's source graph is now compiler.coax. The bootstrap compiles it, then requires the final compiler to regenerate the same C. The loader itself is authored in checked Coax, with an explicit C/header seed and a zero-survivor mutation gate. Native code reads files, resolves filesystem identities and transports storage; it does not provide a second load-syntax parser.
The iOS engine's hud.coax loads hud/types.coax, keeping its native packet identity in a shared declaration. The capstone loads the same checked request policy used by Chapter 15. The frontend book example also uses a source graph instead of shell concatenation.
Name a logical owner
A path says where a file is today; it is not who owns a declaration. Give a group of files an owner by claiming a logical module in one of them:
#module "engine.hud";#load "hud/types.coax";#load "hud/frame.coax";The claiming unit owns itself. hud/types.coax and hud/frame.coax have no claim of their own, so they are members of engine.hud. Each declaration then has the nominal ID coax.decl.v1:engine.hud:struct:HudSlot: the module, the declaration kind and its name. Moving the checkout, reordering loads or moving HudSlot into another member keeps that ID; renaming it, changing its kind or claiming a different module changes it.
coax/bin/coax deps main.coax --declarationsprints coax.declarations.v1 JSON: every unit and its owner, every declaration's ID, file and line, and every resolved reference from one declaration to another. A declaration in a unit with no owner reports "id": null: the compiler does not invent identity from a path or a line.
Each declaration row also has a span: the byte range of exactly the text you wrote for it (from its name to its closing } or ;), its first and last line, and a SHA-256 of those bytes. Move a declaration within its file and its span moves while its ID and hash stay; edit it and the hash changes. A declaration that #import_proto generated has no span; its origin names the directive line instead. The target record says which layout the compiler used: native-lp64, with 8-byte pointers and counts and each scalar's size and alignment. coax layout main.coax --target wasm32 stops with E0612 rather than printing LP64 sizes under another name.
The rules are strict so the answer never depends on traversal order. Two files claiming one ID is E0606. A file without its own claim that two different modules load is E0607; give it its own #module instead. A bad claim is E0605. A claim alone is identity: it changes no lookup and no generated C.
An ID says which declaration; a revision says whether it may have changed. coax deps main.coax --modules prints each module's content_revision (its own files) and revision (its files plus the revisions of the modules it loads). Revisions are module-scoped and conservative: editing any member, even a comment, changes every declaration's revision in that module, while their IDs stay. Everglade's page and its guard policy are compiled separately and both load everglade/npc/guard-types.coax, which claims verse.everglade.guard_types; both report the same IDs and revisions for GaObservation, GaInput and GaEffect.
Name another module's declarations
Two modules may each declare V. Load them with aliases and say which one you mean:
#import "Basic";#load "left.coax" as l; // claims #module "demo.left"#load "right.coax" as r; // claims #module "demo.right"main :: () { a: l.V = l.V.{x = l.g()}; b := r.V.{x = r.g()}; print("% % %\n", a.x, b.x, l.K + r.K);}l.V, l.g() and l.K see only demo.left. A plain V would be ambiguous here (E0386, at the use), because two modules declare it and this file declares none; a name only one module declares still resolves without an alias, so existing #load programs keep working. A file with no #module binds its own files' names first. So when it loads a module's file with no alias and uses a name that module offers, and another file with no #module declares that name too, the plain use is E0386: a later #load never changes in silence what a name from a module you loaded means. Rename one, load the module as an alias and qualify the name, or give the module an #export list that leaves the name out. A name the file declares itself is its own, and a file that does not load the module is never asked. An alias names the loaded file's #module (E0610 if it has none), so renaming l to left changes no declaration ID, and l.V and r.V stay different types even with the same fields (`'a' is demo.left.V but is initialized with demo.right.V). Aliases are not reexported: l.r.V` is E0222. Native C gives colliding private names module-qualified spellings; an #export_c symbol or a library header's type is one global C name, so two modules exporting open_it is E0387.
Choose what a module exports
By default every declaration in a module is visible to every other module. An #export list makes a module's API explicit. The engine HUD does this:
// metaverse/hud.coax#module "metaverse.hud";#export HudRect, HudPoint, metaverse_hud_slot;#export metaverse_hud_frame_point, metaverse_hud_frame_arm, metaverse_hud_tone, metaverse_hud_cut, metaverse_hud_outline, metaverse_hud_arm_down;#load "hud/types.coax";#load "hud/frame.coax";Once a module has a list, the rest of its declarations are private. The landing page's nostr board loads it as `#load "../../metaverse/hud.coax" as hud; and calls hud.metaverse_hud_slot(...); writing hud.HUD_ARM`, or plain HUD_ARM, stops with E0389 ('HUD_ARM' is private to module 'metaverse.hud'). The files the module loads (hud/frame.coax here) are part of it, so they use the private constants freely, and each keeps its own #authority and checks. A list names the module's own declarations: listing another module's name is E0390 and #export other.Name; (a reexport) is E0614. Visibility is a source rule only. It does not change C names: whether a procedure is a native symbol is still #export_c. A module without a list behaves as before, so you can add lists one module at a time. coax deps metaverse/hud.coax --modules prints the list as the module's exports.
Keep source, ABI and protocol identity distinct
A Coax type name identifies a declaration in a compiled source graph. A C symbol and header describe a native ABI. A protobuf package, message and field number identify interchange across builds. These are different contracts.
Compatible generated C declarations now compose through per-type ABI schema guards; conflicting definitions of the same C spelling fail, even when their sizes match. Preserve generated layout assertions and regenerate related headers together. Chapter 20 shows that native boundary.
Those guards establish structural C ABI compatibility, not nominal source identity or protocol interchangeability. Shared source and #module name the source declarations, while #export controls their source visibility. Native symbols still follow #export_c and its global C naming rules.
Keep pure decisions in Coax, representation adapters at protocol boundaries, and lifecycle/effects in the host. A useful API documents what it borrows, copies or allocates, when a result expires, its work and space bounds, failure values and deterministic guarantees.
Basic remains the only named built-in module. Math intrinsics, arrays, views and generated codecs are available; general collection, allocator, file, network and concurrency standard-library modules are not. Internal coax/lib/ folders are authored implementation sources, not promised public package APIs. Build the next library from a real consumer and a checked contract rather than a name in the specification.