FOL Language Specification
FOL is intended as a general-purpose and systems-oriented programming language with a compact declaration syntax, a rich type system, and a strong preference for explicit structure.
This book is the specification draft for the language.
Core Shape
Much of the surface syntax follows the same high-level shape:
declaration[options] name: type = { body }
That pattern appears across:
- bindings
- routines
- type declarations
- module-like declarations
- standards
Main Declaration Families
The main declaration families are:
use // import declarations
def // named definitions such as modules, blocks, and tests
seg // segment/module-like declarations
var // bindings; use var[imu] for immutability
con // constants
lab // labels and label-like bindings
fun // functions
pro // procedures
log // logical routines
typ // named types
ali // aliases
std // standards: protocol, blueprint, extension
Expression And Control Surface
FOL combines block-oriented control flow with expression forms:
if (condition) { ... }
when (value) { ... }
while (condition) { ... }
loop (condition) { ... }
for (binder in iterable) { ... }
each (binder in iterable) { ... }
Expressions include:
- literals
- calls and method calls
- ranges and container literals
- access forms
- pipes
- rolling expressions
- anonymous routines and lambdas
How To Use This Book
The book is organized from language foundation to higher-level facilities:
- lexical structure
- statements and expressions
- metaprogramming
- types
- declarations and items
- modules and source layout
- errors
- sugar and convenience forms
- conversions
- memory model
- concurrency
Read Notation And Conventions before using chapter examples as a normative reference.
For the current user-facing tool workflow, read Frontend Workflow.
Example
This example uses the hosted std.io surface. Its artifact therefore selects
fol_model = "memo", and its build.fol explicitly declares:
build.add_dep({ alias = "std", source = "internal", target = "standard" });
The dependency is required by the source-level hosted calls, not because
main is executable.
use std: pkg = {"std"};
var[hid] prefix: str = "arith";
pro[] main(): int = {
std::io::echo_str(prefix);
std::io::echo_int(add(3, 5));
return 0;
};
fun[exp] add(a, b: int): int = {
return a + b;
};
Toolchain Management
FOL ships as two binaries with two jobs:
| binary | role | where it lives |
|---|---|---|
fol | the toolchain manager — the only binary on your PATH, the only thing a distribution packages | /usr/bin/fol (or anywhere on PATH) |
folc | the toolchain engine — compiler, build graph, package system, LSP | inside a versioned toolchain directory, managed by fol |
You always type fol. It owns the fol self … command family and forwards
everything else (fol code build, fol work init, fol tool lsp, …) to the
right folc for the project you are standing in. You never invoke folc
yourself — if you do, folc self even redirects you back to fol.
This split is what makes multiple language versions coexist on one machine:
fol changes rarely and is version-agnostic; every folc is an immutable,
self-contained unit that can be installed, pinned, and removed independently.
FOL_HOME
Everything the manager owns lives under a single directory:
$FOL_HOMEif the environment variable is set — the shared, machine-wide home (for exampleexport FOL_HOME="$HOME/.fol").- Otherwise,
<project>/.fol/toolchain— the manager walks up from the current directory to the nearestbuild.foland keeps toolchains next to the project’s build artifacts, inside the.fol/directory every project already has. - If neither exists (no variable, not inside a project),
folstops with an error telling you both ways out.
The layout inside the home:
$FOL_HOME/
├── toolchains/
│ ├── v0.2.1/ ← one immutable toolchain per version
│ │ ├── folc ← the engine binary
│ │ ├── std/ ← the standard library, exactly as released
│ │ └── runtime/ ← the runtime crate sources folc compiles against
│ └── dev.toml ← a *linked* toolchain (see below)
├── pkg/ ← third-party packages, shared by all versions
│ ├── cache/git/ ← one clone per git repository
│ └── git/ ← one checkout per repository and revision
└── config ← the default toolchain (`default = 0.2.1`)
A toolchain directory is self-contained: folc resolves std/ and
runtime/ relative to its own binary, so nothing else on the machine — no
environment variables, no source checkout — is needed for it to compile and
run programs.
Where packages are read from and written to
Two different chains govern the package store, and the difference matters.
A read — resolving use x: pkg = {"x"} — consults, most specific first:
- an explicit
--package-store-rootflag orFOL_PACKAGE_STORE_ROOT - a
package_store_rootdeclared infol.work.yaml <project>/.fol/pkg$FOL_HOME/pkg— the shared store, usable by every toolchain- the store bundled with the running toolchain (this is how
stdresolves out of the box)
An explicit or declared root is always used, even if it does not exist, so a
wrong path fails loudly instead of silently resolving somewhere else. The
remaining candidates are skipped unless they actually contain packages — an
empty $FOL_HOME/pkg must never shadow the toolchain’s own store.
A write — where fol pack fetch materializes packages — stops at step 3:
explicit, then declared, then <project>/.fol/pkg. The package a project
resolves under its alias therefore never lands in a shared store or an
installed toolchain.
The download behind it is shared. With FOL_HOME set, fol pack fetch clones a
git dependency once into $FOL_HOME/pkg/cache/git and checks each revision out
once into $FOL_HOME/pkg/git, keyed by repository and revision rather than by
any project’s alias. Every project that needs that revision, under any
toolchain version, reuses it and copies it into its own .fol/pkg/<alias>.
Concurrent fetches take turns on a per-repository lock, and a revision appears
in the shared store whole or not at all, so a fetch that dies half-way leaves
nothing behind for the next one to trust. Without FOL_HOME, or with an
explicit or declared store, the download stays in the project.
Pinning a version
A project declares which toolchain it wants on the first comment line of
build.fol:
//fol 0.2.1
pro[] build(): non = {
...
};
The manager scans only the leading comment block (it never needs to run the
build program to learn the version — that would be a chicken-and-egg problem),
matching //fol <version>. Checking this one line into the repository means
everyone who clones the project builds it with the same toolchain.
Selection order
For any forwarded command, the toolchain is chosen by the first match:
fol +0.1.4 code build— explicit one-shot override,+<version|name>FOL_TOOLCHAIN=dev— environment override- the
//fol <version>pin in the nearestbuild.fol - the default recorded in
$FOL_HOME/config(fol self default …) - if exactly one toolchain is installed, it is used; otherwise an error
Automatic fetching
If a pinned version is not installed, fol downloads it on the spot and
continues:
$ fol code run
toolchain 0.2.1 not installed, fetching...
fetched fol 0.2.1 -> ~/.fol/toolchains/v0.2.1
42
Releases carry exactly two kinds of assets per target
(FOL is Linux-only — x86_64-linux and aarch64-linux):
fol-compiler-and-lib-v<version>-<target>.tar.gz— the toolchain:folc+std/+runtime/, unpacked verbatim into$FOL_HOME/toolchains/v<version>/fol-v<version>-<target>— thefolbinary itself, ready to drop onPATH
Updating the manager
fol self update replaces the fol binary you ran with the newest release’s;
fol self update <version> picks a specific one. The download is checked
against the release’s SHA256SUMS-<target> and swapped in with a single
rename next to the old binary, so a failed or interrupted update leaves the old
manager working. A fol installed by a package manager, in a directory you
cannot write, is refused with a pointer to that package manager.
System toolchains
A distribution can ship complete toolchains read-only in
/usr/lib/fol/toolchains/ (or the absolute directory FOL_SYSTEM_TOOLCHAINS
names), laid out exactly like $FOL_HOME/toolchains/ — v<version>/folc,
std/, runtime/. fol self list shows them as (system, read-only), they
take part in selection and can be the default, and fol self remove refuses
them. A version installed in FOL_HOME takes precedence over the system copy
of the same version.
The fol self commands
fol self install 0.2.1 # fetch a released toolchain
fol self install 0.2.1 --from . # copy folc + std + runtime from a built source tree
fol self link dev ~/code/fol # register a source checkout as toolchain "dev"
fol self default 0.2.1 # set the default toolchain
fol self list # show installed toolchains, default marked
fol self remove 0.2.1 # delete a toolchain (or a link)
fol self which # print the folc the current directory resolves to
See Installing & Developing for the day-to-day flows and Versions In Depth for the dispatch mechanics.
Installing & Developing
Getting fol
fol is the only binary you install by hand — everything else it fetches
itself. Take the fol-v<version>-<target> asset from a release, drop it on
your PATH, and set your home:
$ curl -fL -o ~/.local/bin/fol \
https://github.com/fol-lang/fol/releases/download/v0.2.6/fol-v0.2.6-x86_64-linux
$ chmod +x ~/.local/bin/fol
$ export FOL_HOME="$HOME/.fol" # add to your shell profile
From that moment a plain fol code run inside any pinned project fetches the
right toolchain automatically. To install one ahead of time:
$ fol self install 0.2.1
fetched fol 0.2.1 -> ~/.fol/toolchains/v0.2.1
$ fol self default 0.2.1
default toolchain is now 0.2.1
Every download is verified before it is unpacked: fol fetches the release’s
SHA256SUMS-<target> alongside the tarball and refuses to extract on a
mismatch or when no checksums are published. There is no opt-out.
An install is also atomic. The new toolchain is staged beside its destination
and swapped into place only after all three payloads (folc, std/,
runtime/) are present, so a failed or interrupted install leaves the previous
toolchain exactly as it was.
Prefer keeping everything project-local? Skip FOL_HOME entirely — inside a
project the manager uses <project>/.fol/toolchain as its home, so the
toolchain sits beside the project’s build outputs and nothing global exists.
Working on FOL itself
A source checkout becomes a first-class toolchain through a link — no copying, always fresh:
$ fol self link dev ~/code/fol
linked toolchain 'dev' -> /home/you/code/fol
$ fol self default dev
A linked toolchain resolves its folc from the checkout’s
target/release/folc or target/debug/folc — whichever was built most
recently — and its std and runtime straight from the live source tree.
Rebuild the compiler, and every fol invocation immediately uses it.
fol self link also accepts --bin <path> and --std <path> when the binary
or the standard library lives somewhere other than the checkout defaults.
To freeze a source build into a normal, immutable toolchain instead (useful for testing the install flow offline):
$ cargo build --release --bin folc && cargo build --release -p fol-self
$ fol self install 0.2.2 --from .
installed fol 0.2.2 -> ~/.fol/toolchains/v0.2.2 (from /home/you/code/fol)
Releasing
Pushing a v* tag runs the release workflow, which builds folc and fol
on every supported Linux target, stages {folc, std/, runtime/}, and uploads:
fol-compiler-and-lib-v<version>-<target>.tar.gzfol-v<version>-<target>
The tarball layout is a contract: fol self install unpacks it verbatim into
$FOL_HOME/toolchains/v<version>/, and an integration test pins the workflow
to that layout.
Versions In Depth
Why versions coexist cleanly
Each $FOL_HOME/toolchains/v<version>/ directory is a closed world:
folc— the engine binary for that exact language version.std/— the standard library sources that version was released with.folcfinds them next to its own binary, so a v0.2.1 engine can never accidentally compile against a v0.4.0 standard library.runtime/— the runtime crate sources.folcemits Rust and compiles it against this crate; shipping it inside the toolchain is what makes the directory self-sufficient on a machine that has no FOL checkout.
Because nothing inside a toolchain references anything outside it, installing,
removing, or switching versions can never corrupt another version. The shared
parts of the home — pkg/ for third-party packages and config for the
default — are version-independent by design: packages are source, so every
toolchain compiles them itself. A build only ever reads $FOL_HOME/pkg;
fetches write into the project, so one project cannot corrupt the store another
version relies on.
Dispatch mechanics
fol decides which engine runs before any engine code executes:
fol [+<toolchain>] <anything else> …
│
├─ `self …`? → handled by the manager itself, never forwarded
│
├─ resolve: +arg → FOL_TOOLCHAIN → //fol pin → config default
│ (a pinned version that is missing is fetched now)
│
└─ exec $FOL_HOME/toolchains/v<X>/folc <anything else> …
The manager passes your arguments through verbatim and replaces itself with
folc (exec), so there is no wrapper process at runtime. A recursion guard
(FOL_DISPATCHED) makes a mis-installed toolchain fail loudly instead of
looping.
Help and version flags are forwarded too: fol --help shows the engine’s
help for the toolchain your project resolves to, which is why the commands you
see always match the version you are actually running. Only when nothing is
installed yet does the manager print its own copy of the help, with a hint to
fol self install.
Per-project toolchains in practice
Two projects on one machine, different language versions, zero ceremony:
$ head -1 ~/work/legacy/build.fol
//fol 0.2.1
$ head -1 ~/work/greenfield/build.fol
//fol 0.4.0
$ cd ~/work/legacy && fol code build # runs the v0.2.1 engine
$ cd ~/work/greenfield && fol code build # runs the v0.4.0 engine
Editors get the same guarantee for free: the language server is started as
fol tool lsp, so it goes through the same resolution and always matches the
compiler that builds the project.
One-shot overrides
$ fol +0.4.0 code build # try a newer engine without touching the pin
$ FOL_TOOLCHAIN=dev fol code test # a whole shell session on the dev link
$ fol self which # show which folc the current directory gets
Overview
This opening section explains what FOL is, how this book is organized, and how syntax examples are written.
Use it before diving into the detailed lexical, type, item, and runtime chapters.
It also describes the user-facing workflow tool and the first editor-tooling surface before the language chapters begin.
Notation And Conventions
This book is the language specification for FOL.
It is written as a spec first:
- examples describe intended language behavior
- implementation status may lag behind the book
- when code and prose disagree, the disagreement should be resolved explicitly
Reading Syntax Examples
The examples in this book follow a few conventions.
- Keywords are written literally:
funprotypuse
- Punctuation is written literally:
()[]{}:=
- Placeholder names are descriptive:
nametypeexprbodysource
For example:
fun[options] name(params): return_type = { body }
means:
funis a literal keywordoptionsis a placeholder for zero or more routine optionsnameis the declared routine nameparamsis a parameter listreturn_typeis a type referencebodyis a routine body
Spec Vocabulary
The book uses the following terms consistently:
- declaration: a top-level or block-level form that introduces a named entity
- statement: an executable form that appears in a block
- expression: a form that produces a value
- type reference: a syntactic reference to a type
- type definition: a declaration form that creates a new named type
- source kind:
an import/source locator family; the current public kinds are
locandpkg
Runtime Capability Convention
Examples in this book do not repeat a complete build.fol beside every source
snippet. Read their runtime requirements using this mapping:
fol_model = "core"selects the no-heap, no-source-level-hosted-API modefol_model = "memo"adds heap-backed values such asstr,vec,seq,set, andmap, but still does not expose hosted APIs- a package whose
memoartifact needs shipped hosted APIs declaresbuild.add_dep({ alias = "std", source = "internal", target = "standard" })and imports that alias withuse std: pkg = {"std"};
std is not an accepted fol_model value, and it is not an import source kind.
Bundled std is an explicit dependency that widens the source-visible API tier
of a memo artifact; it is not a third artifact model.
An example that calls .echo(...), a std::io routine, or a V3 processor
construct therefore assumes memo plus that explicit bundled dependency.
Examples that only use core or memo facilities do not need std merely
because they produce an executable.
Execution is a separate tool concern. graph.add_run, graph.add_test,
fol code run, and fol code test do not grant hosted APIs and do not require
bundled std. They may execute a core or memo artifact when its selected
target is compatible with the build host. A foreign target is buildable, but
the current frontend rejects running or testing it because FOL does not yet
provide a cross-target runner configuration.
Examples vs Grammar
Examples are illustrative, not exhaustive.
When a chapter gives one or two examples, that does not imply the syntax is limited to only those exact spellings. The normative rule is the chapter text plus the grammar intent described there.
Terminology Preferences
This book prefers the following terms:
- routine:
umbrella term for
fun,pro, andlog - record: named field-based type
- entry: named variant-based type
- standard: protocol/blueprint/extension-style contract surface
- module:
namespace/package surface addressed through
use,def, orseg
Status Notes
Some older chapters still use inconsistent wording inherited from earlier drafts.
During cleanup, the following principles apply:
- keep examples unless they are contradictory
- prefer clarifying rewrites over removal
- keep the chapter tree stable where possible
- make chapter indexes explain scope before detail
Frontend Workflow
A frontend layer sits above the compiler pipeline. It is implemented in
fol-frontend and shipped as the folc engine, which the fol manager
dispatches to (see Toolchain Management).
The frontend owns:
- workflow commands: project/workspace setup, fetch and update flows, build/run/test/emit
- direct single-file compile dispatch
- root help and output rendering
- frontend diagnostics
- editor tooling dispatch under
fol tool
Use this page as an entrypoint pointer; the detailed reference lives in the Tooling section:
Current Boundary
The current frontend milestone is about local workflows and the first backend.
It already covers:
- project and workspace scaffolding
- documented
build.folpackage entry files for new projects - root discovery
- package preparation through
fol-package - git-backed dependency fetching and materialization
fol.lockwriting, locked fetches, offline warm-cache fetches, and update flows- workspace dependency/status reporting
- build/run/test orchestration for shipped
V1, the boundedV2subset, and the shippedV3surfaces - routed workspace
build/run/test/checkentry throughbuild.fol - emitted Rust and lowered IR output
- editor-tooling entrypoints for parse, highlight, symbols, and LSP startup
- shell completions
- safe cleanup of build/cache/git/package-store roots
- frontend-owned direct compile routing
Future work is still expected around:
- richer package-store policy beyond the current read/write chains
- lockfile/version solving beyond the current pinned git contract
- additional backend targets
Editor Tooling
FOL now has a dedicated editor-tooling crate:
fol-editor
It owns:
- Tree-sitter assets for syntax/highlighting/query work
- the language server for compiler-backed editor services
- build-file affordances for
build.folthrough the same parse/highlight/symbol and LSP surfaces used for ordinary source files - one public editor command surface under
fol tool ...
The detailed operational reference now lives in the Tooling section:
Use this page as the overview pointer, not the full reference.
Tooling
FOL now has a real tooling layer above the compiler.
That layer is split into:
- the
folfrontend workflow tool - editor-facing tooling under
fol tool ...
Use this section for:
- creating and organizing projects
- fetching and updating packages
- building, running, testing, and emitting artifacts
- understanding the editor stack
- integrating FOL with Neovim
The overview chapter only introduces the existence of these pieces.
This section is the detailed operational reference.
Frontend Workflow
The public FOL entrypoint is the fol tool, which dispatches to the versioned
folc engine (see Toolchain Management).
The engine is implemented by the fol-frontend crate. It sits above:
fol-packagefol-resolverfol-typecheckfol-lowerfol-backend
Its job is orchestration, not semantic analysis.
What The Frontend Owns
The frontend owns:
- CLI parsing (hand-rolled, no argument-parser dependency)
- grouped command structure
- package and workspace discovery
- project scaffolding
- package preparation and fetch/update workflows
- build, run, test, and emit orchestration
- editor command dispatch under
fol tool - shell completions
- user-facing summaries and workflow errors
Bundled std reminder:
- the current binary scaffold defaults to
fol_model = "memo"and bundledstdbecause its generated source uses hostedstd.io - a bare executable may use
coreormemoand does not need bundledstd - scaffolding writes the dependency automatically when its generated source
needs
std; users should not have to repair an incomplete scaffold manually - running and testing host-compatible artifacts is frontend/toolchain behavior, not a bundled-std capability
- cross-target
run/testremain rejected until the frontend has a runner configuration, independently of the artifact’s API tier
Compiler truth remains in the compiler crates.
Public Command Groups
The root command groups are:
fol workfol packfol codefol tool
Root aliases are single-letter only:
fol wfol pfol cfol t
Run:
fol --help
fol <group> --help
fol <group> <command> --help
for the relevant usage surface.
Root Discovery
For workflow commands, the frontend discovers roots upward from the current directory or from an explicit path.
It recognizes:
- package roots via
build.fol - workspace roots via
fol.work.yaml
A package root is one buildable package.
A workspace root is a parent root that owns multiple member packages and frontend-managed roots like build/cache/package-store locations.
Direct Package Use
The normal workflow shape is group-first:
fol work init --bin
fol pack fetch
fol code check
fol code build
fol code run
There is still a frontend-owned direct package path for compile-oriented use, but the grouped commands are the public workflow shape.
Output
Frontend summaries support:
humanplainjson
The frontend also owns workflow-level errors such as:
- missing workspace roots
- fetch/update/store failures
- clean/completion/workflow command failures
Compiler diagnostics stay separate and flow through compiler-owned diagnostic models.
Tool Commands
This chapter lists the current frontend surface by workflow area.
Work
Project and workspace commands:
fol work initfol work newfol work infofol work listfol work depsfol work status
Examples:
fol work init --bin
fol work init --workspace
fol work new demo --lib
fol work info
fol work deps
Use work for:
- creating package/workspace roots
- inspecting workspace structure
- seeing member and dependency state
Scaffold reminder:
fol work init --bincreates amemobinary whose generated source uses hostedstd.io- the generated
build.folexplicitly declares bundledstdthroughbuild.add_dep({ alias = "std", source = "internal", target = "standard" }) - source code that uses bundled-library names imports that declared alias with
use std: pkg = {"std"}; - this dependency follows from the generated source using hosted APIs, not from
the package being executable; std-free
coreandmemopackages may also usefol code runandfol code test
Pack
Package acquisition commands:
fol pack fetchfol pack update
Examples:
fol pack fetch
fol pack fetch --locked
fol pack fetch --offline
fol pack fetch --refresh
fol pack update
Use pack for:
- materializing dependencies
- writing or honoring
fol.lock - refreshing pinned git dependencies
Code
Build-oriented commands:
fol code checkfol code buildfol code runfol code testfol code emit rustfol code emit loweredfol code explain <CODE>
Examples:
fol code check
fol code build --release
fol code run -- --flag value
fol code emit rust
fol code emit lowered
fol code explain T1003
Use code for:
- driving the compile pipeline
- building binaries through the current Rust backend
- running produced binaries
- emitting backend/debug artifacts
- explaining a diagnostic code emitted by
fol code check
Capability vs execution
fol code run and fol code test evaluate build.fol, select the requested
artifact or step, compile it, and launch it when its target is compatible with
the host. That tool action is not a source capability:
coreandmemoartifacts can run and test without bundledstd- declaring bundled
stdonly makes hosted source APIs available to amemoartifact; it does not grant execution permission - the compiler still rejects heap-backed or hosted APIs that exceed the artifact’s evaluated capability contract
- a foreign selected target is rejected before launch because the frontend has no cross-target runner configuration yet
graph.add_run and graph.add_test choose graph actions. They do not change
the selected fol_model.
Explain
fol code explain <CODE> prints an extended, plain-language explanation for a
diagnostic code — the same code the pretty diagnostic footer points at
(run \fol code explain T1003` for more). It pairs with fol code check`,
which emits the diagnostics it explains.
fol code explain <CODE>
Codes are accepted case-insensitively (t1003 and T1003 are the same).
Examples:
fol code explain T1003
fol code explain t1003
fol code explain --output json R1003
Output modes:
human(default): a family chip, the code, a short title, and the bodyplain:code:/family:/title:lines followed by the bodyjson/--json:{ "code", "family", "known", "title", "explanation" }
Behavior:
- known codes print their explanation and exit
0 - unknown codes print an honest “no extended explanation for
<CODE>yet” message (pointing at the code’s family when the prefix is recognized) and exit nonzero
Only diagnostic codes the compiler and runtime actually emit have
explanations. The registry lives in fol-diagnostics (compiler truth) and is
kept honest by a completeness test, so explain never documents a code that
does not exist.
Tool
Tooling commands:
fol tool lspfol tool format <PATH>fol tool parse <PATH>fol tool highlight <PATH>fol tool symbols <PATH>fol tool references <PATH> --line <LINE> --character <CHARACTER>fol tool rename <PATH> --line <LINE> --character <CHARACTER> <NEW_NAME>fol tool complete <PATH> --line <LINE> --character <CHARACTER>fol tool semantic-tokens <PATH>fol tool tree generate <PATH>fol tool cleanfol tool completion <bash|zsh|fish>fol tool abi inspect <MANIFEST>fol tool abi check --baseline <MANIFEST> --candidate <MANIFEST> [--allow-breaking]
Examples:
fol tool parse src/main.fol
fol tool format src/main.fol
fol tool highlight src/main.fol
fol tool symbols src/main.fol
fol tool references src/main.fol --line 12 --character 8
fol tool rename src/main.fol --line 12 --character 8 total
fol tool semantic-tokens src/main.fol
fol tool tree generate /tmp/fol
fol tool lsp
fol tool completion bash
fol tool abi inspect prefix/share/fol/abi/libname.folabi.json
fol tool abi check --baseline abi/baseline.folabi.json --candidate .fol/install/share/fol/abi/libname.folabi.json
Reading and comparing an ABI surface
fol tool abi inspect prints what one installed manifest says a library’s C
surface is: every exported symbol with its C parameter and result types, its
error contract, and both fingerprints.
fol tool abi check compares a candidate manifest against a checked-in
baseline and reports one of four outcomes:
| Outcome | Exit | Meaning |
|---|---|---|
| unchanged | 0 | the public surface is byte-identical |
| unchanged, build fingerprint moved | 0 | a compiler or profile change, not an ABI event |
| compatible | 0 | existing symbols unchanged; the candidate only adds |
| breaking | 1 | a symbol, type, layout, or error rule changed |
| target mismatch | 1 | the two describe different targets, so no comparison means anything |
A break is accepted only with --allow-breaking, which says the ABI major is
being incremented on purpose. A target mismatch is never accepted that way: the
flag means “this break is intended”, and a mismatch is not a break to intend.
Neither command needs a package root or compiles anything — an installed prefix and an extracted release archive are where they are useful, and neither has a source tree. Both read through the manifest’s own fingerprints, so a hand-edited file is refused rather than reported on.
Use tool for:
- editor integration
- Tree-sitter debugging
- LSP serving
- generated tool assets
Shell Completion
fol tool completion <bash|zsh|fish> writes the completion script to stdout and
nothing else, so it can be sourced directly. The script registers both fol and
folc.
# bash: source it for the current session
eval "$(fol tool completion bash)"
# or install it
fol tool completion bash > ~/.local/share/bash-completion/completions/fol
# zsh: install into a directory on $fpath
fol tool completion zsh > ~/.zfunc/_fol
fol tool completion fish > ~/.config/fish/completions/fol.fish
With --output json the script is carried in the envelope’s payload field
instead, alongside command and summary.
Parse And Query Results
parse, highlight, and symbols execute the checked-in generated FOL
Tree-sitter parser in-process. They do not estimate results from source text or
report the contents of query files as if those were matches.
fol tool parse <PATH> reports:
parse_status=okfor a tree with noERRORor missing nodes, otherwiseparse_status=ERROR- root kind plus total and named node counts
- exact
error_countandmissing_countvalues - one zero-based source range and escaped source excerpt for every error or missing node
- the real Tree-sitter S-expression as
syntax_tree=...
The command is error-tolerant: a source file with invalid syntax still produces
its recovered tree and exits through the normal command-result path, with the
unparseable region reported as an ERROR node.
fol tool highlight <PATH> runs queries/fol/highlights.scm against that tree
and reports the actual capture count, capture kinds, and every capture as:
capture=<name>@<start-row>:<start-column>-<end-row>:<end-column>:<text>
fol tool symbols <PATH> runs queries/fol/symbols.scm, reports the actual
symbol and scope counts, and reports each non-scope capture in the equivalent
symbol=<name>@...:<text> form. Rows and columns are zero-based. Backslashes,
tabs, carriage returns, and newlines in excerpts are escaped.
These three normal commands need no external tree-sitter executable. The
external CLI is required only by fol tool tree generate, which regenerates an
exportable parser bundle.
The public editor surface stays under fol tool ....
There is no parallel fol editor ... command group.
Future editor features are not exposed as placeholder commands.
Only the shipped fol tool subcommands above are public.
Artifact Reporting
Frontend commands report explicit artifact roots when applicable, including:
- emitted Rust crate roots
- lowered snapshot roots
- final binary paths
- fetch/store/cache roots where relevant
Editor Tooling
FOL editor support lives in one crate:
fol-editor
That crate owns two related subsystems:
- Tree-sitter assets for syntax-oriented editor work
- the language server for compiler-backed editor services
Public Entry
The public entrypoints are exposed through fol tool:
fol tool lspfol tool format <PATH>fol tool parse <PATH>fol tool highlight <PATH>fol tool symbols <PATH>fol tool references <PATH> --line <LINE> --character <CHARACTER>fol tool rename <PATH> --line <LINE> --character <CHARACTER> <NEW_NAME>fol tool semantic-tokens <PATH>fol tool tree generate <PATH>fol tool cleanfol tool completion [bash|zsh|fish]
This keeps editor workflows under the same fol binary rather than introducing
a second public tool.
Split Of Responsibilities
Tree-sitter is the editor syntax layer.
It is responsible for:
- syntax trees while typing
- query-driven highlighting
- locals and symbol-style structure captures
- editor-facing structural parsing
The language server is the semantic editor layer.
It is responsible for:
- JSON-RPC/LSP transport
- open-document state
- compiler-backed diagnostics
- hover
- go-to-definition, go-to-type-definition, and go-to-implementation
- current-document symbol highlights
- whole-document formatting
- code actions for exact compiler suggestions The current shipped inventory is intentionally one diagnostic family: unresolved-name replacements where the compiler attached an exact replacement.
- signature help for plain and qualified routine calls
- references
- prepare-rename and rename for same-file local bindings, routine parameters, and current-package top-level symbols
- semantic tokens
- inferred-type inlay hints
- brace-block folding ranges and word/block/file selection ranges
- document symbols
- workspace symbols across discovered
.folfiles under the mapped workspace root - completion and completion-item resolve
These general editor services cover the implemented V1 contract and the checked-in shipped V2 and V3 example matrices. The exact capability list and version-bounded semantic expectations live in Language Server.
The server keeps diagnostics and semantic snapshots separately.
Formatting is intentionally whole-document only right now.
textDocument/rangeFormatting stays unsupported until there is a safe
structure-preserving boundary instead of a partial line-rewriter.
The current formatter contract is intentionally narrow but explicit:
- indentation is four spaces per brace depth
- ordinary code lines are trimmed before indentation is re-applied
- braces inside cooked/raw quotes or any compiler-recognized comment form do not affect indentation depth
- multiline quote/comment payload lines retain their original content
- outside protected multiline payloads, leading blank lines are removed, repeated blank lines collapse to one, and trailing blank lines are removed
- output always ends with one final newline when the document is non-empty
- line endings are normalized to
\n build.folfollows the same formatter entrypoint and indentation rules as ordinary source files
Diagnostics refresh on didOpen and didChange.
Semantic requests keep one semantic snapshot per open document version and reuse it for hover, definition, type definition, implementation, document highlight, signature help, references, prepare rename, rename, semantic tokens, document/workspace symbols, completion, inlay hints, folding ranges, and selection ranges until the document changes or closes.
Compiler Truth
fol-editor does not create a second semantic engine.
Semantic truth still comes from:
fol-packagefol-resolverfol-typecheckfol-diagnostics
So the model is:
- Tree-sitter answers “what does this text structurally look like?”
- compiler crates answer “what does this code mean?”
For the current maintenance contract between compiler crates, LSP behavior, and Tree-sitter assets, see:
Current Practical Workflow
Use:
fol tool lsp
fol tool format path/to/file.fol
as the language server entrypoint.
Launch it from inside a discovered package or workspace root. The frontend
looks upward for build.fol or fol.work.yaml before starting the server.
Use:
fol tool parse path/to/file.fol
fol tool highlight path/to/file.fol
fol tool symbols path/to/file.fol
fol tool format path/to/file.fol
fol tool references path/to/file.fol --line 12 --character 8
fol tool rename path/to/file.fol --line 12 --character 8 total
fol tool semantic-tokens path/to/file.fol
for parser/query debugging and validation.
The three Tree-sitter inspection commands use the checked-in generated parser and execute queries in-process:
parsereturns the real S-expression, node counts, and recoveredERROR/missing-node rangeshighlightexecutes the shipped highlight query and returns every actual capture with its zero-based range and source textsymbolsexecutes the shipped symbol query and returns every actual symbol capture plus the number of captured scopes
All three include parse_status=ok or parse_status=ERROR. Syntax errors do
not prevent inspection of the recovered tree, so dead syntax examples can be
used to verify that a removed form still produces an ERROR node. The normal
inspection path does not shell out to the Tree-sitter CLI; only bundle
generation does.
Compiler Integration
This chapter explains how the compiler and editor tooling are connected today, and what should remain the source of truth as FOL grows.
The Three Layers
FOL editor tooling is split into three layers:
- compiler truth
- semantic editor services
- syntax editor services
Compiler truth lives in crates such as:
fol-lexerfol-parserfol-packagefol-resolverfol-typecheckfol-intrinsicsfol-diagnostics
Semantic editor services live in:
fol-editorLSP analysis and semantic code
Syntax editor services live in:
- the Tree-sitter grammar
- Tree-sitter query files
- editor bundle generation
That split matters because not every editor feature should be solved in the same way.
What The LSP Should Trust
For semantic meaning, the LSP should trust the compiler pipeline.
That means:
- diagnostics come from compiler diagnostics
- hover should be derived from resolved or typed compiler state
- definition should be derived from resolved symbol data
- document symbols should prefer compiler symbol ownership where practical
- completion should prefer compiler facts over text heuristics
- effective capability comes from the evaluated artifact
fol_modelplus any active bundled-standard dependency, not from whether a run/test command was requested
The LSP should not invent a parallel semantic model.
If a feature needs semantic meaning, the first question should be:
- can this come from
fol-parser/fol-resolver/fol-typecheckinstead of editor-only code?
What Tree-sitter Should Trust
Tree-sitter is not the compiler parser.
It exists for:
- syntax trees while typing
- highlighting
- locals queries
- symbol-style structural captures
- future textobjects and editor movement
So Tree-sitter should stay editor-oriented.
That means:
- the grammar can remain handwritten
- query files can remain handwritten
- but duplicated language facts should not be copied manually forever
Examples of facts that should come from compiler-owned truth:
- builtin type spellings
- implemented intrinsic names
- import source kinds
- keyword families used by syntax tooling
How Diagnostics Flow
Today the intended direction is:
- compiler stage creates a structured
fol_diagnostics::Diagnostic - editor tooling adapts that diagnostic for the active editor protocol
- the editor displays the adapted result
The important rule is:
- the compiler diagnostic object is canonical
So when diagnostic wording, labels, helps, or codes change, the editor should adapt that same structure. It should not create its own free-form diagnosis logic.
What Can Be Generated
Generation is useful when the same language fact appears in multiple places.
Good generation targets:
- keyword manifests
- builtin type manifests
- intrinsic name/surface manifests
- source-kind manifests
- small generated query fragments or validation snapshots
Bad generation targets:
- the entire Tree-sitter grammar
- Tree-sitter precedence/conflict structure
- most highlight policy
- LSP transport behavior
The rule of thumb is:
- generate shared facts
- handwrite editor behavior
What To Update For A New Feature
When you add a new language feature, ask these questions in order:
- Does the lexer need new tokens or token families?
- Does the parser need new syntax or AST nodes?
- Does resolver or typechecker logic need new meaning?
- Do lowering, runtime, or backend transfer/execution rules change?
- Does frontend artifact routing or capability evaluation change?
- Does the feature introduce or change diagnostics and explanations?
- Does the formatter or a public
fol toolinspection command need an update? - Does the LSP need hover, completion, definition, symbols, tokens, positions, or artifact-scope updates?
- Does Tree-sitter need grammar, query, or executable corpus updates?
- Can any new editor-visible facts be generated from compiler-owned sources?
- Do canonical positive/failure inventories, docs, or book claims change?
If the answer to any of those is yes, update that layer in the same change set.
End-To-End Feature Completeness
Compiler-backed editor analysis prevents semantic duplication, but it does not make the other mirrors automatic. A shipped feature is complete only when its meaning survives:
- lowering and runtime/backend execution
- frontend artifact selection and capability routing
- structured CLI diagnostics, explanations, and LSP adaptation
- whole-document formatting and public parse/highlight/symbol commands
- explicit LSP UX such as completion, tokens, navigation, and position mapping
- Tree-sitter grammar, highlight/locals/symbol queries, and executable corpus
- canonical positive/failure examples, integration tests, docs, and the book
For V3 specifically, this rule covers every ownership, borrow, pointer, dfr /
edf, spawn, channel, select, mux[T], async, and await boundary. Reusing the
typechecker is necessary, but it is not permission to skip an explicit syntax,
tooling, inventory, or documentation audit.
Runtime-model synchronization must preserve two independent questions across all of those layers:
- does this source stay within its evaluated
core,memo, or hosted (memoplus bundledstd) API tier? - can the frontend execute the selected target on this host (or through a future configured runner)?
The first is compiler-owned capability truth. The second is frontend execution
routing. Neither the LSP nor Tree-sitter should infer hosted source permission
from graph.add_run, graph.add_test, fol code run, or fol code test.
Current Practical Rule
In FOL today:
- compiler crates own meaning
fol-editorowns editor protocol behavior- Tree-sitter owns syntax-oriented editor structure
The safer future direction is:
- move shared contracts closer to compiler-owned crates
- keep protocol/UI code in tooling crates
- generate duplicated facts instead of hand-copying them
Tree-sitter Integration
The Tree-sitter side of FOL is the editor-facing syntax layer.
It is not the compiler parser.
What Is In The Repo
The editor crate carries:
- the grammar source
- executable corpus cases with expected syntax trees
- a raw showcase fixture kept outside the corpus directory
- query files on disk
Canonical query assets live as real files, not just embedded Rust strings:
queries/fol/highlights.scmqueries/fol/locals.scmqueries/fol/symbols.scm
This is intentional because editors such as Neovim expect query files on disk in the standard Tree-sitter layout.
The checked-in generated C parser is also compiled into fol-editor. Therefore
fol tool parse, fol tool highlight, and fol tool symbols use the same
parser and query assets directly in-process. Their reported trees, captures,
symbols, scopes, and ERROR nodes are runtime results, not grammar/query byte
counts or source-text approximations. These inspection commands do not require
an external Tree-sitter installation.
Generated Bundle
To generate a Neovim-consumable bundle, run:
fol tool tree generate /tmp/fol
That writes a bundle containing the grammar, query assets, executable corpus
cases, and test/fixtures/showcase.fol under the target directory. The
showcase is intentionally a raw .fol fixture rather than a corpus case.
Generated file ownership is recorded in .fol-tree-generated: later runs
remove retired manifest-owned assets while preserving files the user added to
the destination. Unsafe absolute or parent-traversing manifest entries are
rejected rather than removed. The generator also rejects a symlink at the
destination root or anywhere along a managed asset path, so generated writes
and retired-file cleanup cannot escape the selected bundle root.
Generation and parser validation happen in a temporary staging directory. Only a complete bundle is committed to the destination; a generator or commit failure leaves an existing bundle unchanged, including its ownership manifest and retired assets.
Bundle generation is the one public Tree-sitter command that invokes the
external tree-sitter CLI. The checked-in parser used by ordinary inspection
commands remains available without that executable.
The grammar is generated from Rust
The grammar rules live in lang/tooling/fol-editor/src/grammar.rs and render directly to Tree-sitter’s JSON input format (tree-sitter/src/grammar.json). There is no grammar.js and no JavaScript anywhere in this pipeline: Tree-sitter’s own input format is JSON, and grammar.rs constructs and serializes that JSON directly in pure Rust.
Nothing in FOL needs Node. Not building, not testing, not the editor, not consuming a generated bundle. src/parser.c is not checked in: fol-editor’s build.rs generates $OUT_DIR/src/grammar.json from src/grammar.rs, runs the pinned tree-sitter generate into the build’s output directory, and compiles the result with cc, so the tree-sitter CLI (0.26, from the dev shell) is a build dependency. tree-sitter/src/grammar.json stays checked in as a synced generated artifact for editors and external Tree-sitter tooling, and tests fail if it drifts from src/grammar.rs. Regenerating by hand is JS-free too:
FOL_GRAMMAR_UPDATE=1 cargo test -p fol-editor checked_in_grammar_json_matches_generated_output
tree-sitter generate src/grammar.json
fol tool tree generate <dir> runs the same pipeline inside a staging directory.
Editing the grammar
Rules are Rust combinator calls (seq, choice, opt, rep, rep1, field, prec_left, prec_right, s, pat, sym) inside lang/tooling/fol-editor/src/grammar.rs. A new rule needs two edits in src/grammar.rs: the g.rule(...) definition and a reference to it from wherever it should be reachable (expr_atom for an expression form).
After editing src/grammar.rs:
- Refresh the checked-in
grammar.jsonwithFOL_GRAMMAR_UPDATE=1 cargo test -p fol-editor checked_in_grammar_json_matches_generated_output(orfol tool tree generate). - Verify corpus and queries with
make tree-check.
A generation failure prints the conflict Tree-sitter could not resolve. Adding the named rule to add_conflicts in src/grammar.rs (or specifying precedence/associativity) resolves it.
The intended consumer path is:
- generate bundle
- point the editor’s Tree-sitter parser configuration at that bundle
- let the editor compile/use the parser from there
File Ownership
Intentionally Handwritten
These files are human-authored and should remain so:
| File | Purpose | Owner |
|---|---|---|
src/grammar.rs | Grammar rules, precedence, conflicts (generates tree-sitter/src/grammar.json) | Editor/syntax maintainer |
queries/fol/highlights.base.scm | Highlight capture groups and query patterns (generates highlights.scm) | Editor/syntax maintainer |
queries/fol/locals.scm | Scope and definition tracking | Editor/syntax maintainer |
queries/fol/symbols.scm | Symbol navigation captures | Editor/syntax maintainer |
test/corpus/*.txt | Corpus programs plus their expected node trees | Editor/syntax maintainer |
Do not attempt to generate these from the compiler parser. The parsing models are different and auto-generation creates more fragility than value.
Validated Against Compiler Constants
These facts appear in handwritten files but are validated by integration tests to stay in sync with compiler-owned constants:
| Fact | Handwritten Location | Compiler Source |
|---|---|---|
| Builtin type names | highlights.scm regex ^(int|bol|...)$ | BuiltinType::ALL_NAMES in fol-typecheck |
| Dot-call intrinsic names | highlights.scm regex ^(len|echo|...)$ | Implemented DotRootCall entries in fol-intrinsics |
| Container type names | highlights.scm node labels + grammar.json choice | CONTAINER_TYPE_NAMES in fol-parser |
| Shell type names | highlights.scm node labels + grammar.json choice | SHELL_TYPE_NAMES in fol-parser |
| Source kind names | highlights.scm node labels + grammar.json choice | SOURCE_KIND_NAMES in fol-parser |
The sync tests live in test/run_tests.rs under treesitter_sync. If you add
a new builtin type, intrinsic, container, shell, or source kind to the compiler,
these tests fail until the tree-sitter files are updated to match.
When To Update Tree-sitter Files
src/grammar.json
Update when:
- A new declaration form is added (e.g. a new
segorlabdeclaration) - A new expression or statement form is added
- A new type syntax is added (e.g. a new container or shell family)
- A new source kind is added
- Operator precedence or conflict rules change
Do not update for:
- New diagnostic codes or error messages
- New resolver/typecheck rules that don’t change syntax
- New intrinsics (these use existing
dot_intrinsicgrammar rule)
highlights.scm
Update when:
- A new keyword needs highlighting
- A new builtin type is added to the compiler
- A new implemented dot-call intrinsic is added
- A new container or shell type family is added
- A new source kind is added
- Highlight group policy changes (e.g. moving a keyword from
@keywordto@keyword.function)
locals.scm
Update when:
- Scope rules change (e.g. new block forms that introduce scopes)
- Definition capture patterns change
symbols.scm
Update when:
- New declaration forms should appear in document symbol navigation
Corpus fixtures
Update when:
- Any grammar rule is added or modified
- A new syntax family needs parse-tree validation
Corpus Coverage Expectations
Corpus fixtures live in tree-sitter/test/corpus/ and cover syntax families:
| Corpus File | Covers |
|---|---|
declarations.txt | use, ali, typ, fun, log, var declarations |
expressions.txt | Intrinsic calls, when/loop control flow, break/return, index and slice access |
recoverable.txt | Error propagation (/), report, pipe-or (||) |
v3_ownership.txt | owned allocation, borrow options, ~var, and give-back |
v3_pointers.txt | nested ptr[...] / chn[...] types, @ types, address-of, and dereference |
v3_deferred.txt | dfr and error-only edf blocks |
v3_channels_select_mutex.txt | spawn, channel endpoints, multi-arm select, and mux[T] parameters |
v3_eventuals.txt | spawn plus | async and | await stages |
v3_lexical_boundaries.txt | multiline backtick/slash-block comments, exact [doc], and raw single-quoted character/string boundaries |
v4_linear.txt | linear capability types and release obligations |
v4_c_import.txt | C-import handles, records, buffers, and failure routes |
v4_c_build.txt | C-import and C-export build.fol declarations |
v5_logic_proof.txt | relations, queries, logical clauses, ghost decls, theorems, tactics, clc, mutual ind, and loop measures |
v5_lawful.txt | lawful standards, default bodies, receiver theorems, qualified law proofs, and bounded law theorems |
Every file in this directory is a real Tree-sitter corpus case: the FOL source
appears before ---, and the exact expected node tree appears after it. A raw
fixture without an expected tree belongs under tree-sitter/test/fixtures/,
not under test/corpus/.
Regenerate the checked-in bundle and execute the external corpus runner with:
make tree-test
This lane fails when zero corpus cases execute, when any expected tree drifts, or when any case fails. Ordinary Rust editor tests also export the bundle to a temporary root and require the external runner to execute every registered case successfully.
When a new syntax family is added, it should have corpus coverage. The expected families that should each have at least one corpus example:
- Import declarations (
use) - Type declarations (
typ,ali) - Routine declarations (
fun,log) - Variable declarations (
var) - Control flow (
when,loop,case,break,return) - Expressions (binary, call, field access, dot intrinsic)
- Container and shell types
- Record and entry types
- Error handling (
report, pipe-or,check) - V3 ownership and pointer sigils in both expression and nested type positions
- V3 deferred blocks (
dfr/edf) - V3 processor syntax (
[>],chn[...], channel endpoints,select,mux[T],\| async, and\| await) - compiler-recognized lexical protection boundaries, especially multiline comments and raw single-quoted literals containing V3 sigils or braces
Tree-sitter keeps the compiler lexer’s four comment classes visible: ordinary
backtick, exact `[doc]...` documentation comments, //, and non-nested
/* ... */. Backtick, documentation, and slash-block comments may span lines.
Single quotes remain raw: backslashes do not introduce escapes, one Unicode
scalar is a character, and empty or multi-scalar payloads are raw strings.
What Tree-sitter Is For
Use the Tree-sitter layer for:
- highlighting
- locals and capture queries
- symbol-style structural views
- editor textobjects and movement later
Do not use it as a substitute for typechecking or resolution.
Those remain compiler tasks.
In particular, tree-sitter does not decide whether a unique-pointer field can
be dereferenced, whether a moved owner can be reinitialized in deferred work,
whether deferred cleanup may initiate report, whether a call is a legal
direct spawn/async target, whether a nested routine implicitly captures an
outer local, whether a recoverable eventual remains live across fallthrough or
an exiting break/return/report, whether await is used inside edf, or
whether mutex effects can occur inside dfr/edf. The LSP reports compiler
diagnostics for those semantic boundaries. Tree-sitter is responsible only for
the corresponding syntax shape, highlighting/query captures, and corpus
coverage. The exact positive and negative processor package matrix lives in the
shipped processor inventory.
When a language feature changes syntax, use the Feature Update Checklist to decide whether the grammar, queries, corpus, or generated language facts also need updates.
Feature Update Checklist
Use this checklist whenever a new language feature, syntax form, intrinsic, or error surface is added.
This chapter is about maintenance discipline, not just implementation order.
Quick Reference
When adding a feature, touch these layers in order:
- Lexer — new keywords, operators, tokens
- Parser — new AST nodes, syntax rules
- Semantics — resolver, typecheck, lowering, intrinsics
- Runtime/backend — representation, transfer, cleanup, execution
- Frontend/build routing — artifact model, active dependencies, command legality
- Diagnostics — codes, explanations, labels, related sites
- Formatter/tool commands — protected text, parse/highlight/symbol output
- LSP — hover, completion, definition, symbols, positions
- Tree-sitter — grammar, queries, corpus
- Generated facts and inventories — compiler-owned constants, exact examples
- Docs and book — language chapters, tooling pages, boundary claims
- Tests and examples — unit, integration, editor, corpus, positive/failure packages
Automated guards exist for some of these. The treesitter_sync integration
tests verify that highlights.scm matches compiler-owned constants for builtin
types, intrinsic names, container/shell types, and source kinds. Adding a new
constant to the compiler without updating Tree-sitter will fail those tests.
1. Lexical Surface
Check:
- new keywords
- new operators or punctuation
- new literal/token families
- comment or whitespace effects
Update:
fol-lexer- lexical docs under
100_lexical - any generated keyword/facts manifest if one exists
2. Parser Surface
Check:
- new declarations
- new expressions
- new statement forms
- new type forms
- new precedence or ambiguity rules
Update:
fol-parser- parser tests
- Tree-sitter grammar if the syntax is editor-visible
- Tree-sitter corpus fixtures for the new syntax family
3. Semantic Surface
Check:
- name resolution
- type checking
- lowering
- intrinsic availability
- runtime/backend impact
Update:
fol-resolverfol-typecheckfol-lowerfol-intrinsics- runtime/backend crates if needed
4. Runtime And Backend Surface
Check:
- lowered representation and ownership-transfer mode
- runtime type or helper requirements
- cleanup/drop behavior on normal, error, branch, loop, and task paths
- capability-tier imports and backend emission
- executable behavior for every supported positive form
Update:
fol-lowerfol-runtimefol-backend- emitted-code and end-to-end execution tests
5. Frontend And Build Routing
Check:
- artifact source scope and selected
fol_model - evaluated conditional dependencies and bundled-standard aliases
- direct, workspace, and named-step routes
- language API legality versus host target compatibility for
run/test - no accidental bundled-std requirement merely because an artifact executes
- ambiguous mixed-model files and packages
Update:
fol-build/fol-packagewhen graph truth changesfol-frontendrouting and command behavior- editor workspace mapping when analysis scope changes
- direct, routed, mixed-model, and conditional-build integration tests
Important rule:
- use the evaluated artifact contract as the authority
- do not reconstruct capability truth from static
build.foldeclarations - do not fall back from an ambiguous mixed-model file to a wider model
6. Diagnostics Surface
Check:
- new error cases
- new warning/info cases
- changed wording for existing rules
- changed labels, notes, helps, or suggestions
Update:
- compiler producer diagnostics
fol-diagnosticscontract tests- editor/LSP diagnostic adapter tests if the visible shape changes
- docs under
650_errorsif behavior changed materially
7. Formatter And Tool Commands
Check:
- whether new syntax changes indentation or structural scanning
- whether comments, cooked strings, raw strings, or character literals may contain the new syntax without affecting formatting
- whether
fol tool parse,highlight, orsymbolsexpose the new shape - whether command output, exit status, and parse-error recovery remain honest
Update:
- the shared compiler-aware source scanner before adding command-specific textual heuristics
- whole-document formatter tests
- in-process parser/query command tests
- public tool-command documentation
8. LSP Surface
Check:
- hover content
- go-to-definition behavior
- document symbols
- completion
- open-document analysis behavior under broken code
- semantic tokens, signature/type information, and rename eligibility
- UTF-16 position conversion for incoming and outgoing ranges
- related diagnostic URIs and multi-file locations
- active artifact scope and capability-aware suggestions
Update:
fol-editorsemantic analysisfol-editorsemantic display helpers or compiler-owned helpers they consume- LSP tests
Important rule:
- prefer compiler-backed meaning
- use fallback heuristics only when the compiler cannot supply semantic data yet
9. Tree-sitter Surface
Check:
- syntax shape visible while typing
- highlight groups
- locals captures
- symbols captures
- corpus examples
Update:
tree-sitter/src/grammar.jsonqueries/fol/highlights.scmqueries/fol/locals.scmqueries/fol/symbols.scmtree-sitter/test/corpus/*.txt
Important rule:
- Tree-sitter is for syntax-facing editor behavior
- it does not replace compiler semantics
10. Generated Facts And Inventories
Check whether the feature adds a new fact that should be exported once instead of copied by hand.
Examples:
- intrinsic names
- builtin type names
- source kinds
- keyword groups
- shell/container family names
- positive and negative example package directories
If yes:
- update the compiler-owned source
- regenerate editor-facing artifacts from that source
- do not patch multiple copies manually
- update the canonical shared example inventory and its published book matrix together; do not create a private LSP-only list
11. Documentation
Update:
- the language chapter for the feature
- tooling docs if editor behavior changes
- diagnostics docs if compiler reporting changes
- examples/fixtures that demonstrate the preferred form
12. Tests And Examples
Add or update:
- compiler unit tests
- integration tests
- editor/LSP tests if semantic editor behavior changes
- Tree-sitter tests/corpus if syntax-facing behavior changes
- a runnable positive package for shipped behavior
- a
fail_*package for each deliberate boundary or removed form - the canonical inventory guard when an example directory is added, removed, or renamed
Keep the feature test in the same change as the feature.
13. Final Review Questions
Before considering the feature complete, answer:
- Is compiler meaning implemented?
- Does lowering/runtime/backend preserve that meaning on every control-flow path?
- Does frontend routing select the exact evaluated artifact capability?
- Are diagnostics coded, explained, structured, and location-correct?
- Do formatter and public tool commands understand the new syntax boundaries?
- Does the LSP reflect the meaning, model, ranges, and UX where needed?
- Does Tree-sitter reflect the syntax in grammar, queries, and executable corpus?
- Did we generate shared facts and reuse one canonical example inventory?
- Do positive examples run and deliberate boundaries fail with the expected code?
- Do docs and the book state the shipped behavior without preserving dead syntax?
Language Server
The FOL language server is started with:
fol tool lsp
It runs over stdio and is meant to be launched by editors.
Current Feature Set
The current working surface includes:
- initialize / shutdown / exit
- document open / change / close
- diagnostics
- hover
- go-to-definition
- go-to-type-definition (a value’s declared type, unwrapping optional, container, ownership/borrow, pointer, channel, and eventual shells)
- go-to-implementation (a protocol standard’s conforming types)
- document highlight (occurrences of the symbol under the cursor, current file)
- whole-document formatting
- code actions for compiler-suggested unresolved-name replacements
- signature help for plain and qualified routine calls
- references
- rename for same-file local bindings, routine parameters, and current-package top-level symbols, with prepare-rename validation
- semantic tokens
- inlay hints (inferred type for
var/lab/conbindings without an explicit annotation) - folding ranges (brace blocks)
- selection ranges (word -> enclosing block -> file)
- document symbols
- workspace symbols across discovered
.folfiles under the mapped workspace root - completion, including language-keyword suggestions and completion-item resolve
- the same compiler-backed behavior for ordinary source files and
build.fol
The general editor UX above is shared across language versions. Semantic coverage claims are deliberately bounded to the implemented V1 contract, the checked-in V2 generic-routine, generic-type, constrained-generic, and protocol-standard example subset, and the checked-in V3 memory and processor inventories. The server does not claim broad rename outside the documented safe classes, range formatting, or editor-owned semantics beyond what compiler-backed analysis supplies.
The server also does not advertise workspace/executeCommand, so it does not
emit a dead run code lens. Package execution remains the explicit
fol code run CLI path. That path still enforces compiler-owned API legality,
but bundled std is not an execution permission: host-compatible core and
memo artifacts can run without it.
That means build files should not need a separate editor mode.
build.fol goes through the same language server entrypoint as the rest of the
package.
textDocument/didChange accepts both whole-document replacements and ranged
change events. The server applies ranged changes in order against the current
in-memory document version.
The server advertises incremental text sync by default. Full-document sync remains an explicit opt-in for clients/configs that need it.
Formatting is intentionally limited to textDocument/formatting.
textDocument/rangeFormatting remains unsupported until the formatter can
preserve surrounding structure safely instead of guessing at partial blocks.
Current whole-document formatting also normalizes blank-line runs outside multiline quote/comment payloads: leading blank lines are removed and repeated blank lines collapse to one. Payload lines are preserved, and braces inside quotes or compiler-recognized comments do not affect indentation.
Where a declaration is anchored
Every position-based request resolves a symbol at the cursor, so what counts as “on” a declaration decides whether hover, go-to-definition, document highlight, go-to-implementation and the outline respond at all.
A declaration is anchored at its name, not at its leading keyword. Pointing
at Ledger in typ Ledger: rec = { ... } resolves; pointing at the typ
keyword does not. The same holds for ali, std, fun, pro, var and lab,
and each name in a multi-name declaration such as typ Alpha, Beta: int anchors
separately. Document symbols and workspace symbols report that same name range,
so a client’s outline and go-to-symbol land on the name.
This is also why textDocument/implementation answers on a protocol standard’s
own declaration — the gesture an editor performs — and not only where the
standard is named in a conformance header.
Analysis Model
The server works like this:
- receive editor request/notification
- map the open document to a package/workspace context
- materialize an analysis overlay for the in-memory document state
- run parse/package/resolve/typecheck as needed
- convert compiler results into LSP responses
Package/workspace root discovery is cached for the current session once a document directory has been mapped.
When evaluated build.fol state activates a bundled internal standard
dependency, the disposable analysis overlay materializes that dependency under
its active declared alias. Conditional declarations that are inactive for the
selected target/options do not become resolvable merely because their text is
present in build.fol. Hosted examples therefore resolve in a fresh checkout;
editor tests and users do not need to pre-populate .fol/pkg first.
The same evaluated state supplies the artifact’s core or memo contract to
compiler-backed analysis. The LSP never widens that contract because an
artifact has a run or test step: execution registration is not semantic input.
That means diagnostics and navigation are compiler-backed, not guessed from Tree-sitter alone.
For open documents, diagnostics and semantic snapshots are cached separately.
didOpen and didChange refresh diagnostics for the current in-memory text.
Hover, definition, type definition, implementation, document highlight,
signature help, references, prepare rename, rename, semantic tokens, document
symbols, workspace symbols, completion, inlay hints, folding ranges, and
selection ranges use a semantic snapshot keyed by document version
and reuse it until didChange or didClose invalidates it.
Diagnostics
Compiler diagnostics remain canonical.
The server adapts them into LSP diagnostics for the currently open document.
LSP diagnostics include the diagnostic code in the message (e.g.
[R1003] could not resolve name 'answer') so editors display the code inline.
The server removes only exact wire-identical diagnostics before publishing. Diagnostics that share a line and code but differ in range, message, severity, or related information remain visible. This catches true cross-stage duplicates without hiding distinct failures that happen to occupy one line.
Expected Behavior
If the LSP client is attached correctly, you should expect:
- source-file diagnostics in the open file
- hover on resolved symbols
- go-to-definition across current-package and imported symbols where supported
- go-to-type-definition for values with a compiler-known declared type
- go-to-implementation from protocol standards to conforming types
- current-document highlights for a resolved symbol’s declaration and uses
- whole-document formatting edits from
textDocument/formatting - code actions only when the compiler attached an exact replacement suggestion The current shipped code-action inventory is intentionally narrow: unresolved-name replacements only.
- signature help for supported routine call sites
- references for the supported symbol classes
- rename for same-file local bindings, routine parameters, and current-package
top-level symbols only, with
prepareRenameenforcing the same eligibility - semantic tokens for semantic identifier categories
- inferred-type inlay hints for unannotated
var/lab/conbindings - brace-block folding ranges and word/block/file selection ranges
- document symbols for the current file
- workspace symbols across discovered
.folfiles under the mapped workspace root - completion in ordinary source files and
build.fol, including language keyword suggestions (declaration, control-flow, literal, and diagnostic keywords from the lexer’s keyword tables) alongside resolver-backed symbols in plain positions - shipped V2 example diagnostics/navigation for:
- generic routines
- generic types
- constrained generics
- protocol standards
- current positive executable V2 example roots covered directly in editor tests:
examples/generic_type_exec_m1m2examples/generic_standard_constraint_m1m2examples/standards_protocol_m2
- compiler-backed V3 diagnostics and navigation for the checked-in ownership,
borrowing, pointer,
dfr/edf, spawn, channel,select,mux[T], async, and await examples - positive V3 roots in LSP/open/navigation inventory sweeps and
fail_mem_*/fail_proc_*roots in the guarded diagnostic inventory; the exact processor list is maintained in the shipped processor inventory - model-aware completion and semantic-token coverage for the shipped V3 type,
declaration-sigil, channel, mutex, and processor syntax, without suggesting
hosted processor surfaces in
coreor unhostedmemo
The LSP does not independently decide ownership, thread safety, channel
lifecycle, or delayed mutex effects. Those rules come from compiler analysis.
Current negative coverage includes unique-pointer field dereference without
place-aware projection IR, moved-owner reinitialization inside dfr/edf,
terminating report inside deferred cleanup, indirect stored/parameter routine
targets for spawn and async, implicit nested-routine capture of outer locals,
recoverable eventuals left live at fallthrough or an exiting
break/return/report, awaiting an eventual inside edf, and mutex field,
guard, or mux[T] forwarding effects inside deferred bodies.
If the client is attached but you see no diagnostics at all, the likely issue is not Tree-sitter. It is the LSP request/attach path.
For the compiler-owned contracts behind diagnostics and semantic editor behavior, see Compiler Integration.
Neovim Integration
Neovim integration has two separate pieces:
- Tree-sitter for syntax/highlighting/queries
- LSP for diagnostics and semantic editor features
They should be configured together, but they do different jobs.
LSP Setup
The language server command is:
vim.lsp.config("fol", {
cmd = { "fol", "tool", "lsp" },
filetypes = { "fol" },
root_markers = { "fol.work.yaml", "build.fol", ".git" },
})
vim.lsp.enable("fol")
Also ensure Neovim recognizes .fol files:
vim.filetype.add({
extension = { fol = "fol" },
})
Tree-sitter Setup
First generate a bundle:
fol tool tree generate /tmp/fol
Then point Neovim’s Tree-sitter parser config at that bundle:
local parser_config = require("nvim-treesitter.parsers").get_parser_configs()
parser_config.fol = {
install_info = {
url = "/tmp/fol",
files = { "src/parser.c" },
requires_generate_from_grammar = false,
},
filetype = "fol",
}
The query files are expected at:
/tmp/fol/queries/fol/highlights.scm/tmp/fol/queries/fol/locals.scm/tmp/fol/queries/fol/symbols.scm
Neovim also needs that bundle on runtimepath so it can find the queries.
Practical Model
Tree-sitter provides:
- highlight captures
- locals captures
- symbol-style structure queries
LSP provides:
- diagnostics
- hover
- definitions
- references
- rename for same-file local and current-package top-level symbols
- semantic tokens
- document symbols
- proof goals (
fol/goals, below), theorem hovers with the statement and the axioms a proof rests on, and tactic and lemma completion insideprf { }
So the normal editor shape is:
- Neovim opens a
.folfile - Tree-sitter handles syntax/highlighting
- Neovim launches
fol tool lsp - the server provides semantic editor features
Proof Goals
fol/goals is a server request outside the LSP specification; the server
lists it as experimental.folGoals in its capabilities. It takes the usual
text-document position and answers with the goals before the tactic under
the cursor, the same goals fol tool proof goals prints:
{
"theorem": "sample::half_sum_le",
"goals": [
{
"hypotheses": [
{ "names": "a, b", "type": "int" },
{ "names": "h", "type": "(0 <= a and a <= b) and b <= 1000000" }
],
"target": "out::holds(sample::half_sum(a, b), fun(r0: int) => r0 <= b)"
}
],
"rendered": "a, b: int\nh: (0 <= a and a <= b) and b <= 1000000\n|- out::holds(sample::half_sum(a, b), fun(r0: int) => r0 <= b)"
}
That is the goal before unf half_sum; in this package sample:
fun[exp] half_sum(a, b: int): int = {
return (a + b) / 2;
};
thm half_sum_le(a, b: int): 0 <= a and a <= b and b <= 1000000 -> half_sum(a, b) <= b = prf {
fix h;
unf half_sum;
lia;
};
Outside every theorem the result is null. The request runs the proof pass
of the package each time, so it belongs on an idle event rather than on every
cursor move. This keeps the goals of the theorem under the cursor in a
scratch window to the right, refreshed on CursorHold:
local goals = { buf = nil, win = nil }
local function show_goals()
local params = vim.lsp.util.make_position_params(0, "utf-16")
vim.lsp.buf_request(0, "fol/goals", params, function(err, result)
if err or result == nil then
return
end
if not (goals.buf and vim.api.nvim_buf_is_valid(goals.buf)) then
goals.buf = vim.api.nvim_create_buf(false, true)
vim.bo[goals.buf].filetype = "folgoals"
end
local lines = vim.split(result.theorem .. "\n\n" .. result.rendered, "\n")
vim.api.nvim_buf_set_lines(goals.buf, 0, -1, false, lines)
if not (goals.win and vim.api.nvim_win_is_valid(goals.win)) then
goals.win = vim.api.nvim_open_win(goals.buf, false, { split = "right", width = 60 })
end
end)
end
vim.api.nvim_create_autocmd("CursorHold", {
pattern = "*.fol",
callback = show_goals,
})
updatetime sets how long the cursor rests before CursorHold fires. To
show the goals in a floating window instead, pass the lines to
vim.lsp.util.open_floating_preview(lines, "text").
Debugging A Setup
Useful checks:
:echo &filetype
:lua print(vim.inspect(vim.lsp.get_clients({ bufnr = 0 })))
And from the shell:
fol tool tree generate /tmp/fol
fol tool lsp
If fol tool lsp prints nothing and waits, that is correct.
It is a stdio server, not an interactive shell command.
If the server refuses to start, check that Neovim opened the file inside a
directory tree that contains build.fol or fol.work.yaml.
Build System
FOL uses a Zig-style build model. The build specification is a normal FOL
program called build.fol. It goes through the full compiler pipeline and
is executed against a build graph IR instead of emitting backend code.
The build system lives in lang/execution/fol-build. It handles:
- graph IR construction for artifacts, steps, options, modules, and generated files
- full control flow in build programs (when, loop, helper routines)
-DCLI option passing into the build program- named step selection at the command line
Entry Point
Every buildable package must have a build.fol at its root with exactly one
canonical entry:
pro[] build(): non = {
var build = .build();
build.meta({ name = "app", version = "0.1.0" });
var graph = build.graph();
...
};
The active build context is accessed explicitly through the build-only ambient accessor:
.build()
There is no injected graph parameter anymore. .build() returns an opaque
build-only handle. Users do not name its type explicitly. Package metadata and
direct dependencies are configured through that handle, and graph work is
reached through build.graph().
Minimal Example
pro[] build(): non = {
var build = .build();
build.meta({ name = "app", version = "0.1.0" });
var graph = build.graph();
var app = graph.add_exe({
name = "app",
root = "src/main.fol",
fol_model = "core",
});
graph.install(app);
graph.add_run(app);
};
This registers package metadata, adds an executable, marks it for installation,
and binds a default run step. The artifact uses core, so its source has no
heap-backed or hosted APIs. It can nevertheless be launched with fol code run
on a compatible host; no bundled std dependency is needed just to execute it.
fol_model is an artifact capability choice. graph.add_run and
graph.add_test only register tool actions; they neither widen that capability
nor require bundled std.
What fol-build Owns
graph.rs— build graph IR (steps, artifacts, modules, options, generated files)api/— Rust-level graph mutation interfacesemantic.rs— method signatures and type info for the resolver and typecheckerstdlib.rs—BuildStdlibScope: the ambient scope injected intobuild.folexecutor/— executes the lowered FOL IR against the build grapheval/— evaluate abuild.folfrom source; entry point forfol-packageoption.rs— build option kinds, target triples, optimize modesruntime.rs— runtime representation of artifacts, generated files, step bindingsstep.rs— step planning, ordering, cache keys, execution reportscodegen.rs— system tool and codegen request typesartifact.rs— artifact pipeline definitions and output typesdependency.rs— inter-package dependency surfacesnative.rs— native (C interop) build inputs
Use this section for:
- understanding the shape of
build.fol - the full graph API reference
- control flow available inside
build.fol - build options and
-Dflags - artifact types, modules, and generated files
- dependency handles and unified output handles
Near-Term Architecture
The next build round is about extending the existing explicit surface, not replacing it.
The intended layering is:
build.add_dep({...})declares a direct dependency and returns a dependency handlebuild.export_*({...})declares the build-facing surface a package chooses to exposegraph.file_from_root(...)andgraph.dir_from_root(...)remain the typed source-path producers- broader path-oriented exports and dependency path queries sit on top of those producers instead of collapsing back into raw string paths
- dependency modes, install reporting, and system integration should become more
concrete without changing the top-level
.build()structure
This means the near-term additions should look like richer values and richer
queries on top of the current build graph, not a new manifest format and not a
public Graph or Build type.
Standalone Examples
These checked-in example packages exercise the current public build surface:
examples/build_dep_exportsexamples/build_source_pathsexamples/build_dep_modesexamples/build_described_stepsexamples/build_generated_dirsexamples/build_dep_handlesexamples/build_output_handlesexamples/build_install_prefixexamples/build_system_libexamples/build_system_tool
Runtime-model reminder:
- examples that rely on hosted language APIs such as
.echo(...)or V3 processor facilities should spellfol_model = "memo"and declare bundledstd coreandmemoexamples may be executable and use routedrun/test; they should stay free of source-level hosted API assumptions- frontend host-tool and artifact launching is separate from language capability tiering
- the current frontend has no cross-target runner configuration, so routed
run/testreject foreign targets even though those targets may be built
Bundled std reminder:
stdships with FOL underlang/library/std- packages using hosted APIs add bundled std explicitly through:
.build().add_dep({ alias = "std", source = "internal", target = "standard" }) - normal hosted-API packages should rely on the bundled shipped
std, not an external replacement package
build.fol
build.fol is a file-bound FOL compilation unit. It is the build specification
for a package.
File-Bound vs Folder-Bound
Normal FOL packages are folder-bound: every .fol file in the package folder
shares one namespace. build.fol is the one exception.
Rules for build.fol:
- It is its own compilation unit — it does not see sibling
.folfiles - It has one implicit build stdlib scope, exposing
.build()and build-only handle methods - It can define local helper
fun[],pro[], andtypdeclarations - Those local declarations are not exported to the package
- It must declare exactly one
pro[] build(): nonentry
The implicit build stdlib is the restricted API used to evaluate build.fol.
It is not the bundled source package named std, does not change an artifact’s
fol_model, and does not expose hosted language APIs to ordinary package
sources.
Compilation Pipeline
build.fol goes through the full FOL compiler pipeline:
build.fol
│
▼ stream → lexer → parser
│
▼ fol-resolver (build stdlib injected as ambient scope)
│
▼ fol-typecheck (handle types and method signatures validated)
│
▼ fol-lower (lowered IR produced)
│
▼ fol-build executor (IR executed against BuildGraph)
│
▼ BuildGraph
The compiler rejects build.fol files that reference sibling source files,
use filesystem or network APIs, or contain more than one canonical entry.
Canonical Entry
The entry must match exactly:
pro[] build(): non = {
var build = .build();
var graph = build.graph();
...
};
pro[]— procedure with no receivers- no parameters
- return type
non
The active build context is accessed explicitly through the ambient build-only accessor:
.build()
.build() returns an opaque build-only handle. The handle type is not public
language surface and should not be named explicitly in source code. Graph access
is reached through build.graph().
Missing entry, wrong signature, duplicate entries, the old injected graph
parameter form, or explicit Graph type syntax are compile errors.
Ambient Build API
The canonical build shape is:
pro[] build(): non = {
var build = .build();
build.meta({
name = "app",
version = "0.1.0",
kind = "exe",
});
build.add_dep({
alias = "json",
source = "pkg",
target = "json",
});
var graph = build.graph();
var app = graph.add_exe({
name = "app",
root = "src/main.fol",
fol_model = "memo",
});
graph.install(app);
graph.add_run(app);
};
The public layering is:
.build()for package-level build contextbuild.meta({...})for package metadatabuild.add_dep({...})for one direct dependencybuild.export_module({...}),build.export_artifact({...}),build.export_step({...}), andbuild.export_output({...})for the dependency-facing build surface this package exposesbuild.graph()for artifact and step graph work
Capability selection and dependency declaration are separate:
- each artifact selects
fol_model = "core"orfol_model = "memo"; omitting the field currently selects the defaultmemomodel - a
memosource scope that uses hosted names declares bundledstdwithbuild.add_dep({ alias = "std", source = "internal", target = "standard" }) stdis not a validfol_model, and the dependency is not needed merely because an artifact is executable or registered withgraph.add_runfol code runandfol code testlaunch host-compatible artifacts using the evaluated graph; their target check is independent of source API capability
The public surface includes:
- dependency handles returned from
build.add_dep({...}) - unified output handles for generated and copied files
- explicit dependency build arguments
- a cleaner install-prefix model
Build/cache internals and installed outputs are separate:
- build root for emitted and intermediate build artifacts
- cache roots for reusable local state
- install prefix for user-visible installed outputs
Do not put package metadata directly on the graph handle.
Local Helpers
Current boundary:
- defining
fun/prohelpers inbuild.foland calling them frombuild()is not part of the current build surface; the evaluator cannot execute them today - this section describes later design work, not current behavior
when,loop, andcaseinbuild.folare the current build surface
build.fol can define helper functions visible only within itself:
fun[] make_lib(name: str, root: str): Artifact = {
return .build().graph().add_static_lib({ name = name, root = root });
};
pro[] build(): non = {
var build = .build();
var graph = build.graph();
var core = make_lib("core", "src/core/lib.fol");
var io = make_lib("io", "src/io/lib.fol");
var app = graph.add_exe({ name = "app", root = "src/main.fol" });
app.link(core);
app.link(io);
graph.install(app);
};
Helpers may call .build() ambiently, but they do not name a public build or
graph type in source.
Package Control
build.fol is the only package control file.
Package metadata and direct dependencies are configured from inside
pro[] build(): non through the ambient build context.
build.meta({...})
build.meta({...}) configures package metadata for the current package.
Typical fields belong here:
nameversionkinddescriptionlicense
This is package identity and package description data. It is not graph mutation.
build.add_dep({...})
build.add_dep({...}) registers one direct dependency of the current package.
Typical fields belong here:
aliassourcetargetversionhashmodeargs
For example:
build.add_dep({
alias = "shared",
source = "loc",
target = "../shared",
});
build.add_dep({
alias = "json",
source = "pkg",
target = "json",
mode = "lazy",
});
build.add_dep({
alias = "logtiny",
source = "git",
target = "git+https://github.com/bresilla/logtiny.git",
version = "tag:v0.1.3",
hash = "b242d319644a",
});
For git dependencies:
targetis only the repository locatorversionchoosesbranch:<name>,tag:<name>, orcommit:<sha>hashis optional commit-prefix verification- selector query params in
targetare not supported
See examples/build_git_dep_versions for a standalone package that shows branch, tag, commit, and hash-pinned git dependencies together.
Supported dependency modes:
eagerlazyon-demand
Current semantics:
eagerdirect package-store dependencies are prepared immediately during package loadinglazydependency metadata is kept, but package-store preparation is deferred until a later build/import path needs iton-demandsame deferred loading rule aslazy, but user-facing summaries keep the stronger intent visible
fol pack fetch still walks declared dependencies so it can materialize and pin
the workspace graph. The mode is surfaced in fetch/build summaries instead of
being dropped.
Forwarded dependency args stay explicit:
var graph = build.graph();
var target = graph.standard_target();
var optimize = graph.standard_optimize();
var fast = graph.option({ name = "use_fast_parser", kind = "bool", default = true });
build.add_dep({
alias = "json",
source = "pkg",
target = "json",
mode = "lazy",
args = {
target = target,
optimize = optimize,
use_fast_parser = fast,
jobs = 4,
flavor = "strict",
},
});
This declares direct dependencies only.
Transitive dependencies stay declared in each dependency package’s own
build.fol.
Nothing is forwarded implicitly from the parent build. If a dependency should
see target, optimize, or a package-specific option, pass it explicitly in
args.
Explicit Dependency Exports
Dependency handles only see build-facing names that the dependency package
exports from its own build.fol.
var graph = build.graph();
var codec = graph.add_module({ name = "codec", root = "src/codec.fol" });
var lib = graph.add_static_lib({ name = "json", root = "src/main.fol" });
var docs = graph.step("docs", "Validate the package");
build.export_module({ name = "api", module = codec });
build.export_artifact({ name = "runtime", artifact = lib });
build.export_step({ name = "check", step = docs });
Ordinary source imports still resolve by dependency alias under .fol/pkg.
Build-handle queries stay separate from source imports.
build.graph()
build.graph() returns the opaque graph handle used for artifact and step
construction.
Graph-only work belongs here:
add_exeadd_static_libinstalladd_runstandard_target
Named steps may also carry an optional description:
var docs = graph.step("docs", "Generate documentation");
standard_optimizewrite_file
That split keeps the build surface clear:
- package metadata through
build.meta - direct dependencies through
build.add_dep - artifact graph mutation through
build.graph()
Capability Restrictions
The build executor enforces a capability model. Allowed operations:
- graph mutation (adding artifacts, steps, options)
- option reads (
.build().graph().standard_target(),.build().graph().standard_optimize(), etc.) - source-path handles (
.build().graph().file_from_root(...),.build().graph().dir_from_root(...)) - basic string and container operations
- controlled file generation (
.build().graph().write_file(...),.build().graph().copy_file(...)) - controlled process execution (
.build().graph().add_system_tool(...))
Forbidden operations (produce a compile or runtime error):
- arbitrary filesystem reads or writes
- network access
- wall clock access
- ambient environment variable access
- uncontrolled process execution
These restrictions ensure build graphs are deterministic and portable.
Graph API
build.graph() is the public access point to the build graph in build.fol.
All graph construction goes through method calls on the returned handle.
This layer is intentionally narrower than the whole build surface:
- package metadata belongs on
build.meta({...}) - direct dependencies belong on
build.add_dep({...}) - future dependency queries and output handles sit above raw graph mutation and should not collapse back into ad hoc string-only graph APIs
The canonical shape is:
pro[] build(): non = {
var build = .build();
build.meta({ name = "app", version = "0.1.0" });
var graph = build.graph();
...
};
Artifacts
graph.add_exe
Adds an executable artifact.
var app = graph.add_exe({
name = "app",
root = "src/main.fol",
fol_model = "memo", // optional; memo is the default
target = target, // optional
optimize = optimize, // optional
});
Returns an Artifact handle.
Required fields: name, root.
Optional fields: fol_model, target, optimize.
An omitted fol_model currently defaults to memo. Spell core explicitly;
an explicit memo remains useful when showing mixed-model intent, but omission
and fol_model = "memo" select the same capability.
root is the path to the entry-point .fol source file relative to the
package root.
The resolved root must be a real source file contained by that package. The
frontend canonicalizes the path before checking containment, so neither ..
nor a symlink may make an artifact root escape the package.
For an artifact-targeted build, the directory containing root is the source
scope: FOL recursively parses that directory and checks every source in it
under the artifact’s fol_model. A package may declare both core and memo
artifacts only when their source scopes are disjoint. The scopes overlap, and
the graph is rejected, when they are the same directory or one contains the
other. Put different-model artifacts in sibling directories or separate
package members; do not put core.fol and memo.fol beside each other in one
recursively parsed source directory.
Package-wide commands that require one capability model reject mixed-model packages. Use an exact artifact or named build step when targeting one of the disjoint scopes.
fol_model selects one of the two runtime capability modes for the artifact:
coreno heap and no source-level hosted OS/runtime APIsmemoalloc-like heap-backed facilities, still no source-level hosted OS/runtime APIs
The division deliberately follows Rust’s capability shape:
- FOL
coreis analogous to#![no_std]with Rustcore - FOL
memois analogous to#![no_std]withcoreplusalloc - FOL
memoplus the bundledstandarddependency is analogous to hosted Ruststd
This is a capability analogy. It is independent from the build tool’s ability
to launch a resulting host executable. The current Rust backend is still
hosted, so FOL core is a source/runtime contract and is not yet a claim of
finished freestanding backend support.
Bundled std is not a third fol_model. A memo artifact reaches the hosted
API tier only when the package explicitly declares the bundled internal
dependency:
build.add_dep({ alias = "std", source = "internal", target = "standard" });
Source code reaches that dependency through its declared alias, for example
use std: pkg = {"std"};.
The important boundary is semantic and runtime-facing:
coreartifacts must not use heap-backedstr,vec,seq,set, ormapcoreartifacts may still use arrays, records, routines, control flow, anddfrmemoartifacts may use heap-backed runtime types but not hosted language APIs- bundled
stdwrappers require an explicit internalstandarddependency - hosted wrappers and processor features require
fol_model = "memo"plus that explicit bundledstddependency - executable
coreandmemoartifacts may usefol code runandfol code testwithout bundledstd
| Source requirement | fol_model | Bundled standard dependency |
|---|---|---|
| no heap-backed or hosted language APIs | core | no |
| heap-backed values, no hosted APIs | memo | no |
| shipped hosted or processor APIs | memo | yes |
The last row is still a memo artifact. std is not an accepted fol_model
value.
The frontend invoking a host-compatible artifact, compiler, linker, or system tool is build-host behavior. It is not a source-visible hosted capability and does not promote an artifact to the bundled-std tier.
Current implementation note:
corealready means “no heap and no source-level hosted OS/runtime APIs” at the language and runtime-contract levelcoreartifacts are still emitted through the current Rust backend pipelinecoreartifacts can execute through that pipeline without bundledstd- that means
coreis ready for semantic/runtime restriction work now, but it should not yet be read as “finished embedded backend support”
Mixed-model example:
pro[] build(): non = {
var build = .build();
build.meta({ name = "workspace_tools", version = "0.1.0" });
build.add_dep({ alias = "std", source = "internal", target = "standard" });
var graph = build.graph();
var corelib = graph.add_static_lib({
name = "corelib",
root = "core/lib.fol",
fol_model = "core",
});
var memolib = graph.add_static_lib({
name = "memolib",
root = "memo/lib.fol",
fol_model = "memo",
});
var tool = graph.add_exe({
name = "tool",
root = "app/main.fol",
fol_model = "memo",
});
graph.install(tool);
graph.add_run(tool);
};
The separate core/, memo/, and app/ directories above are semantic, not
just organizational: they keep the recursively parsed artifact scopes
disjoint. Moving those roots into the same directory would make the core and
memo contracts overlap and the frontend would reject the targeted build.
Only a memo source scope may import the declared std alias. Its presence in
the package does not make corelib a hosted artifact.
graph.add_static_lib
Adds a static library artifact to the graph.
fol code build produces lib<name>.a and installs it under the package’s
install prefix (.fol/install/lib/). A graph containing only libraries builds
the same way; it has nothing to run, so fol code run has no step to take.
var core = graph.add_static_lib({ name = "core", root = "src/core/lib.fol" });
For thumbv7em-none-eabi, a static library must use fol_model = "core",
debug or release-safe, and an explicit C export allowlist. It does not
select or initialize a board. Compile the generated header with a little-endian
Thumbv7E-M compiler using base AAPCS, not the VFP register calling convention.
The library supports fixed-width scalar and record exports without a hosted
runtime. Ordinary errors return a status; a panic raises a CPU fault. The
final firmware supplies its own exception handlers, startup and memory routines.
Returns an Artifact handle.
Library and test artifact config records follow the same optional fields:
fol_modeltargetoptimize
graph.add_shared_lib
Adds a shared (dynamic) library artifact to the graph.
Not yet implemented, exactly as for
add_static_libabove: the artifact is recorded and no.sois produced.
var sdk = graph.add_shared_lib({ name = "sdk", root = "src/sdk/lib.fol" });
Returns an Artifact handle.
graph.add_test
Adds a test artifact.
var tests = graph.add_test({
name = "tests",
root = "src/tests.fol",
fol_model = "core",
});
Returns an Artifact handle.
The test artifact follows the same capability rules as every other artifact.
fol code test may build and launch this core test on a compatible host
without bundled std. Tests that call hosted APIs instead select memo and
declare the bundled dependency for those API calls, not for the test harness.
graph.add_module
Adds a standalone module that can be imported by other artifacts.
var utils = graph.add_module({ name = "utils", root = "src/utils.fol" });
Returns a Module handle.
Installation and Runs
graph.install
Marks an artifact for installation.
graph.install(app);
Returns an Install handle.
Install projections use the selected install prefix. Artifact installs resolve under the prefix by kind:
- executables under
bin/ - libraries under
lib/
graph.install_file
Installs either a source-file handle or a generated output handle.
var defaults = graph.file_from_root("config/defaults.toml");
graph.install_file({ name = "defaults", source = defaults });
var cfg = graph.write_file({
name = "cfg",
path = "config/generated.toml",
contents = "ok",
});
graph.install_file({ name = "generated-cfg", source = cfg });
Returns an Install handle.
graph.install_dir
Installs a package-local source directory under the selected install prefix at the same relative path. The name labels the install output; it does not rename the directory.
var assets = graph.dir_from_root("assets");
graph.install_dir({ name = "assets", source = assets });
Returns an Install handle. The default build publishes directories
after compiling the selected artifacts. It rejects overlapping output
paths, symlinks and special files in the source tree, and does not
replace a destination it does not own. A reinstall replaces the
previous managed directory rather than merging obsolete files into
the new version.
The install prefix is selected by frontend/workspace configuration, not by the
package itself. Changing the prefix should move projected install destinations
without changing build.fol.
graph.add_run
Registers an artifact as a run target. Binds the default run step when only
one executable exists and no explicit run step has been registered.
var run = graph.add_run(app);
Returns a Run handle. See Handle API for Run methods.
Registration does not alter the artifact’s fol_model and does not imply a
bundled std dependency. When the step is selected, the frontend verifies that
the evaluated artifact target is host-compatible and then launches it. A
foreign target is rejected because there is no configured runner, regardless
of whether the artifact uses core, memo, or bundled std APIs.
Steps
graph.step
Creates a named custom step.
var docs = graph.step("docs");
var docs = graph.step("docs", "Generate documentation");
Returns a Step handle. See Handle API for Step methods.
Named steps are selectable on the command line with --step:
fol code build --step docs
A bare positional argument is a build target path, not a step name, so
fol code build docs looks for a file called docs and fails with F1004.
When a description is present, frontend step planning and unknown-step diagnostics surface it as part of the available step catalog.
Native System Libraries
graph.add_system_lib
Declares a typed system-library request that can be linked into an artifact.
var ssl = graph.add_system_lib({
name = "ssl",
mode = "dynamic",
search_path = "/usr/lib",
});
app.link(ssl);
Supported config fields:
namerequired library or framework namemodeoptional, defaults todynamic, also acceptsstaticframeworkoptional bool, defaults tofalsesearch_pathoptional system library search root
Current scope is intentionally narrow:
- library names are typed, not raw linker fragments
- frameworks are expressed through
framework = true - frameworks must use
dynamic - the build graph records native link intent without exposing a linker-script DSL
Dependency Config Notes
Forwarded dependency args are already best suited for stable build config:
targetoptimize- named user options
The current build story intentionally does not treat dependency config as a general environment-selection surface. Keep forwarded dependency args explicit and typed rather than mixing them with ad hoc environment shaping.
Generated Directories
graph.add_system_tool_dir
Declares a typed system-tool step that produces a directory handle.
var assets = graph.add_system_tool_dir({
tool = "assetpack",
output_dir = "gen/assets",
});
graph.install_dir({ name = "assets", source = assets });
graph.add_codegen_dir
Declares a codegen step that produces a directory handle.
var docs = graph.add_codegen_dir({
kind = "asset",
input = "assets/raw",
output_dir = "gen/packed",
});
Generated directory handles are valid in directory-oriented consumers:
graph.install_dirbuild.export_dir
Current Execution Semantics
Step execution is still serial today. The build graph keeps deterministic step ordering and explicit dependency edges, but it does not claim parallel execution yet.
Current reporting distinguishes:
- requested
- executed
- skipped-from-cache
- skipped-by-foreign-run-policy
- produced outputs
That reporting is intended for frontend summaries and tests. Produced outputs now participate in step cache-key semantics, so generated-file changes can invalidate dependent steps predictably.
Options
graph.standard_target
Reads the -Dtarget option. Returns a Target handle.
var target = graph.standard_target();
The value is provided at build time via -Dtarget=x86_64-linux-gnu. If no
value is provided, target resolves to the host target.
An optional config record is accepted:
var target = graph.standard_target({ default = "x86_64-linux-gnu" });
graph.standard_optimize
Reads the -Doptimize option. Returns an Optimize handle.
var optimize = graph.standard_optimize();
The value is provided via -Doptimize=release-fast. Defaults to debug if
not set.
Valid values: debug, release-safe, release-fast, release-small.
Artifact configuration fields can take the option handles directly:
var app = graph.add_exe({
name = "demo",
root = "src/main.fol",
target = graph.standard_target(),
optimize = graph.standard_optimize(),
});
graph.option
Declares a named user option readable via -D.
var root_opt = graph.option({
name = "root",
kind = "path",
default = "src/main.fol",
});
Returns a UserOption handle.
Required fields: name, kind.
Optional field: default.
Option kinds:
| Kind | Description | CLI Example |
|---|---|---|
bool | Boolean flag | -Dstrip=true |
int | Integer value | -Djobs=4 |
str | Arbitrary string | -Dprefix=/usr/local |
enum | One of a fixed set of strings | -Dbackend=llvm |
path | File or directory path | -Droot=src/main.fol |
target | Target triple | -Dtarget=x86_64-linux-gnu |
optimize | Optimization mode | -Doptimize=release-fast |
Generated Files
graph.write_file
Declares a file to be written with static contents at build time.
var header = graph.write_file({
name = "version.h",
path = "gen/version.h",
contents = "#define VERSION 1\n",
});
Returns a GeneratedFile handle.
graph.copy_file
Declares a file to be copied from a source-file handle.
var template = graph.file_from_root("config/template.toml");
var cfg = graph.copy_file({
name = "config",
source = template,
path = "gen/config.toml",
});
The destination field is path, the same spelling graph.write_file uses.
destination and destination_path are accepted as well.
Returns a GeneratedFile handle.
graph.add_system_tool
Declares a system tool invocation that produces a file.
var packed = graph.add_system_tool({
tool = "flatc",
args = { "--fol" },
file_args = { schema, defaults },
env = { MODE = "strict" },
output = "gen/schema.fol",
});
Returns a GeneratedFile handle.
The generated file is keyed by the output path. Use this handle with
step.attach(...) or artifact.add_generated(...).
Typed fields:
toolrequired tool nameargsoptional string argumentsfile_argsoptional source-file or generated-output handles passed as file argumentsenvoptional string-to-string environment mapoutputrequired generated output path
graph.add_codegen
Declares a FOL codegen step.
var schema = graph.add_codegen({
kind = "schema",
input = "schema/api.yaml",
output = "gen/api.fol",
});
Returns a GeneratedFile handle.
Codegen kinds: fol-to-fol, schema, asset-preprocess.
Path Utilities
graph.file_from_root
Returns a source-file handle rooted under the package root.
var cfg = graph.file_from_root("config/default.toml");
Useful when passing source files into copy_file, install_file, or
run.add_file_arg.
graph.dir_from_root
Returns a source-dir handle rooted under the package root.
var assets = graph.dir_from_root("assets");
graph.build_root
Returns the package root directory as an absolute path string.
var root = graph.build_root();
graph.install_prefix
Returns the installation prefix. Defaults to the workspace install directory.
var prefix = graph.install_prefix();
Dependencies
Direct dependencies are declared on build.add_dep({...}), not on graph.
See Handle API for querying modules, artifacts, steps,
and generated outputs from a Dependency handle.
Handle API
Graph methods return typed handles. Each handle type exposes its own set of methods for configuring relationships and behavior.
Path Handle Audit
Before the broader path convergence work, the public build surface still splits path-like values across multiple families:
SourceFileSourceDirGeneratedFile- dependency-generated outputs returned by
dep.generated(...)
Those values already compose in several places, but they do not yet read like one obvious path capability. This chapter keeps the current concrete names while the underlying path model converges.
Path Convergence Direction
The intended direction is one broader path capability with:
- a path class:
- file
- dir
- a provenance:
- source-root path
- local generated output
- dependency-exported path/output
The producer names can stay concrete:
graph.file_from_root(...)graph.dir_from_root(...)graph.write_file(...)graph.copy_file(...)dep.file(...)dep.dir(...)dep.path(...)dep.generated(...)
But path consumers should read those values through one common model instead of hand-written special cases for every producer. In practice the public rule is:
- producers stay specific
- consumers validate the incoming path by:
- path class: file or dir
- provenance: source, local generated, or dependency-exported
So install_file, run.add_file_arg, and artifact.add_generated now reject
wrong path provenance with exact diagnostics instead of falling through to
generic handle errors.
Artifact
The Artifact handle is returned by add_exe, add_static_lib,
add_shared_lib, and add_test.
artifact.link
Links another artifact as a dependency. The linker will include it.
var core = graph.add_static_lib({ name = "core", root = "src/core/lib.fol" });
var app = graph.add_exe({ name = "app", root = "src/main.fol" });
app.link(core);
Equivalent to Zig’s artifact.linkLibrary(dep).
artifact.import
Imports a module into this artifact’s compilation scope.
var utils = graph.add_module({ name = "utils", root = "src/utils.fol" });
var app = graph.add_exe({ name = "app", root = "src/main.fol" });
app.import(utils);
Equivalent to Zig’s artifact.root_module.addImport(name, module).
artifact.add_generated
Declares that this artifact depends on a generated file being produced before it can compile. The value stays a generated-output handle; it does not need to be converted back into a string path.
var schema = graph.add_codegen({
kind = "schema",
input = "schema/api.yaml",
output = "gen/api.fol",
});
var app = graph.add_exe({ name = "app", root = "src/main.fol" });
app.add_generated(schema);
Run
The Run handle is returned by graph.add_run. All Run methods are
chainable and return Run.
A Run handle describes a build-host action. Creating it does not expose
hosted source APIs and does not require bundled std; the referenced artifact
keeps its declared core or memo capability contract. Execution still
requires a host-compatible target.
run.add_arg
Appends a literal string argument to the run command.
var run = graph.add_run(app);
run.add_arg("--config").add_arg("config/default.toml");
run.add_file_arg
Appends any file-class path handle that the run surface can consume:
- source-file handles
- local generated outputs
- dependency-exported file/path handles
var defaults = graph.file_from_root("config/defaults.toml");
var cfg = graph.copy_file({
name = "config",
source = defaults,
path = "gen/config.toml",
});
var run = graph.add_run(app);
run.add_file_arg(cfg);
run.add_file_arg(defaults);
Equivalent to Zig’s run.addFileArg(file).
Generated-output handles compose across the graph surface:
fun[] emit_cfg() = {
return .build().graph().write_file({
name = "cfg",
path = "config/generated.toml",
contents = "ok",
});
};
var cfg = emit_cfg();
app.add_generated(cfg);
run.add_file_arg(cfg);
graph.install_file({ name = "install-cfg", source = cfg });
Dependency-exported file/path handles compose the same way on file consumers:
var dep = build.add_dep({
alias = "shared",
source = "loc",
target = "deps/shared",
});
var shared_schema = dep.path("schema");
run.add_file_arg(shared_schema);
graph.install_file({ name = "schema", source = shared_schema });
run.add_dir_arg
Appends a directory path as an argument.
var run = graph.add_run(app);
run.add_dir_arg("assets/");
run.capture_stdout
Captures the standard output of the run command as a generated file.
var run = graph.add_run(generator_tool);
var output = run.capture_stdout();
app.add_generated(output);
Returns a GeneratedFile handle. Equivalent to Zig’s run.captureStdOut().
run.set_env
Sets an environment variable for the run command.
var run = graph.add_run(app);
run.set_env("LOG_LEVEL", "debug");
run.depend_on
Makes this run step depend on another step completing first.
var codegen = graph.step("codegen");
var run = graph.add_run(app);
run.depend_on(codegen);
Step
The Step handle is returned by graph.step. All Step methods are
chainable and return Step.
step.depend_on
Makes this step depend on another step.
var compile = graph.step("compile");
var bundle = graph.step("bundle");
bundle.depend_on(compile);
step.attach
Attaches a generated file production to this step. When the step runs, the attached generated file is produced first.
var strip_tool = graph.add_system_tool({
tool = "strip",
output = "gen/app.stripped",
});
var strip_step = graph.step("strip");
strip_step.attach(strip_tool);
Install
The Install handle is returned by graph.install, graph.install_file,
and graph.install_dir.
install.depend_on
Makes this install step depend on another step.
var check = graph.step("check");
var install = graph.install(app);
install.depend_on(check);
Dependency
The Dependency handle is returned by build.add_dep({...}). It exposes the
public surface of another package.
var build = .build();
var dep = build.add_dep({
alias = "logtiny",
source = "git",
target = "git+https://github.com/bresilla/logtiny.git",
version = "tag:v0.1.3",
hash = "b242d319644a",
mode = "lazy",
});
Dependency handles query already-declared package dependencies. They do not add new graph mutations themselves.
Declared dependency modes:
eagerlazyon-demand
Current behavior:
eagerprepares package-store dependencies up front during formal package loadinglazykeeps the declaration and defers package-store preparation until a later import/build path needs iton-demandpreserves the strongest deferred intent and stays visible in summaries and fetch results
Dependency-handle queries resolve only names that the dependency explicitly
exports from its own build.fol:
var build = .build();
var graph = build.graph();
var codec = graph.add_module({ name = "codec", root = "src/codec.fol" });
var lib = graph.add_static_lib({ name = "json", root = "src/main.fol" });
build.export_module({ name = "api", module = codec });
build.export_artifact({ name = "runtime", artifact = lib });
If a dependency does not export a build-facing module, artifact, step, or generated output, dependency handles do not see it.
The implemented explicit export kinds are:
- module —
build.export_module({ name = ..., module = ... }) - artifact —
build.export_artifact({ name = ..., artifact = ... }) - step —
build.export_step({ name = ..., step = ... }) - generated output —
build.export_output({ name = ..., output = ... }) - source file —
build.export_file({ name = ..., file = ... }) - source dir or generated dir —
build.export_dir({ name = ..., dir = ... }) - generated path —
build.export_path({ name = ..., path = ... })
Path exports take handles, not strings:
var cfg = graph.file_from_root("config/default.toml");
var assets = graph.dir_from_root("assets");
var schema = graph.write_file({
name = "schema",
path = "gen/schema.fol",
contents = "ok",
});
build.export_file({ name = "config", file = cfg });
build.export_dir({ name = "assets", dir = assets });
build.export_path({ name = "schema", path = schema });
export_file requires a source-file handle, export_dir accepts a source-dir
handle or a generated-dir handle, and export_path requires a generated-output
handle. Passing anything else names the missing field in the diagnostic. Keeping
path exports handle-typed is what stops them from collapsing back into ad hoc
string registries.
Source import roots remain separate. A dependency can still be imported in ordinary package source through its alias even when it exports no build-facing handles at all.
Import resolution still follows the current alias-projection model under
.fol/pkg/<alias>. Dependency handles do not replace ordinary package imports;
they expose the build-facing surface of the already-declared dependency.
dependency.module
Resolves a named module from the dependency.
var module = dep.module("logtiny");
app.import(module);
dependency.artifact
Resolves a named artifact from the dependency.
var lib = dep.artifact("logtiny");
app.link(lib);
dependency.step
Resolves a named step from the dependency.
var step = dep.step("check");
app_step.depend_on(step);
dependency.generated
Resolves a named generated output from the dependency.
var types = dep.generated("bindings");
app.add_generated(types);
Build Options
Build options are named values passed from the command line into build.fol.
They follow Zig’s -D convention.
Syntax
fol code build -Dname=value
Multiple options can be passed in one command:
fol code build -Dtarget=x86_64-linux-gnu -Doptimize=release-fast -Dstrip=true
Standard Options
Two options are pre-defined by the build system: target and optimize.
They are read via dedicated graph methods.
Target
var target = graph.standard_target();
CLI: -Dtarget=arch-os-env
Format: arch-os-env triple. Examples:
| Triple | Meaning |
|---|---|
x86_64-linux-gnu | x86-64 Linux with glibc |
x86_64-linux-musl | x86-64 Linux with musl libc |
aarch64-linux-gnu | ARM64 Linux with glibc |
aarch64-linux-musl | ARM64 Linux with musl libc |
x86_64-macos-gnu | x86-64 macOS |
aarch64-macos-gnu | ARM64 macOS |
x86_64-windows-gnu | x86-64 Windows with MinGW |
x86_64-windows-msvc | x86-64 Windows with MSVC |
aarch64-windows-msvc | ARM64 Windows with MSVC |
Supported architectures: x86_64, aarch64.
Supported operating systems: linux, macos, windows.
Supported environments: gnu, musl, msvc.
If not set, the host target is used.
standard_target() always exposes the compact FOL spelling shown above, so
when and case comparisons are stable even when the CLI accepted a canonical
Rust triple. Artifact identity and the backend separately retain the matching
canonical Rust triple (for example, x86_64-unknown-linux-gnu).
To pass the resolved value to an artifact:
var target = graph.standard_target();
var app = graph.add_exe({
name = "app",
root = "src/main.fol",
target = target,
});
Optimize
var optimize = graph.standard_optimize();
CLI: -Doptimize=mode
Valid modes:
| Mode | Meaning |
|---|---|
debug | No optimization, full debug info |
release-safe | Optimized release build with safety checks (required for C ABI, Wasm, freestanding) |
release-fast | Optimized release build for pure hosted FOL artifacts; retains FOL safety checks |
release-small | Optimized release build for pure hosted FOL artifacts; retains FOL safety checks |
Default: debug. A fol code ... --release request supplies
release-safe when no explicit optimize value is present. An explicit
-Doptimize=... or --optimize ... value takes precedence and also determines
whether the artifact uses the debug or release output/rustc profile, so the
directory identity cannot disagree with the compiler profile. All release
modes retain FOL runtime and overflow safety checks; artifacts that use C
imports, C ABI library exports, Wasm, or freestanding targets require debug
or release-safe.
To pass the resolved value to an artifact:
var optimize = graph.standard_optimize();
var app = graph.add_exe({
name = "app",
root = "src/main.fol",
optimize = optimize,
});
Sanitize
CLI: --sanitize address,undefined on fol code build, run, and test, or
FOL_SANITIZE=address,undefined in the environment.
The executable or shared library is linked with the C driver’s
-fsanitize= runtime, so a C provider compiled with the same flags links
and reports its violations. The generated Rust itself is not instrumented:
the pinned stable rustc has no sanitizer instrumentation. Every heap
allocation in the process still goes through the sanitizer’s allocator, so
leaks, double frees and foreign frees are reported on the Rust side too. A
static library is unchanged, because its C consumer links the runtime. Only
Linux GNU targets are accepted, and an unknown name is refused.
User Options
graph.option(...) declares a named option specific to the package.
var strip = graph.option({
name = "strip",
kind = "bool",
default = false,
});
CLI: -Dstrip=true
Option Kinds
| Kind | Example CLI | Default type |
|---|---|---|
bool | -Dverbose=true | false |
int | -Djobs=8 | 0 |
str | -Dprefix=/usr | "" |
enum | -Dbackend=llvm | first value |
path | -Droot=src/main.fol | "" |
target | -Dtarget=x86_64-linux-gnu | host target |
optimize | -Doptimize=release-fast | debug |
Using Option Values
Option handle values can be interpolated into strings or compared with ==:
var root_opt = graph.option({ name = "root", kind = "path", default = "src/main.fol" });
var app = graph.add_exe({ name = "app", root = root_opt });
Comparing in a when condition:
var strip = graph.option({ name = "strip", kind = "bool", default = false });
when(strip == true) {
{
var strip_step = graph.step("strip");
}
};
Shorthand vs Long Form
Both of these are equivalent:
fol code build -Dtarget=x86_64-linux-gnu
fol code build --build-option target=x86_64-linux-gnu
-D is the shorthand. -Dtarget= and -Doptimize= route to the dedicated
standard option slots. All other -Dname=value pairs route to user-declared
options.
Control Flow in build.fol
build.fol is a real FOL program. It supports when, loop, and user-defined
helper routines.
when
when conditionally executes build operations based on a boolean expression.
The canonical form for a conditional block with no case arms uses a double-brace default body:
when(optimize == "release-fast") {
{
var strip_step = graph.step("strip");
var packed = graph.add_system_tool({
tool = "strip",
output = "gen/app.stripped",
});
strip_step.attach(packed);
}
};
With explicit case arms:
when(target) {
case("x86_64-linux-gnu") {
graph.step("asan", "Enable address sanitizer");
}
case("aarch64-linux-gnu") {
graph.step("tsan", "Enable thread sanitizer");
}
* {
graph.step("default-check");
}
};
The inner double-brace { { ... } } is required for the default arm when no
case clauses are present. This is how the FOL parser distinguishes the
default body from raw statements.
Conditional Expressions
Any boolean or option value comparison is valid:
when(optimize == "release-fast") { { ... } };
when(strip == true) { { ... } };
when(target == "x86_64-linux-gnu") { { ... } };
The comparison is resolved at build evaluation time using the values passed
via -D flags. If no value was provided, the declared default is used.
loop
loop iterates over a list and runs the body for each element.
loop(name in {"core", "io", "utils"}) {
graph.add_static_lib({ name = name, root = name });
};
The loop variable (name) is bound in scope for each iteration. It can be
used anywhere inside the body as a string value.
Loop over a list with multiple fields:
loop(name in {"core", "io"}) {
var lib = graph.add_static_lib({ name = name, root = name });
graph.install(lib);
};
The iterable is a container literal { elem1, elem2, ... }. Currently only
string lists are supported as loop iterables in build.fol.
Helper Routines
Current boundary:
- defining helper
fun[]/pro[]routines inbuild.foland calling them frombuild()is not part of the current build surface; the evaluator cannot execute them today - this section describes later design work, not current behavior
- the
when,loop, andcasebuild control flow above is the current build surface
build.fol can define helper fun[] and pro[] routines. They are visible
only within the file — they are not exported to the package.
Helper Function
fun[] make_lib(name: str, root: str): Artifact = {
return .build().graph().add_static_lib({ name = name, root = root });
};
pro[] build(): non = {
var build = .build();
build.meta({ name = "app", version = "0.1.0" });
var graph = build.graph();
var core = make_lib("core", "src/core/lib.fol");
var io = make_lib("io", "src/io/lib.fol");
var app = graph.add_exe({ name = "app", root = "src/main.fol" });
app.link(core);
app.link(io);
graph.install(app);
graph.add_run(app);
};
The helper make_lib accesses the graph through .build().graph(). The graph
handle is not a public type name and is not passed as a user-declared
parameter.
Helpers Calling Helpers
Helpers can call other helpers:
fun[] lib_root(name: str): str = {
return "src/" + name + "/lib.fol";
};
fun[] add_lib(name: str): Artifact = {
return .build().graph().add_static_lib({ name = name, root = lib_root(name) });
};
pro[] build(): non = {
var build = .build();
build.meta({ name = "app", version = "0.1.0" });
var graph = build.graph();
var core = add_lib("core");
var app = graph.add_exe({ name = "app", root = "src/main.fol" });
app.link(core);
graph.install(app);
};
Combined Example
fun[] make_lib(name: str): Artifact = {
return .build().graph().add_static_lib({ name = name, root = name });
};
pro[] build(): non = {
var build = .build();
build.meta({ name = "app", version = "0.1.0" });
var graph = build.graph();
var target = graph.standard_target();
var optimize = graph.standard_optimize();
var strip = graph.option({ name = "strip", kind = "bool", default = false });
loop(name in {"core", "io", "net"}) {
make_lib(name);
};
var app = graph.add_exe({
name = "app",
root = "src/main.fol",
target = target,
optimize = optimize,
});
graph.install(app);
graph.add_run(app);
when(strip == true) {
{
var strip_step = graph.step("strip");
var packed = graph.add_system_tool({
tool = "strip",
output = "gen/app.stripped",
});
strip_step.attach(packed);
}
};
};
Artifacts, Modules, and Generated Files
The build graph tracks three kinds of compilable or producible outputs: artifacts, modules, and generated files.
Artifacts
Artifacts are the primary compiled outputs of a package.
| Kind | Method | Output | Status |
|---|---|---|---|
| Executable | graph.add_exe | Binary | built |
| Static library | graph.add_static_lib | .a / .lib | declared only |
| Shared library | graph.add_shared_lib | .so / .dylib | declared only |
| Test bundle | graph.add_test | Runnable test binary | built |
A declared only kind is accepted by the graph and produces no file. The
output column names what it will produce once V4 milestone M3 lands, not what
you will find in .fol/build today.
All artifact constructors accept the same base config record:
var app = graph.add_exe({
name = "app", // required: output name
root = "src/main.fol", // required: entry-point source file
fol_model = "core", // optional: core or memo (memo if omitted)
target = target, // optional: Target handle
optimize = optimize, // optional: Optimize handle
});
fol_model governs source-visible capabilities, not whether the artifact is a
binary. Both core and memo can produce runnable executables and test
bundles. A memo artifact declares bundled std separately only when its
source needs hosted APIs.
name must be lowercase. Allowed characters: a-z, 0-9, -, _, ..
Exit Status
A built artifact’s exit status is its entry routine’s int return value, and
0 when the entry returns non. A recoverable entry that reports exits 1
after printing the error. The full contract lives in the built-ins chapter.
This is what makes a test bundle able to fail: graph.add_test runs the
binary, and an entry that returns a nonzero int — or reports — fails the
run.
fol code run and fol code test exit with the program’s own status rather
than a status of their own. A program that fails on its own terms is reported
under F1005, which says the build succeeded and the program did not; a real
build or configuration failure keeps F1004.
Artifact Name Validation
The build system validates artifact names at evaluation time. Invalid names (uppercase, spaces, special characters) produce a build error.
Linking
Static and shared libraries are built as real .a and .so files and
installed under .fol/install/lib/. artifact.link(dep) adds dep to the
artifact’s native link plan, which orders every provider after the artifacts
that need it:
var core = graph.add_static_lib({ name = "core", root = "src/core/lib.fol" });
var app = graph.add_exe({ name = "app", root = "src/main.fol" });
app.link(core);
Typed system-library requests use the same surface. They reach the build
graph and the projected artifact definition, and stop there: nothing outside
fol-build reads native_attachments, so no -l flag is ever passed to the
linker.
var ssl = graph.add_system_lib({ name = "ssl", mode = "dynamic" });
app.link(ssl);
Framework-style requests use the same surface:
var metal = graph.add_system_lib({
name = "Metal",
framework = true,
});
app.link(metal);
Linking is transitive through the graph. If core itself links utils, app
will also see utils.
Installation
Any artifact can be marked for installation:
graph.install(app);
graph.install(core);
Files and directories can also be installed directly:
var defaults = graph.file_from_root("config/defaults.toml");
var assets = graph.dir_from_root("assets");
graph.install_file({ name = "defaults", source = defaults });
graph.install_dir({ name = "assets", source = assets });
Modules
Modules are named source units that can be shared across artifacts without being standalone binaries.
var utils = graph.add_module({ name = "utils", root = "src/utils.fol" });
var app = graph.add_exe({ name = "app", root = "src/main.fol" });
app.import(utils);
artifact.import(module) makes the module visible in the importing artifact’s
source scope. Equivalent to Zig’s artifact.root_module.addImport(name, dep).
Modules from dependencies are accessed via dep.module(name):
var build = .build();
var dep = build.add_dep({ alias = "mylib", source = "loc", target = "../mylib" });
var logger = dep.module("logger");
app.import(logger);
dep.module(name) resolves only explicitly exported build modules. It does not
change the ordinary package import rules used in source files.
Generated Files
Generated files are outputs produced before compilation. They must be declared in the graph so the build system knows to produce them and what depends on them.
Kinds
| Kind | Method | Description |
|---|---|---|
| Write | graph.write_file | Written with literal string contents |
| Copy | graph.copy_file | Copied from a source path |
| Tool output | graph.add_system_tool | Produced by an external tool |
| Tool dir | graph.add_system_tool_dir | Produced as a generated directory |
| Codegen | graph.add_codegen | Produced by the FOL codegen pipeline |
| Codegen dir | graph.add_codegen_dir | Produced as a generated directory |
| Captured run | run.capture_stdout() | Stdout of a run step |
Connecting Generated Files
A generated file must be connected to the graph entity that depends on it.
Attach to a step (the step triggers its production):
var schema = graph.file_from_root("schema/api.yaml");
var defaults = graph.write_file({
name = "defaults",
path = "gen/defaults.txt",
contents = "strict",
});
var gen = graph.add_system_tool({
tool = "flatc",
args = { "--fol" },
file_args = { schema, defaults },
env = { MODE = "strict" },
output = "gen/types.fol",
});
var step = graph.step("proto");
step.attach(gen);
Add to an artifact (artifact cannot compile without it):
var schema = graph.add_codegen({
kind = "schema",
input = "schema/api.yaml",
output = "gen/api.fol",
});
var app = graph.add_exe({ name = "app", root = "src/main.fol" });
app.add_generated(schema);
Capture stdout and feed it as an arg to another run:
var gen_tool = graph.add_exe({ name = "gen", root = "tools/gen.fol" });
var gen_run = graph.add_run(gen_tool);
var gen_output = gen_run.capture_stdout();
var app_run = graph.add_run(app);
app_run.add_file_arg(gen_output);
Generated directories can be installed or exported as dirs:
var assets = graph.add_system_tool_dir({
tool = "assetpack",
output_dir = "gen/assets",
});
build.export_dir({ name = "assets", dir = assets });
graph.install_dir({ name = "assets", source = assets });
Steps
Steps are named build phases. The build system has several implicit steps
(build, run, test, install). Custom steps are declared with
graph.step.
var docs = graph.step("docs", "Generate documentation");
Steps are executed in dependency order. A step depends on another step via
step.depend_on:
var compile = graph.step("compile");
var docs = graph.step("docs");
docs.depend_on(compile);
Default Step Bindings
When only one executable exists in a package, the build system automatically
binds it to the default build and run steps. When multiple executables
exist, explicit step bindings are required via graph.add_run(artifact).
These bindings select what the frontend launches; they do not upgrade the
artifact to hosted std. fol code run and fol code test accept std-free
core and memo artifacts when the evaluated target matches the host.
Selecting Steps at the Command Line
fol code build # run the install steps
fol code build docs # run the "docs" step
fol code run # run the default run step
fol code run --step serve # run the "serve" step
fol code test # run test steps
Cross-target artifacts can still be built. The current frontend has no runner
configuration, so run and test reject a foreign selected target before
launch instead of treating bundled std as execution permission.
Graph Validation
After the build program executes, the graph is validated:
- No step dependency cycles
- All artifact inputs (modules, generated files) are resolvable
- Install targets point to declared artifacts
Validation errors are reported as build evaluation errors before any compilation begins.
Cross Compilation
FOL package builds now stay on one backend path:
FOL source
-> lowered FOL IR
-> generated Rust crate
-> rustc
-> native binary
Normal artifact builds do not call Cargo anymore. Cargo is still useful for
fol code emit rust, but fol code build and fol code run compile the
generated crate directly with rustc.
Selecting A Target
Use either:
fol code build --target aarch64-unknown-linux-gnu
fol code build --target x86_64-pc-windows-gnu
or inside build.fol:
pro[] build(): non = {
var build = .build();
build.meta({ name = "app", version = "0.1.0" });
var graph = build.graph();
var target = graph.standard_target();
var app = graph.add_exe({
name = "app",
root = "src/main.fol",
target = target,
});
graph.install(app);
graph.add_run(app);
};
Target precedence is:
--target- artifact target declared in
build.fol - host default
Accepted Target Spellings
The backend accepts both canonical Rust triples and the shorter FOL spellings already used in build code.
Examples:
x86_64-linux-gnu->x86_64-unknown-linux-gnux86_64-linux-musl->x86_64-unknown-linux-muslaarch64-linux-gnu->aarch64-unknown-linux-gnuaarch64-linux-musl->aarch64-unknown-linux-muslx86_64-windows-gnu->x86_64-pc-windows-gnux86_64-windows-msvc->x86_64-pc-windows-msvcaarch64-windows-msvc->aarch64-pc-windows-msvcx86_64-macos-gnu->x86_64-apple-darwinaarch64-macos-gnu->aarch64-apple-darwin
Unknown spellings are rejected before the backend tries to build.
Build vs Run
Cross-building and cross-running are different operations.
fol code buildsupports host and non-host targetsfol code emit ruststays available for source inspectionfol code runis host-onlyfol code testis host-only
If the selected target does not match the current machine, run and test
fail early with a diagnostic instead of trying to execute the foreign binary.
“Host-only” here is a target-compatibility rule. It is independent of the
source-language capability tier: host-compatible core and memo artifacts
can execute without bundled std.
There is no public cross-target runner configuration yet. When such a runner is
added, it will be an execution-tool setting, not a reason to expose bundled
std APIs to the target program.
Output Layout
Compiled binaries are target-scoped so host and cross builds do not overwrite each other.
Typical layout:
.fol/build/<profile>/bin/<target>/<artifact>
.fol/build/<profile>/fol-backend/runtime/<target>/<profile>/...
That means:
- host builds and cross builds can coexist
- runtime artifacts are compiled per target
- the generated entry crate links against the matching target runtime
emit rust
fol code emit rust still writes a Cargo-compatible crate for debugging and
inspection. That command is source emission, not the product binary build path.
The binary build path remains direct rustc.
Build Direction
This note records the near-term direction of the FOL build system.
It is not a promise to copy another build system exactly. It is the current
shape we intend to grow into from the existing build.fol surface.
Current Shape
Today the public layering is:
.build()for the package build contextbuild.meta({...})for package metadatabuild.add_dep({...})for direct dependenciesbuild.graph()for artifact and step graph mutation
This already covers the core FOL build contract:
- one control file
- one canonical
pro[] build(): non - package metadata and dependencies in the build language
- graph-based artifact construction
What Is Still Missing
The next useful pieces are not more random graph methods. They are missing capability classes.
Round 3 Gap Audit
The current public build surface is materially stronger than it was before:
- dependency handles are real values
- explicit build exports exist
- source file and source dir handles exist
- generated outputs use one composable handle family
- dependency modes are public
- install-prefix projection is real
- step descriptions are real
- typed system tools exist
The remaining gaps that still matter are:
- no named dependency exports for source files, source dirs, or broader path values
- no dependency-handle queries for exported files, dirs, or general paths
- path capability is still split across multiple public handle families
- dependency modes are public and preserved end to end, but only package-store eager preloading is fully distinct today; deeper deferred preparation can still become more aggressive later
- CLI/help/reporting still under-exposes step, install, and output information
- there is still no typed system-library surface
- generated-directory workflows are still thin compared to generated-file flows
Path Handle Split Today
The current path-like values are still exposed through separate concrete families:
SourceFileSourceDirGeneratedFile- dependency-generated output handles
That split is honest today, but it is not the final intended feel. The next path round should preserve the strong producer distinctions while making path consumers behave as though they are working against one broader path capability.
The intended public feel is:
- producers remain explicit
- consumers validate against one common path model
- diagnostics name both:
- the required path class
- the actual path provenance when that matters
That means this round does not need to delete SourceFile, SourceDir, or
GeneratedFile immediately. It does need to stop treating every consumer as a
fresh handwritten branch over those concrete producers.
Dependency Handles
Direct dependencies are now real build values instead of only metadata declarations.
The current shape is:
var logtiny = build.add_dep({
alias = "logtiny",
source = "git",
target = "git+https://github.com/bresilla/logtiny.git",
version = "tag:v0.1.3",
hash = "b242d319644a",
});
and then:
var logtiny_mod = logtiny.module("logtiny");
var logtiny_lib = logtiny.artifact("logtiny");
var logtiny_gen = logtiny.generated("bindings");
The current dependency import model stays explicit:
- ordinary source imports still resolve by alias projection under
.fol/pkg/<alias> - dependency handles query the build-facing surface of that package
- dependency handles only see explicit exports from the dependency package
That public contract is:
build.export_module({ name = "api", module = codec });
build.export_artifact({ name = "runtime", artifact = lib });
build.export_step({ name = "check", step = docs });
build.export_output({ name = "schema", output = bindings });
This keeps source imports and build-surface queries separate instead of collapsing them into one implicit registry.
Output Handles
Generated and copied files now use one output-handle family that can represent:
- files written by
graph.write_file(...) - files copied by
graph.copy_file(...) - captured stdout from run/system-tool/codegen steps
- generated files exported by dependency packages
This behaves like one composable build value instead of a pile of unrelated string paths. The same handle family now covers local and dependency-generated outputs alike.
Explicit Dependency Arguments
Dependencies now accept explicit forwarded build arguments:
var dep = build.add_dep({
alias = "json",
source = "pkg",
target = "json",
args = {
target = graph.standard_target(),
optimize = graph.standard_optimize(),
use_fast_parser = true,
},
});
The important rule is explicitness:
- no ambient forwarding
- no hidden inheritance
- the package author chooses what to pass
Install Prefix
The build graph now describes what gets installed, while the output prefix stays a user/tool choice rather than something hardcoded into the package.
That means FOL should continue to separate:
- build/cache internals
- fetched dependency storage
- final installed outputs
Step Execution
Step execution is still serial today. The current work is about making cache boundaries and reporting honest and explicit, not pretending the executor is already parallel.
The current reporting direction is:
- requested
- executed
- skipped-from-cache
- skipped-by-foreign-run-policy
- produced outputs
System Integration
System integration now exists as a narrow typed surface through
graph.add_system_tool({...}).
The current typed inputs are:
toolargsfile_argsenvoutput
That is intentionally smaller than a full native-toolchain DSL. It is enough to model external build tools without collapsing back into vague stringly build helpers.
What is still missing here:
- first-class system-library requests
- provider selection
- richer native linking policy
- parallel command execution
What This Does Not Mean
This direction does not mean:
- reintroducing public
GraphorBuildtypes - collapsing package metadata back into YAML
- making dependency behavior implicit
- turning the graph API into a stringly catch-all
- introducing a separate build manifest file
- pretending step execution is parallel before it is
- adding compatibility string-path fallbacks beside typed path handles
- growing a broad shell-script DSL inside
build.fol - reintroducing public build type names just to expose more features
The current design constraint remains:
- package metadata through
build.meta - direct dependencies through
build.add_dep - graph mutation through
build.graph
The next round should add richer values on top of that layering, not replace it.
Lexical Structure
This section defines the smallest syntactic building blocks of FOL source code.
All FOL source is interpreted as Unicode text encoded in UTF-8. The lexer groups raw characters into tokens such as:
- keywords
- identifiers
- literals
- symbols
- comments
- whitespace/newline boundaries
The lexical chapters answer questions such as:
- which words are reserved
- how identifiers are formed
- which literal forms exist
- how comments and spacing affect parsing
The detailed chapters are:
- keywords
- identifiers
- comments
- whitespace
- strings, characters, and booleans
- numbers
- symbols
Keywords
Fol has a number of restricted groups of keywords:
BK (build-in keywords)
BK_NOT `not`
BK_OR `or`
BK_XOR `xor`
BK_NOR `nor`
BK_AND `and`
BK_NAND `nand`
BK_IF `if`
BK_FOR `for`
BK_WHEN `when`
BK_EACH `each`
BK_LOOP `loop`
BK_IS `is`
BK_AT `at`
BK_HAS `has`
BK_IN `in`
BK_ON `on`
BK_OF `of`
BK_THIS `this`
BK_SELF `self`
BK_BREAK `break`
BK_RETURN `return`
BK_YEILD `yield`
BK_DFR `dfr`
BK_PANIC `panic`
BK_REPORT `report`
BK_CHECK `check`
BK_ASSERT `assert`
BK_WHERE `where`
BK_TRUE `true`
BK_FALSE `false`
BK_AS `as`
BK_DO `do`
BUILD-IN KEYWORDS - BK:
`(BK_AS|BK_IN|...)`
AK (assignment keywords)
AK_USE `use`
AK_DEF `def`
AK_VAR `var`
AK_FUN `fun`
AK_PRO `pro`
AK_LOG `log`
AK_TYP `typ`
AK_STD `std`
ASSIGNMENT KEYWORDS - AK:
`(AK_USE|AK_DEF|...)`
PK (proof keywords)
PK_THM `thm`
PK_PRF `prf`
PK_ALL `all`
PK_EXI `exi`
These are reserved for theorems, proof blocks, and the all / exi binders
(see Proofs). No grammar accepts them yet, so a
program cannot use them at all, not even as names.
TK (type keywords)
TK_INT `int`
TK_FLT `flt`
TK_CHR `chr`
TK_BOL `bol`
TK_ARR `arr`
TTKVEC `vec`
TK_SEQ `seq`
TK_MAT `mat`
TK_SET `set`
TK_MAP `map`
TK_STR `str`
TK_NUM `num`
TK_OPT `opt`
TK_MUL `mul`
TK_ANY `any`
TK_PTR `ptr`
TK_ERR `err`
TK_NON `non`
TK_REC `rec`
TK_LST `lst`
TK_ENM `enm`
TK_UNI `uni`
TK_CLS `cls`
TK_STD `std`
TK_MOD `mod`
TK_BLK `blk`
TYPE KEYWORDS - TK:
`(TK_INT|TK_FLT|...)`
Note that all of the type keywords are of three characters long. It is recomanded that new identifiers not to be of the same number of characters, as one day in the future that same identifier can be used s a keyword in FOL compiler.
OK (option keywords)
OK_EXP `exp`
OK_HID `hid`
exp marks exported visibility and hid file-local visibility.
OPTION KEYWORDS - OK:
`((OK_EXP|OK_HID|...),?)*`
Assigning
`(`*WS*`)*(\W)?(`*AK*`)(\[(`*OK*`)?\])?`
`(`*WS*`)*(`*AK*`)`
| `(`*WS*`)*\W(`*AK*`)`
| `(`*WS*`)*(`*AK*`)(\[\])`
| `(`*WS*`)*\W(`*AK*`)(\[\])`
| `(`*WS*`)*(`*AK*`)(\[(`*OK*`)\])`
| `(`*WS*`)*\W(`*AK*`)(\[(`*OK*`)\])`
Identifiers
Identifiers in the current front-end are ASCII names built from letters, digits, and
underscores, but they may not start with a digit. Repeated underscore runs __ are
not allowed.
IDENTIFIER:
[a-z A-Z _] [a-z A-Z 0-9 _]*
The hardened front-end currently accepts:
- leading underscores
- internal underscores
- non-leading digits
The hardened front-end currently rejects:
- leading digits
- repeated underscore runs
- non-ASCII identifier spellings
_ by itself is still accepted by the current lexer/parser boundary as a dedicated
placeholder or binder surface. It should not be treated as an ordinary named identifier
for later-phase semantic work.
Identifier equality
Parser-owned duplicate checks currently treat two identifiers as equal if the following algorithm returns true:
pro sameIdentifier(a, b: string): bol = {
result = a.replace("_", "").toLowerAscii == b.replace("_", "").toLowerAscii
}
That means ASCII letters are compared case-insensitively and underscores are ignored for those parser-owned duplicate checks. The lexer and stream still preserve original identifier spelling; they do not canonicalize token or namespace text up front.
Comments
FOL has two comment families, and both are first-class.
Slash comments
// runs to the end of the line, and /* ... */ spans lines without nesting.
These are what most FOL source uses.
// a line comment
/* a block
comment */
Backtick comments
A backtick-delimited comment spans as many lines as it needs:
SINGLE_LINE_COMMENT:
`this is a single line comment`
MULTI_LINE_COMMENT:
`this is a
multi
line
comment`
Doc comments
Documentation comments use the [doc] prefix inside the backtick form, which
is the only documentation-comment spelling:
DOC_COMMENT:
`[doc] this is a documentation comment`
What the front end keeps
The current front-end also preserves comment kind and raw spelling past lexing. In the
parser today, standalone root comments and standalone routine-body comments lower to
explicit AST comment nodes, and many inline expression-owned comments now survive
through AstNode::Commented wrappers around the parsed node they belong to. That
gives later doc-comment tooling retained comment content to build on instead of
re-scanning raw source text.
Whitespaces
Whitespace is any non-empty string containing only characters that have the below Unicode properties:
U+0009(horizontal tab, ‘\t’)U+000B(vertical tab)U+000C(form feed)U+0020(space, ’ ’)U+0085(next line)U+200E(left-to-right mark)U+200F(right-to-left mark)U+2028(line separator)U+2029(paragraph separator)
New lines
New line are used as end-of-line separators:
U+000A(line feed, ‘\n’)U+000D(carriage return, ‘\r’)
Strings
Characters
A character is a single Unicode element enclosed within quotes U+0022 (") with the exception of U+0022 itself, which must be escaped by a preceding U+005C character (\).
var aCharacter: chr = "\n"
var anotherOne: str = "語\n"
Raw characters
Raw character literals do not process any escapes. They are enclosed within single-quotes U+0027 (') with the exception of U+0027 itself:
var aCharacter: chr = 'z'
Strings
A string is a single or a sequence of Unicode elements enclosed within quotes U+0022 (") with the exception of U+0022 itself, which must be escaped by a preceding U+005C character (\).
Because both readings use ", a one-character double-quoted literal is
ambiguous on its face: "a" is a valid chr and a valid str. The type it is
being used as decides, so all of these are fine:
var letter: chr = "a";
var text: str = "a";
var loud: str = std::strn::to_upper("a");
var found: int = .str_find("banana", "n");
Read on its own, with nothing to shape it, such a literal is a chr. That
matters in one place: a generic parameter has no concrete type to shape it
from yet, so bind it to a typed name first. 'a' is unambiguous when you want a
character and nothing is telling the literal what to be.
var hiInEnglish: str = "Hello, world!\n"
var hInCantonese: str = "日本語"
Line-breaks are allowed in strings. A line-break is either a newline (U+000A) or a pair of carriage return and newline (U+000D, U+000A). Both byte sequences are normally translated to U+000A, but as a special exception, when an unescaped U+005C character (\ occurs immediately before the line-break, the U+005C character, the line-break, and all whitespace at the beginning of the next line are ignored. Thus a and b are equal:
var a: str = "foobar";
var b: str = "foo\
bar";
assert a == b;
Escape sequences
Some additional escapes are available in either character or non-raw string literals.
| code | description |
|---|---|
| \p | platform specific newline: CRLF on Windows, LF on Unix |
| \r, \c | carriage return |
| \n, \l | line feed (often called newline) |
| \f | form feed |
| \t | tabulator |
| \v | vertical tabulator |
| \\ | backslash |
| \“ | quotation mark |
| \’ | apostrophe |
| \ ‘0’..‘9’+ | character with decimal value d; all decimal digits directly following are used for the character |
| \a | alert |
| \b | backspace |
| \e | escape [ESC] |
| \x HH | character with hex value HH; exactly two hex digits are allowed |
| \u HHHH | unicode codepoint with hex value HHHH; exactly four hex digits are allowed |
| \u {H+} | unicode codepoint; all hex digits enclosed in {} are used for the codepoint |
Raw strings
Just like raw characters, raw string literals do not process any escapes either. They are enclosed within single-quotes U+0027 (') with the exception of U+0027 itself:
var hiInEnglish: str = 'Hello, world!'
Booleans
The two values of the boolean type are written true and false:
var isPresent: bol = false;
Numbers
A number in the current front-end is either an integer or a floating-point literal. Imaginary suffix forms are intentionally outside the hardened lexer/parser contract for this phase.
Intigers
An integer has one of four forms:
- A decimal literal starts with a decimal digit and continues with decimal digits and optional separating underscores.
- A hex literal starts with
0xor0Xand then uses hex digits with optional separating underscores. - An octal literal starts with
0oor0Oand then uses octal digits with optional separating underscores. - A binary literal starts with
0bor0Band then uses binary digits with optional separating underscores.
var decimal: int = 45;
var hexadec: int = 0x6AF53BD5;
var octal: int = 0o722371;
var binary: int = 0b010010010;
Underscore
Underscore character U+005F (_) is a special character, that does not represent anything withing the number laterals. An integer lateral containing this character is the same as the one without. It is used only as a syntastc sugar:
var aNumber: int = 540_467;
var bNumber: int = 540467;
assert aNumber == bNumber;
Floating points
A floating-point has one of two forms:
- A decimal literal followed by a period character
U+002E(.). This is optionally followed by another decimal literal. - A decimal literal that follows a period character
U+002E(.). - A decimal literal followed by a period with no fractional digits is also accepted by the current front-end.
var aFloat: flt = 3.4;
var bFloat: flt = .4;
var cFloat: flt = 1.;
Current front-end note
Imaginary literals such as 5i remain a language-design topic in the book, but they
are not tokenized or lowered by the current hardened stream/lexer/parser pipeline.
Symbols
Operators
Fol allows user defined operators. An operator is any combination of the following characters:
= + - * / > .
@ $ ~ & % < :
! ? ^ # ` \ _
The grammar uses the terminal OP to refer to operator symbols as defined here.
Brackets
Bracket punctuation is used in various parts of the grammar. An open bracket must always be paired with a close bracket. Here are type of brackets used in FOL:
| bracket | type | purpose |
|---|---|---|
{ } | Curly brackets | Code blocks, Namespaces, Containers |
[ ] | Square brackets | Type options, Container acces, Multithreading |
( ) | Round brackets | Calculations, Comparisons, Argument passing |
< > | Angle brackets |
The grammar uses the terminal BR to refer to operator symbols as defined here.
Statements And Expressions
This section covers executable syntax.
FOL separates executable forms into two broad groups:
- statements: forms executed for control flow, side effects, or declaration within a block
- expressions: forms that compute a value
Statements
Statements include:
- local declarations
- assignments
- routine calls used for side effects
- branching
- looping
- nested blocks
Examples:
var x: int = 0;
x = 5;
if (x > 0) { .echo(x) }
for (item in items) { .echo(item) }
Expressions
Expressions include:
- operator expressions
- literal expressions
- range expressions
- access expressions
- call expressions
Expressions can be nested freely and may appear in declarations, assignments, return statements, control-flow headers, and other expressions.
Statements
Statements are executable forms that primarily control behavior, perform side effects, or introduce local declarations inside a block.
This chapter family focuses on:
- declaration statements
- assignment-like statements
- control flow
- block structure
Examples:
var x: int = 0;
x = 1;
if (x > 0) { .echo(x) }
for (item in items) { .echo(item) }
Control
At least two linguistic mechanisms are necessary to make the computations in programs flexible and powerful: some means of selecting among alternative control flow paths (of statement execution) and some means of causing the repeated execution of statements or sequences of statements. Statements that provide these kinds of capabilities are called control statements. A control structure is a control statement and the collection of statements whose execution it controls. This set of statements is in turn generally structured as a block, which in addition to grouping, also defines a lexical scope.
There are two types of control flow mechanisms:
- choice -
when - loop -
loop(withwhile,for, andeachas loop-header spellings of the same mechanism)
Choice type
when(condition){ case(condition){} case(condition){} * {} };
when(variable){ is (value){}; is (value){}; * {}; };
when(variable){ in (iterator){}; in (iterator){}; * {}; };
when(iterable){ has (member){}; has (member){}; * {}; };
when(generic){ of (type){}; of (type){}; * {}; };
Current boundary:
caseandisarms (plus the required*default) are the currentV1surface, in both statement bodies and the arrow expression form (is 3 -> 7;)- a
whenwith nocase/isarms is a statement-only boolean gate: its default body runs only when the selector istrue; arbitrary values are not coerced to truth values - an
on(value)arm binds the value inside anopt[...]orerr[...]shell and runs when the shell holds one;*covers the empty or error case in(range/set matching),has(membership), andof(type matching) are declared matching syntax whose semantics are later-milestone work; the compiler rejects them with explicit boundary diagnostics- channel multiplexing is not an
on-arm variant of ordinarywhen; the shipped V3 processor form is the separateselect { when channel as value { ... } }statement shown below
Condition
when(true) {
case (x == 6){ // implementation }
case (y.set()){ // implementation }
* { // default implementation }
}
Valueation
when(x) {
is (6){ // implementation }
is (>7){ // implementation }
* { // default implementation }
}
Iteration
when(2*x) {
in ({0..4}){ // implementation }
in ({ 5, 6, 7, 8, }){ // implementation }
* { // default implementation }
}
Contains
when({4,5,6,7,8,9,0,2,3,1}) {
has (5){ // implementation }
has (10){ // implementation }
* { // default implementation }
}
Generics
when(T) {
of (int){ // implementation }
of (str){ // implementation }
* { // default implementation }
}
Channel multiplexing (V3)
select waits on direct channel bindings. Each when arm names one channel
and binds the payload received from it:
select {
when first as value {
consume(value);
}
when second as value {
consume(value);
}
* {
handle_not_ready();
}
};
The optional * arm runs immediately when no receiver is ready. Without it,
the statement polls until one source-order arm receives a value or every arm
has closed. The processor surface is hosted std-only. See
Tasks, Channels, and Mutexes for the
endpoint lifecycle and fairness contract.
Loop type
loop(condition){};
loop(iterable){};
Condition
loop( x == 5 ){
// implementation
};
Enumeration
loop( x in {..100}){
// implementation
}
loop( x in {..100}) if ( x % 2 == 0 )){
// implementation
}
loop( x in {..100} if ( x in somearra ) and ( x in anotherarray )){
// implementation
}
Iteration
loop( x in array ){
// implementation
}
Expressions
Expressions are value-producing forms.
An expression may be:
- a literal
- a reference
- an operator application
- a call
- an access form
- a range or container form
The detailed chapters in this section focus on:
- calculations and operators
- literals
- ranges
- access expressions
Calculations
assert in this chapter’s examples is the real intrinsic: it takes one boolean
condition, optionally followed by a message, and faults when the condition does
not hold. It is a keyword rather than a dot call, so it takes no parentheses of
its own — assert a == b;, never assert(a, b). See the intrinsics chapter.
In fol, every calcultaion, needs to be enclosed in rounded brackets ( //to evaluate ) - except in one line evaluating, the curly brackets are allowed too { // to evaluate }:
fun adder(a, b: int): int = {
retun a + b // this will throw an error
}
fun adder(a, b: int): int = {
retun (a + b) // this is the right way to enclose
}
Order of evaluation is strictly left-to-right, inside-out as it is typical for most others imperative programming languages:
.echo((12 / 4 / 8)) // 0.375 (12 / 4 = 3.0, then 3 / 8 = 0.375)
.echo((12 / (4 / 8))) // 24 (4 / 8 = 0.5, then 12 / 0.5 = 24)
Calculation expressions include:
- arithmetics
- comparison
- logical
- compounds
Arithmetics
The behavior of arithmetic operators is only on intiger and floating point primitive types. For other types, there need to be operator overloading implemented.
| symbol | description |
|---|---|
| - | substraction |
| * | multiplication |
| + | addition |
| / | division |
| % | reminder |
| ^ | exponent |
assert (3 + 6) == 9;
assert (5.5 - 1.25) == 4.25;
assert (-5 * 14) == -70;
assert (14 / 3) == 4;
assert (100 % 7) == 2;
Current integer semantics:
- division truncates toward zero (
-7 / 2is-3) - remainder takes the sign of the dividend (
-7 % 2is-1) - integers are two’s-complement; overflow is a runtime fault rather than a wrap, in debug and release builds alike, and division/modulo by zero faults
- a declared width such as
int[8]oru32is the value’s real width: a constant that does not fit is refused at compile time, operands of different widths are refused rather than silently converted, and.widen(...)/.narrow(...)convert between widths (see the casting chapter) - an integer literal takes the width it is stored at, and without one it is
int; every width’s whole range is writable, from-128forint[8]to340282366920938463463374607431768211455foru128 - floats follow IEEE-754:
1.0 / 0.0is infinity,0.0 / 0.0is NaN (no panic)
Comparisons
Comparison operators are also defined both for primitive types and many type in the standard library. Parentheses are required when chaining comparison operators. For example, the expression a == b == c is invalid and may be written as ((a == b) == c).
| Symbol | Meaning |
|---|---|
| == | equal |
| != | not equal |
| > | greater than |
| < | Less than |
| >= | greater than or equal to |
| <= | Less than or equal to |
assert 123 == 123;
assert 23 != -12;
assert 12.5 > 12.2;
assert 1 < 3;
assert 'A' <= 'B';
assert "World" >= "Hello";
Logical
A branch of algebra in which all operations are either true or false, thus operates only on booleans, and all relationships between the operations can be expressed with logical operators such as:
and(conjunction), denoted(x and y), satisfies(x and y) = 1ifx = y = 1, and(x and y) = 0otherwise.or(disjunction), denoted(x or y), satisfies(x or y) = 0ifx = y = 0, and(x or) = 1otherwise.not(negation), denoted(not x), satisfies(not x) = 0ifx = 1and (not x) = 1ifx = 0`.
assert (true and false) == (false and true);
assert (true or false) == true;
assert (not true) == false;
Current evaluation note:
and/orevaluate both operands eagerly; they do NOT short-circuit, so the right operand runs even when the left already decides the result ((false) and (1/0 > 0)still evaluates1/0). Guard side-effecting or fallible right operands explicitly.
Compounds
There are further assignment operators that can be used to modify the value of an existing variable. These are the compounds or aka compound assignments. A compound assignment operator is used to simplify the coding of some expressions. For example, using the operators described earlier we can increase a variable’s value by ten using the following code:
value = value + 10;
This statement has an equivalent using the compound assignment operator for addition (+=).
value += 10;
There are compound assignment operators for each of the six binary arithmetic operators: +, -, *, /, % and ^. Each is constructed using the arithmetic operator followed by the assignment operator. The following code gives examples for addition +=, subtraction -=, multiplication *=, division /= and modulus %=:
var value: int = 10;
(value += 10); // value = 20
(value -= 5); // value = 15
(value *= 10); // value = 150
(value /= 3); // value = 50
(value %= 8); // value = 2
Compound assignment operators provide two benefits. Firstly, they produce more compact code; they are often called shorthand operators for this reason. Secondly, the variable being operated upon, or operand, will only be evaluated once in the compiled application. This can make the code more efficient.
Literals
A literal expression consists of one or more of the numerical/letter forms described earlier. It directly describes a numbers, characters, booleans, containers and constructs.
There are two type of literals:
- values
- calls
Value literals
Value literals are the simpliest expressions. They are direct values assigned to variables and are divided into two types:
- singletons
- clusters
Singelton literals
Singleton literals represent one sigle values:
4 // intiger literal
0xA8 // hex-intiger literal
4.6 // floating-point literal
"c" // character literal
"one" // string literal
true // boolean literal
The current hardened front-end does not yet implement imaginary literal lowering, so imaginary examples are intentionally omitted from the active literal surface here.
Cluster literals
Cluster literals represent both container types and construct types. Cluster literals are always enclosed within curly brackets { }. The difference between scopes and cluster literals is that cluster literals shoud always have comma , within the initializaion and assignment brackets, e.g { 5, }.
Containers
Some simple container expressions
{ 5, 6, 7, 8, } // array, vector, sequences
{ "one":1, "two":2, } // maps
{ 6, } // single element container
A 3x3x3 matrix
{{{1,2,3},{4,5,6},{7,8,9}},{{1,2,3},{4,5,6},{7,8,9}},{{1,2,3},{4,5,6},{7,8,9}}}
Constructs
// constructs
{ email = "someone@example.com", username = "someusername123", active = true, sign_in_count = 1 }
// nested constructs
{
FirstName = "Mark",
LastName = "Jones",
Email = "mark@gmail.com",
Age = 25,
MonthlySalary = {
Basic = 15000.00,
Bonus = {
HTA = 2100.00,
RA = 5000.00,
},
},
}
Call literals
Call literals are function calls that resolve to values:
var seven: int = add(2, 5); // assigning variables "seven" to function call "add"
`typ Vector: rec = { var x: flt var y: flt }
typ Rect: rec = { var pos: Vector var size: Vecotr }
fun make_rect(min, max: Vector): Rect { return [Rect]{{min.x, min.y}, {max.x - max.y, max.y - max.y}} return [Rect]{pos = {min.x, min.y}, size = {max.x - max.y, max.y - max.y}} }
`
Ranges
Current boundary:
- range expressions are not part of the current compiler surface; the compiler rejects them with a “not yet supported” diagnostic (T1002)
- range-based loop headers and range matching described in other chapters inherit this boundary and are not executable today
- everything below describes intended design, not current behavior
- this is later design work, not part of the current V1 compiler surface
There are two range expressions:
- Defined ranges
- Undefined ranges
Defined ranges
Defined ranges represent a group of values that are generated as a sequence based on some predefined rules. Ranges are represented with two dots .. operator.
{ 1..8 } // a range from 1 to 8
{ 1,2,3,4,5,6,7,8 }
{ 8..1 } // a range from 8 to 1
{ 8,7,6,5,4,3,2,1 }
{ 1..8..2 } // a range from 1 to 8 jumping by 2
{ 1,3,5,7 }
{ 3..-3 } // a range from 4 to -4
{ 3,2,1,0,-1,-2,-3 }
{ -3..3 } // a range from -3 to 3
{ -3,-2,-1,0,1,2,3 }
{ ..5 } // a range form 0 to 5
{ 0,1,2,3,4,5 }
{ ..-5 } // a range from 0 to -5
{ 0,-1,-2,-3,-4,-5 }
{ 5.. } // a range from 5 to 0
{ 5,4,3,2,1,0 }
{ -5.. } // a range from -5 to 0
{ -5,-4,-3,-2,-1,0 }
| syntax | meaning |
|---|---|
start..end | from start to end |
..end | from zero to end |
start.. | from start to zero |
Undefined ranges
Undefined ranges represent values that have only one side defined at the definition time, and the compiler defines the other side at compile time. They are represented with three dots ...
{ 2... } // from 2 to infinity
| syntax | meaning |
|---|---|
start... | from start to infinite |
In most of the cases, they are used for variadic parameters passing:
fun calc(number: ...int): int = { return number[0] + number[1] + number[2] * number[3]}
Access
Current boundary:
- namespace access, receiver-qualified routine access, single-element container
indexing (
c[i]), map key access, and record field access are the current compiler surface - bounded forward slicing (
c[1:3],c[:3],c[1:], and the whole-containerc[:]) is implemented forvec[...]andseq[...]; fixed-size array slices still need an explicit runtime-sized result type c[:]is a slice and stays distinct fromc[]: the empty form is the inner-place access, which a container rejects with “inner-place access ‘[]’ requires a pointer, ‘opt[T]’, or ‘err[T]’ receiver” (see pointers)- single-element assignment (
c[i] = v) is implemented forarr[...]andvec[...]; see the container chapter for which containers and bindings qualify - reverse slicing (
c[::]), the bulk in-place form (c[x => Y]), slice assignment, and the whole axiom (axi) access family are later design work, not part of the current compiler surface - the sections below are marked where they cross that line
There are four access expressions:
- namespace member access
- receiver-qualified routine access
- container member access
- field member access
Receiver-Qualified Routine Access
One access form is the receiver-style routine call. In FOL this remains procedural syntax: the receiver value is the first routine input, and the dot form is only call-site sugar.
A receiver-qualified call consists of an expression (the receiver), followed by
a single dot ., a routine name, and a parenthesized expression list:
"3.14".cast(float).pow(2);
Read:
value.method(arg1, arg2)
as:
method(value, arg1, arg2)
This spelling does not create classes, objects, inheritance, or runtime method ownership. It is just a shorter way to call a receiver-qualified routine.
Namespace Access
Accessing namespaces is done through the double-colon operator :::
use std: pkg = {"std"};
var shown: int = std::nums::gcd(84, 36);
This particular namespace is part of bundled std, so the package must use a
memo artifact and declare the internal standard dependency in build.fol.
The pkg target is the declared alias ("std"); the module inside it is reached
with ::, not by embedding std/... in the import target.
Container Access
Array, Vectors, Sequences, Sets
Containers can be indexed by writing a square-bracket-enclosed expression of
type int[arch] after them.
var collection: int = { 5, 4, 8, 3, 9, 0, 1, 2, 7, 6 }
collection[5]
collection[-2]
Containers can be accessed with a specified range too, by using colon within a square-bracket-enclosed:
The current executable subset applies these forward forms to vec[...] and
seq[...]. It creates a new container, so V3 rejects slices whose elements are
move-only. Fixed-size arr[...] slicing and the reverse forms below remain
design material.
| syntax | meaning |
|---|---|
: | the whole container |
elA:elB | from element elA to element elB |
:elA | from beginning to element elA |
elA: | from element elA to end |
collection[-0] // last item in the array
{ 6 }
collection[-1:] // last two items in the array
{ 7, 6 }
collection[:-2] // everything except the last two items
{ 5, 4, 8, 3, 9, 0, 1, 2 }
If we use double colon within a square-bracket-enclosed then the collection is inversed:
| syntax | meaning |
|---|---|
:: | the whole container in reverse |
elA::elB | from element elA to element elB in reverse |
::elA | from beginning to element elA in reverse |
elA:: | from element elA to end in reverse |
collection[::] // all items in the array, reversed
{ 6, 7, 2, 1, 0, 9, 3, 8, 4, 5 }
collection[2::] // the first two items, reversed
{ 4, 5 }
collection[-2::] // the last two items, reversed
{ 6, 7 }
collection[::-3] // everything except the last three items, reversed
{ 2, 1, 0, 9, 3, 8, 4, 5 }
Matrices
Matrices are 2D+ arrays, so they use nested index access:
var aMat = mat[int, int] = { {1,2,3}, {4,5,6}, {7,8,9} };
nMat[[1][0]]
All other access forms behave like arrays.
Maps
Accessing maps is done by using the key inside square brackets:
var someMap: map[str, int] = { {"prolog", 1}, {"lisp", 2}, {"c", 3} }
someMap["lisp"]
Axioms
Accessing axioms is similar to accessing maps, but matching is broader and the result is always a vector of matches:
var parent: axi[str, str] = { {"albert","bob"}, {"alice","bob"}, {"bob","carl"}, {"bob","tom"} };
parent["albert",*]
parent["bob",*]
parent[*,_]
Matching can be with a vector too:
var parent: axi[str, str] = { {"albert","bob"}, {"alice","bob"}, {"bob","carl"}, {"bob","tom"}, {"maggie","bill"} };
var aVec: vec[str] = { "tom", "bob" };
parent[*,aVec]
A more complex matching example:
var class: axi;
class.add({"cs340","spring",{"tue","thur"},{12,13},"john","coor_5"})
class.add({"cs340","winter",{"tue","fri"},{12,13},"mike","coor_5"})
class.add({"cs340",winter,{"wed","fri"},{15,16},"bruce","coor_3"})
class.add({"cs101",winter,{"mon","wed"},{10,12},"james","coor_1"})
class.add({"cs101",spring,{"tue","tue"},{16,18},"tom","coor_1"})
var aClass = "cs340"
class[aClass,_,[_,"fri"],_,*,_]
In-Place Assignment
Some access forms can bind a value while matching:
var val: vec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
var even: vec = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
val[even => Y]
.echo(Y)
Field Access
Field access expressions access stored data inside record-like values. Here is
an example record user:
var user1: user = {
email = "someone@example.com",
username = "someusername123",
active = true,
sign_in_count = 1
};
fun (user)getName(): str = { result = self.username; };
There are two things you may access on such a value:
- receiver-qualified routines
- data fields
Receiver-Qualified Routines
The same dot spelling is used for receiver-qualified routines, but they remain ordinary routines rather than object-owned behavior:
user1.getName()
Data
There are multiple ways to access stored data. The simplest is the dot
operator .:
user1.email
Another way is by using square bracket enclosed by name:
user1[email]
And lastly, by square bracket enclosed by index:
user1[0]
Metaprogramming
This section describes the compile-time extension surface of FOL.
Metaprogramming facilities allow source to be generated, transformed, or specialized before normal execution semantics apply.
The chapter family currently covers:
- built-ins
- macros
- alternatives
- defaults
- templates
These features are powerful but high-risk for readability. They should be used to remove repetitive structure, not to obscure ordinary program logic.
Intrinsics
Intrinsics are compiler-owned language operations.
They are not ordinary library functions, and they are not imported through
use.
FOL currently keeps compiler intrinsics and three API tiers separate:
- intrinsics:
compiler-owned operations such as
.eq(...),.len(...),check(...), andpanic(...) core: the minimal runtime model with no heap and no source-level hosted OS/runtime APIsmemo: alloc-like heap-backed library/runtime support without source-level hosted OS/runtime APIsstd: the hosted API tier layered onmemoby an explicit bundled internal dependency, with shipped services such as console I/O
This split is not a source-level import trick and not an object-system feature.
core and memo are artifact capability models selected through fol_model
in build.fol. Bundled std is not a third model; it is declared separately
with build.add_dep({ alias = "std", source = "internal", target = "standard" })
for a memo artifact that needs hosted source APIs.
Whether an artifact can be launched is orthogonal. Host-compatible core and
memo programs can use fol code run or fol code test without bundled
std; the frontend launching them does not expose extra intrinsics.
If an operation can live as an ordinary library API, that is usually the better home for it. Intrinsics are reserved for surfaces the compiler must understand directly.
Surfaces
The current compiler recognizes two intrinsic surfaces.
Dot-root calls
These are written with a leading dot:
.eq(a, b)
.not(flag)
.len(items)
.echo(value)
Dot-root intrinsics are the main current intrinsic family.
Keyword calls
These look like language keywords rather than dot calls:
check(read_code(path))
panic "unreachable state"
assert count > 0, "the queue was drained twice"
The current compiler treats check, panic, and assert as intrinsics too,
even though they are not written with ..
panic and assert take their arguments without parentheses, like the
keywords they are. assert(flag) happens to parse only because (flag) is a
parenthesized expression; assert(flag, "message") is a parse error.
Current V1 implemented intrinsics
The current compiler implements this subset end to end through type checking and lowering.
For current V1, backend execution of the implemented intrinsic set still goes
through the current runtime layer where policy matters. The runtime contract is
split by the artifact’s fol_model and active bundled dependency, so the rule
is:
coreartifacts must not rely on heap-backed or source-level hosted APIsmemoartifacts may use heap-backed facilities but not source-level hosted APIs- bundled
stdwrappers require amemoartifact plus explicit internalstandarddependency
Because that last tier is two things, the diagnostic for it names whichever half
is missing. On a core artifact it asks for both; on a memo artifact it asks
only for the dependency and says so, since the model is already the right one:
'.chr_to_int(...)' requires hosted std support; declare
build.add_dep({ alias = "std", source = "internal", target = "standard" })
(current artifact model is 'memo', which is already the right one)
There is no third fol_model to reach for — the accepted values are core and
memo, and hosted std is memo plus the dependency.
All three API tiers may back executable artifacts. Process entry and recoverable outcome adaptation are backend-only support, not bundled-std intrinsics.
In the current implementation that means:
.len(...)uses the runtime length helper.echo(...)uses the runtime echo hook and formatting contractcheck(...)uses the runtime recoverable-result inspection contract- scalar comparisons and
.not(...)may lower to native target operations
Comparison
.eq(left, right)
.nq(left, right)
.lt(left, right)
.gt(left, right)
.ge(left, right)
.le(left, right)
Current V1 rule:
.eq(...)and.nq(...)work on comparable scalar pairs.lt(...),.gt(...),.ge(...), and.le(...)work on ordered scalar pairs
If you call them with the wrong number of arguments or with unsupported type families, the compiler reports an intrinsic-specific type error.
Boolean
.not(flag)
Current V1 rule:
.not(...)accepts exactly onebol
Query
.len(items)
Current V1 rule:
.len(...)accepts exactly one operand- the operand must currently be one of:
strarr[...]vec[...]seq[...]set[...]map[...]
.len(...) measures bytes for a str, not characters. .str_char_len(...)
is the character count; see “Text and characters” below for why the two worlds
are kept apart.
Under the runtime model split, array .len(...) belongs to core, while
string and dynamic-container .len(...) belongs to memo. It remains
available when a memo artifact also declares bundled std because the hosted
tier layers on top of memo; .len(...) does not itself require std.
Diagnostic
.echo(value)
Current V1 rule:
.echo(...)accepts exactly one argument- it requires a
memoartifact with the explicit bundledstddependency - it emits the value through the hosted runtime hook
- it then forwards the same value unchanged
.echo(...) belongs to std, not core or memo.
Introspection
.type_name(value)
.size_of(value)
Both read a fact about the operand’s type and never read the value, so they accept an operand of any type — including a generic parameter, which is what they exist for:
fun[exp] describe(T)(value: T): str = {
return .type_name(value) + " (" + .int_to_str(.size_of(value)) + " bytes)";
};
Called with an int that yields int (8 bytes); called with a vec[int],
vec[int] (24 bytes). The answer follows the caller, not the declaration.
Current rule:
.type_name(...)returns the FOL spelling:int,vec[int],map[str, int],opt[int], and the declared name for arecorenttype.size_of(...)returns the size of the value, not of what it owns — astrand avec[int]both report24, the size of the handle, because the characters and elements live on the heap- both peel
@andborfirst, so a loanedLedgerdescribes asLedgerand measures the Ledger rather than the loan;ptr[...]is not peeled, because a pointer is a value you hold .size_of(...)works incore;.type_name(...)returnsstrand so needsmemo, by virtue of its return type rather than any capability gate
Terminal and OS hooks
Everything from here down shares .echo(...)’s build contract: a memo
artifact with the explicit bundled std dependency. That includes the purely
numeric operations such as .bit_and(...) and .sqrt(...), which touch no OS
facility but are still gated this way today.
With that build contract, this is valid:
pro[] main(flag: bol): bol = {
return .echo(flag);
};
How failure is reported
A hosted call reports failure with a sentinel, not a recoverable error: -1
for an integer result, and the empty string for a text one. That is uniform —
there is no routine here that signals failure with 1.
A sentinel says that something went wrong and nothing about what, so the
reason is fetched afterwards, the way errno works:
.os_error()— the reason as text, or""when the last hosted call succeeded.os_error_kind()— a stable integer code, or0on success
var text: str = .read_file(path);
if (.len(text) == 0) {
.write("cannot read " + path + ": " + .os_error() + "\n");
} else {
};
Both are cleared by a successful call, so a stale reason is never read as a fresh one, and both are per-thread, so two threads failing at once do not overwrite each other.
Branch on the code rather than the message — the text is the operating system’s
wording and is not a contract. std::os exports the codes by name
(ERR_NOT_FOUND, ERR_DENIED, …) along with not_found() and denied():
0 none 8 address in use
1 not found 9 address unavailable
2 denied 10 broken pipe
3 exists 11 would block
4 refused 12 timed out
5 reset 13 invalid input
6 aborted 14 invalid data
7 not connected 15 unexpected end of file
16 interrupted
17 wrote zero
99 anything else
The numbers are part of the surface and will not be renumbered. 99 absorbs
every other cause, including kinds Rust has not stabilised, so a toolchain
upgrade cannot silently change an existing code.
This is what makes .read_file(...) usable: it returns "" for a missing file,
an empty file, and one that is not valid UTF-8, and the error kind is what
tells those apart.
Console and terminal
.write(text)— write a string to stdout without a trailing newline and flush it; forwards the string unchanged.write_err(text)— write to standard error without a trailing newline.read_key()— block for one byte of standard input; yields-1at end of input.read_key_ms(timeout)— like.read_key()but gives up after the timeout, yielding-2on timeout and-1at end of input.read_line()/.read_all()— a line, or the whole of standard input.raw_mode(enable)— enable or disable terminal raw mode; forwards the requested state.term_cols()/.term_rows()— terminal size (80×24 when it cannot be determined)
Numbers
Integer helpers:
.min(a, b)/.max(a, b)/.abs(value).parse_int(text, fallback)— parse an integer, or the caller’s fallback; the fallback is an argument because every sentinel is also a valid parse result
Bitwise, on signed 64-bit int values, including negative operands. These pure
scalar operations are available in core, memo, and hosted artifacts without
adding a bundled std dependency:
.bit_and(a, b)/.bit_or(a, b)/.bit_xor(a, b)/.bit_not(value).shl(value, count)/.shr(value, count)—.shr(...)is arithmetic, so a negative value shifts sign bits in.rotl(value, count)/.rotr(value, count).pop_count(value)/.clz(value)/.ctz(value)— set bits, leading zeros, trailing zeros
Shifts require a count from 0 through 63 and fault otherwise in every profile. Rotations reduce their count modulo 64, including negative counts. Counts of leading or trailing zero bits in zero are both 64.
.bit_not(...) is the one that leaves the non-negative range: an int is 64-bit
two’s complement, so .bit_not(0) is -1. Work at a narrower width by masking
after each step — .bit_and(value, 0xFFFFFFFF) keeps a 32-bit word 32 bits wide,
which is how std::hash’s SHA-256 is built out of these.
Overflow-mode arithmetic. Plain +, -, and * fault on overflow; these are
how you choose a different answer:
.checked_add(a, b)/.checked_sub(a, b)/.checked_mul(a, b)/.checked_div(a, b).wrapping_add(a, b)/.wrapping_sub(a, b)/.wrapping_mul(a, b).saturating_add(a, b)/.saturating_sub(a, b)/.saturating_mul(a, b)
Floating point:
.sqrt(value),.flt_abs(value).sin(value),.cos(value),.tan(value),.asin(value),.acos(value),.atan(value),.atan2(y, x),.hypot(x, y).ln(value),.log2(value),.log10(value),.exp(value).is_nan(value),.is_inf(value),.flt_is_finite(value).flt_floor(value),.flt_ceil(value),.flt_round(value).flt_copysign(magnitude, sign),.flt_rem(a, b),.flt_mul_add(a, b, c),.flt_next_after(from, toward).flt_bits(value)/.flt_from_bits(bits)— the IEEE-754 bit pattern, which is how you compare or hash a float exactly
Conversions:
.int_to_str(value)/.float_to_str(value, decimals).flt_to_str_exact(value)— the shortest text that parses back to the identical value..float_to_str(...)takes a fixed number of decimals, which either loses precision or pads noise, so neither setting round-trips:0.1renders as0.100000at six decimals but as0.1here..flt_bits(...)remains the exact machine form; this is the exact human-readable one.int_to_flt(value)/.flt_to_int(value)/.parse_flt(text, fallback)
Text and characters
FOL strings are UTF-8, and the intrinsics are split into a byte world and a character world. Mixing them is the usual source of bugs, so the names say which one they belong to:
- byte world:
.len(text),.str_sub(text, start, count),.str_find(text, needle),.str_byte(text, index) - character world:
.str_char_len(text),.str_char(text, index),.str_chars(text)
.str_char_index(text, char_index) is the only bridge between them: it turns a
character index into a byte index.
There is a third measure that is neither: terminal columns. 日本 is 6
bytes, 2 characters, and 4 columns, so padding a table with .len(...) or
.str_char_len(...) misaligns it. .str_width(text) and .chr_width(c) are
what a column width has to be computed from.
-
.str_bytes(text)/.str_from_bytes(bytes)— text to its UTF-8 bytes and back..str_from_bytes(...)is the only way to rebuild text from.read_bytes(...),.random_bytes(...), or.file_read(...):.byte_to_str(...)handles one byte and so cannot express a multi-byte character at all. Invalid input yields the empty string rather than substituting replacement characters, so a caller never acts on half-decoded text -
.bytes_valid_utf8(bytes)— whether a byte vector decodes; worth asking when empty input and invalid input have to be told apart -
.utf8_prefix_len(bytes)— how many leading bytes form complete UTF-8. Required by any chunked reader: a fixed-size read splits characters across chunk boundaries, and a chunk ending mid-character decodes to the empty string. Decode the prefix, carry the remainder.std::fs::decoderwraps the whole pattern, andstd::fs::read_streameduses it -
.str_normalize(text, form)/.str_is_normalized(text, form)— see below -
.str_width(text)/.chr_width(c)— terminal columns: 0 for combining marks and controls, 2 for CJK, kana, Hangul, fullwidth forms and the common emoji planes, 1 otherwise. It is a range table, aswcwidthalways is, so a rare combining mark outside the listed ranges counts as one column instead of zero -
.str_sub(text, start, count)— a byte-range slice snapped to UTF-8 boundaries -
.str_byte(text, index)/.byte_to_str(value)— byte inspection and single-byte construction -
.str_byte_len(text)/.str_char_len(text)— length in bytes, length in characters -
.str_valid_utf8(text)— whether the bytes decode -
.str_find(text, needle)— the byte index of the first occurrence, or-1 -
.str_replace(text, from, to)— replace every occurrence -
.str_trim(text),.str_upper(text),.str_lower(text) -
.str_chars(text)/.str_from_chars(chars)— a string asvec[chr]and back -
.chr_upper(c)/.chr_lower(c)— full Unicode case, not ASCII-only -
.chr_is_alpha(c)/.chr_is_digit(c)/.chr_is_space(c) -
.chr_to_int(c)/.int_to_chr(value)/.chr_to_str(c)
Normalization
The same word can be typed two ways. é as e plus a combining accent and é
precomposed look identical, compare unequal, and report different lengths:
var typed: str = "e\u{0301}llo";
var stored: str = "éllo";
// typed == stored is false
// .str_char_len(typed) is 5
// .str_char_len(stored) is 4
// std::strn::same_text(typed, stored) is true
Any comparison against text a person typed — a login name, a search box, a filename — has to normalize both sides first, or it rejects input the user believes is correct.
.str_normalize(text, form) takes a form selector:
0NFC — compose. The default for storing and comparing1NFD — decompose. Useful for stripping accents, since it separates the base letter from its marks2NFKC — compose, folding compatibility variants first:fibecomesfi, fullwidthAbecomesA. Lossy by design: right for a search key, wrong for text handed back to the user, because it discards distinctions the author made3NFKD — decompose with the same folding
An unknown form returns the input unchanged. .str_is_normalized(text, form)
answers without doing the work, which is worth it for stored text where the
answer is usually yes.
std::strn wraps these as nfc, nfd, nfkc, nfkd, is_nfc, plus
same_text(left, right) for comparing user input and search_key(text) for
duplicate detection.
The Unicode data behind this is generated into the runtime, not pulled from
a crate: the runtime is compiled by a bare rustc with no dependency
resolution, so it can only carry plain data. See
fol-runtime/tools/README.md to regenerate.
Time and randomness
-
.now_ms()/.now_ns()— since the unix epoch; wall-clock, so it can jump -
.mono_ns()— a monotonic reading, which is the one to measure durations with -
.sleep_ms(ms)/.sleep_ns(ns) -
.time_parts(epoch_secs)— a timestamp split into calendar fields, in UTC -
.time_from_parts(fields)— the inverse -
.tz_offset_sec(epoch_secs)— seconds to add to UTC for local time. Since.time_parts(...)is UTC-only, without this every timestamp a program shows its reader is wrongIt takes the instant because the offset is not a constant: the same zone is
3600in January and7200in July. The whole zone database applies, including the daylight-saving rule in force at that moment, which is the part a hand-rolled reader gets wrong.std::time::local_parts(...)combines the two -
.random_int(low, high)/.random_flt()— from the operating system, so unpredictable and unrepeatable -
.random_bytes(count)— raw entropy
Two kinds of randomness
The intrinsics above take entropy from the operating system, so they are unpredictable and unrepeatable. That second property is often the problem: a test, a simulation, or procedural generation needs to produce the same result twice.
std::rand is the other tool — seeded, repeatable, and written in FOL over the
bitwise intrinsics rather than reaching the OS at all:
var[mut] rng: std::rand::Rng = std::rand::seeded(2024);
var roll: std::rand::Draw = std::rand::next_range(rng, 1, 7);
// roll.value is the die; roll.rng is the advanced generator
The generator is a pure routine, so it returns the advanced state alongside the
value and the caller threads it along. Seed from std::rand::from_os() when you
want a different stream each run but still want to be able to log the seed and
reproduce a failure.
The algorithm is xorshift64*: Vigna’s 12/25/27 shift triple over a full 64-bit state, with the output passed through a multiplicative scrambler.
That final multiply is not decoration. A plain xorshift is linear over GF(2) — every output is a linear function of the state — so its outputs are far more predictable than their frequency histogram suggests. Reading 96-bit vectors out of the two generators and taking the rank of a 96×96 binary matrix shows it plainly:
plain xorshift, no scrambler: rank 46 of 96 (on every seed)
xorshift64* as shipped: rank 95 of 96 (on every seed)
95 is the expected rank for a genuinely random binary matrix. A %-reduction
test — die rolls, bucket indices, coin flips — cannot see the difference at
all; both look uniform. This is why the scrambler is there.
It is still not cryptography. The state is recoverable from the output,
which is precisely what makes it repeatable. When unpredictability matters, use
.random_bytes(...).
Seeds are ordinary 64-bit integers, negatives included. Only zero is special: it is a fixed point that would emit zeros forever, so it is replaced.
Files and directories
Whole-file access:
.read_file(path)/.write_file(path, contents)/.append_file(path, text).read_bytes(path)/.write_bytes(path, bytes)— for content that is not UTF-8; the text forms assume it is.file_exists(path),.is_file(path),.is_dir(path),.file_is_link(path).file_size(path),.file_mtime(path).make_dir(path),.remove_file(path),.remove_dir_all(path).rename_file(from, to),.copy_file(from, to).dir_list(path)— the sorted entries, directories suffixed with/.dir_entries(path)— the same as a vector.read_link(path),.make_symlink(target, link)— follow and create. Creating was missing, which left any program managing acurrent -> releasesymlink unwritable.permissions(path),.set_permissions(path, mode).current_dir(),.set_current_dir(path),.temp_dir(),.home_dir().realpath(path)— the absolute path with symlinks and..resolved on disk.std::path::normalizeresolves..textually, which is a different answer whenever a symlink is involved, so only this one can decide whether a path stays inside an allowed directory. The path must already exist.temp_file(prefix)— creates a uniquely named empty file in the temp directory and returns its path. The create is the point: choosing a name in FOL and then opening it would race, because another process could take the name in between. With.rename_file(...), this is the safe-write pattern — write a temp file, then rename it over the target so a reader never sees a half-written one.file_lock(handle, exclusive, wait)/.file_unlock(handle)— advisory whole-file locking, which is how a program stays single-instance: take an exclusive lock on a known path and exit if another process holds it.waitfalse returns-1immediately instead of blocking, so a caller can report “already running” rather than hang. Advisory means it binds only processes that also ask; it does not stop an unrelated writer
Streaming, for a file larger than memory or one still being written — the whole-file forms cannot do either:
.file_open(path, mode)— mode0read,1truncate-or-create,2append,3read-write. An integer rather than"r"/"w", matching the selector arguments this surface already uses in.file_seek(...)and.tcp_shutdown(...).std::fsexportsMODE_READ…MODE_UPDATEandopen_read/open_write/open_append/open_updateso nobody has to remember the numbers.file_read(handle, count)— up tocountbytes. Short reads are not EOF. For a positive count, an empty result is EOF only when.os_error_kind()is zero; an error also returns an empty vector. Negative counts are rejected.file_write(handle, bytes)— the byte count written, or-1.file_seek(handle, offset, whence)—whence0start,1current,2end; returns the new absolute position.file_flush(handle)/.file_close(handle).pipe_open()— an anonymous byte pipe as[read_handle, write_handle]on Unix, or[-1, -1]on failure. Both ends use the file read/write/close API.std::fs::pipe()wraps it
Open/read/write/close set the thread-local OS error on failure and clear it on success, including EOF. Writes may be short; callers must loop over remaining bytes. Pipe ends and their duplicates are close-on-exec. Closing a registry handle does not interrupt I/O already using a duplicated descriptor and is not a durable-storage synchronization operation. Every copy of a pipe writer must close before readers observe EOF.
Reads and writes are bytes, not text, so the surface is binary-safe;
.str_bytes(...) and .str_from_bytes(...) bridge to text. Do not feed a
raw chunk to .str_from_bytes(...) — see .utf8_prefix_len(...) above, and
prefer std::fs::read_streamed(path, chunk), which is lossless at every chunk
size.
Process and environment
.arg_count()/.arg_at(index)— the command-line arguments, excluding the program name; an index past the end reads as the empty string.arg_program()— argv[0], the path this program was invoked as.arg_at(0)is the FIRST argument, so this is what a usage message should name and what a program re-executes.env_var(name),.env_vars(),.set_env_var(name, value).unset_env_var(name)— removing is not the same as setting to"". An empty value is still a present variable, and a child process can tell the difference.process_id().shell(command)— run throughsh -cwith inherited streams and yield the exit status;128 + signalif a signal killed it,127if the shell could not be launched.shell_out(command)— the same, capturing standard output.run_capture(program, args)/.run_status(program, args)— run a program directly, without a shell, so no quoting or word-splitting applies.run_input(program, args, stdin)— the same, with text on the child’s standard input, written concurrently with stdout/stderr capture. Early stdin closure preserves the child’s status and captured output..run_capture(...)gives the child a closed stdin, so every filter-shaped program (sort,sha256sum,git hash-object --stdin) needs this one.exit_process(status)
Supervised children. .run_capture(...), .run_status(...) and
.run_input(...) all block until the child exits — right for a filter, useless
for anything you intend to watch and stop. These separate starting from waiting:
.child_spawn(program, args)— start without waiting, yielding a handle. Standard streams are inherited, so the child shares this program’s terminal; when the output is what you want,.run_capture(...)is still the answer.child_spawn_io(program, args, streams)— start with exactly three stream selectors[stdin, stdout, stderr]:0inherits,-1uses the null device, and positive file handles are duplicated. Caller handles are not consumed; close unused pipe ends after spawning. Invalid selectors or spawn failure return-1with an OS error and release temporary descriptors. Separate pipe read/write tasks can stream binary data while the child remains cancellable.std::os::spawn_iowraps it; waiting does not close caller-owned pipe handles.child_pid(handle)— the unreaped child’s process id, for logging only; it is not an ownership token for later raw PID signaling.child_try_wait(handle)— the exit status if it has finished,-2while it is still running,-1for an unknown handle, signal exit or OS error. A finished child keeps its status, so reading it twice gives the same answer and a later.child_wait(...)still works.child_wait(handle)— block until it exits, then release the handle so the child is never left as a zombie. Returns the kept status when a poll already saw it finish. The child remains available for concurrent polling/signaling during the wait; unrelated children remain usable. Only one waiter can consume a handle; a concurrent second waiter returns-1. An OS wait error retains the handle for retry.child_kill(handle, signum)—0meansSIGKILL, which cannot be caught; positive signed-32-bit numbers are sent as given, so15requests termination. Negative or wider numbers are rejected without signaling. Signaling is serialized with reaping, and a reaped/consumed handle is never signaled. These APIs supervise a direct child, not its process group or descendants
Signals:
.signal_trap(signum)— record a signal instead of dying from it. Returns0, or-1for an out-of-range number or one the kernel refuses (SIGKILLandSIGSTOPcannot be caught).signal_pending()— the lowest trapped signal that has arrived since the last call, or0. Reading it clears the flag, so each delivery is reported once
The surface is a poll rather than a callback on purpose: the handler itself can only do async-signal-safe work, and running FOL code inside one would not be safe. Trap the signal, then check for it at a point of your choosing — the top of an event loop, or between units of work.
Network
TCP sockets are integer handles:
.tcp_listen(address),.tcp_accept(handle),.tcp_connect(address).tcp_connect_timeout(address, ms)— connect to one numeric IPv4 or bracketed IPv6 endpoint with a positive millisecond budget. Returns-1on error;.os_error_kind()distinguishes timeout, refusal and invalid inputs. It does not resolve host names or set later I/O deadlines..tcp_read(handle),.tcp_write(handle, text),.tcp_close(handle).tcp_local_addr(handle),.tcp_peer_addr(handle).tcp_set_timeout(handle, ms)— without it, a read on a peer that stopped talking blocks until the peer goes away.tcp_set_nodelay(handle, enable).poll_read(handles, ms)waits for readable sockets, EOF, or socket errors. A negative budget waits until a watched socket is ready or all watched handles are retired. Retired handles are never reported as ready..tcp_try_read(handle)— the text result is empty both when no data is available yet and when the peer closed its write side. Use the binary interface when the distinction matters..tcp_shutdown(handle, how)— half-close:0read,1write,2both. This is not.tcp_close(...); shutting down the write side tells the peer no more data is coming while the read side stays open for its reply
UDP and name resolution:
.udp_bind(address),.udp_send_to(handle, address, text),.udp_recv_from(handle)— the receive form returns the payload and the sender’s address.dns_resolve(host)— every address a name resolves to; an empty vector when it resolves to none, rather than a fault
For binary protocols, use these byte operations (also exported from
std::os). They never interpret a payload as text.
.tcp_read_bytes(handle, count)performs one read with a limit from 1 to 65,536 bytes. An empty result with.os_error_kind() == 0is stream EOF..tcp_try_read_bytes(handle, count)does not change the socket’s blocking mode;.os_error_kind() == 11means nothing is ready yet..tcp_write_bytes(handle, bytes)accepts at most 65,536 octets and returns the count written. A short write leaves its suffix to the caller. Negative means failure. Octets must be integers from 0 to 255..tcp_try_write_bytes(handle, bytes, offset)attempts one write of the suffix starting at a byte offset in the same bounded vector. On Linux it does not change the socket mode. Advance the offset by the returned count; a would-block result is -1 with OS error kind 11 and requires no advance..udp_recv_bytes(handle, limit)consumes one datagram with a 1–65,536 byte limit and no peer address. Zero bytes with no error is a valid empty packet. An oversized datagram is consumed and reports invalid data (code 14); no partial datagram is returned..udp_send_bytes(handle, address, bytes)sends one datagram and returns the byte count or-1. Check.os_error_kind()before another hosted operation.
Serving several connections at once:
.poll_read(handles, timeout_ms)— which requested sockets are readable or have pending EOF/error. It waits up totimeout_ms; negative waits indefinitely. Unknown and retired handles are ignored. An empty result can mean timeout or no live sockets; check the OS error slot for failure. Closing a handle does not make a waiting poll return immediately.
Without it, serving several connections means a thread per connection — which
FOL can do with [spn], and which stops scaling once the connections outnumber
what the scheduler should carry. This is the other shape: one thread, many
sockets. A listener becomes ready when a connection is pending, so the same call
covers both accepting and reading.
Concurrency
.cpu_count()— how many threads can genuinely run at once; sizing a worker pool above this adds scheduling cost, not throughput.thread_yield()— hand back the rest of the time slice.thread_id()— a small integer per thread, stable within a run
Atomic counters are shared integers addressed by handle. They are deliberately
narrower than mux[T]: a mutex protects arbitrary compound state and costs a
lock, while these compile to one instruction and cannot deadlock, because there
is no window in which the value is held. Reach for mux[T] the moment two
fields have to agree.
.atomic_new(initial)— create one, yielding its handle.atomic_load(handle)/.atomic_store(handle, value).atomic_add(handle, delta)— returns the value before the addition, so concurrent callers each receive a distinct number; that is what makes it a ticket dispenser.atomic_cas(handle, expected, desired)— swap if unchanged, returning the value it found. Equal toexpectedmeans the swap happened; anything else is the current value to retry against, which is what a lock-free update loop needs
Because a handle is an ordinary int, a counter crosses a [spn] boundary
with no reference threading. A missing handle is inert: a load reads 0 and a
store yields -1.
Hashing and secrets
.hash_bytes(text)— a stable 64-bit SipHash-2-4. The same input gives the same number in every run and every build, so it is safe to persist or shard on, unlike the randomly-keyed hash behindmap[K, V]. That stability is also the limit: the key is fixed, so it does not resist an attacker who chooses inputs to collide, and it is not a cryptographic digest. Usestd::hashfor SHA-256 when an adversary is involved. The result covers the full 64-bit range and is often negative..bytes_equal_ct(left, right)— compare in time that depends only on length, never on where the two first differ. Ordinary==returns as soon as it finds a mismatching byte, so anyone who can time it learns how many leading bytes they guessed correctly and can recover a secret one byte at a time. A FOL loop compiles to the same early exit, which is why this cannot be written in FOL. Use it for tokens, MACs, and password hashes; use==everywhere else, since this is slower by design.
The bundled std package wraps much of this surface — std::io::write,
std::fs::read_file, std::os::env, std::fmt::int_to_str, std::strn::find,
std::time::now_ms, std::sync::counter, and so on. Prefer the wrappers: they
are named for what you are doing rather than for the primitive underneath, and
they are where the shared logic accumulates.
The entry point’s command line and exit status
An entry routine’s parameters are bound, in order, to the command-line
arguments that follow the program name. Only the scalar builtins are bound
this way: int, flt, bol, chr, and str. bol accepts
true/1/yes/on and false/0/no/off.
A command line that does not satisfy the signature is a usage error, not a
default. A missing argument, or one that does not parse as the declared type,
writes a message naming the position and the expected type to standard error
and exits with status 2. Nothing silently becomes 0 or "".
pro[] main(count: int, label: str): int = {
return .echo(count);
};
$ ./program notanumber hello
fol: command-line argument #1 is not a valid `int`: `notanumber`
$ echo $?
2
A parameter of any other type is not bound from the command line; it is
constructed empty. Read the command line yourself with .arg_count() and
.arg_at(index) when you need anything richer than a scalar.
The entry’s int return value is the process exit status:
fun[] main(): int = {
return 3;
};
$ ./program; echo $?
3
This holds on both channels. A plain fun[] main(): int exits with the value
it returns, and a recoverable fun[] main(): int / E exits with the returned
value when it returns and with 1, after printing the error, when it reports.
An entry declared : non always exits 0. Exit statuses are truncated to
their low 8 bits by the operating system, so keep them in 0..=255; 0 means
success by convention.
Because main’s return is the exit status, return .echo(value) makes the
echoed value the status too. Return 0 explicitly when a program succeeds.
Recoverable and control intrinsics
check(read_code(path))
panic "fatal"
assert total >= 0;
assert total >= 0, "a ledger total went negative";
Current rule:
check(expr)asks whether a recoverable/ ErrorTypeexpression failed and returnsbol; that expression may be a direct routine call or, in V3, an awaited recoverable eventualpanic(...)aborts control flow immediatelyassert conditionandassert condition, messagefault unless the condition holds
assert is not a terminator the way panic is. Control continues when the
condition holds, so it is an ordinary effect rather than a diverging one; the
compiler does not treat the code after it as unreachable.
A failing assert produces a normal runtime fault:
fol runtime fault: assertion failed: a ledger total went negative
The bare form works in every capability model. The message form takes a str
and so needs memo, since str does not exist below it.
check and panic are described in more detail in the recoverable-error
chapter.
Backtraces
.backtrace()
Returns the call stack at that point as text, captured whether or not
RUST_BACKTRACE is set. Frames carry the generated symbol names rather than
FOL source spellings, and an optimized build may inline frames away entirely.
It is a debugging aid, not something to parse. Like the other hosted hooks it
needs a memo artifact with bundled std.
Intrinsics are not shell operations
Do not confuse intrinsics with shell operations such as nil and [uwp]
unwrapping.
For example:
ali MaybeText: opt[str];
ali Failure: err[str];
fun[] unwrap_optional(value: MaybeText): str = {
return [uwp]value
};
fun[] unwrap_failure(value: Failure): str = {
return [uwp]value
};
That [uwp] operation is part of shell typing, not the intrinsic registry.
Likewise, recoverable routine calls such as:
fun[] read_code(path: str): int / str = { ... }
and V3 recoverable results produced by eventual | await are handled with:
check(expr)expr || fallback
not with shell unwrap.
Current compiler truth
The current compiler has one shared intrinsic registry crate:
fol-intrinsics
That registry is the source of truth for:
- canonical intrinsic names and aliases
- milestone availability (
V1/V2/V3) - type-checking selection rules
- lowering mode
- backend/runtime role classification
The current runtime companion for implemented V1 intrinsics is:
fol-runtime
- intrinsic names
- aliases
- categories
- current milestone availability
- deferred-roadmap classification
- lowering mode
- backend-facing role
So the short rule is:
- parser recognizes intrinsic syntax
fol-intrinsicsowns intrinsic identity- type checking validates intrinsic calls
- lowering maps them to explicit IR shapes
This page should describe only the subset that is actually implemented, plus clearly marked deferred surfaces.
Macros
Current boundary:
- the
def-based meta family (macros, alternatives, defaults, templates) is planned for a future release; none of it is part of the current compiler surface - everything below describes intended design, not current behavior
Macros are intended to support source-level replacement. They will not be able
to redefine the compiler-owned ownership surface: the bracketed operations
([mov], [bor], [ref], [drf], [cpy], [cln], …) and the binding sigils
that remain in the language have fixed ownership, borrowing, and pointer
semantics.
def '$'(a: any): mac = '.to_string'
Alternatives
Current boundary:
- the
def-based meta family (macros, alternatives, defaults, templates) is planned for a future release; none of it is part of the current compiler surface - everything below describes intended design, not current behavior
Alternatives are intended to provide shorter source spellings. They will not alias or override the compiler-owned memory sigils. The exact future grammar and supported replacement targets remain open until the meta family is implemented.
Defaults
Current boundary:
- the
def-based meta family (macros, alternatives, defaults, templates) is planned for a future release; none of it is part of the current compiler surface - everything below describes intended design, not current behavior
Defaults are intended to change option defaults within an already legal
capability tier. They cannot turn a heap-backed type into a core type or grant
hosted APIs. In particular, str remains a memo type regardless of a future
mutability/default declaration. A possible future spelling for changing its
option defaults is:
def 'str': def[] = 'str[new,mut,nor]'
Templates
Current boundary:
- the
def-based meta family (macros, alternatives, defaults, templates) is planned for a future release; none of it is part of the current compiler surface - everything below describes intended design, not current behavior
Templates are supposed to be mostly used for operator overloading. They are glorified functions, hence used with pro or fun instead of def.
For example here is how the != is defined:
fun '!='(a, b: int): bol = { return .not(.eq(a, b)) }
assert 5 != 4;
or define $ to return the string version of an object (careful, it is object$ and not $object, the latest is a macro, not a template):
pro (file)'$': str = { return "somestring" }
.echo( file$ )
Type System
This section defines the built-in type families used throughout the language.
Every expression has a type, and every declaration that introduces a value or callable surface interacts with the type system.
The built-in type families are grouped as:
- ordinal types: integers, floats, booleans, characters
- container types: arrays, vectors, sequences, matrices, maps, sets
- complex types: strings, numeric abstractions, pointers, errors
- special types: optional, union-like/sum-style surfaces, any-like and none-like forms
User-defined type construction is described later in the declarations section under typ, ali, records, entries, and standards.
Ordinal
Ordinal types
Ordinal types have the following characteristics:
- Ordinal types are countable and ordered. This property allows the operation of functions as inc, ord, dec on ordinal types to be defined.
- Ordinal values have a smallest possible value. Trying to count further down than the smallest value gives a checked runtime or static error.
- Ordinal values have a largest possible value. Trying to count further than the largest value gives a checked runtime or static error.
Ordinal types are the most primitive type of data:
- Intigers:
int[options] - Floating:
flt[options] - Characters:
chr[options] - Booleans:
bol
Intiger type
An integer is a number without a fractional component. We used one integer of the u32 type, the type declaration indicates that the value it’s associated with should be an unsigned integer (signed integer types start with i, instead of u) that takes up 32 bits of space:
var aVar: int[u32] = 45;
Each variant can be either signed or unsigned and has an explicit size. Signed and unsigned refer to whether it’s possible for the number to be negative or positive—in other words, whether the number needs to have a sign with it (signed) or whether it will only ever be positive and can therefore be represented without a sign (unsigned). It’s like writing numbers on paper: when the sign matters, a number is shown with a plus sign or a minus sign; however, when it’s safe to assume the number is positive, it’s shown with no sign.
Length | Signed | Unsigned |
-----------------------------------
8-bit | 8 | u8 |
16-bit | 16 | u16 |
32-bit | 32 | u32 |
64-bit | 64 | u64 |
128-bit | 128 | u128 |
arch | arch | uarch |
Float type
Fol also has two primitive types for floating-point numbers, which are numbers with decimal points. Fol’s floating-point types are flt[32] and flt[64], which are 32 bits and 64 bits in size, respectively. The default type is flt[64] because on modern CPUs it’s roughly the same speed as flt[32] but is capable of more precision.
Length | Type |
--------------------
32-bit | 32 |
64-bit | 64 |
arch | arch |
Floating-point numbers are represented according to the IEEE-754 standard. The flt[32] type is a single-precision float, and flt[f64] has double precision.
pro[] main: int = {
var aVar: flt = 2.; // float 64 bit
var bVar: flt[64] = .3; // float 64 bit
.echo(.eq(aVar, bVar)) // compare values with the V1 intrinsic surface
var bVar: flt[32] = .54; // float 32 bit
}
Character type
In The Unicode Standard 8.0, Section 4.5 “General Category” defines a set of character categories. Fol treats all characters in any of the letter as Unicode letters, and those in the Number category as Unicode digits.
chr[utf8,utf16,utf32]
def testChars: tst["some testing on chars"] = {
var bytes = "hello";
.echo(.len(bytes));
.echo(bytes[1]);
.echo(.eq("e", "\x65"));
}
Current `V1` intrinsic note:
- `.eq(...)` is implemented for scalar equality
- `.len(...)` is implemented for strings and supported containers
- string `.len(...)` counts UTF-8 BYTES, not characters (`.len("héllo")` is 6);
`.str_char_len("héllo")` is 5
- `assert` is a keyword, not a dot call: `assert a == b;`, optionally with a
message as `assert a == b, "why this matters";`
- `.type_name(value)` reports a value's type as its FOL spelling, and
`.size_of(value)` its size in bytes; both accept an operand of any type
Boolean type
The boolean type is named bol in Fol and can be one of the two pre-defined values true and false.
bol
Container
Model reminder:
- examples here that call
.echo(...)assume amemoartifact with bundledstdsupport available arr[...]is valid incorevec[...],seq[...],set[...], andmap[...]requirememo
Current boundary:
- static
arr[...],vec[...],seq[...], andmap[...]are the current compiler surface - the
axi[...]axiom container and.add(...)mutation shown later are not implemented; they are later design work, not current behavior - element assignment (
c[i] = v) IS implemented, forarr[...]andvec[...]only, on a mutable binding or on one field of a record reached through a[mut, bor]receiver. It replaces an element; it never makes one appear.map(a write would have to add a key),set[...](each position has its own type) andseq[...](a persistent linked list) each reject it with their own message, as dofinand move-only element types, whose displaced value could not be accounted for vec[...]andmap[...]DO grow, through the methods in Container methods below.arr[...]carries its length in its type andseq[...]/set[...]have no method surface- the
set[...]tuple-member form typechecks, but only single-member sets are executable today; those homogeneous runtime sets support.len(...), deterministic positional lookup, and ordinary iteration
Containers are of compound types. They contain other primitive or constructed types. To access the types in container those brackets are used: [], so:
var container: type = { element, element, element } // declaring a container
var varable: type = container[2] // accessing the last element
Note
Containers are always zero indexed
Static Arrays
Arrays
arr[type,size]
Arrays are the most simple type of container. They contain homogeneous type, meaning that each element in the array has the same type. Arrays always have a fixed length specified as a constant expression arr[type, size]. They can be indexed by any ordinal type to acces its members.
pro[] main: int = {
var anArray: arr[int, 5] = { 0, 1, 2, 3, 4 }; // declare an array of intigers of five elements
var element = anArray[3]; // accessing the element
.echo(element) // prints: 3
}
To give a value unique heap ownership, use var[new] in a memo artifact. See
Ownership:
pro[] main: int = {
var[new] values: arr[int, 3] = { 1, 2, 3 }; // uniquely owned heap array
}
Dynamic arrays
Dynamic are similar to arrays but of dynamic length which may change during runtime (like strings). A dynamic array s is always indexed by integers from 0 to .len(s)-1 and its bounds are checked.
Current V1 intrinsic note:
.len(...)is implemented.low(...),.high(...),.cap(...), and.is_empty(...)are registry-owned deferred surfaces, not activeV1intrinsics
So the safe current query surface for containers is .len(...).
Current V1 runtime note:
arr[...]remains the fixed-size container familyarr[...]itself is available incore, provided its element type is also legal therevec[...],seq[...],set[...], andmap[...]are heap-backedmemofamilies and remain available when bundledstdlayers hosted APIs on top- runtime-backed
set[...]andmap[...]preserve deterministic ordering for rendering and backend-visible behavior in the current compiler
Tip
Dynamic containers remain heap-backed. FOL does not silently convert a
vec[...]orseq[...]intoarr[...]to make it legal incore; choose an explicit fixed-size array when the program needs thecoremodel.
There are two implementations of dynamic arrays:
- vectors
vec[] - sequences
seq[]
Vecotors
Vectors are dynamic arrays, that resizes itself up or down depending on the number of content.
Advantage:
- accessing and assignment by index is very fast O(1) process, since internally index access is just [address of first member] + [offset].
- appending object (inserting at the end of array) is relatively fast amortized O(1). Same performance characteristic as removing objects at the end of the array. Note: appending and removing objects near the end of array is also known as push and pop.
Disadvantage:
- inserting or removing objects in a random position in a dynamic array is very slow O(n/2), as it must shift (on average) half of the array every time. Especially poor is insertion and removal near the start of the array, as it must copy the whole array.
- Unpredictable performance when insertion or removal requires resizing
- There is a bit of unused space, since dynamic array implementation usually allocates more memory than necessary (since resize is a very slow operation)
In FOL vectors are represented like this:
vec[type]
Example:
pro[] main: int = {
var[new] aVector: vec[str] = { "get", "over", "it" }; // declare a vector of three strings
var element = aVector[2]; // accessing the last element
}
Sequences
Sequences are linked list, that have a general structure of [head, [tail]], head is the data, and tail is another Linked List. There are many versions of linked list: singular, double, circular etc…
Advantage:
- fast O(1) insertion and removal at any position in the list, as insertion in linked list is only breaking the list, inserting, and repairing it back together (no need to copy the tails)
- linked list is a persistent data structure, rather hard to explain in short sentence, see: wiki-link . This advantage allow tail sharing between two linked list. Tail sharing makes it easy to use linked list as copy-on-write data structure.
Disadvantage:
- Slow O(n) index access (random access), since accessing linked list by index means you have to recursively loop over the list.
- poor locality, the memory used for linked list is scattered around in a mess. In contrast with, arrays which uses a contiguous addresses in memory. Arrays (slightly) benefits from processor caching since they are all near each other
In FOL sequneces are represented like this:
seq[type]
Example:
pro[] main: int = {
var[new] aSequence: seq[str] = { "get", "over", "it" }; // declare an array of intigers of five elements
var element = aSequence[3]; // accessing the element
}
Container methods
Element assignment replaces an element; these make one appear or disappear, and
reorder what is already there. They are methods on the container — not
.dot(...) intrinsics — so they are written on the binding itself, and every one
that writes needs a binding the call can mutate: a var[mut] local, or one field
of a record reached through a [mut, bor] receiver.
vec[T] owns nine:
var[mut] xs: vec[int] = {};
xs.push(3); // append
xs.push(1);
xs.insert_at(0, 2); // insert before an index -> {2, 3, 1}
xs.sort(); // ascending, in place -> {1, 2, 3}
xs.swap(0, 2); // exchange two positions -> {3, 2, 1}
xs.reserve(16); // room for n more; the length does not change
var last: opt[int] = xs.pop(); // 1, leaving {3, 2}
var head: opt[int] = xs.remove_at(0); // 3, leaving {2}
xs.truncate(1); // keep the first n
xs.clear(); // keep none
pop and remove_at answer opt[T] because an empty vector has nothing to hand
back. sort needs an element type that satisfies ord.
map[K, V] owns seven:
var[mut] ages: map[str, int] = {};
var displaced: opt[int] = ages.insert("ada", 36);
var found: opt[int] = ages.get("ada");
var known: bol = ages.contains("ada");
var keys: vec[str] = ages.keys();
var values: vec[int] = ages.values();
var dropped: opt[int] = ages.remove("ada");
ages.clear();
insert answers the value it displaced, so inserting over an existing key tells
you what was there; on a fresh key the answer is nil. get, contains, keys
and values only read, so they do not require a mutable binding.
arr[T, N] carries its length in its type, so it has none of these. seq[T] and
set[T] have no method surface either: set[...] is the tuple-member form, where
each position has its own type, and asking it to .insert(...) says so.
SIMD
Matrixes are of type SIMD (single instruction, multiple data )
Matrix
mat[sizex]
mat[sizex,sizey]
mat[sizex,sizey,sizez]
Sets
set[type,type,type..]
A set is a general way of grouping together a number of values with a variety of types into one compound type. Sets have a fixed length: once declared, they cannot grow or shrink in size. In other programming languages they usually are referenced as tuples.
pro[] main: int = {
var aSet: set[str, flt, arr[int, 2]] = { "go", .3, { 0, 5, 3 } };
var element = aSet[2][1]; // accessing the [1] element of the `arr` in the set
.echo(element) // prints: 5
}
Maps
map[key,value]
A map is an unordered group of elements of one type, called the element type, indexed by a set of unique keys of another type, called the key type.
pro[] main: int = {
var aMap: map[str, int] = { {"US",45}, {"DE",82}, {"AL",54} };
var element = aMap["US"]; // accessing the "US" key
.echo(element) // prints: 45
}
The number of map elements is called its length. For a map aMap, it can be
discovered using the intrinsic .len(...).
Growing a map is design work, not current behavior — the same boundary the
top of this chapter states for .add(...). Neither form below is implemented:
aMap.add(...) is rejected as an unavailable method, and aMap+[...] parses
but adds nothing. A map is built once from its literal.
.echo(.len(aMap)) // prints: 3
aMap.add( {"IT",55} ) // NOT implemented — rejected
aMap+[{"RU",24}] // NOT implemented — no effect
In current V1, backend execution should treat .len(...) and runtime-visible
container rendering as part of the fol-runtime contract rather than
re-deriving container policy per backend.
A key type must have a total order, since the map is kept sorted by key. That
admits the scalars and any rec or ent whose fields are themselves orderable,
and rules out flt (NaN compares equal to nothing), routines, and any type
holding a weak pointer. The same rule decides what may be a set[...] member.
A record key needs no conformance header for this — ord is structural — but
note that an aggregate compares by field name order rather than declaration
order, because structural interning normalizes the field list. That is fine for
key identity and wrong to rely on for presentation. See the
capabilities chapter.
Tip
Maps are heap-backed
memocontainers. They are not silently converted into a staticcorecontainer based on their initializer.
Axiom
axi[typ, typ]
A axiom is a list of facts. A fact is a predicate expression that makes a declarative statement about the problem domain. And whenever a variable occurs in a expression, it is assumed to be universally quantified as silent.
var likes: axi[str, str] = { {"bob","alice"} , {"alice","bob"}, {"dan","sally"} };
Info
Accesing any container always returns the value, but if we put an
:before the access symbol so:[], then it will returntrueorfalseif there is data or not on the specified access.
likes["bob","alice"] // will return {"bob","alice"}
likes:["bob","alice"] // will return true
likes["sally","dan"] // will return {}
likes:["sally","dan"] // will return false
Axioms are a data types that are meant to be used with logic programming. There are containers where facts are stated, and when we want to acces the data, they are always served as containers.
var parent: axi[str, str] = { {"albert","bob"}, {"alice","bob"}, {"bob","carl"}, {"bob","tom"} };
parent["bob",*] // this gets all elements that "bob" relates to
{"carl", "tom"}
parent[*,"bob"] // this gets all elements that "bob" relates from
{"albert", "alice"}
Adding new element can be done like in other containers:
var parent: axi[str, str] = { {"albert","bob"}, {"alice","bob"}, {"bob","carl"}, {"bob","tom"} };
parent.add({"albert","betty"})
parent.add({"albert","bill"})
parent.add({"alice","betty"})
parent.add({"alice","bill"})
And they can be nesetd too:
var line: axi[axi[int, int], axi[int, int]] = {{{4,5},{4,8}},{{8,5},{4,5}}}
And we can use the simplified form too, just axi instead of all the type. We let the compiler fill in the for us:
var line: axi = {{{4,5},{4,8}},{{8,5},{4,5}}}
Complex
Strings
str is the heap-backed UTF-8 string type. It requires the memo capability
model; a memo artifact with bundled std remains heap-capable. It is not
available in core.
var label: str = "fol";
Number
num is a planned abstraction over integer and floating-point types. It is not
part of the current compiler surface. Imaginary-number support is likewise
outside the active stream, lexer, parser, and lowering contract.
Pointers
V3 ships typed unique and shared pointers:
var[mut] unique: ptr[int] = [ref]value;
var shared: ptr[shared, int] = [ref]value;
ptr[T] is uniquely owned and writable through a mutable pointer binding.
ptr[shared, T] is reference-counted and read-only. Pointer types can be
analyzed in core, but [ref]value constructs an allocation and therefore
requires memo. A memo artifact may additionally declare bundled std, but
the pointer operation itself does not require hosted APIs. Raw ptr[raw, T]
remains a V4 interop boundary.
See Pointers for transfer, dereference, shared recursion, and current place-projection rules.
Error shells
err[T] is the storable error shell:
var failure: err[str] = "not found";
It is distinct from a routine’s recoverable : Result / Error contract. See
Recoverable Errors for that boundary.
Special
Current boundary:
- the
opt[...]optional shell, theerr[...]error shell, and thenevnever type are the current compiler surface uni[...](union) andanyare not implemented; the compiler rejects them with a “not yet supported” diagnostic- those sections describe later design work, not current behavior
Optional
Either are empty or have a value
opt[]
Never
nev[]
The never type is a type with no values, representing the result of computations that never complete.
Union
Union is a data type that allows different data types to be stored in the same memory locations. Union provides an efficient way of reusing the memory location, as only one of its members can be accessed at a time. It uses a single memory location to hold more than one variables. However, only one of its members can be accessed at a time and all other members will contain garbage values. The memory required to store a union variable is the memory required for the largest element of the union.
We can use the unions in the following locations.
- Share a single memory location for a variable and use the same location for another variable of different data type.
- Use it if you want to use, for example, a long variable as two short type variables.
- We don’t know what type of data is to be passed to a function, and you pass union which contains all the possible data types.
var aUnion: uni[int[8], int, flt];
Any
any[]
Null
nil
In the current V1 compiler milestone, nil is accepted only when type
checking already knows it is flowing into an opt[...] or err[...] shell.
Plain inference from nil alone is not supported.
Current V1 shell note:
opt[...]anderr[...]are shell values.- Unwrap
[uwp]valueapplies to those shell values. - routine calls declared with
ResultType / ErrorTypeare noterr[...]shells. - use
check(...)orexpr || fallbackfor those routine calls instead of!. - use
err[...]when you need a storable error value.
Declarations And Items
This section covers the main named program elements of FOL.
The declaration families include:
- bindings:
var,con,lab - routines:
fun,pro,log - type and construct declarations:
typ,ali - contract-like declarations:
std
Module-like forms such as use, def, and seg are covered in the modules chapter because they primarily define source layout, namespace, and composition boundaries.
Variables
Current boundary:
- ordinary
var,con, andlabdeclarations are the current compiler surface @varandvar[new]are the shipped V3 unique-heap forms and requirefol_model = "memo"; amemoartifact with bundledstdremains heap-capable too- the pipe-ternary and many-to-many assignment forms shown below are later design work, not current behavior
Here are some of the ways that variables can be defined:
var[mut] counter: int = 98
var[exp] label: str = "this is a string"
~var ratio = 192.56
+var short_flag = true
var names: arr[str, 3] = { "one", "two", "three" }
var scores: seq[int] = { 20, 25, 45, 68, 73, 98 }
var pair: set[int, str] = { 12, "word" }
var picked = names[1]
Assignments
Following the general rule of FOL:
declaration[options] name: type[options] = { implementation; };
then declaring a new variable is like this:
var[exp] aVar: int = 64
however, the short version can be used too, and the compiler figures out at compute time the type:
var shortVar = 24; // compiler gives this value the type `int`
When new variable is created, and uses an old variable to assign, the resulting binding is a new value binding rather than an alias to the old name:
pro[] main: int = {
var aVar: int = 55;
var newVar: int = aVar;
return newVar;
}
V3 adds explicit unique-heap ownership, lexical borrowing, and typed pointers. See the memory chapters for their transfer and aliasing rules.
Variables can be assigned to an output of a function:
pro[] main: int = {
fun addFunc(x, y: int): int = {
return x + y;
}
var aVar: int = addFunc(4, 5);
}
Piping / Ternary
Piping can be used as ternary operator. More about piping can be found here. Here is an example, the code below basically says: if the function internally had an error, don’t exit the program, but assign another value (or default value) to the variable:
pro[] main: int = {
fun addFunc(x, y: int): int = {
return x + y;
}
var aVar: int = addFunc(4, 5) | result > 8 | return 6;
}
Borrowing
var[bor] creates a read-only lexical borrow. The owner is inaccessible while
the borrow is active and becomes accessible again when the borrow’s scope ends.
The !borrow prefix may give it back earlier.
fun[] main(): int = {
var value: int = 55;
{
var[bor] view: int = [bor]value;
var seen: int = view;
};
return value;
};
See Ownership for the full borrowing rules.
Options
As with all other blocks, var have their options: var[opt]:
Options can be of two types:
- flags eg.
var[mut] - values eg.
var[pri=2]
Some binding options have prefix alternatives. Mutable var[mut] may be
written as ~var, but ~ is never accepted inside the option brackets.
| opt | s | type | description | control |
----------------------------------------------------------------------------------------------
| mut | ~ | flag | making a variable mutable | mutability |
| imu | | flag | making a variable imutable (default) | |
| sta | ! | flag | making a variable a static | |
| new | @ | flag | allocating a uniquely owned heap value | ownership |
| bor | | flag | declaring a lexical borrow binding | ownership |
| rac | ? | flag | making a variable reactive | |
----------------------------------------------------------------------------------------------
| exp | + | flag | making a global variable exported | visibility |
| nor | | flag | making a global variable normal (default) | |
| hid | - | flag | making a global variable file-local | |
Alternatives
There is a shorter way for variables using alternatives, for example, instead of using var[+], a leaner +var can be used instead.
+var aVar: int = 55
pro[] main(): int = {
.echo(aVar)
return aVar
}
When combining options, one may use a prefix alternative. For example,
var[mut,exp] may be written as +var[mut] or ~var[exp]:
+var[mut] aVar: int = 55
pro[] main(): int = {
.echo(aVar)
return aVar
}
Types
Mutable variables
By default a variable declared without options is mutable:
pro[] main: int = {
var aNumber: int = 5;
aNumber = 54;
}
The explicit var[mut] option and its ~var prefix alternative select the
same mutable behavior:
pro[] main: int = {
var[mut] aNumber: int = 5
~var anotherNumber: int = 24
aNumber, anotherNumber = 6 // this is completely fine, we assign two wariables new values
}
Immutable variables
Use var[imu] when a local binding must not be reassigned:
pro[] main: int = {
var[imu] aNumber: int = 5;
aNumber = 54; // typecheck error: immutable binding
}
Reactive types
Current milestone note: reactive variables are part of a later milestone, not
the current V1 compiler contract. The syntax may appear in design examples,
but present-day V1 typechecking rejects reactive semantics explicitly.
Reactive types is a types that flows and propagates changes.
For example, in an normal variable setting, var a = b + c would mean that a is being assigned the result of b + c in the instant the expression is evaluated, and later, the values of b and c can be changed with no effect on the value of a. On the other hand, declared as reactive, the value of a is automatically updated whenever the values of b or c change, without the program having to re-execute the statement a = b + c to determine the presently assigned value of a.
pro[] main: int = {
var[mut] b, c = 5, 4;
var[rac] a: int = b + c
.echo(a) // prints 9
c = 10;
.echo(a) // now it prints 10
}
Static types
Current milestone note: static variables are also part of later systems/runtime
work. The current V1 compiler keeps them outside the implemented subset.
Is a variable which allows a value to be retained from one call of the function to another, meaning that its lifetime declaration. and can be used as var[sta] or var[!]. This variable is special, because if it is initialized, it is placed in the data segment (aka: initialized data) of the program memory. If the variable is not set, it is places in .bss segmant (aka: uninitialized data)
pro[] main: int = {
{
var[!] aNumber: int = 5
}
{
.echo(aNumber) // it works as it is a static variable.
}
}
Scope
As discussed before, files in the same package share one package scope. That means package-level functions and variables may be used across sibling files without importing those sibling files one by one.
However, package-private declarations are still different from exported declarations:
- default visibility means the declaration is available inside the same package
exp/+means the declaration may be used through imports from outside the packagehid/-means the declaration is visible only inside its own file
So the visibility model is:
- package scope by default
- exported outside the package with
exp - file-only with
hid
In order for a variable to be accessed by the importer, it needs the exp flag option, so var[exp], or var[+].
package shko, file1.fol
fun[exp] add(a, b: int): int = { return a + b }
fun sub(a, b: int): int = { return a - b }
package vij, file1.fol
use shko: loc = {"../folder/shko"}
pro[] main(): int = {
.echo(add(5, 4)) // this works, `add` is exported
.echo(sub(5, 4)) // this fails, `sub` is not exported
return add(5, 4)
}
There is even the opposite option too. If we want a function or variable to be used only inside its own file, even though the package is shared, then we use the hid option flag: var[hid] or var[-].
file1.fol
var[-] aVar: str = "yo, sup!"
file2.fol
pro[] main(): int = {
.echo(aVar) // this throws, `aVar` is hidden to its own file
return 0
}
Multiple
Many to many
Many variables can be assigned at once, This is especially usefull, if variables have same options but different types eg. variable is mutabe and exported:
~var[exp] oneVar: int[32] = 24, twoVar = 13, threeVar: string = "shko";
Or to assign multiple variables of the same type:
~var[exp] oneVar, twoVar: int[32] = 24, 13;
To assign multiple variables of multiple types, the type is omitted, however, this way we can not put options on the type (obviously, the default type is assign by compiler):
~var[exp] oneVar, twoVar, threeVar = 24, 13, "shko";
Another “shameless plagiarism” from golang can be used by using ( ... ) to group variables:
~var[exp] (
oneVar: int[32] = 13,
twoVar: int[8] = 13,
threeVar: str = "shko",
)
Many to one
Many variables of the same type can be assigned to one output too:
var oneVar, twoVar: int[8] = 2;
However, each of them gets a copy of the variable on a new memory address:
assert [ref]oneVar == [ref]twoVar; // this fails: the addresses differ
One to many
And lastly, one variable can be assigned to multiple ones. This by using container types:
oneVar grouppy: seq[int] = { 5, 2, 4, 6 }
Or a more complicated one:
var anothermulti: set[str, seq[num[f32]]] = { "string", {5.5, 4.3, 7, .5, 3.2} }
Or a very simple one:
var simplemulti: any = { 5, 6, {"go", "go", "go"} }
Containers
Containers are of special type, they hold other types within. As described before, there are few of them
Access
To acces container variables, brackets like this [] are use:
var shortvar = anothermulti[1][3] // compiler will copy the value `anothermulti[1][3]` (which is a float) to a new memory location
Routines
Routines are callable declarations.
FOL has three routine families:
pro: procedures, the only routines that may perform effectsfun: functions: pure value-producing computation, checked by the compiler (see Functions)log: logicals: relations, pure likefun(see Logicals)
Routine declarations support a shared structural pattern:
fun[options] name(params): return_type = { body }
pro[options] name(params): return_type = { body }
log[options] name(params): return_type = { body }
FOL also allows an alternate header style:
fun[options] name: return_type = (params) { body }
This chapter family covers parameters, calls, defaults, variadics, return values, and routine-specific semantics.
Current V1 routine model:
- values are returned with an explicit
return; there is no implicitresultvariable in the current compiler - the short form that omits the return type is not current; the return type must be declared
- last-expression / implicit-tail return is not current
- routine overloading is not supported; duplicate routine names are rejected
- a routine that declares a recoverable error type (
: T / E) must have both a return path and areportpath
Types
There are two main types of routines in fol:
-
Procedurues
A procedure is a piece of code that is called by name. It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value). All data that is passed to a procedure is explicitly passed.
-
Functions
A function is called pure function if it always returns the same result for same argument values and it has no side effects like modifying an argument (or global variable) or outputting to I/O. The only result of calling a pure function is the return value.
Parameters
Formal parameters
Routines typically describe computations. There are two ways that a routine can gain access to the data that it is to process: through direct access to nonlocal variables (declared elsewhere but visible in the routine) or through parameter passing. Data passed through parameters are accessed using names that are local to the routine. Routine create their own unnamed namespace. Every routine has its own Workspace. This means that every variable inside the routine is only usable during the execution of the routine (and then the variables go away).
Parameter passing is more flexible than direct access to nonlocal variables. Prrameters are special variables that are part of a routine’s signature. When a routine has parameters, you can provide it with concrete values for those parameters. The parameters in the routine header are called formal parameters. They are sometimes thought of as dummy variables because they are not variables in the usual sense: In most cases, they are bound to storage only when the routine is called, and that binding is often through some other program variables.
Parameters are declared as a list of identifiers separated by semicolon (or by a colon, but for code cleanness, the semicolon is preferred). A parameter is given a type by : typename. If after the parameter the : is not declared, but , colon to identfy another paremeter, of which both parameters are of the same type if after the second one the : and the type is placed. Then the same type parameters continue to grow with , until : is reached.
fun[] calc(el1, el2, el3: int[64]; changed: bol = true): int[64] = { return el1 + el2 - el3; }
In routine signatures, you must declare the type of each parameter. Requiring type annotations in routine definitions is obligatory, which means the compiler almost never needs you to use them elsewhere in the code to figure out what you mean.
Routine names are unique: declaring two routines with the same name in one scope is rejected, so there is no overload-resolution step. Give the variants distinct names, or take a generic parameter when the bodies are the same shape:
fun[] twice_int(value: int): int = {
return value + value;
};
fun[] twice_str(value: str): str = {
return value + value;
};
Actual parameters
routine call statements must include the name of the routine and a list of parameters to be bound to the formal parameters of the routine. These parameters are called actual parameters. They must be distinguished from formal parameters, because the two usually have different restrictions on their forms.
Positional parameters
The correspondence between actual and formal parameters, or the binding of actual parameters to formal parameters - is done by position: The first actual parameter is bound to the first formal parameter and so forth. Such parameters are called positional parameters. This is an effective and safe method of relating actual parameters to their corresponding formal parameters, as long as the parameter lists are relatively short.
fun[] calc(el1, el2, el3: int): int = { return el1 + el2 - el3; }
pro main: int = {
calc(3,4,5); // calling routine with positional arguments
}
Keyword parameters
When parameter lists are long, however, it is easy to make mistakes in the order of actual parameters in the list. One solution to this problem is with keyword parameters, in which the name of the formal parameter to which an actual parameter is to be bound is specified with the actual parameter in a call. The advantage of keyword parameters is that they can appear in any order in the actual parameter list.
fun[] calc(el1, el2, el3: int): int = { return el1 + el2 - el3; }
pro main: int = {
calc(el3 = 5, el2 = 4, el1 = 3); // calling routine with keywords arguments
}
Mixed parameters
Keyword and positional arguments can be used at the same time too. In V1,
ordinary positional arguments must come before named arguments. After a named
argument appears, later ordinary arguments are rejected because position is no
longer well defined.
The one supported exception is call-site unpack for the final variadic
parameter. ...items may appear after named arguments when it is feeding that
final variadic input.
fun[] calc(el1, el2, el3: int, el4, el5: flt): int = { result[0] = ((el1 + el2) * el4 ) - (el3 ^ el5); }
pro main: int = {
calc(3, 4, el5 = 2, el4 = 5, el3 = 6); // element $el3 needs to be keyeorded at the end because
// its positional place is taken by keyword argument $el5
}
This remains invalid:
calc(el3 = 5, 4, el1 = 3)
But this is valid in V1 when the last parameter is variadic:
fun[] score(base: int, step: int = 2, extras: ... int): int = {
return base;
};
fun[] run(): int = {
var extras: seq[int] = {4, 5};
return score(base = 3, ...extras);
};
Default arguments
Formal parameters can have default values too. A default value is used if no actual parameter is passed to the formal parameter.
In V1:
- omitted parameters use their declared default
- named arguments may skip over defaulted parameters
- defaults can coexist with a final variadic parameter
fun[] calc(el1, el2, el3: int, rise: bol = true): int = { result[0] = el1 + el2 * el3 | this | el1 + el2; }
pro main: int = {
calc(3,3,2); // this returns 6, last positional parameter is not passed but
// the default `true` is used from the routine declaration
calc(3,3,2,false) // this returns 12
calc(el1 = 3, el2 = 3, el3 = 2) // named arguments may also rely on the default
}
Variadic routine
The use of ... as the type of argument at the end of the argument list
declares the routine as variadic. This must appear as the last argument of the
routine.
In V1, the final variadic parameter is bound as a seq[...] value. Extra
trailing call arguments are collected into that sequence.
fun[] calc(rise: bol; ints: ... int): int = { result[0] = ints[0] + ints[1] + ints[2] * ints[3] | this | ints[0] + ints[1]; }
pro main: int = {
calc(true,3,3,3,2); // this returns 81, four parmeters are passed as variadic arguments
calc(true,3,3,2) // this returns 0, as the routine multiplies with the forth varadic parameter
// and we have given only three (thus the forth is initialized as zero)
}
Call-site unpack is the companion feature to variadics. It forwards an existing sequence into the final variadic parameter:
fun[] calc(rise: bol; ints: ... int): int = {
return ints[0];
};
fun[] run(values: seq[int]): int = {
return calc(true, ...values);
};
This also works after named arguments:
fun[] score(base: int, step: int = 2, extras: ... int): int = {
return base;
};
fun[] run(values: seq[int]): int = {
return score(base = 3, ...values);
};
V1 intentionally does not support pseudo-arguments such as
extras[0] = 1 at call sites. Variadic inputs are still just routine
parameters, so call binding stays limited to:
- ordinary positional arguments
- named arguments by declared parameter name
- one final
...sequenceunpack for the variadic tail
Warning
Nested procedures don’t have access to the outer scope, while nested function have but can’t change the state of it.
Return
A routine always declares its return type after the formal parameters, and a
value leaves the routine through an explicit return:
fun[] add(el1, el2: int[64]): int[64] = {
return el1 + el2;
};
There is no short form that omits the return type, no implicitly declared
result variable, and no last-expression return: a routine body that falls off
the end without return does not produce a value.
Info
Routine summary:
- routines declare a success type after
:- routines may also declare a recoverable error type after
/report exprexits through that declared error path- routine call results declared with
/ ErrorTypeare noterr[...]shell values- use
check(...)orexpr || fallbackfor those calls- ordinary plain-value use of
/ ErrorTypecalls is rejected- keep postfix
[uwp]foropt[...]anderr[...]shell values
Recoverable error-aware routines use the current signature form:
fun[] read(path: str): int / str = {
report "missing path";
};
and are handled at the call site with check(...) or || rather than shell
unwrap or plain propagation.
Intrinsic note:
.echo(...)is a dot-root diagnostic intrinsiccheck(...)is a keyword intrinsic for recoverable-call inspectionpanic(...)is a keyword intrinsic for immediate abort
Model reminder:
- any routine example that calls
.echo(...)assumes amemoartifact with bundledstdsupport available - routine examples without hosted behavior should stay valid in
coreormemowhere the surrounding chapter claims they are model-neutral
return and report can also exit a routine early from within control flow.
See the recoverable-error chapter for the full contract and the
shell-vs-routine distinction.
Procedures
Procedures are most common type of routines in Fol. When a procedure is “called” the program “leaves” the current section of code and begins to execute the first line inside the procedure. Thus the procedure “flow of control” is:
- The program comes to a line of code containing a “procedure call”.
- The program enters the procedure (starts at the first line in the procedure code).
- All instructions inside of the procedure are executed from top to bottom.
- The program leaves the procedure and goes back to where it started from.
- Any data computed and RETURNED by the procedure is used in place of the procedure in the original line of code.
Procedures have side-effects, it can modifies some state variable value(s) outside its local environment, that is to say has an observable effect besides returning a value (the main effect) to the invoker of the operation. State data updated “outside” of the operation may be maintained “inside” a stateful object or a wider stateful system within which the operation is performed.
Current milestone note:
- ordinary procedure declarations are part of
V1 - recoverable procedure errors (
Result / Error) are part ofV1 - ownership-aware transfers, unique heap moves, and explicit
[bor]parameters are part of the shippedV3memory contract mux[T]parameters and the direct named-routine task boundary are part of the shippedV3processor contract
Pointer and borrowing examples in this chapter therefore describe current V3 behavior when the artifact’s capability mode permits the underlying value. Broader indirect task dispatch and future ownership/interop designs remain outside that shipped surface.
Procedures can also declare a custom recoverable error type with / after the result type:
pro[] write(path: str): int / io_err = {
report "permission denied";
}
The first : declares the result type, and / declares the routine error type.
Current V1 note:
- a procedure declared as
pro[] write(...): T / Edoes not produce anerr[E]shell value that can be unwrapped with[uwp] - it produces a recoverable routine result with a success path and an error path
- use
check(...)orexpr || fallbackat the call site - keep postfix
!foropt[...]anderr[...]shell values only
Passing values
Procedure parameters are ordinary typed inputs unless the parameter has an
explicit ownership option. Values passed to ordinary parameters follow the
type’s transfer rule. A parameter written as name[bor]: T borrows its
argument for the call without taking ownership. The borrow is explicit on both
sides: the call site must pass [bor]argument or an existing borrow binding,
otherwise the borrow checker rejects the call with O2002.
Simple example:
pro[] inspect(value[bor]: int): int = {
return value;
};
pro[] main(): int = {
var value: int = 7;
return inspect([bor]value);
};
Ownership and borrowing
The authoritative version split is:
- ordinary procedures and functions are part of
V1 - recoverable routine errors are part of
V1 - explicit
name[bor]: Tborrow parameters are part of the shippedV3memory contract - typed pointers and unique heap ownership are also part of that
V3contract
Borrow give-back uses the !borrow prefix. Ownership behavior never depends on
identifier casing, and there is no alternate parenthesized parameter grammar.
See the memory chapters and plan/VERSIONS.md for the version boundary.
Functions
Functions compared to procedure are pure. A pure function is a function that has the following properties:
- Its return value is the same for the same arguments (no variation with local static variables, non-local variables, mutable reference arguments or input streams from I/O devices).
- Its evaluation has no side effects (no mutation of local static variables, non-local variables, mutable reference arguments or I/O streams).
Thus a pure function is a computational analogue of a mathematical function. Pure functions are declared with fun[]
fun[] add(el1, el2: int[64]): int[64] = { result = el1 + el2 }
Current boundary:
- the current compiler requires an explicit
returnand a declared return type; theresult = ...spelling, short-form return-type omission, and last-expression return shown here are earlier design, not current behavior - the closures, currying, and generator material at the end of this chapter is later design work, not part of the current compiler surface
- nested and anonymous routine bodies cannot implicitly capture an outer local in the shipped compiler; pass the value through a declared parameter instead
Purity is checked
The compiler enforces purity: a fun (named or anonymous) whose body performs
an effect is error T1008, which names the effect and asks for pro. The
effects are:
- hosted intrinsics that touch the terminal, the clock, the environment, child
processes, signals, the filesystem, the network, randomness, atomics, the last
host error, or the call stack:
.echo,.write,.read_file,.now_ms,.random_int, and the rest of that family. Pure hooks such as.len,.str_find,.parse_int, and the arithmetic and conversion intrinsics are not effects, and neither arepanic,assert, andreport; - a call to a
proor to a C import, directly, through a namespace, or as a method. Hostedstdroutines built on effectful intrinsics, such asstd::io::echo_intandstd::fs::read_file, arepro; - spawning (
[>],[spn]),| async, and| await; - channels:
c[tx],c[rx], a send through a sender value, andselect; .lock()and.unlock()on a mutex;- pointers:
[ref],[weak],[upg], and writing through[drf]p = v; - writes to a global binding: assignment, a mutating container method such as
.push, or a[mut, bor]loan of it. Reading a global is not an effect.
fun[] add(a, b: int): int = {
return a + b;
};
pro[] main(): int = {
return .echo(add(2, 3));
};
Declaring main as fun here is rejected, because .echo is terminal output.
A log is checked the same way.
Routine values carry the same split. A {fun (...): T} value is pure, so a
fun may call one. A {pro (...): T} value may perform effects, so calling it
is itself an effect. A fun value fits a {pro ...} slot, and a pro value
never fits a {fun ...} slot:
pro[] run(step: {pro (n: int): int}): int = {
return step(1);
};
pro[] main(): int = {
var loud: {pro (n: int): int} = pro(n: int): int = { return .echo(n); };
return run(loud);
};
A C import’s callback parameter is a {pro ...} slot, so either kind of
closure may be handed to C.
When a function has a custom recoverable error type, use / after the result type:
fun[] read(path: str): str / io_err = {
report "file not found";
}
The first : declares the result type, and / declares the routine error type.
Current V1 note:
- a function declared as
fun[] read(...): T / Edoes not return anerr[E]shell value - it returns through a recoverable routine error path
- handle that path immediately with
check(...)orexpr || fallback - plain assignment, return, and ordinary expression use are rejected
- postfix
!stays reserved foropt[...]anderr[...]shell values
Warning
Functions in FOL are lazy-initialized.
So it is an evaluation strategy which delays the evaluation of the function until its value is needed. You call a function passing it some arguments that were expensive to calculate and then the function don’t need all of them due to some other arguments.
Consider a function that logs a message:
log.debug("Called foo() passing it " + .to_string(argument_a) + " and " + .to_string(argument_b));
The log library has various log levels like “debug”, “warning”, “error” etc. This allows you to control how much is actually logged; the above message will only be visible if the log level is set to the “debug” level. However, even when it is not shown the string will still be constructed and then discarded, which is wasteful.
Tip
Since Fol supports first class functions, it allows functions to be assigned to variables, passed as arguments to other functions and returned from other functions.
Anonymous functoins
Anonymous function is a function definition that is not bound to an identifier. These are a form of nested function, in allowing access to variables in the scope of the containing function (non-local functions).
Staring by assigning a anonymous function to a vriable:
var f = fun (a, b: int): int = { // assigning a variable to function
return a + b
}
.echo(f(5,6)) // prints 11
var f: int = (a, b: int){ // this is an short alternative of same variable assignmet to function
return a + b
}
It is also possible to call a anonymous function without assigning it to a variable.
`version 1`
fun[] (a, b: int) = { `define anonymous function`
return a + b
}(5, 6) `calling anonymous function`
`version 2`
(a, b: int){ `define anonymous function`
return a + b
}(5, 6) `calling anonymous function`
Closures
Functions can appear at the top level in a module as well as inside other scopes, in which case they are called nested functions. A nested function can access local variables from its enclosing scope and if it does so it becomes a closure. Any captured variables are stored in a hidden additional argument to the closure (its environment) and they are accessed by reference by both the closure and its enclosing scope (i.e. any modifications made to them are visible in both places). The closure environment may be allocated on the heap or on the stack if the compiler determines that this would be safe.
This remains future design. Any eventual heap-allocated closure environment
must require memo; an implementation must not hide a source-visible heap
capability inside core merely as an optimization.
There are two types of closures:
- anonymous
- named
Anonymus closures automatically capture variables, while named closures need to be specified what to capture. For capture we use the [] just before the type declaration.
fun[] add(n: int): int = {
fun added(x: int)[n]: int = { // we make a named closure
return x + n // variable $n can be accesed because we have captured ti
}
return adder()
}
var added = add(1) // assigning closure to variable
added(5) // this returns 6
fun[] add(n: int): int = {
return fun(x: int): int = { // we make a anonymous closure
return x + n // variable $n can be accesed from within the nested function
}
}
Currying
Currying is converting a single function of “n” arguments into “n” functions with a “single” argument each. Given the following function:
fun f(x,y,z) = { z(x(y));}
When curried, becomes:
fun f(x) = { fun(y) = { fun(z) = { z(x(y)); } } }
And calling it woud be like:
f(x)(y)(z)
However, the more iportant thing is taht, currying is a way of constructing functions that allows partial application of a function’s arguments. What this means is that you can pass all of the arguments a function is expecting and get the result, or pass a subset of those arguments and get a function back that’s waiting for the rest of the arguments.
fun calc(x): int = {
return fun(y): int = {
return fun (z): int = {
return x + y + z
}
}
}
var value: int = calc(5)(6) // this is okay, the function is still finished
var another int = value(8) // this completes the function
var allIn: int = calc(5)(6)(8) // or this as alternative
Higer-order functions
A higher-order function is a function that takes a function as an argument. This is commonly used to customize the behavior of a generically defined function, often a looping construct or recursion scheme.
They are functions which do at least one of the following:
- takes one or more functions as arguments
- returns a function as its result
//function as parameter
fun[] add1({fun adder(x: int): int}): int = {
return adder(x + n)
}
//function as return
fun[] add2(): {fun (x: int): int} = {
var f = fun (a, b: int): int = {
return a + b
}
return f
}
Generators (future design)
Generators and the language yield expression are not part of the shipped
V1, bounded V2, or V3 contracts. The lexer, parser, and resolver preserve
the syntax, which also lets tree-sitter keep it readable, but the current
typechecker rejects yield and lowering retains a defensive unsupported
boundary. Parser or highlighting support must not be read as executable
generator support.
An earlier design sketch proposed a container-returning routine that yielded one value at a time:
fun someIter: vec[int] = {
var curInt = 0;
loop(){
yield curInt.inc(1)
}
}
That snippet is a future syntax sketch, not current source. Its eligible return
types, ownership behavior, suspension model, lowering, and runtime contract
remain undecided. Generator yield is also unrelated to V3 | async and
| await, which produce and consume internal eventuals without suspending the
calling routine as a generator.
Methods
A method is a routine associated with a receiver type. In FOL, methods can be
declared as either fun or pro and called with dot syntax
(value.method(...)).
Methods in FOL are procedural sugar, not object-oriented behavior.
A method call is just sugar for calling a routine whose first explicit input is the receiver value. In other words:
tool.parse_msg(10)
should be read as the procedural call:
parse_msg(tool, 10)
This syntax does not introduce:
- classes
- inheritance
- object-owned method bodies
- object-method dispatch as a separate runtime model
typ declares data. Receiver-qualified routines are still ordinary routines.
Current parser-supported receiver declaration syntax is:
fun (parser)parse_msg(code: int): str = {
return "ok";
};
pro (parser)update(code: int): int = {
return code;
};
The receiver type appears in parentheses right after fun or pro, followed by the method name.
That receiver clause does not move the routine “inside” the type. It only says which type may be used in dot-call form for that routine.
The current parser accepts a broader receiver syntax than the final V1 semantic subset. At parse time, receiver positions can still accept named, qualified, builtin-scalar, and bracketed/composite type references. That is a parser fact, not an object model.
The dedicated parser-level rejection in this hardening phase is still for special
builtin forms such as any, none, and non.
Invalid example:
fun (any)parse_msg(code: int): str = {
return "ok";
};
This form reports: Method receiver type cannot be any, non, or none.
Method calls use standard dot syntax:
var tool: parser = parser.new()
var msg: str = tool.parse_msg(10)
This is equivalent in meaning to passing tool as the first routine argument.
The dot form is only the call-site spelling.
Method calls use the same V1 call-binding rules as free routine calls:
- ordinary positional arguments may appear before named arguments
- named arguments bind by declared parameter name
- defaulted parameters may be omitted
- a final variadic parameter may collect trailing arguments
- variadic collection comes only from the explicit
... Tmarker; a plainseq[T]parameter takes one sequence value ...sequencemay appear after named arguments when it feeds that final variadic parameter
Example:
typ Counter: rec = {
total: int
};
fun (Counter)shift(step: int = 2, extras: ... int): int = {
return step;
};
fun[] run(current: Counter, extras: seq[int]): int = {
return current.shift(step = 3, ...extras);
};
V1 does not support indexed pseudo-arguments such as
current.shift(extras[0] = 1, ...extras). That spelling looks like assignment,
not call binding, so the language keeps variadic binding explicit and simple.
Inside a receiver-qualified routine body, the receiver value is available
through self. self is typed as the receiver type and is lowered as the
routine’s ordinary first argument; it does not introduce an object model.
typ Counter: rec = {
var total: int;
};
fun (Counter)read(): int = {
return self.total;
};
Generic receiver types participate too: fun (Box[T])get(T)(): T can return
self.value, and each concrete call site monomorphizes the routine.
For record-focused V1 code, the intended reading is:
- records hold data
- routines stay separate
- the receiver clause enables
value.method(...)spelling and gives the body procedural access to the receiver throughself
Custom error routines also support reporting method call results when receiver-qualified signatures are available:
fun (parser)parse_err(code: int): str = {
return "bad-input";
};
fun run(tool: parser, code: int): int / str = {
report tool.parse_err(code)
return 0
};
Logicals
A logical is a relation. Facts are relation values, rules are log
declarations, and a query is a call. The model is Datalog with stratified
negation:
- every rule set the checker accepts terminates on every finite fact base, so a query can never hang;
- answers are sets: clause order and goal order change the cost of a query, never its answers, and there is no cut and no first-solution commitment;
- unsafe variables, negation cycles, and value invention are reported by
fol code check, not discovered at run time.
Facts and rules have one spelling. A caller cannot tell whether the relation it queries is a stored fact base or a rule.
The code blocks on this page read in order as one program, and the book audit type-checks them that way.
Relations
rel[T1, ..., Tn] is a finite set of tuples. Its columns are positional and
typed, and every column type must satisfy ord, because joins and indexes need
a total order. A column is an ordered scalar: an int width up to 64 bits or
i128, bol, chr, or str. A flt column is error Q1006.
con[exp] parent: rel[str, str] = {
{ "albert", "bob" },
{ "albert", "betty" },
{ "alice", "bob" },
{ "alice", "betty" },
{ "bob", "carl" },
{ "bob", "tom" },
};
con dances: rel[str] = { "albert", "alice", "carl" };
- A
conrelation is a compile-time constant fact base. Its initializer is a literal of constants, which the checker evaluates. - A
var[mut]relation is a runtime fact base, changed with methods on the binding:
pro[] edges_demo(): int = {
var[mut] edges: rel[int, int] = {};
edges.add(1, 2);
edges.add(2, 3);
edges.add(2, 3);
edges.remove(1, 2);
var known: bol = edges.has(2, 3);
var[mut] total: int = 0;
each (edge in edges) {
total = total + edge.c0 + edge.c1;
};
return edges.len() + total;
};
.addand.removetake one value per column,.hasanswers membership, and.len()counts distinct tuples: duplicates collapse..addand.removechange a binding in a routine; a file-scope relation is read with.has,.len(), and queries.each (t in edges) { ... }visits tuples in column order. A one-column relation yields its element type; a wider one yields a positional record whose fields arec0,c1, and so on.relneeds the heap, so it is available fromfol_model = "memo"up. A relation copies (cpy) when every column does, which astrcolumn does not; it always clones and issendandshare, since every column is a scalar.- A rule never reads ambient mutable state. A
varrelation reaches a rule only as an argument (see Relation parameters).
Rules
A log body is a list of clauses separated by ;. A tuple belongs to the
relation when any clause holds for it. An optional label => names a
clause.
log[exp] grandparent(g, c: str) = {
exi p: str, parent(g, p) and parent(p, c);
};
log[exp] ancestor(a, d: str) = {
direct => parent(a, d);
step => exi m: str, parent(a, m) and ancestor(m, d);
};
A log has no return type: it is always a relation, and its head parameters
are its columns. It is not generic.
A clause body is a formula, not a statement. It may contain:
- relation goals
r(args), whereris arelbinding, arelparameter, or anotherlog; and,or,not, and parentheses;exi x: T, formula, which introduces a clause-local variable;_as a goal argument, an anonymous variable that is projected away;- comparisons
== != < <= > >=and integer arithmetic+ - * / %on bound values; - calls to pure
funs that take ordered scalars and return an ordered scalar or anoptof one.
or is distributed into one clause per alternative, and not is pushed
through and and or onto goals and comparisons, where not a < b becomes
a >= b. The alternatives of a labelled clause that or splits are labelled
<label>_1, <label>_2, and so on in source order, so a proof names each
one. not cannot wrap an exi: write not r(x, _) for “no r(x, y) for
any y”. all, ->, and <-> belong to ghost logicals and theorems (see
Proofs); an executable log rejects them as
Q1007, as it does any other expression with no rule reading.
More rules over the same facts:
log dancing_parent(a: str) = {
parent(a, _) and dances(a);
};
log sibling(a, b: str) = {
exi p: str, parent(p, a) and parent(p, b) and a != b;
};
con brothers: rel[str, str] = { { "bob", "bill" }, { "bill", "bob" } };
log uncle(u, c: str) = {
exi p: str, parent(p, c) and brothers(p, u);
};
dancing_parent(a) holds when a is the parent of anyone, which _ leaves
unnamed, and a dances.
A rule that derives new facts from old ones is just another clause:
con stabs: rel[str, str, str] = { { "tybalt", "mercutio", "sword" } };
con friends: rel[str, str] = { { "romeo", "mercutio" } };
log hates(a, b: str) = {
friends(a, _) and stabs(b, "mercutio", _);
};
Variables
- Head parameters are the relation’s columns.
exi x: T,introduces a variable local to one clause. Its type annotation is required._in a goal is a fresh anonymous variable, sonot likes(a, _)reads “alikes nobody”. Outside a goal or a query argument,_is an error.- A name that resolves to nothing is an ordinary unresolved-name error. No variable is ever invented from a spelling.
- An expression goal argument, as in
edges(a, b + 1), reads as a fresh variable that equals the expression.
Negation and stratification
not goal is allowed when the goal’s relation does not depend, directly or
transitively, on the relation being defined. The checker builds the dependency
graph between relations and computes its strongly connected components; a
negative edge inside one component is error Q1002, which prints the cycle.
log lonely(people: rel[str]; likes: rel[str, str]; a: str) = {
people(a) and not likes(a, _);
};
Safety
Every head variable, every variable inside a not, and every variable used in
a comparison or a fun call must be bound by a positive relation goal in the
same clause. An equality x == expr binds x once everything in expr is
bound. Otherwise the clause is error Q1001, which names the variable and the
goal that needs it. Safety is what keeps every answer drawn from the finite
fact bases.
Arithmetic and value invention
A clause may compute a value from bound variables:
log next_hop(edges: rel[int, int]; a, b: int) = {
exi k: int, edges(a, k) and b == k + 1;
};
Inside a recursive component a computed value may not reach the head or a
recursive goal’s argument, because count(n + 1) style rules never terminate.
Crossing that line is error Q1003. A non-recursive clause may compute freely,
since it fires a finite number of times.
Arithmetic that overflows its column type, divides by zero, or takes a
remainder by zero is undefined, and the comparison that holds it does not hold:
answers never depend on the order goals run in. A call to a fun that breaks
is undefined the same way, so a query never breaks because a clause call did.
A call to a fun that returns opt[T] compares at T, as a side of a
comparison, a goal argument, or a bol condition. The comparison holds when
the call returns a value that satisfies it, and nil is undefined, as a break
is: the comparison does not hold whichever way it points.
fun[] half(n: int): opt[int] = {
if (n % 2 == 0) {
return n / 2;
};
return nil;
};
con sizes: rel[int] = { 2, 3, 4 };
log halves(n, m: int) = {
sizes(n) and m == half(n);
};
halves holds { 2, 1 } and { 4, 2 }; 3 has no half, so no tuple starts
with it.
Queries
A query is a call. With every argument bound it returns bol. Each _ marks
an output column: one free column returns set[T], and several return a
rel[...] of the free columns in order.
fun[] reach_count(edges: rel[int, int]): int = {
var pairs: rel[int, int] = reach(edges, _, _);
return pairs.len();
};
pro[] main(): int = {
var yes: bol = grandparent("albert", "carl");
var kids: set[str] = parent("albert", _);
var pairs: rel[str, str] = ancestor(_, _);
var dancers: set[str] = dancing_parent(_);
var cousins: set[str] = uncle("bill", _);
var[mut] ring: rel[int, int] = {};
ring.add(1, 2);
ring.add(2, 1);
var hops: int = reach_count(ring);
return hops;
};
A query is a pure expression, so a fun may run one.
Relation parameters
A log may take rel parameters: its input fact bases, passed as loans. In a
goal or a query the relation arguments come in the parameters’ positions.
log reach(edges: rel[int, int]; a, b: int) = {
edges(a, b);
exi m: int, edges(a, m) and reach(edges, m, b);
};
Inside a recursive component a relation parameter must be passed through
unchanged (Q1004). It is then a fixed parameter of the whole component: the
engine evaluates the component once per distinct argument, and the prover reads
it as an inductive parameter, so a theorem about reach holds for every edge
relation. Inside a clause, a relation argument names a relation parameter, a
con relation, or a log without relation parameters.
Relations of other packages
A rule reads the log and con relations a dependency exports through the
dependency’s namespace, and ordinary code queries them the same way:
// graph/lib.fol
con[exp] edge: rel[int, int] = { { 1, 2 }, { 2, 3 }, { 3, 4 } };
log[exp] reach(a, b: int) = {
edge(a, b);
exi m: int, edge(a, m) and reach(m, b);
};
// app/src/main.fol
use graph: loc = {"../../graph"};
log far(a: int) = {
graph::reach(a, 4) and not graph::edge(a, 4);
};
pro[] main(): int = {
var pairs: rel[int, int] = graph::reach(_, _);
return pairs.len() - 6;
};
A dependency never reads its dependents, so each package’s strata are
computed on their own, in dependency order. To the dependent’s rules, a
dependency’s relation is an input fact base: a con relation’s tuples, or the
answers of the dependency’s own compiled rules. A dependency’s log that takes
relation parameters is not read by a rule of another package; ordinary code
queries it with its relation arguments.
Evaluation
- The checker lowers every exec
logand every file-scope relation of a package into one checked rule IR, the same IR the prover reads. - The backend emits typed Rust for each component of rule sets: one nested
loop per clause plan, scanning or probing an index keyed by the bound
columns, filtering, assigning, and antijoining for
not. - A recursive component runs semi-naive iteration to a fixpoint: each round joins only the tuples the previous round derived.
- A component that takes no relation parameters is computed once per process; one that does is computed per query.
Diagnostics
| Code | Meaning |
|---|---|
| Q1001 | unsafe variable: not bound by a positive goal |
| Q1002 | negation inside a recursive component (the cycle is printed) |
| Q1003 | a computed value reaches a recursive head or goal |
| Q1004 | a relation parameter changes inside a recursive component |
| Q1005 | goal, query, or relation-method arity mismatch |
| Q1006 | a column type is not an ordered scalar |
| Q1007 | a construct outside the Datalog subset in an executable log |
Each code has a fol code explain entry with a failing and a fixed example.
Logicals in proofs
Inside a proof, a log is an inductive predicate: each clause is a constructor,
each exi binder a constructor argument, and each relation parameter an
inductive parameter. A con relation is decidable membership in its literal.
The Proofs chapter shows both readings.
Construct Types
This section covers named type construction beyond the built-in type families.
The main construct surfaces are:
- aliases:
ali - record-like definitions
- entry-like definitions
These chapters describe how named data models are introduced, how members are declared, and how construct values are initialized and accessed.
Aliases
An alias declaration gives a new name to an existing type surface. The alias does not create a new object model. It gives the type a stable name that can be reused in declarations, signatures, and receiver-qualified routines.
There are two related forms:
- aliasing
- extending
Aliasing
typ[ali] I5: arr[int, 5];
Now code can use I5 instead of repeating arr[int, 5]:
var fiveIntegers: I5 = { 0, 1, 2, 3, 4 };
A designed-but-unbuilt example is naming a constrained colour component type. The limit surface it uses is not implemented; the current compiler reports “limited/constrained types are not yet supported”:
typ[ali] rgb: int[8][.range(255)];
typ[ali] rgbSet: set[rgb, rgb, rgb];
Aliases are useful because:
- they avoid repeating long type expressions
- they give a type surface a meaningful name
- they provide a named receiver surface for receiver-qualified routines
Receiver-qualified routines remain procedural. If a value is written as
value.method(arg), read that as call-site sugar for method(value, arg).
The routine is still separate from the data declaration.
Standalone alias declarations
The standalone ali declaration is the short form of the same aliasing
surface:
ali Meters: int;
Like other declarations, an alias is package-visible by default. Exporting it
across package boundaries uses the same option surface as typ, fun, and
var:
ali[exp] Meters: int;
exp is the only option an alias declaration accepts.
Current milestone note:
- aliasing over current
V1built-in and declared types is part of the present language surface - extension is not:
typ[ext] ...reports “type extension declarations are planned for a future release” - true foreign-type interop remains later work
- C ABI and Rust interop belong to the planned
V4milestone, not the current compiler contract
Extending
Extensions are designed to expose an existing type under an explicit receiver surface so that new receiver-qualified routines can be declared for it. This is future work — the current compiler rejects the declaration below. Write the receiver-qualified routines against the type directly instead.
typ[ext] type: type;
This is still procedural. It does not turn the type into an object or create inheritance. It only allows routines to be written against that receiver surface.
For example, an explicit receiver surface for int:
typ[ext] int: int;
pro (int)print(): non = {
.echo(self)
};
pro main(): non = {
5.print()
};
The call 5.print() is still just receiver sugar for print(5).
An older version of this chapter used a string-to-vector extension containing
yield. That mixed future generator design into the current alias contract.
Language yield is parsed and retained for future work, but the current
typechecker and lowerer reject it; it is not part of V3. Alias and extension
support therefore does not imply generator support.
Structs
Structs are the way to declare new type of data. A struct binds an identifier, the type name, to a type.
A struct definition creates a new, distinct type and are few of them in FOL:
- records
- entries
Definition
Records
A record is an aggregate of data elements in which the individual elements are identified by names and types and accessed through offsets from the beginning of the structure. There is frequently a need in programs to model a collection of data in which the individual elements are not of the same type or size. For example, information about a college student might include name, student number, grade point average, and so forth. A data type for such a collection might use a character string for the name, an integer for the student number, a floating- point for the grade point average, and so forth. Records are designed for this kind of need.
It may appear that records and heterogeneous set are the same, but that is not the case. The elements of a heterogeneous set[] are all references to data values that may reside in scattered locations. The elements of a record are of potentially different sizes and reside in adjacent memory locations. Records are primarily data layouts.
typ user: rec = {
var username: str;
var email: str;
var sign_in_count: int[64];
var active: bol;
};
Records are data, not objects
typ ...: rec = { ... } declares a data type. FOL does not treat records as
objects with hidden behavior, inheritance, or class-owned method bodies. If a
record has operations associated with it, those operations are still declared
as ordinary receiver-qualified routines outside the record body.
typ computer: rec = {
brand: str;
memory: int
};
fun (computer)get_type(): str = {
return self.brand
};
var laptop: computer = { brand = "acme", memory = 16 }
.echo(laptop.get_type())
The call laptop.get_type() is procedural sugar for calling the receiver
routine with laptop as its first explicit input.
Current V1 backend/runtime note:
- backends may emit records and entries as plain target-language structs/enums
- that does not change the language model: they are still data plus ordinary receiver-qualified routines
- when runtime-visible formatting is needed, generated backends should preserve
the
fol-runtimeaggregate formatting contract instead of inventing a backend-specific display shape
Entries
Is an a group of constants (identified with ent) consisting of a set of named values called elements.
typ color: ent = {
var BLUE: str = "#0037cd"
var RED str = "#ff0000"
var BLACK str = "#000000"
var WHITE str = "#ffffff"
};
if( something == color.BLUE ) { doathing } else { donothing }
Entries as enums
Unums represent enumerated data. An enumeration type (or enum type) is a value type defined by a set of named constants of the underlying integral numeric type.
typ aUnion: ent = {
var BLUE, RED, BLACK, WHITE: int[8] = {..3}
}
ABI discriminants
A variant is numbered by its declaration position, which is fine inside FOL and cannot be promised to anyone outside it: inserting a variant renumbers every later one. An entry that crosses the C boundary states each tag instead.
typ[exp] Lookup: ent = {
con[tag = 4] MISSING;
con[tag = 1] FOUND;
con[tag = 9] DENIED;
};
[tag = N] is not a default value. con NAME: int = 7 gives the variant a
default payload; the tag is a separate thing with a separate spelling. Either
every variant states one or none does, tags cannot repeat, and a tag lives in
the 32-bit range the discriminant carries. See
the interop chapter for what crosses.
Initializaion
To use a record after we’ve defined it, we create an instance of that record by specifying concrete values for each of the fields. We create an instance by stating the name of the record and then add curly brackets containing key: value pairs, where the keys are the names of the fields and the values are the data we want to store in those fields. We don’t have to specify the fields in the same order in which we declared them in the record. In other words, the record definition is like a general template for the type, and instances fill in that template with particular data to create values of the type.
@var user1: user = {
email = "someone@example.com",
username = "someusername123",
active = true,
sign_in_count = 1,
};
Named initialization:
@var[mut] user1: user = { email = "someone@example.com", username = "someusername123", active = true, sign_in_count = 1 }
Ordered initialization
@var[mut] user1: user = { "someone@example.com", "someusername123", true, 1 }
Accessing
To get a specific value from a record, use dot notation: if we wanted just
this user’s email address, we can use user1.email wherever we want that
value. If the instance is mutable, we can change a value by assigning into a
particular field. Note that the entire instance must be mutable; FOL doesn’t
allow us to mark only certain fields as mutable.
var user1: user = {
email = "someone@example.com",
username = "someusername123",
active = true,
sign_in_count = 1,
};
user1.email = "new.mail@example.com";
Current boundaries:
- assignment targets a single field of a mutable binding (
user1.email = ...); nested targets such asa.b.c = ...are not part of the current surface - bracket field access (
user1[email]) is a later design surface, not part of the current compiler contract
Returning
As with any expression, we can construct a new instance of the record as the last expression in the function body to implicitly return that new instance. A record instance is returned like any other value, with an explicit return (see Routines). Here we declare one variable user1 whose initializer spans several lines:
pro buildUser(email, username: str): user = { user1: user = {
email = "someone@example.com",
username = "someusername123",
active = true,
sign_in_count = 1,
} }
Nesting
Records can be nested by creating a record type using other record types as the type for the fields of record. Nesting one record within another can be a useful way to model more complex structures:
var empl1: employee = {
FirstName = "Mark",
LastName = "Jones",
Email = "mark@gmail.com",
Age = 25,
MonthlySalary = {
Basic = 15000.00,
Bonus = {
HTA = 2100.00,
RA = 5000.00,
},
},
}
Defauling
Records can have default values in their fields too.
typ user: rec = {
var username: str;
var email: str;
var sign_in_count: int[64] = 1;
var active: bol = true;
};
This makes possible to enforce some fields (empty ones), and leave the defaults untouched:
@var[mut] user1: user = { email = "someone@example.com", username = "someusername123" }
Limiting
We can also restrict the values (with ranges) assigned to each field:
typ rgb: rec[] = {
var r: int[8][.range(255)];
var g: int[8][.range(255)];
var b: int[8][.range(255)];
}
var mint: rgb = { 153, 255, 187 }
This of course can be achieve just with variable types and aliased types and sets too, but we would need to create two types:
typ rgb: set[int[8][.range(255)], int[8][.range(255)], int[8][.range(255)]];
var mint: rgb = { 153, 255, 187 }
Methods
A record may have receiver-qualified routines associated with it. This does not turn the record into an object model. It only means a routine may use dot-call syntax when its first explicit input is a value of that record type. To create such a routine for a record, declare the receiver type on the routine itself:
fun (recieverRecord)someFunction(): str = { self.somestring; };
After declaring the record receiver, the routine body may refer to that input
through self. A receiver is simply the explicit first input that enables
dot-call syntax. The data and the routine remain separate declarations.
typ user: rec = {
var username: str;
var email: str;
var sign_in_count: int[64];
var active: bol;
};
fun (user)getName(): str = { result = self.username; };
Receiver-qualified routines have one main ergonomic benefit over plain routine
calls: they let the call site read value.method(...). In the same package,
multiple routines may still share the same method name if the receiver types
are different.
Each record value can therefore use the dot form, but the underlying model remains procedural:
user1.getName()
should be read as:
getName(user1)
There is no hidden record-owned method table in that spelling.
The routine itself is still declared separately:
var[mut] user1: user = { email = "someone@example.com", username = "someusername123", active = true, sign_in_count = 1 }
.echo(user1.getName());
Standards
This chapter now has a split status:
- one narrow
V2Milestone 2 subset is implemented - the broader standards design is still future
V2
Current implemented Milestone 2 subset:
- protocol standards declared with
std name: pro = { ... } - required receiver-qualified routine signatures only
- type-side conformance claims through the existing contract-header shape
- exact routine-signature matching for conformance
- current hardened example set for that subset is:
examples/standards_protocol_m2examples/standards_protocol_pair_m2examples/standards_protocol_multi_m2examples/fail_standard_blueprint_m2examples/fail_standard_as_type_m2examples/fail_standard_missing_routine_m2examples/fail_standard_signature_m2examples/fail_standard_import_ambiguity_m2
Still future:
- blueprint standards as real semantic contracts
- extended standards as real semantic contracts
- required data-member conformance
- standards as ordinary concrete types
- dispatch/inference driven by standards
- object-style method semantics
Part of the current shipped full-V2 contract:
- standards-as-constraints through protocol standards
- procedural constrained-generic call binding
- static conformance checking for those constraints
- calling a constraint’s required routines on the constrained generic
parameter itself:
fun measure(T: sized)(thing: T): int = { return thing.size(); };monomorphizes per instantiation, dispatching to each conformer’s own receiver routine (or the standard’s default body) at compile time - blueprint standards (
std X: blu) as static field contracts - extended standards (
std X: ext) combining required routines and fields
The intent of standards is procedural and data-oriented. They are not class hierarchies, inheritance trees, or object systems.
Standard
In later milestones, a standard is intended to be a named collection of
required receiver-qualified routine signatures and/or required data, created
with std.
std geometry: pro = {
fun area(): flt[64];
fun perim(): flt[64];
};
The shipped forms are:
- protocol
pro[]for required routines - blueprint
blu[]for required data - extended
ext[]for routines plus data
std geometry: pro = {
fun area(): flt[64];
fun perim(): flt[64];
};
std geometry: blu = {
var color: rgb;
var size: int;
};
std geometry: ext = {
fun area(): flt[64];
fun perim(): flt[64];
var color: rgb;
var size: int;
};
Contract
Current Milestone 2 support allows a type to declare that it satisfies a protocol standard and requires matching receiver-qualified routines.
Current implemented shape:
std geo: pro = {
fun area(): int;
};
typ Rect()(geo): rec = {
var width: int;
};
fun (Rect)area(): int = {
return 1;
};
This subset is intentionally narrow:
- only
prois semantic today - only required routines are semantic today
- richer requirement forms such as generic, receiver-qualified, and capturing standard requirements remain unsupported
- the type claim is checked procedurally
- lowering preserves protocol-standard and conformance metadata for audits and procedural backend lowering
- backend execution works for the checked-in positive protocol examples through ordinary receiver-qualified routine calls, not through a runtime object model
- editor hardening now covers contract-header hover/definition on checked-in standards examples while keeping broader required-routine hover support out of the claimed contract
A generic type conforms through generic receiver routines. A routine whose
receiver is the type over its own generics, fun (Box[T])size(T)(), supplies
the requirement for every instance; a routine of one instance, fun (Box[int])size(), does not, and the claim stays “missing required routine”.
A claim of a generic standard may name the type’s generics, holder[T], and
each instance claims it at its own arguments, so Box[int] satisfies a
holder[int] bound and Box[str] does not. A call through a bound reaches
each instance’s own routine, also for two generic types with the same fields;
examples/generic_standard_conform_m1m2 runs this.
std sized: pro = {
fun size(): int;
};
std holder(I): pro = {
fun fetch(): I;
};
typ Box(T)(sized, holder[T]): rec = {
var item: T;
var count: int;
};
fun (Box[T])size(T)(): int = {
return self.count;
};
fun (Box[T])fetch(T)(): T = {
return self.item;
};
fun measure(X: sized)(thing: X): int = {
return thing.size();
};
fun pull(X: holder[int])(thing: X): int = {
return thing.fetch();
};
The broader design remains future work. Later milestones may allow a type to declare that it satisfies richer standards and check required data and receiver-qualified routines together.
std geo: pro = {
fun area(): flt[64];
fun perim(): flt[64];
};
std rect(geo): rec[] = {
width: int[64];
heigh: int[64];
};
Under that design, rect would need matching receiver-qualified routines such
as:
fun (rect)area(): flt[64] = { result = self.width + self.heigh }
fun (rect)perim(): flt[64] = { result = 2 * self.width + 2 * self.heigh }
The goal is still procedural. A call like shape.area() remains sugar for a
receiver-qualified routine call, not an object-owned virtual method.
For the current full V2 target, broader dispatch and inference semantics stay
outside the shipped contract.
Laws
A standard may also state laws: thm members about its required routines and
the conforming type, which a law calls self. Each law is a proof obligation of
every type that claims the standard, proven with thm (T)law or by the law’s
default proof, and fol code check refuses a type that leaves one unproven
(V1008). A generic type proves each law once for every instance, with
thm (Box[T])law(T)(..). The Proofs chapter has the details and a worked
example.
Generics
This chapter describes V2 generic-language work rather than current V1
compiler behavior.
Current milestone note:
- Milestone 1 now includes a narrow generic-routine subset through:
- parser
- resolver
- typecheck
- editor audit
- that current subset supports:
- generic routine declarations
- type parameters
- generic parameter references in parameter and return types
- direct calls with narrow argument-driven inference
- current hardened example set for that subset is:
examples/generic_routine_m1examples/generic_routine_pair_m1examples/generic_routine_cross_file_m1examples/generic_receiver_m1examples/generic_receiver_cross_file_m1examples/generic_receiver_overload_m1m2examples/generic_type_semantic_m1m2- positive semantic-check fixture for generic type declarations
examples/generic_type_exec_m1m2examples/generic_standard_constraint_m1m2examples/generic_standard_constraint_generic_m1m2examples/fail_generic_misuse_m1examples/fail_generic_cross_file_m1examples/fail_generic_receiver_m1examples/fail_generic_standard_constraint_m1m2
- generic routine lowering now succeeds for the shipped Milestone 1 example set
- generic routine backend execution now works for the shipped positive Milestone 1 examples
- ownership at a generic call boundary follows the concrete argument: clone-safe arguments remain available to the caller, while owned values and unique pointers move. Inside a routine, an unconstrained generic parameter is conservatively move-only because the routine cannot prove that every future instantiation is clone-safe; forwarding it therefore moves rather than deep-cloning a unique value
- an unresolved generic parameter cannot cross
[>]or| asyncuntil FOL defines a thread-safety and lifetime contract for generics; calls whose arguments infer concrete thread-safe types remain valid - an imported generic routine is instantiable: a mounted signature keeps its
generic parameter list and its capability bounds, so a call in one package
binds the parameters and monomorphizes a routine declared in another. This is
what lets the standard library export generic container routines rather than
a concrete wrapper per element type. A signature that mentions a generic
parameter but carries no list to bind still reports the boundary, because the
call would otherwise type as a bare
T - a generic parameter is an opaque placeholder and is never expanded to an underlying type. That matters most for an imported one, which keeps its DEFINING package’s symbol identity: expanding it could reach an unrelated symbol in the importing package and check the call against that type instead
- receiver-qualified generic routines, matching default arguments, and concrete instantiated generic-type receivers and concrete recoverable error types are now part of the executable Milestone 1 subset
- generic receiver routines are now current contract: a routine such as
fun (Box[T])get(T)(): Tdeclares its generic parameters explicitly, binds them through the receiver and ordinary arguments at each call site, and monomorphizes into one concrete routine per instantiation - receiver-qualified routine bodies read receiver state through
self, which is typed as the receiver and lowered as the routine’s first argument - generic type execution and constrained generic execution now have checked-in example packages too
- nested generic-type composition now works for the checked nested-record
subset such as
Box[Box[int]] - generic type instantiations carry nominal identity:
Box[int]andCup[int]are distinct types even with an identical field shape, so a method shared by name dispatches to each base’s own receiver routine rather than being rejected as ambiguous;examples/generic_receiver_overload_m1m2pins this - broader Milestone 1 edge-case policy is still tracked separately from that shipped positive core
- current editor hardening covers hover/definition on checked-in generic examples without claiming broader generic-aware completion than the shipped editor currently provides
- generic error shells remain outside the current shipped Milestone 1 routine subset
- recursive value edges remain rejected because they have no finite inline
layout. V3 owned heap recursion is now supported: an edge such as
opt @Nodelowers nominally toOption<Box<Node>>. Recursive generic instantiation through an inline container remains outside the shipped generic subset, pinned byexamples/fail_generic_recursive_m1m2 - generic types are not part of
V1; they now belong to the shipped narrow full-V2contract instead - examples here should be read as:
- current narrow
V2Milestone 1 generic-routine work where noted - otherwise later
V2design
- current narrow
Types
Generic Functions
Generic programming aims to express one routine over a family of concrete types, with the requirements written explicitly in the signature.
pro max[T: gen](a, b: T): T = {
result = a | a < b | b;
};
fun biggerFloat(a, b: flt[32]): flt[32] = { max(a, b) }
fun biggerInteger(a, b: int[64]): int[64] = { max(a, b) }
Generic Types
Full V2 now includes generic type declarations and explicit instantiation.
Chosen contract:
- the canonical declaration surface follows the existing parser-owned shape
- generic records and generic aliases are in scope for full
V2 - generic arguments are explicit and arity-checked
- generic types use the same monomorphization-oriented execution strategy as generic routines
Example declaration shapes:
typ Box(T: item): rec = {
value: T;
};
typ Pair(T: left, U: right): map[T, U];
Generic Calls
Full V2 includes standards-as-constraints, but not broad dispatch semantics.
Chosen constraint contract:
- protocol standards are the only generic-constraint surface in the full
V2target - a constraint may name a generic standard at concrete arguments
(
fun drive(T: Holder[int])(...)): the standard’s own generic parameters are bound to those arguments, so a constraint call substitutes them (a requiredfun fetch(): ItemonHolder[int]types asint), and the conformer must claim the standard at the same arguments;examples/generic_standard_constraint_generic_m1m2pins this - constrained generic calls remain procedural and are checked through declared conformance
- standards-as-constraints do not imply runtime object dispatch
This chapter still does not define an object-dispatch system. If later work uses receiver-qualified routine syntax together with constraints, that remains a procedural call-binding rule unless the contract changes explicitly.
std foo: pro = { fun bar(); }
typ[ext] int, str: int, str;
fun (int)bar() = { }
fun (str)bar() = { }
pro callBar(T: foo)(value: T) = { value.bar() } // dispatch with generics
pro barCall( value: foo ) = { value.bar() } // dispatch with standards
pro main: int = {
callBar(2);
callBar("go");
barCall(2);
barCall("go")
};
Modules And Source Layout
This section defines how FOL source is organized across files, folders, packages, imports, and named module-like declarations.
It covers:
- imports through
use - namespaces and package layout
- block-like named definitions
- test-oriented module surfaces
At a high level:
- files in the same package contribute to the same package surface
- namespaces are expressed through folder structure and
::access - imported sources use the public source kinds
locandpkg - bundled std is reached through a declared internal dependency and a
pkgimport, not through a third public source kind
Imports
An import declaration states that the source file containing the declaration depends on functionality of the imported package and enables access to exported identifiers of that package.
Syntax to import a library is:
use alias: source_kind = {"source"}
Current source kinds are:
locfor local directory importspkgfor formal dependency packages, including installed/fetched packages and a declared bundled-standard alias
What use imports
use works against the source-layout model:
- the folder root is the package
- subfolders are namespaces inside that package
- a file is only a source file, not a separate module by itself
So a use target is normally:
- a whole package
- or one namespace inside that package
use does not mean “import another file from the same folder”.
Files in the same package already share package scope.
Imports are for reaching another package or another namespace boundary.
Also note:
usebrings in exported functionalityhiddeclarations remain file-only even inside the same package- importing a package does not erase the original file boundary rules
useis for consuming functionality, not for defining package dependencies
Import kinds
loc
loc is the simplest import kind:
- it points to a local directory
- that directory is scanned as a FOL package / namespace tree
- no
build.folis required
This makes loc useful for local workspace code, experiments, and monorepo-style sharing.
pkg
pkg is for formal dependency packages. The dependency may come from an
installed/fetched external package or from the explicitly declared internal
standard target; source syntax does not gain a separate std source kind.
Unlike loc, a pkg import does not just point at an arbitrary source directory.
It points at an installed package root that must define its identity and build surface explicitly.
The package layer discovers that root first, and ordinary name resolution happens only after the package has been prepared.
For a pkg package root:
build.folis requiredbuild.folstores package metadata, direct dependencies, and build logic
Package Metadata And Build Files
Formal packages use one control file at the root:
build.fol
build.fol
build.fol is the package build entry file.
This file is responsible for:
- declaring package metadata
- declaring direct dependencies
- declaring package build logic
- declaring artifacts, steps, and generated outputs through the build API
- becoming the canonical package entrypoint for
fol code build/run/test/check
build.fol is still an ordinary FOL file.
It is parsed with the same front-end as other .fol sources.
The difference is that the package layer evaluates one canonical build routine inside it.
Today that means:
fol code build/run/test/checkstarts frombuild.fol- the canonical entry is
pro[] build(): non
So:
defis still a general FOL declaration formbuild.folis not a separate mini-languagebuild.foluses an ordinary routine entrypoint, like Zig’sbuild.zig
That means:
- ordinary source
.folfiles useuseto consume packages/namespaces build.folusespro[] build(): nonplus.build()to configure package metadata, direct dependencies, and the build graph
So use and the build routine serve different jobs:
use= consume functionalitypro[] build()inbuild.fol= define package/build surface
Standard library
Bundled std is reached through the dependency system. In build.fol, add:
build.add_dep({
alias = "std",
source = "internal",
target = "standard",
});
This dependency is valid for a memo artifact and exposes the hosted API tier.
It is not a third artifact model: std is not an accepted fol_model value.
It is also not an execution switch. A core or unhosted memo executable can
use fol code run and fol code test without declaring this dependency;
declare it only when source code needs a shipped hosted API.
Then import from the std dependency alias with pkg:
use std: pkg = {"std"};
fun[] main(): int = {
return std::fmt::digit_count(1234567);
};
One import reaches every module of std; name the one you want after the alias:
use std: pkg = {"std"};
fun[] main(): int = {
return std::nums::gcd(84, 36);
};
Using the bundled std.io bootstrap surface:
use std: pkg = {"std"};
pro[] main(): int = {
var shown: str = std::io::echo_str("hello");
return 7;
};
Local libraries
To include a local package or namespace, point loc at the directory:
use bend: loc = {"../folder/bender"};
Then to acces only a namespace:
use space: loc = {"../folder/bender/space"};
That second form is namespace import, not “single file import”.
If space contains multiple .fol files in the same folder, they still belong to the same imported namespace.
loc does not require build.fol.
But if the target directory already defines build.fol at its root, that directory is treated as a formal package root and should be imported through pkg, not loc.
External packages
External packages are imported through their declared pkg dependency alias:
use space: pkg = {"space"};
Nested installed package paths use the same quoted target rule:
use nested: pkg = {"other/package/nested"};
pkg imports are different from loc:
- the imported root is an installed package root
- that root must contain
build.fol build.folis the package control file and currently defines package metadata, dependencies, exports, and build declarations that package loading depends on- raw transport URLs do not appear in source code; package acquisition and installed-package preparation are separate from ordinary source resolution
Declarations
Each .fol file inside a folder is part of the same package.
The important part is that files are connected, but not merged:
- every physical
.folfile is still its own source file - files in the same folder share one package scope
- declarations are order independent across those files
- a declaration started in one file can not continue into the next file
There is no need to import sibling files from the same package. They already belong to the same package scope.
Package, Namespace, And File Scope
It helps to think about source layout in three layers:
- package scope: all
.folfiles directly inside the package folder - namespace scope: declarations inside subfolders of that package
- file scope: declarations marked
hid, which stay visible only inside their own file
In short:
- same folder = same package
- subfolder = nested namespace
hid= file only- files are never imported directly as standalone modules
Package scope
Files that live directly in the package root share one package scope:
root/
math/
add.fol
sub.fol
Both add.fol and sub.fol belong to package math, so declarations from one file may be used by the other without importing the sibling file.
Namespace scope
Subfolders do not create a new package by themselves. They create nested namespaces inside the same package:
root/
math/
add.fol
stats/
mean.fol
Here:
add.folis in package namespacemathmean.folis in package namespacemath::stats
Code may reach namespace members either by:
- direct
use - or qualified access with
::
File scope
Sometimes a declaration should stay inside one file even though the package is shared.
That is what hid is for.
// file1.fol
var[hid] cache_key: str = "local"
// file2.fol
pro[] main: int = {
.echo(cache_key) // error: hidden declarations are file-only
}
Namespaces
A namespace can be defined in a subfolder of the main folder, and namespaces can be nested.
To acces the namespace there are two ways:
- direct import with
use - or code access with
::
Direct import
use aNS: loc = {""home/folder/printing/logg""}
pro[] main: int = {
logg.warn("something")
}
Code access
use aNS: loc = {""home/folder/printing""}
pro[] main: int = {
printing::logg.warn("something")
}
Mental model
For source layout, the mental model is:
- one folder root gives one package
- each file in that folder is a real source file in that package
- subfolders extend the namespace path
useimports packages or namespaceshidkeeps a declaration private to one filelocimports a local directory tree without a package control filepkgimports a formal external package defined bybuild.fol- bundled std is declared as an internal dependency and imported through
pkg
This means FOL is not “one file = one module”. The package is the folder; the file is a source unit inside that package.
Package Roots
When a directory is treated as a package root, the exact contract depends on the import kind:
loc: plain local directory import, no package metadata requiredpkg: installed external package import with explicit root files
For pkg, the root is not just “a folder containing .fol files”.
It is a formal package root with:
build.folas the package control file
This keeps the language model clean:
- source files
useother namespaces/packages - package build execution starts from
pro[] build(): noninbuild.fol - package metadata and direct dependencies are configured through
.build()insidebuild.fol - package loading happens before ordinary name resolution
build.fol itself is still ordinary FOL syntax.
It is not a separate mini-language.
The package layer simply gives package/build meaning to the canonical build
routine there.
Blocks
Current boundary:
- the namespace, package-scope, and import material above is the current compiler surface
- the block forms in this section (
_{},.{}, namedblk[]blocks, and unconditional jump) are not implemented; they are later design work, not part of the current compiler surface
Block statement is used for scopes where members get destroyed when scope is finished. And there are two ways to define a block:
- unnamed blocks and
- named blocks
Unnamed blocks
Are simply scopes, that may or may not return value, and are represented as: { //block }, with . before the brackets for return types and _ for non return types:
pro[] main: int = {
_{
.echo("simple type block")
}
.echo(.{ return "return type block" })
}
Named blocks
Blocks can be used as labels too, when we want to unconditionally jump to a specific part of the code.
pro[] main: int = {
def block: blk[] = { // $block A named block that can be referenced
// implementation
}
def mark: blk[] // $mark A named block that can be referenced, usually for "jump" statements
}
Tests
Current boundary:
def ... : tst[...]test blocks are not implemented in the current compiler surface- everything below describes intended design, not current behavior
Blocks defined with type tst, have access to the module (or namespace) defined in tst["name", access].
def test1: tst["sometest", shko] = {}
def "some unit testing": tst[shko] = {}
The Standard Library
std is a FOL package that ships with the compiler. It is ordinary FOL source —
you can read every line of it — layered over the intrinsics described in the
intrinsics chapter.
That split is the thing to hold onto. An intrinsic exists because the compiler must understand it: it crosses an OS boundary, it is the only way to observe a builtin, or it is something FOL would get subtly wrong (Unicode tables, float bit layout, calendar arithmetic). Everything else belongs here, in FOL, where you can read it and fix it. SHA-256, base64, CSV, JSON, sorting, path handling and the rest are all FOL routines, not compiler surface.
Depending on it
std is not implicit. Declare it in build.fol:
build.add_dep({ alias = "std", source = "internal", target = "standard" });
and import it in any source file that uses it:
use std: pkg = {"std"};
Then reach routines through their module:
pro[] main(): int = {
std::io::write("total " + std::fmt::int_to_str(6 * 7) + "\n");
return 0;
};
The artifact must be fol_model = "memo". std layers on the heap-backed tier;
a core artifact has no heap and cannot use it.
Three conventions that explain most of the API
Reading a few signatures raises the same three questions every time. All three follow from language rules rather than from taste.
Routines are pure, so updates return a new value
A free FOL routine cannot take a [mut, bor] parameter — only a receiver can.
So a routine that “modifies” a container takes it and returns the new one:
var members: vec[int] = std::sets::from_vec(std::vecs::range_int(0, 5));
var larger: vec[int] = std::sets::insert(members, 9);
members is unchanged; larger is the result. Where a routine has to carry
state across calls — the random generator is the clearest case — it returns a
record pairing the new state with the value.
Container routines are generic, and two bounds carry them
std::vecs, std::sets, std::iter, std::heap, std::grid, and std::maps
are generic over the types they hold:
var numbers: vec[int] = std::vecs::sort(measurements);
var names: vec[str] = std::vecs::sort(labels);
var places: vec[Point] = std::vecs::sort(waypoints);
Two capability bounds do most of the work:
clone, because a pure routine has to copy elements out of its argument rather than move them — so the argument is still usable afterwardsord, wherever elements are compared. It promises a total order, and a total order also decides equality, socontainsanddedup_sortedneed nothing more
A bound is checked against the actual type at every call, including across a package boundary. Passing a type that cannot satisfy one is an ordinary type error, not a failure further down the pipeline.
A remaining _int or _flt suffix means a real restriction
A few names keep a type in them, and each has a reason that will not go away soon:
vecs::sum_intanditer::zip_add_intadd elements together, and FOL has no numeric capability bound, so+is unavailable on aT. For any other element type, useiter::foldand supply the combining step yourselfvecs::range_intgenerates integers rather than copying them out of an argument, so there is nothing to be generic overvecs::sort_fltexists becauseordpromises a total order andflthas none — NaN compares equal to nothing. The container method behind it needs only a partial order, whichfltdoes have
So the suffix now marks a genuine restriction. It is not a placeholder for work still to be done.
Passing a literal to a generic routine
A literal is shaped by the type it is being passed to, so a one-character
"a" becomes a str where a str is wanted and {1, 2} becomes a vec where
a vec is wanted. That works for every concrete parameter, in std and in the
intrinsics:
var loud: str = std::strn::to_upper("a");
var text: str = .str_from_bytes({104, 105});
A generic parameter is the exception. There is no concrete type to shape the literal from yet, so it falls back to its own reading — a container literal is an array, not a vector — and the call is rejected:
// rejected: nothing has told the literal it is a `vec[int]`
var sorted: vec[int] = std::vecs::sort({3, 1, 2});
// bind it first, and the binding's type does the shaping
var values: vec[int] = {3, 1, 2};
var sorted: vec[int] = std::vecs::sort(values);
A “set” here is a sorted vector
std::sets operates on vec[T] kept sorted with no duplicates, not on the
builtin set[...] type. The builtin is a fixed tuple of member types — closer
to a record than to a growable collection — so the growable set is built in FOL
instead. Membership is a binary search, and the operations are single merges.
The modules
text strn strings: search, split, pad, case, normalization
chars character classification and conversion
fmt numbers to text, radix, padding
containers vecs sort, search, slice, fold over vec
sets growable sets over sorted vectors
maps iteration and updates over map[K, V]
iter map/filter/fold with routine values
heap stack, queue, and binary min-heap
grid 2D addressing over one flat vector
numbers nums clamp, gcd, sign, overflow-reporting arithmetic
rand seeded, repeatable random numbers
data json JSON escaping, scanning, flat objects
jsondoc a full JSON value tree
csv RFC 4180 rows and fields
codec hex, base64, CRC-32
hash SHA-256 and FNV-1a
system io console reads and writes
fs files, whole and streaming
os arguments, environment, shell
path path surgery
term terminal size and raw mode
time clock and sleep
sync atomic counters and thread facts
Each group has its own page.
Text
std::strn — strings
FOL strings are UTF-8, and .len(...) counts bytes. std::strn inherits
that: sub, find, and byte_at are byte-oriented, matching the intrinsics
they wrap. For character-oriented work use .str_char_len(...) and friends, and
see the intrinsics chapter for why the two worlds
are kept apart.
Searching and testing
fun[exp] find(text: str, needle: str): int
fun[exp] find_from(text: str, needle: str, start: int): int
fun[exp] last_index_of(text: str, needle: str): int
fun[exp] contains(text: str, needle: str): bol
fun[exp] starts_with(text: str, prefix: str): bol
fun[exp] ends_with(text: str, suffix: str): bol
fun[exp] is_empty(text: str): bol
fun[exp] count_matches(text: str, needle: str): int
find and last_index_of return a byte index, or -1. There is no
optional here: -1 is the sentinel, so test it before using the result as an
offset.
Slicing and trimming
fun[exp] sub(text: str, start: int, count: int): str
fun[exp] byte_at(text: str, index: int): int
fun[exp] from_byte(value: int): str
fun[exp] is_space_byte(value: int): bol
fun[exp] trim(text: str): str
fun[exp] trim_start(text: str): str
fun[exp] trim_end(text: str): str
fun[exp] strip_prefix(text: str, prefix: str): str
fun[exp] strip_suffix(text: str, suffix: str): str
strip_prefix and strip_suffix return the text unchanged when it does not
start or end with the given piece, so they are safe to chain.
is_space_byte is the byte-oriented partner to byte_at: it answers for space,
tab, newline and carriage return, which is ASCII whitespace and nothing wider.
Use .chr_is_space(...) when the input is a chr and Unicode whitespace counts.
Building
fun[exp] replace(text: str, from: str, to: str): str
fun[exp] repeat(text: str, times: int): str
fun[exp] reverse(text: str): str
fun[exp] pad_left(text: str, width: int, fill: str): str
fun[exp] pad_right(text: str, width: int, fill: str): str
fun[exp] split(text: str, sep: str): vec[str]
fun[exp] lines(text: str): vec[str]
fun[exp] join(parts: vec[str], sep: str): str
fun[exp] to_upper(text: str): str
fun[exp] to_lower(text: str): str
fun[exp] to_int(text: str, fallback: int): int
to_upper and to_lower are full Unicode mappings, not per-character ASCII:
straße uppercases to STRASSE, which is one character longer than the input.
to_int takes the fallback as an argument because every sentinel is also a
valid parse result — there is no integer that can mean “not a number”.
Padding counts bytes. For a table containing non-ASCII text, compute the
width with .str_width(...) instead; 日本 is 6 bytes, 2 characters, and 4
terminal columns.
Normalization
The same word can be typed two ways, and they do not compare equal:
fun[exp] nfc(text: str): str
fun[exp] nfd(text: str): str
fun[exp] nfkc(text: str): str
fun[exp] nfkd(text: str): str
fun[exp] is_nfc(text: str): bol
fun[exp] same_text(left: str, right: str): bol
fun[exp] search_key(text: str): str
same_text is the one to reach for when comparing anything a person typed — a
login name, a search box, a filename:
var typed: str = "e\u{0301}llo";
var stored: str = "éllo";
// typed == stored is false
// std::strn::same_text(typed, stored) is true
search_key folds harder still — case and compatibility variants both — which
suits duplicate detection and search indexes but discards distinctions, so
never store its output as the user’s text.
std::chars — characters
fun[exp] code(value: chr): int
fun[exp] from_code(value: int): chr
fun[exp] is_digit(value: chr): bol
fun[exp] is_alpha(value: chr): bol
fun[exp] is_alnum(value: chr): bol
fun[exp] is_upper(value: chr): bol
fun[exp] is_lower(value: chr): bol
fun[exp] is_space(value: chr): bol
fun[exp] is_hex_digit(value: chr): bol
fun[exp] to_upper(value: chr): chr
fun[exp] to_lower(value: chr): chr
fun[exp] digit_value(value: chr): int
The classifiers are Unicode-aware, not ASCII ranges: is_alpha accepts é and
is_space accepts a non-breaking space. digit_value yields -1 for a
character that is not a digit.
Single-character case mapping cannot express every rule — ß uppercases to two
characters — so use std::strn::to_upper for text and chars::to_upper only
for a character you have already isolated.
std::fmt — numbers to text
fun[exp] int_to_str(value: int): str
fun[exp] float_to_str(value: flt, decimals: int): str
fun[exp] bol_to_str(value: bol): str
fun[exp] digit_count(value: int): int
fun[exp] pad_int(value: int, width: int): str
fun[exp] with_thousands(value: int, sep: str): str
fun[exp] to_radix(value: int, radix: int): str
fun[exp] to_hex(value: int): str
fun[exp] to_bin(value: int): str
fun[exp] to_oct(value: int): str
to_radix handles bases 2 through 36 using 0-9a-z; to_hex, to_bin, and
to_oct are the usual three named.
pad_int pads with zeros, not spaces — it is for fixed-width numeric fields
such as timestamps and identifiers. For space-aligned columns use
std::strn::pad_left with a space fill.
var stamp: str = std::fmt::pad_int(42, 6) + " " + std::fmt::to_hex(255);
// "000042 ff"
The sign is added after padding, so a negative comes out one character wider
than the requested width: pad_int(-42, 6) is -000042.
For floats, float_to_str takes a fixed number of decimals. When the value has
to survive a round trip — writing JSON, say — use the .flt_to_str_exact(...)
intrinsic instead, which emits the shortest text that parses back to the
identical value.
Containers
Every routine on this page is pure: it takes a container and returns a new one.
Nothing here mutates its argument, because a free FOL routine cannot take a
[mut, bor] parameter.
For in-place work, the container methods are the other half of the story —
values.push(x), values.pop(), values.sort(), values.swap(i, j) — and
cells[i] = v assigns an element directly. Those are language surface, not
std, and they are what these routines are built from. The full set of them is
in Container methods.
All of it is generic over the element type. clone is needed because a pure
routine copies elements out of its argument; ord appears wherever elements are
compared, and since it promises a total order it also decides equality. See the
index chapter for what a remaining _int suffix means, and for
why a bare literal has to be bound before it is passed.
std::vecs — ordering and search
fun[exp] sort(T: ord + clone)(values: vec[T]): vec[T]
fun[exp] sort_flt(values: vec[flt]): vec[flt]
fun[exp] reverse(T: clone)(values: vec[T]): vec[T]
fun[exp] is_sorted(T: ord + clone)(values: vec[T]): bol
fun[exp] index_of(T: ord + clone)(values: vec[T], needle: T): int
fun[exp] contains(T: ord + clone)(values: vec[T], needle: T): bol
fun[exp] binary_search(T: ord + clone)(values: vec[T], needle: T): int
fun[exp] min_of(T: ord + clone)(values: vec[T], fallback: T): T
fun[exp] max_of(T: ord + clone)(values: vec[T], fallback: T): T
fun[exp] fill(T: clone)(count: int, value: T): vec[T]
fun[exp] slice(T: clone)(values: vec[T], start: int, count: int): vec[T]
fun[exp] concat(T: clone)(left: vec[T], right: vec[T]): vec[T]
fun[exp] dedup_sorted(T: ord + clone)(values: vec[T]): vec[T]
fun[exp] sum_int(values: vec[int]): int
fun[exp] range_int(start: int, stop: int): vec[int]
sort delegates to the container method, so it is a real sort rather than an
insertion sort written in FOL. sort_flt exists because flt cannot satisfy
ord.
Sorting records works, but the comparison is by field name order, not
declaration order — { row, col } compares on col first. It is a stable total
order rather than a meaningful one, so use it for grouping and deduplication and
not for presentation. The
capabilities chapter explains why.
index_of scans and binary_search bisects; both return -1 when absent, and
the bisecting one requires a sorted input, which is_sorted can confirm.
min_of and max_of take a fallback because an empty vector has no answer.
range_int(start, stop) is half-open, so range_int(0, 5) is 0 1 2 3 4.
slice clamps rather than faulting: a start past the end yields an empty
vector.
var evens: vec[int] = std::vecs::range_int(0, 10);
var top: vec[int] = std::vecs::slice(evens, 5, 99);
// top is 5 6 7 8 9 -- the count is clamped, not an error
std::sets — growable sets
A set here is a sorted vector with no duplicates, not the builtin set[...]
type, which is a fixed tuple of member types. Membership is a binary search; the
algebra is a single merge each.
fun[exp] from_vec(T: ord + clone)(values: vec[T]): vec[T]
fun[exp] contains(T: ord + clone)(members: vec[T], value: T): bol
fun[exp] insert(T: ord + clone)(members: vec[T], value: T): vec[T]
fun[exp] remove(T: ord + clone)(members: vec[T], value: T): vec[T]
fun[exp] union(T: ord + clone)(left: vec[T], right: vec[T]): vec[T]
fun[exp] intersect(T: ord + clone)(left: vec[T], right: vec[T]): vec[T]
fun[exp] difference(T: ord + clone)(left: vec[T], right: vec[T]): vec[T]
fun[exp] is_subset(T: ord + clone)(inner: vec[T], outer: vec[T]): bol
from_vec is the entry point — it sorts and de-duplicates. Every other routine
assumes that invariant and will misbehave on an unsorted vector, so build
sets with it rather than passing a raw vector. insert on an element already
present returns the set unchanged, so calling it twice is the same as once.
var low: vec[int] = std::vecs::range_int(0, 6);
var high: vec[int] = std::vecs::range_int(4, 10);
var shared: vec[int] = std::sets::intersect(
std::sets::from_vec(low),
std::sets::from_vec(high),
);
// shared is 4 5
std::maps — map iteration and updates
Generic over both parameters. K needs ord because it is a map key; V needs
ord only where the routine compares values.
typ[exp] Pair(K, V): rec = { key: K, value: V };
fun[exp] pairs(K: ord + clone, V: clone)(source: map[K, V]): vec[Pair[K, V]]
fun[exp] values_of(K: ord + clone, V: clone)(source: map[K, V]): vec[V]
fun[exp] get_or(K: ord + clone, V: clone)(source: map[K, V], key: K, fallback: V): V
fun[exp] has_key(K: ord + clone, V: clone)(source: map[K, V], key: K): bol
fun[exp] merge(K: ord + clone, V: clone)(left: map[K, V], right: map[K, V]): map[K, V]
fun[exp] invert(K: ord + clone, V: ord + clone)(source: map[K, V]): map[V, K]
fun[exp] keys_where(K: ord + clone, V: ord + clone)(source: map[K, V], least: V): vec[K]
fun[exp] bump(K: ord + clone)(source: map[K, int], key: K, amount: int): map[K, int]
fun[exp] tally(K: ord + clone)(items: vec[K]): map[K, int]
fun[exp] sum_values(K: ord + clone)(source: map[K, int]): int
pairs is how you iterate: a map yields a vector of key/value records, which
for can then walk. The record is the pair — FOL has no tuple type, so a
two-field record is what carries one. Keys come out sorted, because the backing
store is a BTreeMap.
bump and tally fix the value type to int because they add, and + needs a
numeric capability bound FOL does not have. Both stay generic over the key, so a
frequency table works over anything orderable:
var counts: map[str, int] = std::maps::tally(words);
var more: map[str, int] = std::maps::bump(counts, "fol", 1);
var readings: vec[int] = {7, 7, 8};
var spread: map[int, int] = std::maps::tally(readings);
invert needs V: ord because the values become keys; two keys sharing a value
collapse to one entry. merge lets the right side win on a duplicate key.
std::iter — adapters over vectors
These take routine values, so the step is an ordinary FOL closure. Two of them carry a second type parameter, because they may change the type:
fun[exp] map_to(T: clone, U: clone)(values: vec[T], step: {fun (value: T): U}): vec[U]
fun[exp] filter(T: clone)(values: vec[T], keep: {fun (value: T): bol}): vec[T]
fun[exp] fold(T: clone, A: clone)(values: vec[T], start: A, step: {fun (carried: A, value: T): A}): A
fun[exp] any(T: clone)(values: vec[T], test: {fun (value: T): bol}): bol
fun[exp] every(T: clone)(values: vec[T], test: {fun (value: T): bol}): bol
fun[exp] position(T: clone)(values: vec[T], test: {fun (value: T): bol}): int
fun[exp] count_if(T: clone)(values: vec[T], test: {fun (value: T): bol}): int
fun[exp] take(T: clone)(values: vec[T], count: int): vec[T]
fun[exp] skip(T: clone)(values: vec[T], count: int): vec[T]
fun[exp] take_while(T: clone)(values: vec[T], test: {fun (value: T): bol}): vec[T]
fun[exp] skip_while(T: clone)(values: vec[T], test: {fun (value: T): bol}): vec[T]
fun[exp] zip_add_int(left: vec[int], right: vec[int]): vec[int]
They are eager: each returns a complete vector, so a chain allocates at every step. There is no lazy iterator protocol; for a hot loop, write the loop.
map_to and fold are where the second parameter earns its place — rendering
numbers to text, or folding a vector down to a single string:
var numbers: vec[int] = std::vecs::range_int(1, 4);
var texts: vec[str] = std::iter::map_to(numbers, fun (value: int): str = {
return std::fmt::int_to_str(value);
});
var joined: str = std::iter::fold(texts, "", fun (carried: str, value: str): str = {
return carried + value;
});
// joined is "123"
take_while stops at the first element that fails, unlike filter, which tests
them all. position returns -1 when nothing matches.
zip_add_int adds elements together, which needs a numeric bound FOL does not
have. For any other element type, use fold and supply the combining step.
std::heap — stack, queue, and min-heap
Three structures over one vector, distinguished by which end they work on. The
heap compares, so it needs ord; the stack and queue only need clone.
fun[exp] stack_push(T: clone)(values: vec[T], value: T): vec[T]
fun[exp] queue_push(T: clone)(values: vec[T], value: T): vec[T]
fun[exp] queue_pop(T: clone)(values: vec[T]): vec[T]
fun[exp] queue_front(T: clone)(values: vec[T], fallback: T): T
fun[exp] heap_push(T: ord + clone)(values: vec[T], value: T): vec[T]
fun[exp] heap_peek(T: ord + clone)(values: vec[T], fallback: T): T
fun[exp] heap_pop(T: ord + clone)(values: vec[T]): vec[T]
fun[exp] heap_drain(T: ord + clone)(values: vec[T]): vec[T]
A stack needs no pop routine — values.pop() is the container method.
The heap is a binary min-heap, so heap_peek is the smallest element and
heap_drain returns everything in ascending order. heap_pop returns the heap
without its smallest element; read it with heap_peek first if you need the
value.
std::grid — 2D over one flat vector
A grid is a vector plus a width, addressed row-major. Keeping it flat means one allocation and no nested-vector indexing.
fun[exp] offset(width: int, row: int, col: int): int
fun[exp] in_bounds(width: int, height: int, row: int, col: int): bol
fun[exp] make(T: clone)(width: int, height: int, fill: T): vec[T]
fun[exp] cell(T: clone)(cells: vec[T], width: int, row: int, col: int, fallback: T): T
fun[exp] put(T: clone)(cells: vec[T], width: int, row: int, col: int, value: T): vec[T]
fun[exp] row_of(T: clone)(cells: vec[T], width: int, row: int, fallback: T): vec[T]
fun[exp] column_of(T: clone)(cells: vec[T], width: int, height: int, col: int, fallback: T): vec[T]
fun[exp] neighbours(T: clone)(cells: vec[T], width: int, row: int, col: int, fallback: T): vec[T]
offset and in_bounds are pure index arithmetic and carry no element type at
all.
Every reader takes a fallback, so an out-of-range read is a value rather than a
fault — which is what a flood fill or a cellular automaton wants at the edges,
and what a generic cell type needs, since there is no zero to default to.
neighbours returns all eight surrounding cells, reading row by row and
skipping the centre; for the four orthogonal ones, call cell yourself.
var origin: Point = { x = 0, y = 0 };
var mark: Point = { x = 9, y = 9 };
var board: vec[Point] = std::grid::make(3, 3, origin);
var marked: vec[Point] = std::grid::put(board, 3, 1, 1, mark);
var centre: Point = std::grid::cell(marked, 3, 1, 1, origin);
// centre.x is 9
Numbers
std::nums — arithmetic helpers
fun[exp] clamp_int(value: int, low: int, high: int): int
fun[exp] clamp_flt(value: flt, low: flt, high: flt): flt
fun[exp] sign_int(value: int): int
fun[exp] is_even(value: int): bol
fun[exp] is_odd(value: int): bol
fun[exp] gcd(left: int, right: int): int
fun[exp] lcm(left: int, right: int): int
fun[exp] pow_int(base: int, exponent: int): int
fun[exp] degrees_to_radians(value: flt): flt
fun[exp] radians_to_degrees(value: flt): flt
sign_int yields -1, 0, or 1. gcd takes absolute values, so it is safe
on negatives, and lcm is built from it.
Both clamps swap bounds given the wrong way round, so clamp_int(5, 10, 2)
is 5 rather than a value outside both. That keeps them total – every input has
a sensible answer – and keeps the int and flt spellings agreeing, which they
did not when one was min(max(v, low), high) and the other tested low first.
These live in FOL because none of them needs the compiler: they are a few lines
each over the operators. The transcendental functions — .sqrt(...),
.sin(...), .ln(...) and the rest — are intrinsics instead, because
reimplementing them in FOL would be slower and less accurate than the ones the
platform already has.
Overflow that reports rather than faults
Plain +, -, and * fault on overflow rather than wrapping. When you
want the other behaviour, the .checked_*, .wrapping_*, and .saturating_*
intrinsics give it directly. What they cannot give is the value and a flag,
because an intrinsic returns one value — so that pair lives here:
typ[exp] Overflowed: rec = {
value: int,
overflowed: bol,
};
fun[exp] overflowing_add(left: int, right: int): Overflowed
fun[exp] overflowing_sub(left: int, right: int): Overflowed
The record is the pair. FOL has no tuple type, so this is how any routine returns two things.
std::rand — seeded random numbers
The .random_int(...), .random_flt(...), and .random_bytes(...) intrinsics
take entropy from the operating system: unpredictable, and unrepeatable.
That second property is usually the problem — a test or a simulation needs the
same answer twice. This module is the other tool.
typ[exp] Rng: rec = { state: int };
typ[exp] Draw: rec = { rng: Rng, value: int };
typ[exp] DrawVec: rec = { rng: Rng, values: vec[int] };
fun[exp] seeded(seed: int): Rng
pro[exp] from_os(): Rng
fun[exp] next(rng: Rng): Draw
fun[exp] next_range(rng: Rng, low: int, high: int): Draw
fun[exp] next_bool(rng: Rng): Draw
fun[exp] shuffle_int(rng: Rng, values: vec[int]): DrawVec
fun[exp] choice_int(rng: Rng, values: vec[int], fallback: int): Draw
Because the routines are pure, each returns the advanced generator alongside
the value, and the caller threads it along. That is what Draw is for:
var[mut] rng: std::rand::Rng = std::rand::seeded(2024);
var roll: std::rand::Draw = std::rand::next_range(rng, 1, 7);
rng = roll.rng;
// roll.value is the die
Forgetting to carry roll.rng forward is the one easy mistake: the next call
then starts from the same state and returns the same number.
next_range is half-open — next_range(rng, 1, 7) is a six-sided die — and
uses rejection rather than a modulo, so no value is favoured when the span does
not divide evenly. choice_int needs a fallback because an empty vector has
nothing to choose.
Seed from from_os() when you want a different stream per run but still want to
log the seed and reproduce a failure.
What the generator is
xorshift64*: Vigna’s 12/25/27 shift triple over a full 64-bit state, with the output passed through a multiplicative scrambler.
The scrambler matters more than it looks. A plain xorshift is linear over GF(2), so its outputs are far more predictable than a frequency histogram suggests. Taking the rank of a 96×96 binary matrix built from its output shows it immediately:
plain xorshift, no scrambler: rank 46 of 96 (on every seed)
xorshift64* as shipped: rank 95 of 96 (on every seed)
95 is the expected rank for a genuinely random binary matrix. A test that only
reduces values with % — die rolls, buckets, coin flips — cannot see the
difference at all.
It is not cryptography. The state is recoverable from the output, which is
exactly what makes it repeatable. Use .random_bytes(...) when unpredictability
matters.
Any 64-bit seed works, negatives included. Only zero is special: it is a fixed point that would emit zeros forever, so it is replaced.
Data Formats
Everything on this page is FOL, including SHA-256 and CRC-32. None of it needs the compiler: they are loops over the bitwise intrinsics, and they match the published reference vectors.
std::json — flat JSON
Escaping, scanning, and single-level objects. For nested documents use
std::jsondoc below.
fun[exp] escape(text: str): str
fun[exp] unescape(text: str): str
fun[exp] encode_string(text: str): str
fun[exp] is_balanced(text: str): bol
fun[exp] split_top_level(text: str): vec[str]
fun[exp] max_depth(text: str): int
fun[exp] key_split_point(entry: str): int
fun[exp] decode_flat(text: str): map[str, str]
fun[exp] decode_array(text: str): vec[str]
fun[exp] encode_flat(values: map[str, str]): str
escape handles the string body; encode_string adds the surrounding quotes.
split_top_level splits on commas that are not inside a nested brace, bracket,
or string, which is what makes it usable as a scanner rather than a naive
split. It records where each part starts and slices once, rather than growing
the part a character at a time – accumulating would copy the whole part on every
character, and this runs over untrusted input.
max_depth reports the deepest nesting the text reaches, walked iteratively.
jsondoc::parse uses it to refuse a document too deep to descend recursively.
decode_flat returns every value as a str, including numbers and booleans —
a flat map cannot carry mixed types, and converting is the caller’s decision.
std::jsondoc — the value tree
A JSON value contains JSON values, and FOL has no recursive type. The tree
is therefore an arena: every node lives in one flat vec[Node] and refers to
its children by integer index.
typ[exp] Node: rec = {
kind: int,
text: str,
first: int,
next: int,
};
typ[exp] Doc: rec = { nodes: vec[Node] };
Children are a singly-linked list — first is the first child’s index, each
child’s next is its sibling, and both are -1 when absent. That keeps a node
fixed-size, so adding a child never has to reallocate a parent’s field. This is
the documented workaround for recursive shapes, and it costs nothing here: a
document is parsed once and read many times.
con[exp] NULL: int = 0;
con[exp] BOOL: int = 1;
con[exp] NUM: int = 2;
con[exp] STR: int = 3;
con[exp] ARR: int = 4;
con[exp] OBJ: int = 5;
con[exp] MEMBER: int = 6;
fun[exp] none(): int // the absent-index sentinel, -1
fun[exp] parse(text: str): Doc
fun[exp] kind_of(doc: Doc[bor], index: int): int
fun[exp] text_of(doc: Doc[bor], index: int): str
fun[exp] child_indices(doc: Doc[bor], index: int): vec[int]
fun[exp] member_value(doc: Doc[bor], member: int): int
fun[exp] field(doc: Doc[bor], object: int, name: str): int
fun[exp] element(doc: Doc[bor], array: int, position: int): int
fun[exp] length_of(doc: Doc[bor], index: int): int
fun[exp] path(doc: Doc[bor], from: str): int
fun[exp] render(doc: Doc[bor], index: int): str
none() is a routine rather than a constant because con needs a literal
initializer and -1 is a negation, not a literal.
What parse promises
parse is lenient, not validating. It never faults, whatever it is handed –
truncated input, an unterminated string, a lone backslash, a trailing comma, or
text that is not JSON at all. What it does not do is reject malformed input, so
check the shape you expect rather than assuming a document is well formed:
- a container it cannot build yields an empty arena, so
kind_of(...)on index 0 answers-1; that is the signal that nothing parsed NUMis a fallthrough, not a claim. Anything that is not a quoted string,true,falseornullis classifiedNUMwith the raw text kept verbatim, sohelloand the empty string both arrive asNUM. Parse the text before trusting it as a number- a trailing comma is accepted;
[1,2,]reads as a two-element array - nesting deeper than
MAX_DEPTH(512) is refused the same way, giving the empty arena. Building the tree recurses once per level, and a stack overflow aborts the process rather than faulting, so no caller could catch it – the cap is what keeps hostile input a refusal instead of a crash
That leniency is deliberate – a parser that faults on hostile input is a denial of service – but it puts the validation burden on the caller.
The document is passed as Doc[bor] — a read-only loan — so walking it never
copies the arena. That means every call takes [bor]doc, not doc;
ownership transfers are explicit in FOL, and passing the document bare is an
O2002 error.
An object member is its own node: it holds the key in text and its value
as its only child, which is what lets objects and arrays share one walk. Use
field to go straight from an object to a value index, and path for a dotted
lookup:
var doc: std::jsondoc::Doc = std::jsondoc::parse(source);
var name: int = std::jsondoc::path([bor]doc, "user.name");
var text: str = std::jsondoc::text_of([bor]doc, name);
Every lookup returns an index, and a missing one is none(). Check before
reading.
std::csv — RFC 4180
fun[exp] parse_row(line: str): vec[str]
fun[exp] parse(text: str): vec[str]
fun[exp] field_at(line: str, index: int, fallback: str): str
fun[exp] column_count(line: str): int
fun[exp] encode_field(value: str): str
fun[exp] encode_row(fields: vec[str]): str
Quoting is handled on both sides: parse_row understands quoted fields with
embedded commas and doubled quotes, and encode_field adds quotes only when the
value needs them.
field_at takes a fallback so a short row reads as a value rather than a fault,
which is what makes a malformed file survivable.
std::codec — encodings and checksums
fun[exp] hex_encode(text: str): str
fun[exp] hex_decode(text: str): str
fun[exp] base64_encode(text: str): str
fun[exp] base64_decode(text: str): str
fun[exp] crc32(text: str): int
fun[exp] crc32_hex(text: str): str
Both decoders are all-or-nothing: malformed input yields the empty string rather than a partial result, so a caller cannot act on half a value.
CRC-32 detects accidental corruption. It is not a hash and not a signature — producing a colliding input is trivial.
std::hash — digests
fun[exp] sha256_hex(text: str): str
fun[exp] sha256_bytes_hex(bytes[bor]: vec[int]): str
fun[exp] sha256_start(): Sha256
fun[exp] sha256_update(state[bor]: Sha256, chunk[bor]: vec[int]): Sha256
fun[exp] sha256_digest(state[bor]: Sha256): str
fun[exp] fnv1a(text: str): int
fun[exp] round_constants(): vec[int]
sha256_hex is real SHA-256, matching the published test vectors. Use it when a
digest has to resist an adversary — and pair it with .bytes_equal_ct(...) when
comparing digests, since a normal == returns early and leaks how much of a
secret was guessed correctly.
For files and binary protocols, use sha256_bytes_hex or feed sequential
octet vectors from sha256_start through sha256_update. The state holds
the chaining words, byte count, and at most 63 pending bytes; it does not
retain earlier chunks. Finalization returns the lowercase digest without
altering the state. An octet outside 0–255 or a count above 2⁶⁰−1 makes the
state invalid; its digest is the empty string.
fnv1a is a small non-cryptographic hash for bucketing. For that job the
.hash_bytes(...) intrinsic is usually better: it is SipHash, mixes far more
thoroughly, and is equally stable across runs.
round_constants is exposed because SHA-256’s table is useful to verify
against; there is rarely a reason to call it.
System
These modules are thin. Most are a named wrapper over one intrinsic, and the
value is the name: std::os::env("HOME") says what it does where
.env_var("HOME") says where it comes from. Prefer the wrappers — they are
where shared behaviour accumulates, and std::fs’s streaming decoder is already
an example of a wrapper doing real work.
std::io — console
pro[exp] write(value: str): str
pro[exp] write_err(value: str): str
pro[exp] read_key(): int
pro[exp] read_key_ms(timeout: int): int
pro[exp] echo_int(value: int): int
pro[exp] echo_str(value: str): str
pro[exp] echo_bool(value: bol): bol
pro[exp] echo_chr(value: chr): chr
write adds no newline and flushes, and returns its argument unchanged so it
can sit inside an expression. The echo_* family prints a value in its FOL
form and forwards it, which suits tracing.
read_key blocks for one byte and yields -1 at end of input. read_key_ms
gives up after the timeout, yielding -2 — a distinct value, so a timeout is
not mistaken for a closed stream.
std::fs — files
Whole-file access:
pro[exp] read_file(path: str): str
pro[exp] write_file(path: str, contents: str): int
pro[exp] dir_list(path: str): str
read_file returns "" for a missing file, an empty file, and a file that
is not valid UTF-8. When those need telling apart, or the file is not text, read
it as bytes with the .read_bytes(...) intrinsic and convert with
.str_from_bytes(...).
Streaming
A file larger than memory, or one still being written, cannot be handled by the whole-file routines at all.
con[exp] MODE_READ: int = 0;
con[exp] MODE_WRITE: int = 1;
con[exp] MODE_APPEND: int = 2;
con[exp] MODE_UPDATE: int = 3;
con[exp] FROM_START: int = 0;
con[exp] FROM_HERE: int = 1;
con[exp] FROM_END: int = 2;
pro[exp] open_read(path: str): int
pro[exp] pipe(): vec[int]
pro[exp] open_write(path: str): int
pro[exp] open_append(path: str): int
pro[exp] open_update(path: str): int
pro[exp] read_chunk(handle: int, count: int): vec[int]
pro[exp] write_chunk(handle: int, bytes: vec[int]): int
pro[exp] write_text(handle: int, text: str): int
pro[exp] seek(handle: int, offset: int, whence: int): int
pro[exp] rewind(handle: int): int
pro[exp] flush(handle: int): int
pro[exp] sync(handle: int): int
pro[exp] close(handle: int): int
A handle is an integer. The open_* routines exist because the underlying
.file_open(path, mode) takes an integer mode, matching the selector arguments
elsewhere on that surface; these give the modes names.
Reads and writes are bytes, which keeps the surface binary-safe.
pipe() creates an anonymous binary pipe and returns [read_handle, write_handle].
The handles use the same read/write/close operations as files. Failure returns
[-1, -1] and sets .os_error_kind(). Close both handles when finished; a
reader cannot observe EOF while any copy of the write end remains open.
Pipe creation requires hosted std and is a procedure, not a pure function.
A positive-sized read_chunk returning no bytes means EOF only when
.os_error_kind() is zero. Read/write/open/close failures set that error
channel, and successful operations clear it. Check it immediately, before
another host operation can replace it. A short nonempty read is not EOF.
write_chunk and write_text answer the number of bytes written, not a
status code – -1 is the failure value, so test for that rather than for zero.
A short write is possible on a pipe or a full disk, which is why the count is
returned at all. flush, seek, rewind and close do answer 0 on success.
Decoding a chunked read
This is the trap, and it is worth stating plainly. A fixed-size read splits
multi-byte characters across chunk boundaries, and a chunk that ends
mid-character is not valid UTF-8 — so converting each chunk on its own silently
loses those characters. Reading héllo two bytes at a time yields lo.
Decoder holds the partial character until the rest of it arrives:
typ[exp] Decoder: rec = { carry: vec[int], text: str };
fun[exp] decoder(): Decoder
fun[exp] feed(state: Decoder, chunk: vec[int]): Decoder
pro[exp] read_streamed(path: str, chunk: int): str
feed returns the new state, whose text is what became decodable from that
chunk. read_streamed wraps the whole pattern and is lossless at every chunk
size:
var whole: str = std::fs::read_streamed(path, 4096);
Use it in preference to hand-rolling the loop.
Paths, atomic writes, and locking
pro[exp] resolve(path: str): str
pro[exp] temp_path(prefix: str): str
pro[exp] write_atomic(path: str, contents: str): int
pro[exp] make_link(target: str, link: str): int
pro[exp] lock_exclusive(handle: int): int
pro[exp] try_lock_exclusive(handle: int): int
pro[exp] lock_shared(handle: int): int
pro[exp] unlock(handle: int): int
resolve asks the filesystem, so symlinks and .. come out resolved as they
really are. std::path::normalize does it textually and is a different answer
whenever a symlink is involved — use resolve for any decision about whether a
path stays inside an allowed directory.
write_atomic writes a temp file and renames it over the target, so a reader
never sees a half-written file:
var wrote: int = std::fs::write_atomic("config.toml", rendered);
Rename is atomic only within a filesystem. write_atomic uses the temp
directory, so writing across a mount boundary falls back to a copy and loses the
guarantee; when that matters, make the temp file next to the target yourself with
temp_path and call rename_file.
Atomic visibility is separate from durable publication. std::fs::flush
flushes buffers; std::fs::sync(handle) asks the OS to synchronize data and
metadata and returns -1 on error. To publish a staged Linux file durably,
sync the staged file, rename it, and sync its containing directory using an
open directory handle. Treat a directory sync failure after rename as an
unconfirmed publication, not as evidence that the old file remains visible.
try_lock_exclusive returns -1 immediately instead of blocking, which is how a
program reports “already running” rather than hanging:
var handle: int = std::fs::open_update("/tmp/mytool.lock");
if (std::fs::try_lock_exclusive(handle) != 0) {
std::io::write("another instance is running\n");
return 1;
} else {
};
The lock is advisory: it binds only processes that also ask, and does not stop an unrelated writer.
std::os — errors, process, environment
Why the last call failed
Every fallible routine in std reports failure as a sentinel — -1, or an
empty string — which says that something went wrong and nothing about what.
These read the reason afterwards:
pro[exp] error(): str
pro[exp] error_kind(): int
pro[exp] failed(): bol
pro[exp] not_found(): bol
pro[exp] denied(): bol
var text: str = std::fs::read_file(path);
if (std::os::not_found()) {
std::io::write("no such file: " + path + "\n");
} else {
};
A successful call clears them, so a stale reason is never mistaken for a fresh
one. Prefer the predicates and the ERR_* constants over matching error()
text — the message is the operating system’s wording, not a contract.
ERR_NONE, ERR_NOT_FOUND, ERR_DENIED, ERR_EXISTS, ERR_REFUSED,
ERR_RESET, ERR_ABORTED, ERR_NOT_CONNECTED, ERR_ADDR_IN_USE,
ERR_ADDR_UNAVAILABLE, ERR_BROKEN_PIPE, ERR_WOULD_BLOCK, ERR_TIMED_OUT,
ERR_INVALID_INPUT, ERR_INVALID_DATA, ERR_UNEXPECTED_EOF,
ERR_INTERRUPTED, ERR_WRITE_ZERO, ERR_OTHER.
Byte sockets
pro[exp] tcp_connect_timeout(address: str, millis: int): int
pro[exp] tcp_read_bytes(handle: int, count: int): vec[int]
pro[exp] tcp_try_read_bytes(handle: int, count: int): vec[int]
pro[exp] tcp_write_bytes(handle: int, bytes: vec[int]): int
pro[exp] tcp_try_write_bytes(handle: int, bytes: vec[int], offset: int): int
pro[exp] udp_recv_bytes(handle: int, limit: int): vec[int]
pro[exp] udp_send_bytes(handle: int, address: str, bytes: vec[int]): int
These std::os functions work on the handles returned by the network
intrinsics. TCP has byte offsets, not message boundaries. A write can be short;
retry only its unwritten suffix. TCP EOF returns an empty vector and no error.
The try-read operation reports ERR_WOULD_BLOCK when nothing is ready.
UDP receives exactly one datagram per call; an empty datagram is valid, while
an over-limit datagram is discarded with ERR_INVALID_DATA. For these
functions, inspect std::os::error_kind() immediately after the operation.
Arguments and environment
pro[exp] arg_count(): int
pro[exp] arg(index: int): str
pro[exp] program(): str
pro[exp] env(name: str): str
pro[exp] set_env(name: str, value: str): int
pro[exp] unset_env(name: str): int
pro[exp] shell(command: str): int
arg excludes the program name, and an index past the end reads as "".
program() is argv[0] — what a usage message should name.
unset_env is not set_env(name, ""): an empty value is still a present
variable, and a child can tell the difference.
Supervised children
con[exp] SIGNAL_KILL: int = 0;
con[exp] SIGNAL_TERM: int = 15;
fun[exp] still_running(): int // the -2 sentinel
pro[exp] spawn(program: str, args: vec[str]): int
pro[exp] spawn_io(program: str, args: vec[str], streams: vec[int]): int
pro[exp] child_id(handle: int): int
pro[exp] child_status(handle: int): int
pro[exp] child_running(handle: int): bol
pro[exp] await_child(handle: int): int
pro[exp] signal_child(handle: int, signum: int): int
shell and the run_* intrinsics block until the child finishes. These do not,
so a program can start something, watch it, and stop it:
var args: vec[str] = {"9000"};
var server: int = std::os::spawn("./serve", args);
loop (std::os::child_running(server)) {
std::time::sleep_ms(100);
};
var status: int = std::os::await_child(server);
child_status returns three things — the exit status, still_running() while
it is going, or -1 for an unknown handle — so a poll loop cannot confuse “not
yet” with “gone”. A polled child keeps its status, which is what makes the
loop above safe: await_child after the poll returns the same value rather than
failing on a handle the poll consumed. await_child is the collecting call, so it
releases the handle – child_status afterwards answers -1, the unknown-handle
value. Poll as often as you like; await once. signal_child with SIGNAL_TERM
lets the child clean up;
SIGNAL_KILL cannot be caught.
spawn_io takes exactly three stream selectors: [stdin, stdout, stderr].
Zero inherits the corresponding parent stream, -1 selects the null device,
and a positive value duplicates an existing file or pipe handle. Invalid
selectors or a failed spawn return -1 with .os_error_kind() set. The caller
retains its handles; close unused parent pipe ends after spawning. Arguments
are passed directly, without a shell. Drain output while feeding input to
avoid backpressure deadlocks. These are direct-child handles, not automatic
process-group or descendant supervision.
still_running() is a routine rather than a constant because a global binding
needs a literal initializer and -2 is a negation.
shell runs through sh -c and returns the exit status: 128 + signal when a
signal killed it, 127 when the shell could not start. Because it is a shell,
the command is subject to quoting and word-splitting — when the arguments come
from user input, use the .run_capture(...) or .run_status(...) intrinsics
instead, which execute a program directly with no shell in between.
std::path — path surgery
Pure string manipulation. It never touches the filesystem, so it works on paths that do not exist yet.
con SEP: str = "/";
fun[exp] is_absolute(value: str): bol
fun[exp] join(left: str, right: str): str
fun[exp] file_name(value: str): str
fun[exp] parent(value: str): str
fun[exp] extension(value: str): str
fun[exp] file_stem(value: str): str
fun[exp] with_extension(value: str, ext: str): str
fun[exp] components(value: str): vec[str]
fun[exp] normalize(value: str): str
normalize resolves . and .. textually. That is not the same as resolving
symlinks — a .. after a symlink means something different on disk — so use it
for tidying displayed paths, not for security decisions.
extension returns "" when there is no dot, and file_stem is the file name
without it.
std::term — terminal
pro[exp] raw_mode(enable: bol): bol
pro[exp] cols(): int
pro[exp] rows(): int
cols and rows report 80×24 when the size cannot be determined, so a
redirected program still gets usable numbers.
Column counts are not string lengths: pad with .str_width(...), since
日本 occupies four columns while .len(...) reports six bytes.
std::time — clock
pro[exp] now_ms(): int
pro[exp] sleep_ms(ms: int): int
pro[exp] local_offset(epoch_secs: int): int
pro[exp] local_parts(epoch_secs: int): vec[int]
now_ms is wall-clock, so it can jump backwards when the system clock is
adjusted. To measure a duration use the .mono_ns() intrinsic, which cannot.
.time_parts(...) is UTC-only, so a timestamp shown to a reader needs the local
offset. local_parts applies it for you:
var fields: vec[int] = std::time::local_parts(std::time::now_ms() / 1000);
local_offset takes the instant because the offset is not a constant — the same
zone is 3600 in January and 7200 in July, and the daylight-saving rule in
force at that moment decides which.
std::sync — shared counters
typ[exp] Counter: rec = { handle: int };
pro[exp] counter(initial: int): Counter
pro[exp] read(slot: Counter): int
pro[exp] write(slot: Counter, value: int): int
pro[exp] add(slot: Counter, delta: int): int
pro[exp] next(slot: Counter): int
pro[exp] compare_swap(slot: Counter, expected: int, desired: int): int
pro[exp] swapped(slot: Counter, expected: int, desired: int): bol
pro[exp] add_saturating(slot: Counter, delta: int, ceiling: int): int
pro[exp] cores(): int
pro[exp] this_thread(): int
pro[exp] relax(): int
A Counter is a handle, so copying it shares the count rather than
duplicating it — which is what lets one cross a [spn] boundary with no
reference threading:
var tally: std::sync::Counter = std::sync::counter(0);
[spn]worker::run(tally);
This is deliberately narrower than mux[T]. A mutex protects arbitrary compound
state and costs a lock; these compile to one instruction and cannot deadlock,
because there is no window in which the value is held. The moment two fields
have to agree, use mux[T].
add and next return the value before the addition, so concurrent callers
each receive a distinct number — that is what makes next a ticket dispenser.
compare_swap returns the value it found: equal to expected means the swap
happened, anything else is the current value to retry against. add_saturating
shows the retry loop that is built from it.
cores is what a worker pool should size itself from; more threads than that
adds scheduling cost without adding throughput. Counters are never freed — they
live until the process exits, which suits program-wide tallies and not
per-request state.
Error Handling
FOL does not center error handling around exceptions.
This section distinguishes two broad error categories:
- breaking errors:
unrecoverable failures, typically associated with
panic - recoverable errors:
errors that can be propagated or handled, typically associated with
report
The detailed chapters explain:
- how each category behaves
- how routines expose recoverable error types
- how error-aware forms interact with control flow and pipes
- how the current compiler reports syntax, package, and resolver failures
Current compiler diagnostics
The current compiler surface guarantees the following reporting behaviors across the active parser/package/resolver/typecheck/lower/backend chain:
- every diagnostic carries a stable producer-owned code (e.g.
R1003); the defaulthumanoutput shows it next to a family chip, and--output plainshows it in brackets (error[R1003]:) - any code can be expanded with
fol code explain <CODE> - all failures keep exact primary
file:line:columnlocations - human-readable diagnostics render source snippets and underline the primary span
- related sites such as duplicate declarations or ambiguity candidates appear as secondary labels
- JSON diagnostics preserve the same structured information with labels, notes, helps, and stable producer-owned diagnostic codes
- the parser recovers after failed declarations instead of cascading errors
- exact consecutive diagnostic duplicates are suppressed in compiler reports, with a hard cap at 50
- LSP publishing removes only exact wire-identical duplicates; diagnostics that merely share a line and code remain distinct
The exact wording of messages is still implementation detail, but the current compiler contract is that locations, codes, and structured diagnostic shape are stable enough to build tests and tooling around them.
For the detailed compiler-facing reporting model, see Compiler Diagnostics.
Breaking errors
panic keyword allows a program to terminate immediately and provide feedback to the caller of the program. It should be used when a program reaches an unrecoverable state. This most commonly occurs when a bug of some kind has been detected and it’s not clear to the programmer how to handle the error.
pro main(): int = {
panic "Hello";
.echo("End of main"); //unreachable statement
}
In the above example, the program will terminate immediately when it encounters the panic keyword.
Output:
main.fol:3
routine 'main' panicked at 'Hello'
-------
Trying to acces an out of bound element of array:
pro main(): int = {
var a: arr[int, 3] = {10,20,30};
a[10]; //invokes a panic since index 10 cannot be reached
}
Output:
main.fol:4
routine 'main' panicked at 'index out of bounds: the len is 3 but the index is 10'
-------
a[10];
^-------- index out of bounds: the len is 3 but the index is 10
A program can invoke panic if business rules are violated, for example: if the value assigned to the variable is odd it throws an error:
pro main(): int = {
var no = 13;
//try with odd and even
if (no % 2 == 0) {
.echo("Thank you , number is even");
} else {
panic "NOT_AN_EVEN";
}
.echo("End of main");
}
Output:
main.fol:9
routine 'main' panicked at 'NOT_AN_EVEN'
-------
Recoverable errors
Recoverable errors are part of the current V1 language contract, but they are
split into two different surfaces:
T / Efor routine-call handlingerr[...]for normal storable values
Those are intentionally not the same thing.
T / E is immediate call-site handling
Use / ErrorType after the success type:
fun read_code(path: str): int / str = {
when(path == "") {
case(true) { report "missing path" }
* { return 7 }
}
};
This means:
- success yields
int report exprexits through the routine error path withstr- the call result is not a storable plain value
report expr must match the declared error type. A routine that declares one
needs both exits — a return for the value and a report for the error:
fun read_code(path: str): int / str = {
when(.len(path) == 0) {
case(true) { report "missing path"; }
* { }
}
return 0;
};
The following is invalid because the reported value is the wrong type:
fun read_code(path: str): int / str = {
report 1
};
No plain propagation
In current V1, / ErrorType routine results do not flow through ordinary
expressions.
These are rejected:
read_code(path)
var value = read_code(path)
return read_code(path)
consume(read_code(path))
read_code(path) + 1
/ ErrorType must be handled immediately at the call site. Evaluating a
recoverable call as a standalone statement does not count as handling it.
The same rule applies after V3 | async: a recoverable eventual must be
awaited, and the awaited result must be consumed by check(...) or ||.
Moving the eventual to another binding moves that obligation; dropping,
overwriting, or leaving the final binding at scope exit is rejected. An
infallible eventual has no recoverable error obligation and may remain
unawaited, although it is still joined at process exit.
The obligation must be discharged before lexical fallthrough and before a
break, return, or report exits any scope that still owns it. At a branch
join, all continuing branches must leave compatible obligation state: all may
preserve the same owner for handling after the join, transfer consistently, or
await and handle it. Consuming or transferring on only some paths is rejected.
Process-exit joining waits for work; it does not count as handling a recoverable
error.
check(...)
check(expr) asks whether a / ErrorType expression failed. The expression may
be a direct recoverable routine call or a V3 awaited recoverable eventual.
It returns bol.
fun main(path: str): bol = {
return check(read_code(path))
};
check(...) works on direct recoverable routine calls and on expressions such
as pending | await when pending carries a recoverable result. It does not
inspect err[...] shell values.
||
expr || fallback handles a / ErrorType expression immediately. That may be
a direct recoverable routine call or a V3 awaited recoverable eventual.
Rules:
- if
exprsucceeds, use its success value - if
exprfails, evaluatefallback fallbackmay:- provide a default value
reportpanic
Examples:
fun with_default(path: str): int = {
return read_code(path) || 0
};
fun with_context(path: str): int / str = {
return read_code(path) || report "read failed"
};
fun must_succeed(path: str): int = {
return read_code(path) || panic "read failed"
};
err[...] is the storable error form
err[...] is a normal value type. It is a nil-able shell: nil is the
no-error (success) state and a present value carries a stored error payload.
return nil produces the no-error state; return payload stores an error.
You may store it, pass it, return it, and unwrap it later:
ali Failure: err[str];
fun keep(value: Failure): Failure = {
return value
};
fun unwrap(value: Failure): str = {
return [uwp]value
};
Because it is nil-able, an err[T] scrutinee also drives when ... on ... *:
on(payload) binds the stored error and * takes the nil (no-error) branch.
Postfix [uwp]value and inner-place value[] unwrap the stored error and panic on
nil.
This is different from:
fun read_code(path: str): int / str = { ... }
A call to read_code(...) is not an err[str] value. If you need a storable
error container, use err[...]. If you use / ErrorType, handle it with
check(...) or ||.
Current V1 boundary
The current compiler supports:
- declared routine error types with
/ report exprcheck(expr)expr || fallbackerr[...]shell/value behavior
The current compiler rejects:
- plain assignment of
/ ErrorTypecall results - direct returns of
/ ErrorTypecall results - implicit conversion from
/ ErrorTypeintoerr[...] - postfix
!on/ ErrorTyperoutine calls
For backend work:
/ ErrorTyperoutine calls lower through the recoverable runtime ABIerr[...]remains a separate shell/value runtime type- a recoverable executable entry is adapted through the shared backend-only
fol_runtime::processseam in every runtime model; it does not require bundledstd
That process adapter translates the entry outcome for the generated host
wrapper. It is not importable source API, does not promote core or memo to
the hosted tier, and is present for execution support regardless of whether the
program declares bundled std.
Those two categories are intentionally not merged.
Compiler Diagnostics
This chapter is about compiler reporting, not about language-level panic or
report semantics.
In other words:
panicandreportdescribe what your program does- diagnostics describe what the compiler tells you when it cannot continue or when it wants to surface important information
Why this chapter exists
FOL now has a real compiler pipeline:
fol-streamfol-lexerfol-parserfol-packagefol-resolverfol-typecheckfol-lowerfol-runtimefol-backendfol-diagnostics
That means errors are no longer just loose strings printed from one place. Compiler failures now move through a shared diagnostics layer with stable structure.
This matters for three reasons:
- humans need readable compiler output
- tests need stable enough structure to assert against
- future tools need a machine-readable format that is not just a copy of the human renderer
What a diagnostic contains
At the current compiler stage, a diagnostic can carry:
- severity
- main message
- a stable diagnostic code (e.g.
P1001,R1003,T1003,O1001) - one primary location
- zero or more related locations
- notes
- helps
- suggestions
The current compiler mostly emits Error, but the reporting layer also supports
Warning and Info.
Diagnostic codes
Every diagnostic carries a stable producer-owned code. The code identifies the error family and specific failure without relying on message text.
Current code families:
| Prefix | Producer | Examples |
|---|---|---|
P1xxx | parser | P1001 syntax, P1002 file root |
K1xxx | package loading | K1001 metadata, K1002 layout |
R1xxx | resolver | R1003 unresolved, R1005 ambiguous |
T1xxx | type checker | T1003 type mismatch |
O1xxx | ownership checker | O1001 move, task, or resource-state violation |
O2xxx | lexical borrow checker | O2001 owner borrowed, O2002 conflict, O2003 mutability, O2004 returned borrow reused |
L1xxx | lowering | L1001 unsupported surface |
F1xxx | frontend | F1001 invalid input, F1002 workspace not found |
K11xx | build evaluator | K1101 build failure |
Codes are structurally assigned. The parser carries an explicit ParseErrorKind
field on each error rather than deriving the code from message text. This means
message wording can change without breaking code identity.
The default human output shows the code after the message, alongside a
plain-language family chip (e.g. NAMES ... R1003). The plain output shows it
in brackets:
error[R1003]: could not resolve name 'answer'
Any code can be expanded on demand with fol code explain <CODE> (see
Tool Commands).
JSON output includes the code as a top-level field:
{ "code": "R1003", "message": "could not resolve name 'answer'" }
Primary location
The most important part of a diagnostic is its primary location.
That location is currently expressed as:
- file
- line
- column
- optional span length
This is what allows the compiler to point at the exact token or source span that caused the failure.
Every diagnostic now carries a real location. Parser errors that previously lacked locations (safety-bound overflows, constraint violations like duplicate parameter names) now extract file/line/column from the current token position.
Typical examples:
- a parser error at the token that made a declaration invalid
- a package-loading error at the control file or package root that failed
- a resolver error at the unresolved identifier or ambiguous reference
- a typecheck error at the expression or declaration whose types do not match
- an ownership error at the transfer, borrow, task, channel, or delayed-effect boundary that made the value inaccessible
- a lowering error at a typed surface with no current lowering rule
Related locations
Some compiler failures are not well described by one location alone.
For example:
- duplicate declarations
- ambiguous references
- duplicate package metadata fields
In those cases the compiler keeps one primary site and can also attach related sites as secondary labels.
That allows the compiler to say things like:
- this declaration conflicts with an earlier declaration
- this name could refer to either of these two candidates
- this metadata field was already defined elsewhere
Notes, helps, and suggestions
FOL diagnostics separate extra guidance into different buckets instead of forcing everything into one long message.
The current contract is:
- the main message says what went wrong
- notes add technical context
- helps add actionable guidance
- suggestions describe a possible replacement or next step when the producer can express one
This split matters because tooling and tests can preserve structure instead of trying to parse intent back out of prose.
Error recovery
The parser implements error recovery so that a single syntax mistake does not cascade into dozens of unrelated errors.
When a declaration parse fails, the parser calls sync_to_next_declaration to
skip forward to the next declaration-start keyword (fun, var, def, typ,
pro, log, seg, ali, lab, con, use) or EOF. This means:
fun[exp] emit(...) = { ... }produces exactly 1 error, not 20+- two broken declarations separated by a good one produce 2 errors, and the good declaration still parses correctly
Cascade suppression
Even with parser recovery, edge cases in any pipeline stage can cascade.
The diagnostic report layer applies two safety nets:
- exact consecutive dedup: if the most recently added diagnostic is fully identical to a new one, the new one is suppressed; a shared line/code alone is not enough, so distinct ranges, messages, labels, and related sites remain visible
- hard cap: the report accepts at most 50 diagnostics total and shows “(output truncated)” when the limit is reached
These limits prevent walls of identical errors without hiding genuinely distinct failures.
Human-readable diagnostics
The CLI has two human-facing output modes, selected with the global --output
flag. Both render from the same structured diagnostic model.
human (default)
The default renderer prints a framed, colored report:
- a family chip that names the problem in plain language (
PARSER,NAMES,TYPES,OWNERSHIP,LOWERING,PACKAGE,BUILD,BACKEND), the bold message, and the diagnostic code - a framed source snippet (
┌─ file:line:column) with the offending line and a caret under the primary span - secondary labels for related sites
= note:,= help:, and= try:lines- a footer with a one-line plain-language hint and a
run `fol code explain <CODE>` for morepointer - a closing
found N error(s)summary
Illustrative shape (colors omitted):
NAMES could not resolve name 'answer' R1003
┌─ app/main.fol:3:12
│
3 │ return answer
│ ^^^^^^ unresolved name
= note: no visible declaration with that name was found in the current scope chain
= help: check imports or declare the name before use
a name or import problem — a symbol could not be resolved · run `fol code explain R1003` for more
found 1 error
Colors disable themselves automatically when stdout is not a terminal, so piped and CI output stays plain text.
plain
--output plain prints the older, unstyled human format:
- a severity prefix with the diagnostic code in brackets (e.g.
error[R1003]:) - an arrow line with
file:line:column - a source snippet with an underline for the primary span
note:/help:lines and related-label summaries
Illustrative shape:
error[R1003]: could not resolve name 'answer'
--> app/main.fol:3:12
|
3 | return answer
| ^^^^^^ unresolved name
note: no visible declaration with that name was found in the current scope chain
help: check imports or declare the name before use
In both modes the messages are clean human-readable text. The compiler does not
prepend internal kind labels like ResolverUnresolvedName: to messages; the
diagnostic code is the stable identifier.
Source fallbacks
Sometimes the compiler knows the location but cannot render the source line itself.
Examples:
- the file is no longer readable
- the file path is missing
- the requested line is outside the current file contents
In those cases the compiler still keeps the location and falls back cleanly instead of crashing the renderer.
So the priority order is:
- exact location
- source snippet when available
- explicit fallback note when the snippet cannot be shown
JSON diagnostics
When the CLI is invoked with --json, diagnostics are emitted as structured
JSON instead of human-readable text.
This output is meant for scripts, tests, editor tooling, and future integration layers.
Important rule:
- JSON is not a lossy summary of human output
Instead, both human and JSON outputs are generated from the same structured diagnostic model.
The editor/LSP layer should follow that same rule too: editor diagnostics should be adapted from the shared structured diagnostic model rather than rebuilt from free-form strings.
That means JSON can preserve:
- severity
- code
- message
- primary location
- related labels
- notes
- helps
- suggestions
Illustrative shape:
{
"severity": "Error",
"code": "R1003",
"message": "could not resolve name 'answer'",
"location": {
"file": "app/main.fol",
"line": 3,
"column": 12,
"length": 6
},
"labels": [
{
"kind": "Primary",
"message": "unresolved name",
"location": {
"file": "app/main.fol",
"line": 3,
"column": 12,
"length": 6
}
}
],
"notes": [
"no visible declaration with that name was found in the current scope chain"
],
"helps": [
"check imports or declare the name before use"
],
"suggestions": []
}
Again, the exact payload can evolve, but the important guarantee is that the structured fields are first-class rather than reverse-engineered from text.
Which compiler phases currently participate
At head, the main producers that lower into the shared diagnostics layer are:
- parser
- package loading
- resolver
- type checking
- lowering
- build evaluator
- backend
- frontend (workspace discovery and input validation)
That means diagnostics are already strong across:
- syntax errors (with error recovery so cascades are contained)
- package metadata and package-root errors
- import-loading failures
- unresolved names
- duplicate names
- ambiguous references
- type mismatches and unsupported capability surfaces in the shipped V1, V2, and V3 contracts
- V2 generic/protocol conformance failures for the checked-in shipped subset
- V3 move/resource-state failures (
O1xxx) and lexical borrow failures (O2xxx) - V3 processor tier, direct-task-target, channel lifecycle, thread-boundary, eventual must-handle, and deferred mutex-effect failures
- unsupported lowered surfaces before target emission
- backend emission and build failures when lowered workspaces cannot become runnable artifacts
- build graph evaluation failures
Runtime-capability and execution-routing failures remain distinct. Using
heap-backed values from core, or hosted APIs without a memo artifact and its
declared bundled std, is a compiler-owned capability diagnostic. Trying to
run or test a foreign selected target is a frontend target-compatibility
diagnostic. Merely running or testing a host-compatible core or memo
artifact is not a missing-std error.
This is the important boundary for the current compiler stage:
- the compiler can parse, resolve, type-check, lower, and execute the supported V1 contract, the explicitly shipped V2 subset, and both shipped V3 pillars
- diagnostics already cover failures from each of those stages plus backend emission/build failures
- current hard boundaries are diagnosed rather than silently accepted: for
example unique-pointer field dereference without place-aware projection IR,
moved-owner deferred reinitialization, terminating
reportinside deferred cleanup, indirect spawn/async targets, unhandled recoverable eventuals, channel endpoint lifecycle violations, and deferred mutex guard effects - later targets, optimizations, C ABI work, and Rust interop remain outside the current V1/V2/V3 contract
V3 diagnostic completeness is inventory-driven. Every checked-in fail_mem_*
and fail_proc_* package must appear in the shared
test/v3_example_inventory.rs table with its expected producer code, message
fragment, and related-site requirement. Compiler integration and LSP tests
consume that same table, so the editor cannot silently weaken a boundary or
replace a structured compiler failure with an editor-only guess. The published
directory lists live in the memory and processor section indexes.
What diagnostics do not guarantee
Diagnostics are strong, but a structured error family is not a promise that every future language design is implemented.
Current limits still matter:
- parser diagnostics do not imply type checking has happened
- V2 diagnostics cover only the explicitly shipped generic/protocol subset, not every standards, blueprint, or generic design in the book
- V3 ownership diagnostics do not imply place-aware partial moves, general thread-safety contracts for unconstrained generics, or a flow-sensitive/NLL borrow checker
- V3 processor diagnostics do not imply indirect task dispatch, nameable eventual types, arbitrary channel composites, deferred mutex guard effects, cancellation, or an async runtime
- coercion and conversion diagnostics only cover conversions the current compiler actually implements
- C ABI diagnostics are future
V4package/type/backend work - Rust interop diagnostics are future
V4package/type/backend work
So the current guarantee is:
- if stream, lexer, parser, package loading, resolver, typechecker (including ownership/borrowing), lowering, backend, build evaluation, or frontend can identify the problem now, diagnostics should be structured and exact
But not:
- all language-semantic errors already exist today
Practical rule of thumb
When reading compiler output, think in this order:
- look at the diagnostic code in brackets to identify the error family
- trust the primary location
- use related labels to understand competing or earlier sites
- read notes for technical context
- read helps for the most actionable next step
That mental model matches how the compiler currently structures reporting.
Syntactic Sugar
This section collects forms that are primarily about expressiveness, convenience, or alternate notation.
These chapters should be read after the core statement, expression, and declaration rules, because most sugar expands on top of those more fundamental forms.
The current sugar chapters cover:
- silent/discard forms
- pipes
- dfr and edf
- mixed/compound convenience forms
- limits
- matching
- rolling
- unpacking
- inquiry
- chaining
Silents
Single letter identifiers (SILENTs) identifiers are a form of languages sugar assignment.
Letter
Lowercase
Many times is needed to use a variable in-place and to decluter the code we use silents:
each(var x: str; x in {..10}){
// implementation
}
each(x in {..10}){ // we use the sicale `x` here
// implementation
}
Uppercase
If a silent is uppercase, then it is a constant, can’t be changed. This is very important when using FOL for logic programming:
log vertical(l: line): bol = {
l[A:B] and // we assign sicales `A` and `B`
A[X:Y] and // we assign sicales `X` and `Y`
B[X:Y2] // here we assign only `Y2` becase `X` exists from before
}
Symbols
Meh
Meh is the _ identifier. The use of the term “meh” shows that the user is apathetic, uninterested, or indifferent to the question or subject at hand. It is occasionally used as an adjective, meaning something is mediocre or unremarkable.
We use meh when we want to discard the variable, or we dont intend to use:
var array: arr[int, 3] = {1, 2, 3};
var a, _, b: int = array; // we discard, the middle value
Y’all
Y’all is the * identifier. It represents app possible values that can be.
when(true) {
case (x == 6){ // implementation }
case (y.set()){ // implementation }
* { // default implementation }
}
Pipes
Pipes connect the value on the left to the expression on the right.
The basic idea is still:
left | right
where the right-hand side sees the left-hand side as this.
Ordinary value piping
Current boundary:
- the ordinary value-pipe (
left | ... this) shown in this section is later design work, not part of the current compiler surface - the recoverable-call surfaces below (
check(...)and||) are the current compiler surface - the specialized
call() | asyncandeventual | awaitprocessor stages are shipped V3std-only forms; they do not enable generalthis-based piping
Use | when you want to continue transforming a normal value:
fun add(x: int, y: int): int = {
return x + y
};
fun main(): int = {
return add(4, 5) | when(this > 8) {
case(true) { 6 }
* { 0 }
}
};
This is ordinary value flow. The pipe itself does not create a special error model.
Recoverable calls are separate from ordinary pipes
Routines declared with / ErrorType produce recoverable call results:
fun read_code(path: str): int / str = {
when(path == "") {
case(true) { report "missing path" }
* { return 7 }
}
};
For these calls, the current V1 compiler does not treat plain | as the
main error-handling tool.
Instead, the implemented recoverable-call surfaces are:
check(expr)expr || fallback
check and panic are compiler intrinsics in the current V1 compiler. They
are not imported library functions.
check(expr)
check(expr) asks whether a recoverable / ErrorType expression failed. That
may be a direct routine call or, in V3, an awaited recoverable eventual.
It returns bol.
fun main(path: str): int / str = {
when(check(read_code(path))) {
case(true) { report "read failed" }
* { return 0 }
}
};
This is the current inspection surface for direct V1 recoverable calls and V3 awaited recoverable results.
|| fallback
Double-pipe is the current shorthand for recovery:
fun read_code(path: str): int / str = {
when(path == "") {
case(true) { report "missing path" }
* { return 7 }
}
};
fun with_default(path: str): int = {
return read_code(path) || 5
};
Meaning:
- if the call succeeds, use the success value
- if the call fails, evaluate the right-hand side
The fallback may be:
- a default value
report ...panic ...
Examples:
fun recover(path: str): int = {
return read_code(path) || 5
};
fun re_report(path: str): int / str = {
return read_code(path) || report "read failed"
};
fun must_succeed(path: str): int = {
return read_code(path) || panic "read failed"
};
V3 async and await stages
V3 ships two exact processor pipe stages:
pro[] load_async(path: str): int = {
var pending = read_code(path) | async;
return (pending | await) || 0;
};
pro[] async_failed(path: str): bol = {
var pending = read_code(path) | async;
return check(pending | await);
};
| async starts a direct named call on an OS thread and produces an internal
eventual. | await consumes that eventual binding and blocks for its result. If
the original call is recoverable, the awaited result must flow immediately into
check(...) or ||. These stages require the explicit bundled std
dependency; see Eventuals.
What ordinary | does not mean
The current compiler does not claim that plain | automatically forwards both
the success value and the error to the next stage.
That older description is too broad for the current implementation.
For recoverable calls, use check(expr) or expr || fallback. The exact V3
async and await stages above are specialized processor forms; they do not
make the later general value-pipe design part of the shipped language.
Dfr
dfr is scope-exit cleanup sugar. edf is its error-only V3 counterpart.
The shipped forms are intentionally narrow:
- only the
dfr { ... }andedf { ... }block forms are supported - each block registers work on the current lexical scope
dfrruns when that scope exits by fallthrough orbreak, and before areturn, recoverablereport, orpanicleaves it- multiple deferred blocks run in reverse registration order
edfruns only on a recoverablereportexit, not on normal return or panic
This is control-flow sugar.
It is not a destructor system, user-defined drop hook, object system, or async cleanup system.
Model reminder:
-
memoalone does not expose the hosted.echo(...)substrate -
the printing examples below use
fol_model = "memo", declare the bundled standard library explicitly inbuild.fol, and call itsstd.iowrappers:build.add_dep({ alias = "std", source = "internal", target = "standard" }); -
source files then import that dependency with
use std: pkg = {"std"}; -
the explicit dependency upgrades the effective tier to hosted;
stdis not a thirdfol_model -
dfrandedfare not std-only; both remain valid incoreandmemo -
a
coreor unhostedmemoprogram using them can still run; bundledstdappears here only because these examples print from source
Basic form
use std: pkg = {"std"};
pro[] main(): int = {
dfr {
std::io::echo_str("closing");
};
std::io::echo_str("work");
return 7;
};
The deferred body runs before control leaves main.
Reverse order
use std: pkg = {"std"};
pro[] main(): non = {
dfr { std::io::echo_int(1); };
dfr { std::io::echo_int(2); };
};
This executes as:
2- then
1
Nested scopes
Deferred bodies belong to the scope where they are declared:
use std: pkg = {"std"};
pro[] main(flag: bol): non = {
dfr { std::io::echo_str("outer"); };
when(flag) {
case(true) {
dfr { std::io::echo_str("inner"); };
return;
}
* { }
}
};
If the inner scope exits first, its deferred bodies run before the outer scope’s deferred bodies.
Error-only cleanup
edf registers a body for recoverable error exits only:
use std: pkg = {"std"};
pro[] load(fail: bol): int / int = {
edf {
std::io::echo_int(2);
};
dfr {
std::io::echo_int(1);
};
when(fail) {
case(true) { report 7; }
* { return 0; }
}
};
On success, only dfr runs. On report, both registrations run in reverse
registration order. On panic, dfr runs but edf does not, because panic is
not a recoverable error-shell exit.
Deferred-body limits
The registered body is checked now but executed later. V3 therefore rejects effects that the current lowering cannot replay safely:
return,break,report, andpaniccannot appear inside adfroredfbody; deferred cleanup cannot initiate another exit while the surrounding exit is being replayed- a moved binding cannot be reinitialized there
- channel sender or receiver endpoints cannot be acquired there
| awaitand access to an existing eventual binding cannot occur insideedf; an error-only body cannot discharge eventual ownership on normal exits, and the restriction remains active inside adfrnested within thatedf- a
mux[T]handle cannot be locked, unlocked, used for guarded field access, or forwarded to anothermux[T]parameter there
These are compile-time boundaries, not cleanup operations that are silently
skipped. An outer report still triggers registered dfr and edf bodies;
only a new report from inside one of those bodies is rejected. An all-exit
dfr may await and handle a recoverable eventual, because it runs on every
modeled exit. Error-only edf cannot. Put the other affected control flow,
channel acquisition, owner reinitialization, or mutex work in ordinary code.
Ownership ordering
At lexical scope exit FOL applies this order:
- select the registered blocks for the exit kind (
dfr, plusedffor a recoverable error) - run those blocks in reverse registration order
- release any still-active borrows
- free still-owned heap values by ordinary scope drop
A moved value is no longer in the source binding’s owned set, so it is not freed twice. Deferred work always runs before the scope drops its remaining owned heap values.
A dfr or edf body that references a move-only binding from an enclosing
scope reserves that binding through the exit of the registration scope. The
binding cannot be transferred after the deferred block is registered, because
the deferred body still needs its value. Moving the value before registration
instead makes the reference inside the deferred body an ordinary use-after-move
error. A reservation registered in a nested block ends after that block’s
deferred work has run, so the owner may be transferred afterward.
Mutex guard effects are not deferred in V3. A dfr or edf body cannot
call .lock() or .unlock() on a mux[T] parameter, and it cannot access
mutex-guarded fields even when the surrounding scope currently holds the
guard. It also cannot forward the mutex handle to another mux[T] routine,
because that would hide delayed guard transitions behind the call. Perform
guarded work in ordinary control flow before registering deferred cleanup.
Channel endpoint acquisition is similarly rejected inside dfr and edf.
Acquire any sender handle before registration and perform receiver operations
in ordinary control flow.
The same delayed-effect boundary applies to owner reinitialization. A moved
binding cannot be reinitialized inside dfr or edf: typechecking that write
as immediate would make the binding look usable before the deferred assignment
actually runs. Reinitialize the binding in ordinary control flow before the
deferred block is registered.
Explicit captures
A delayed block declares how outer locals enter it with a capture list — every routine-local binding the body uses must appear in it. Each entry names an outer binding and states its operation:
var seen: int = 2;
var owned: ptr[int] = [ref]seed;
dfr[seen[bor], owned[mov]] {
std::io::echo_int(seen + [drf]owned);
};
[bor] observes the binding — the owner stays restricted while the block can
still run, and the loan is read-only: assigning through a [bor] capture is
rejected. A block that mutates its capture states the composite [mut, bor]
mutable loan instead:
var[mut] total: int = 5;
dfr[total[mut, bor]] { total = total + 37; };
mut composes only with bor. [mov] transfers the value into the block’s
environment: the outer binding is invalidated for the rest of the scope, and
the block still owns the value when scope-exit cleanup executes it. [cpy]
and [cln] duplicate the value under the same capability rules as spawn
captures. A bare capture name without an operation is rejected, as is a
channel endpoint capture — endpoints belong to spawned tasks, not delayed
blocks. Using an undeclared outer local
inside the block is an ownership error; module-level values and routine names
are not captures and need no declaration.
Current milestone boundary
The basic dfr form belongs to V1. Ownership-aware ordering and edf are the
shipped V3 memory contract. V3 processor resources do not become generalized
deferred-cleanup hooks: outstanding tasks join at process exit, channels close
through endpoint ownership/lifecycle, and an eventual can be consumed at most
once by | await. Recoverable eventuals must be awaited and handled on every
exit path; an all-exit dfr may do so, while an error-only edf may not.
Infallible eventuals may instead remain outstanding for the process-exit join.
Await inside edf—including inside a nested dfr—channel endpoint acquisition,
and mutex guard effects inside dfr/edf are rejected. Native/foreign resource
cleanup remains V4 interop work.
Mixture
Optional
var someMixtureInt: ?int = 45;
Never
var someNverType: !int = panic();
Limits
Current boundary:
- the
type[][.range(...)]limit surfaces are not implemented in the current compiler - everything below describes intended design, not current behavior; limits are later design work, not part of the current compiler surface
Limiting is a syntactic way to set boundaries for variables. The way FOL does is by using [] right after the type declaration type[], so: type[options][limits]
Initger limiting
Example, making a intiger variable have only numbers from 0 to 255 that represents an RGB value for a single color:
var rgb: int[][.range(255)];
Character limiting
It works with strings too, say we want a string that can should be of a particular form, for example an email:
var email: str[][.regex('[._a-z0-9]+@[a-z.]+')]
Matching
Current boundary:
- only
isarms (plus thecaseand*default forms) are the current compiler surface in(range/set matching) andhas(membership) arms are declared syntax whose semantics are later-milestone work; the compiler rejects them with explicit boundary diagnostics
Variable
As variable assignment:
var checker: str = if(variable) {
in {..10} -> "in range of 1-10";
in {11..20} -> "in range of 11-20";
* -> "out of range";
}
var is_it: int = if(variable) {
is "one" -> 1;
is "two" -> 2;
* -> 0;
}
var has_it: bol = if(variable) {
has "o", "k" -> true;
* -> false;
}
Function
As function return:
fun someValue(variable: int): str = when(variable) {
in {..10} -> "1-10";
in {11..20} -> "11-20";
* -> "0";
}
Rolling
Current boundary:
- rolling / list-comprehension expressions are not part of the current compiler surface; the compiler rejects them with an explicit “not yet supported” diagnostic
- everything below describes intended design, not current behavior
- this is later design work, not part of the current V1 compiler surface
Rolling or list comprehension is a syntactic construct available FOL for creating a list based on existing lists. It follows the form of the mathematical set-builder notation - set comprehension.
Rolling has the same syntactic components to represent generation of a list in order from an input list or iterator:
- A variable representing members of an input list.
- An input list (or iterator).
- An optional predicate expression.
- And an output expression producing members of the output list from members of the input iterable that satisfy the predicate.
The order of generation of members of the output list is based on the order of items in the input. Syntactically, rolling consist of an iterable containing an expression followed by a for statement. In FOL the syntax follows exacly the Python’s list comprehension syntax:
var aList: vec[] = { x for x in iterable if condition }
Rolling provides an alternative syntax to creating lists and other sequential data types. While other methods of iteration, such as for loops, can also be used to create lists, rolling may be preferred because they can limit the number of lines used in your program.
var aList: vec[] = {..12};
var another: vec[] = { ( x * x ) for ( x in aList ) if ( x % 3 == 0 ) }
var matrix: mat[int, int] = { x * y for ( x in {..5}, y in {..5} ) }
Unpacking
Current boundary: fixed-name unpacking (
var a, b = container) is implemented over set, array, vector, and sequence sources. Rest patterns (*name) parse but are rejected by typechecking in this milestone.
Current boundary:
- unpacking / iterable-destructuring forms (
var a, *_ = ...) are not part of the current compiler surface; the compiler rejects them - everything below describes intended design, not current behavior
- this is later design work, not part of the current V1 compiler surface
Unpacking—also known as iterable destructuring—is another form of pattern matching used to extract data from collections of data. Take a look at the following example:
var start, *_ = { 1, 4, 3, 8 }
.echo(start) // Prints 1
.echo(_) // Prints [4, 3, 8]
In this example, we’re able to extract the first element of the list and ignore the rest. Likewise, we can just as easily extract the last element of the list:
var *_, end = { "red", "blue", "green" }
.echo(end) // Prints "green"
In fact, with pattern matching, we can extract whatever we want from a data set assuming we know it’s structure:
var start, *_, (last_word_first_letter, *_) = { "Hi", "How", "are", "you?" }
.echo(last_word_first_letter) // Prints "y"
.echo(start) // Prints "Hi"
Now, that has to be one of the coolest programming language features. Instead of extracting data by hand using indices, we can just write a pattern to match which values we want to unpack or destructure.
Inquiry
Current boundary:
- inquiry
where(...)clauses parse, and the checker refuses every one of them: nothing lowers an inquiry, so an accepted clause would never run - everything below describes intended design, not current behavior; inquiries are later design work, not part of the current compiler surface
Inquiries are inline unit tests and are a part of the basic syntax sugar. In other words, we don’t have to import any libraries or build up any suites to run tests.
Instead, FOL includes a couple of clauses for testing within the source code:
fun sum(l: ...?int): int = {
when(l.length()) {
is 0 => 0;
is 1 => l[0];
$ => l[0] + sum(l[1:]);
}
where(self) {
sum() is 0;
sum(8) is 8;
sum(1, 2, 3) is 6;
}
}
Here, we can see an awesome list sum function. Within the function, there are two basic cases: empty and not empty. In the empty case, the function returns 0. Otherwise, the function performs the sum.
At that point, most languages would be done, and testing would be an afterthought. Well, that’s not true in FOL. To add tests, we just include a where clause. In this case, we test an empty list and a list with an expected sum of 6.
When the code is executed, the tests run. However, the tests are non-blocking, so code will continue to run barring any catastrophic issues.
Chaining
Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil, the property, method, or subscript call returns nil. Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.
Before I can really explain optional chaining, we have to get a grasp of what an optional value is. In FOL, variables cannot be empty. In other words, variables cannot store a value of NIL, at least not directly. This is a great feature because we can assume that all variables contain some value. Of course, sometimes variables need to be NIL. Fortunately, FOL provides that through a boxing feature called optionals. Optionals allow a user to wrap a value in a container which can be unwrapped to reveal either a value or NIL:
var printString: opt[str] = "Hello, World!";
.echo([uwp]printString);
In this example, we declare an optional string and give it a value of “Hello, World!” Since we know that the variable stores a str, we can unconditionally unwrap the value and echo it. Of course, unconditional unwrapping is typically bad practice, so I’m only showing it for the purposes of showing off optionals.
Current V1 compiler note:
nilis type-checked only when the surrounding context already expects anopt[...]orerr[...]shell.- A standalone
nilwith no expected shell type is rejected during typechecking. - Unwrap
[uwp]valueis currently type-checked foropt[T]anderr[T]and yieldsT. - Bare
err[]does not currently support unwrap because there is no payload value to recover. - This
!surface is shell-only. It does not unwrap routine call results declared withResultType / ErrorType.
At any rate, optional chaining takes this concept of optionals and applies it to method calls and fields. For instance, imagine we have some long chain of method calls:
important_char = commandline_input.split('-').get(5).charAt(7)
In this example, we take some command line input and split it by hyphen. Then, we grab the fifth token and pull out the seventh character. If at any point, one of these method calls fails, our program will crash.
With optional chaining, we can actually catch the NIL return values at any point in the chain and fail gracefully. Instead of a crash, we get an important_char value of NIL. Now, that’s quite a bit more desirable than dealing with the pyramid of doom.
The current V1 compiler milestone only implements the plain nil/!
surfaces described above. Full optional chaining remains later work.
Value Conversion
This section covers conversions between types.
FOL distinguishes:
- coercion: conversions considered safe and unambiguous
- casting: conversions that should be explicit in source
Coercion
The book-level idea of coercion is simple:
- coercion is implicit
- it should only happen when the conversion is safe and unambiguous
For the current V1 compiler milestone, that contract is intentionally narrow.
V1 coercion currently allows:
- exact type matches
- alias-wrapped values whose apparent type matches the expected type
neverflowing into any expected type- the current optional/error shell lifting used by ordinary
V1surfaces
V1 coercion currently does not allow:
- implicit
int -> flt - implicit
flt -> int - implicit width or signedness changes
- implicit container reshaping
- implicit string/character/container conversions
So today the rule is:
- if two values are not already the same semantic family, the compiler should reject the implicit conversion
This is deliberate.
The conversion chapter in the language design is broader than the current
compiler guarantee, and V1 chooses explicit rejection over silent guessing.
Examples that are accepted in V1:
var count: int = 1
var ratio: flt = 1.5
fun[] take_int(value: int): int = {
return value;
};
fun[] take_float(value: flt): flt = {
return value;
};
Examples that are rejected in V1:
var count: int = 1.5
var ratio: flt = 1
fun[] take_float(value: flt): flt = {
return value;
};
fun[] bad(): flt = {
return take_float(1);
};
Later versions may widen this contract, but V1 keeps coercion intentionally
small so type behavior stays predictable.
Casting
Casting is the explicit side of value conversion.
The language direction is:
- coercion stays implicit and narrow
- casting stays explicit and source-visible
FOL has no general cast operator. The explicit conversions that exist are named
intrinsics with checked semantics: .widen(...) and .narrow(...) for integer
widths below, and the text and number conversions in the library chapters.
A general cast would need a legality contract answering questions such as:
- which scalar casts are allowed beyond the width conversions below
- whether lossy casts are permitted
- whether container casts exist
- how aliases interact with explicit conversion
- how foreign/ABI types participate in conversion
Until that contract exists, conversions are added one named intrinsic at a time, each with its own checks, rather than through an operator whose meaning would have to be guessed.
Integer widths
Integer widths never mix implicitly. i32 and int are different types, and
adding them is a type error rather than a silent promotion:
var small: i32 = 1;
var big: int = 2;
var sum: int = small + big; // rejected: 'i32' and 'int'
.widen(...) converts a value to a wider type. It takes its result width from
the context, so the binding or parameter it fills decides the target:
var small: i32 = 2000000000;
var wide: i64 = .widen(small);
var byte: u8 = 200;
var signed: i16 = .widen(byte); // every u8 fits an i16
Widening is checked in both directions rather than assumed. The compiler refuses a conversion that could lose value, one where nothing could be lost, and one with no target to read:
'i32' does not hold every 'int', so this is not a widening
the value is already 'i32', so it needs no conversion
'.widen(...)' takes its result width from the context
“Wider” means the target holds every value of the source, not that it has more
bits. u8 widens to i16 because every byte is a valid i16; i32 does not
widen to u32, and u32 does not widen to i32, because each holds values the
other cannot.
.narrow(...) converts the other way. It can lose the value, so it reports
through the ordinary error channel and the failure has to be handled:
var wide: i64 = 5000000000;
var fitted: i32 = .narrow(wide) || 0; // 5000000000 does not fit, so 0
The direction is checked here too. Narrowing to a type that holds every value of the source is refused, because nothing could be lost:
'int' holds every 'i32', so nothing can be lost; use '.widen(...)'
Memory Model
This section explains FOL’s V3 memory model: explicit ownership operations
([mov]/[cpy]/[cln]/[bor] and friends) at every transfer boundary,
non-lexical borrows, static places and partial moves, named and elided
lifetimes, capability standards, custom finalization, closure environments,
and the unique/shared/weak/synchronized pointer family. The normative contract
is plan/FINISHED/V3_MEM.md; the first-shipped historical subset is recorded in its
Appendix A.
The main topics are:
- ownership
- pointers
- stack vs heap intuition
- allocation lifetime
- cross-thread memory concerns
The detailed chapters are the normative source. This index also keeps the
published example matrix aligned with the shared machine inventory in
test/v3_example_inventory.rs. Adding, removing, or renaming a mem_* or
fail_mem_* package requires updating both inventories in the same change.
The memory pillar is not complete at compiler acceptance. Each row below is
also guarded through lowering/runtime behavior, frontend capability routing,
structured diagnostics and explanations, formatter/tool commands, LSP
diagnostics/navigation/completion/tokens, Tree-sitter grammar/queries/corpus,
tests, docs, and the book. The exact cross-layer mapping lives in
Compiler Integration
and the repository-level docs/editor-sync.md matrix.
Shipped example inventory
M1: ownership and owned allocation
Positive:
examples/mem_owner_reinitialize_m1examples/mem_set_observation_m1examples/mem_index_assign_m1examples/mem_generic_ord_bound_m1examples/mem_when_bool_gate_m1examples/mem_linked_list_m1examples/mem_tree_m1examples/mem_move_stack_vs_heap_m1examples/mem_partial_move_m1examples/mem_fin_finalizer_m1examples/mem_fin_move_m1examples/mem_fin_early_m1examples/mem_fin_deferred_m1examples/mem_fin_field_m1
Negative:
examples/fail_mem_use_after_move_m1examples/fail_mem_loop_move_m1examples/fail_mem_explicit_move_reuse_m1examples/fail_mem_discarded_move_m1examples/fail_mem_deferred_reinit_m1examples/fail_mem_recursive_value_m1examples/fail_mem_heap_in_core_m1examples/fail_mem_uninit_borrow_m1examples/fail_mem_partial_move_m1examples/fail_mem_global_fin_m1examples/fail_mem_fin_partial_move_m1examples/fail_mem_fin_fun_finalizer_m1examples/fail_mem_fin_reuse_m1examples/fail_mem_fin_nested_m1examples/fail_mem_clone_fin_m1examples/fail_mem_clone_fin_claim_m1examples/fail_mem_generic_ord_operand_m1examples/fail_mem_generic_copy_operand_m1examples/fail_mem_generic_copy_bound_m1examples/fail_mem_generic_send_bound_transitive_m1
M2: lexical borrowing and deferred ownership
Positive:
examples/mem_borrow_m2examples/mem_borrow_giveback_m2examples/mem_borrow_param_m2examples/mem_mut_borrow_m2examples/mem_ownership_ops_m2examples/mem_capabilities_m2examples/mem_copy_clone_m2examples/mem_custom_clone_m2examples/mem_borrow_receiver_m2examples/mem_mut_receiver_m2examples/mem_receiver_ops_m2examples/mem_nested_receiver_call_m2examples/mem_reborrow_m2examples/mem_nll_last_use_m2examples/mem_named_lifetime_m2examples/mem_temp_borrow_m2examples/mem_place_borrow_m2examples/mem_edf_m2examples/mem_dfr_capture_m2examples/mem_dfr_capture_mut_m2examples/mem_closure_capture_m2examples/mem_closure_borrow_m2examples/mem_closure_env_lifetime_m2
Negative:
examples/fail_mem_deferred_report_m2examples/fail_mem_dfr_capture_bare_m2examples/fail_mem_dfr_capture_bor_mutation_m2examples/fail_mem_dfr_capture_undeclared_m2examples/fail_mem_closure_move_only_m2examples/fail_mem_closure_escape_m2examples/fail_mem_closure_env_leak_m2examples/fail_mem_copy_moveonly_m2examples/fail_mem_copy_record_field_m2examples/fail_mem_send_field_m2examples/fail_mem_send_nested_field_m2examples/fail_mem_clone_nested_field_m2examples/fail_mem_share_field_m2examples/fail_mem_owner_while_borrowed_m2examples/fail_mem_second_mut_borrow_m2examples/fail_mem_mut_borrow_immutable_owner_m2examples/fail_mem_borrow_reuse_m2examples/fail_mem_conditional_giveback_m2examples/fail_mem_deferred_giveback_m2examples/fail_mem_ownership_op_combo_m2examples/fail_mem_copy_fin_conflict_m2examples/fail_mem_copy_field_m2examples/fail_mem_copy_nested_field_m2examples/fail_mem_copy_operand_unclaimed_m2examples/fail_mem_fun_mut_receiver_m2examples/fail_mem_escaping_borrow_m2examples/fail_mem_temp_borrow_escape_m2examples/fail_mem_place_borrow_owner_m2
M3: typed pointers
Positive:
examples/mem_ptr_unique_m3examples/mem_ptr_shared_m3examples/mem_ptr_shared_recursive_m3examples/mem_ptr_weak_m3examples/mem_ptr_weak_clone_m3examples/mem_ptr_weak_upgrade_m3examples/mem_ptr_weak_cycle_m3examples/mem_ptr_weak_nested_m3examples/mem_shell_access_m3examples/mem_shell_prefix_m3
Negative:
examples/fail_mem_borrowed_ptr_move_deref_m3examples/fail_mem_ptr_raw_m3examples/fail_mem_ptr_weak_m3examples/fail_mem_shell_access_m3examples/fail_mem_ptr_in_core_m3examples/fail_mem_pointer_field_deref_m3examples/fail_mem_shared_ptr_move_deref_m3examples/fail_mem_shared_ptr_write_m3
Ownership
FOL’s V3 memory model uses compile-time ownership. It does not add a garbage collector, runtime ownership tags, or user-defined destructors.
V3 ships unique heap ownership, move checking, lexical borrowing, and typed unique/shared pointers. Transfer behavior follows the value type, not merely the binding’s location: clone-safe values are copied by cloning, while unique ownership and aggregates containing unique ownership move.
Stack and heap bindings
Bindings live on the stack unless heap allocation is explicit:
var stack_value: int = 64;
var[new] heap_value: int = 64;
@var other_heap_value: int = 64;
@var is sugar for a binding with [new]. Heap allocation requires the
memo capability model. A memo artifact with bundled std remains
heap-capable, but allocation does not itself require hosted APIs. Ownership
checking is a compile-time rule and is also active in core.
There is no [@] binding option and no manual .free(). A .de_alloc()
placeholder once stood here and was deleted: it named no allocator and no
destructor provenance.
Unique heap values lower to Rust Box<T> and are freed implicitly when their
owning scope ends.
Assignment and ownership transfer
Assignment and rebinding use the value’s ownership class:
- clone-safe values clone, so the source and destination remain usable
- heap-owned values and unique pointers move, so the source becomes inaccessible
- an aggregate is move-only when it contains a move-only value
- a shared pointer clones its reference count instead of moving its source
fun[] main(): int = {
var stack_a: int = 2;
var stack_b: int = stack_a;
@var heap_a: int = 3;
@var heap_b: int = [mov]heap_a;
return stack_a + stack_b;
};
The transfer itself must state its operation. Writing @var heap_b: int = heap_a; is rejected with O1001, because a move-only value never transfers
implicitly: [mov] moves it, [cpy] and [cln] produce an independent value.
Adding a later read of heap_a to that body — say return heap_a; after the
[mov] — is a compile error in the O#### OWNERSHIP diagnostic family. The
diagnostic points at both the invalid use and the transfer site.
The backend emits clone-safe transfers with .clone() and unique transfers as
ordinary Rust moves. No runtime tag decides which operation occurs.
Evaluating a move-only value as a standalone expression is also a transfer even when its result is discarded. Lowering still evaluates that expression, so the source cannot be used afterward. Clone-safe scalar expression statements remain usable because their values clone.
A whole mutable binding can be reinitialized after its old value moves:
var[mut] pointer: ptr[int] = [ref]first;
consume(pointer);
pointer = [ref]second;
return [drf]pointer;
The assignment target is a storage place, not a read of the missing old value. The right-hand side is checked and transferred first, then a successful store makes the binding usable again. Ordinary mutability and active-borrow rules still apply. Self-assignment of a live mutable owner transfers the value through the assignment and leaves the same binding initialized. Assignment is a statement and does not yield a second copy of the stored value.
Transferring a move-only record field consumes the whole source binding. V3 does not leave a partially moved record available through its other fields. Any indexed read whose element or map value is move-only remains unsupported, including selecting a clone-safe field from that element afterward. Index access materializes the whole element, so these containers need an explicit removal operation rather than a clone-based read.
Container queries are observations, not transfers. .len(local) and indexed
lookup through direct locals preserve the receiver and map key, including when
their types contain unique pointers. A move-only receiver or key reached
through a field projection is not yet observable because V3 has no place-aware
projection IR; such a lookup is rejected instead of partially moving its
source. The same boundary rejects nested field access through a move-only
intermediate.
Dereferencing is a by-value operation whose ownership effect depends on the
pointee. [drf]pointer clones a clone-safe pointee and leaves the pointer usable.
If the pointee is move-only, dereferencing a direct unique ptr[T] transfers
the pointee and consumes that pointer. A shared or borrowed pointer cannot
surrender a move-only pointee, so those dereferences are rejected; their
read-only dereference is available only when the pointee is clone-safe.
Dereferencing a unique-pointer field is also a place observation, not a whole
field transfer. Until V3 has place-aware projection IR, [drf]record.pointer is
rejected even when its pointee is clone-safe; otherwise backend lowering would
partially move the pointer just to observe its target. Direct pointer bindings
remain available. A field containing ptr[shared, T] can be dereferenced when
T is clone-safe.
Forward slices currently create a new vec[...] or seq[...] by cloning the
selected elements. Their element type must therefore be clone-safe. Fixed-size
array slices need a distinct runtime-sized result contract and remain
unsupported. Ordinary collection iteration is also index-based and clone-based,
so a collection containing move-only elements cannot use it yet. Channel
receiver iteration is different: it consumes each payload and may carry
move-only values.
Top-level storage is limited to clone-safe, non-borrowed values that are safe in
the backend’s shared static cells. Move-only values, borrowed values, full
channels, and values containing ptr[shared, T] must be declared inside a
routine. This prevents global loads from duplicating unique ownership, extending
a lexical borrow to static lifetime, or placing Rc in thread-safe storage.
A when result transfers the final value of the selected branch into its join
value. Branches are checked from the same incoming ownership state, so the same
owner may be transferred by mutually exclusive alternatives. After the when,
every owner that could have been transferred by a continuing branch is treated
as moved.
Value-matching when arms use the same equality contract as ==: selector and
case values must have the same equality-safe scalar type. Pointer, record, and
other move-only selectors are rejected rather than being moved by an implicit
comparison. A when without value arms is instead a boolean control gate, so it
also rejects move-only selectors rather than evaluating and silently moving an
unused owner.
Loop bodies are lexical scopes that execute once per iteration. A move-only
binding declared outside a repeating loop cannot be transferred from the loop
body or its repeated condition: a later iteration would try to consume the
same value again. Create the move-only value inside the loop when each
iteration needs a fresh owner, or transfer it after the loop. A return that
transfers a value is allowed because it exits the routine instead of reaching
another iteration.
Deferred bodies also participate in ownership checking. When a dfr or edf
body references a move-only binding from an enclosing scope, that binding is
reserved until the registration scope exits and the selected deferred work has
run. A later transfer in the same scope is rejected with both the transfer and
deferred-use locations. If the deferred block belongs to a nested scope, the
reservation ends with that nested scope.
Reinitializing an already-moved binding inside dfr or edf is rejected in
V3. The assignment runs only at scope exit, so applying its ownership effect
when the deferred body is registered would unsafely expose the binding before
the new value exists.
Recursive owned data
Owned heap indirection gives recursive types a finite runtime shape:
typ Node: rec = {
value: int,
next: opt @Node,
};
In type position, @Node means an owned heap Node. The example above lowers
to one nominal Rust structure whose recursive field has the shape
FolOption<Box<Node>>.
A recursive value edge without owned indirection is still invalid:
typ Bad: rec = {
next: Bad,
};
Such a type has no finite value layout. The compiler recommends an owned edge
such as opt @Bad instead.
Borrowing
A borrow is an alias that does not take ownership:
var owner: Node = { value = 7, next = nil };
var[bor] view: Node = owner;
var value: int = view.value;
[bor]owner borrows from an owner as an expression:
var[bor] view: Node = [bor]owner;
Borrowing is non-lexical. A borrow stays active only until its last use, not until the end of the lexical scope where its binding was created. Once a loan’s final read has passed, the owner becomes usable again in the same scope with no explicit give-back.
While a borrow is active:
- the owner cannot be read, written, moved, or borrowed incompatibly
- an immutable borrower is read-only
- a borrowed value cannot transfer move-only data out of its owner; clone-safe observations remain available
- any mutable borrower excludes every other borrower of that owner
Leaving the scope returns access to the owner automatically:
var owner: Node = { value = 7, next = nil };
{
var[bor] view: Node = owner;
var value: int = view.value;
};
return owner.value;
[end]view gives a borrow back before scope exit. A returned borrow cannot be used
again; attempting to read view afterward reports O2004 with the give-back
site as related information:
var[bor] view: Node = owner;
var value: int = view.value;
[end]view;
return view.value;
The ! prefix is give-back only. It is not deletion or manual memory free.
A borrow binding may be reborrowed: [bor]view creates a nested loan from an
existing borrow, released like any other loan by its last use or an explicit
[end]. A reborrow cannot outlive the loan it derives from.
Mutable borrowing
A mutable borrow requires both an explicitly mutable owner and an explicitly mutable borrow binding:
var[mut] owner: Node = { value = 7, next = nil };
var[mut, bor] view: Node = owner;
view.value = 9;
[end]view;
return owner.value;
var[bor] is immutable unless mut is also present. A var[mut, bor] binding
may update the original owner, but it still does not own the value and cannot
move unique data out of it. Attempting a mutable borrow from var[imu], or
creating another borrow while a mutable borrow is active, is an O####
ownership diagnostic.
Borrow parameters
Routine parameters use the same explicit option position:
fun[] inspect(item[bor]: Node): int = {
return item.value;
};
The backend emits a Rust reference parameter. Passing an owner requires an
explicit [bor]owner; an existing compatible borrow binding can be passed directly
and reused by later [bor] calls. The call borrow ends when the call returns,
while an existing borrow binding keeps its surrounding lexical lifetime.
Parameter spelling or casing never changes ownership semantics;
name[bor]: T is the only borrow-parameter form. A borrowed parameter can
observe clone-safe data, but it cannot return or forward a move-only value as
an owned argument.
Borrowing is compile-time-only and legal in core. It does not allocate or add
runtime reference bookkeeping.
Named lifetimes
When a routine returns a borrow, the compiler must know which input the result
may alias. A lifetime parameter L: lif names a single region and ties the
borrowed inputs and the borrowed result together:
fun pick(L: lif)(left: Item[bor=L], right: Item[bor=L]): Item[bor=L] = {
return left;
};
Item[bor=L] is a borrow bound to region L. The returned borrow is valid for
as long as every input it may alias, so the caller’s owners must outlive the
result. A routine that borrows a single input and returns a borrow may leave the
region implicit; naming it is required only when several borrows share one
result region.
Receiver ownership
A method states how it takes its receiver with the same option position; the
receiver binds to self:
fun (Node[bor])inspect(): int = { return self.value; };
pro (Node[mut, bor])update(): non = { self.value = 9; return; };
fun (Node)consume(): int = { return self.value; };
A fun may take a shared [bor] receiver or move its receiver by value; only a
pro may take a mutable [mut, bor] receiver. At the call site the ownership
operation binds the receiver directly, with no surrounding parentheses:
[bor]node.inspect();
[mut, bor]node.update();
[mov]node.consume();
[op]receiver.method() groups as ([op]receiver).method(): the operation
describes how the receiver crosses the call boundary, not the call’s result, and
a [mut, bor] receiver’s field updates persist to the original binding. The
rule is scoped to a trailing method call — a plain place chain keeps the
operation over the place, so [mov]bundle.held still moves the held subfield
rather than bundle. The same grouping applies to the bracket unary operations,
so [drf]pointer.method() dereferences pointer and then calls the method.
Closure captures
An anonymous routine used as a first-class value declares how outer locals enter its environment with the same capture list delayed blocks use. The routine value’s type is its visible call signature; the environment re-supplies the captured values on every invocation:
var base: int = 30;
var adder: {fun (n: int): int} = fun(n: int)[base[cpy]]: int = { return n + base; };
var first: int = adder(12);
[cpy] and [cln] duplicate the outer value into the environment, leaving the
source live. [mov] transfers a clone-safe value and invalidates the outer
binding; moving a move-only value into a routine value is rejected because the
closure may run more than once — spawn the routine directly when the value
should transfer into exactly one execution.
A local, nonescaping closure may also borrow: [bor] captures infer their
lifetime as the enclosing scope. The owner stays readable but is frozen — no
mutation, no transfer — while the closure can still run, and the closure value
itself cannot escape that scope: returning it, passing it to a call, storing
it, or rebinding it is rejected. The one sanctioned crossing is a parameter
whose routine type names its environment lifetime — {fun (): int}[bor=L]
with a declared L: lif — which receives the closure and obeys the same
nonescaping rules inside the callee
(examples/mem_closure_env_lifetime_m2 and
examples/fail_mem_closure_env_leak_m2 pin that boundary). Channel-endpoint captures never enter routine
values (examples/mem_closure_capture_m2, examples/mem_closure_borrow_m2,
examples/fail_mem_closure_move_only_m2, and
examples/fail_mem_closure_escape_m2 pin the contract).
Capabilities
Seven compiler-owned standards describe what may be done with a value. A type lists the ones it guarantees in its conformance position, and the compiler verifies each claim against the type’s fields.
| Standard | Meaning |
|---|---|
copy | [cpy]value may duplicate the value; the source stays usable |
clone | [cln]value may create an independent copy; the source stays usable |
fin | the type runs custom finalization when it is dropped |
lin | the value must be consumed exactly once, explicitly, on every path |
send | owned access may cross a task or thread boundary |
share | shared access may cross a task or thread boundary |
ord | the type has a total order, so < and > compare its values |
A type states its capabilities in the conformance list:
typ Point()(copy): rec = { x: int, y: int };
typ Job()(clone): rec = { input: int };
typ Buffer()(clone, send): rec = { bytes: seq[int] };
Verification
Each claim is checked recursively against the type’s fields. clone has a
structural default: a type is clonable when every field is clonable, so a
clone claim needs no extra code for ordinary data. copy has no structural
default — every aggregate field of a copy type must itself claim copy.
copy implies clone, and copy and fin cannot coexist.
send and share require every field to be thread-safe transitively, so a type
holding a non-synchronized shared pointer or a fin resource cannot claim them.
lin is the one standard that constrains use rather than describing a
property, so its rules are their own chapter: Linear resources.
A lin type may not also claim copy or clone — a duplicate would carry a
release obligation nothing tracks — and a type holding a lin field must itself
claim lin, so the obligation cannot be hidden inside a wrapper.
ord is the one standard that is never claimed in a conformance header. It
is structural throughout: a record or entry is ordered when its fields are.
flt does not satisfy ord, because NaN compares equal to nothing and a
total order is what the standard promises.
An aggregate compares field by field in field-NAME order, not declaration
order. Record types are interned structurally, and that interning normalizes
field order so { a: int, b: int } and { b: int, a: int } are the same type —
which means there is no declaration order left to compare by. A record declared
{ row: int, col: int } therefore compares on col first:
typ Cell: rec = { row: int, col: int };
// sorting these yields (2,0) before (1,3): `col` decides, not `row`
So treat ord on an aggregate as “some stable total order” — enough to be a map
key, a set member, or to deduplicate. Do not rely on it for presentation order.
To sort records the way a reader expects, sort a vector of the field you care
about, or give the type a field order whose names sort the way you need.
Because a total order decides equality as well, a value bound by ord may be
compared with == too. Only ord is needed to search a container, not ord
plus some separate equality standard.
Operations
[cpy]value requires the value’s type to declare copy; a structurally
copy-safe record without the (copy) header is clone- or move-only.
[cln]value requires clone, which the structural default usually satisfies.
Custom clone
A type may override the structural clone with a pure borrowed-receiver method
named clone:
typ Counter()(clone): rec = { value: int, clones: int };
fun (Counter[bor])clone(): Counter = {
return { value = self.value, clones = self.clones + 1 };
};
[cln]counter then dispatches to this method instead of copying fields
structurally. A custom clone is a fun with a shared [bor] receiver: it
observes the source and returns an independent value.
Generic bounds
A capability may constrain a generic parameter. The obligation is checked at each call site against the concrete type argument, so the routine is only usable with types that satisfy the standard:
fun keep(T: copy)(value: T): T = { return [cpy]value; };
Several bounds combine with +, which is how most of the standard library’s
container routines are written:
fun[exp] sort(T: ord + clone)(values: vec[T]): vec[T] = {
var[mut] out: vec[T] = [mov]values;
out.sort();
return out;
};
clone appears there because a pure routine has to copy elements out of its
argument rather than move them, and ord because the sort compares.
The parts need not all be capabilities. A declared standard joins the same way, so one parameter can carry both a contract and a capability, and the standard may be qualified:
fun[exp] is_affine(U: scale::unit + copy)(item: U): bol = {
return magnitude(offset_of([cpy]item)) > 0.000000001;
};
The standard half is resolved to its declaration; the capability half is checked against the concrete type at the call site.
copy is the one capability with no structural default. A record whose fields
are all copy-safe still does not satisfy copy until it says so, because copy
is a claim rather than a shape — the same rule [cpy] enforces on a value:
call to 'keep' requires type 'Tally' to satisfy the 'copy' capability for generic
parameter 'T'; the type does not; add a '(copy)' conformance header to it, or
bound the parameter with 'clone'
The check applies across a package boundary as well. Calling an imported generic routine with a type that cannot satisfy its bound is an ordinary type error at the call site, not a failure further down the pipeline:
call to 'std::vecs::sort' requires type 'flt' to satisfy the 'ord' capability
for generic parameter 'T'; the type does not
Finalization
A type that claims the fin capability runs custom cleanup when its owner is
released. The cleanup is a compiler-owned receiver contract: a pro named
finalize that takes the value by value and returns non.
typ File()(fin): rec = { descriptor: int };
pro (File)finalize(): non = {
close(self.descriptor);
return;
};
The finalizer is a pro because releasing a foreign resource is an effect. A
fin type cannot also claim copy: a value with cleanup is not trivially
duplicable.
Scope-exit cleanup
The finalizer runs automatically when the owning scope exits, exactly once per value:
fun[] main(): int = {
var handle: File = { descriptor = 3 };
return handle.descriptor;
// handle.finalize() runs here, as the scope exits
};
When a value is moved, responsibility for finalization moves with it: the new owner finalizes it, and the original binding does not.
A [mov] capture into a dfr or edf block is the one move that stays in the
frame. The delayed block replays at scope exit, so the value is finalized right
after the block body runs:
fun[] main(): int = {
var handle: File = { descriptor = 3 };
dfr[handle[mov]] {
observe(handle.descriptor);
};
return 0;
// the deferred body runs, then handle.finalize()
};
What can own a fin value
A finalizer runs for a value that a binding, a parameter or a dfr/edf
capture owns — directly, or through a record field. A record names what it
holds, so at scope exit its owner walks the field path and runs each contained
finalizer, deepest field first:
typ Pair: rec = { left: File, right: File };
var pair: Pair = { left = { descriptor = 1 }, right = { descriptor = 2 } };
// at scope exit: right is finalized, then left
Ownership still decides who finalizes. Moving the holder moves the duty with it, so the receiving routine releases the fields at its scope exit and the original owner does not.
A container finalizes what it holds too. It has no field name for each value, so at scope exit it hands out its elements one by one instead:
var pool: vec[File] = { { descriptor = 1 }, { descriptor = 2 } };
// at scope exit: every element is finalized, in order
That covers vec/arr/seq elements, set members, map keys and values,
and opt/err payloads — including a container reached through a record field.
What is still refused is a fin value buried below one of those positions:
inside a container’s element, an entry variant, or a generic argument. Reaching
those would need a field walk per element at scope exit, which the compiler
cannot emit, so the program is rejected rather than skipping the cleanup:
typ Holder: rec = { file: File };
var many: vec[Holder] = { { file = { descriptor = 3 } } };
// rejected: the 'fin' value sits below the element, out of reach
Hold such a value directly, or give it its own binding and transfer it with
[mov].
Early finalization
[fin]value runs the finalizer immediately and invalidates the source. The
value is finalized exactly once, so scope-exit cleanup does not run a second
time:
var handle: File = { descriptor = 3 };
observe(handle.descriptor);
[fin]handle;
// handle is now consumed; no second finalize at scope exit
Linear resources
A type that claims lin holds a resource whose release can fail, and whose
failure means something. Closing a file can lose buffered writes; closing a
socket can report that the data never reached the other end; closing a database
handle can refuse while statements are still open. A program that ignores those
statuses loses data silently.
Finalization cannot carry such a failure anywhere. A
finalizer runs when a scope ends, and a scope ending has no caller waiting on a
result: there is no expression to return an error to and no || to route one
into. This is the wall Rust’s Drop, C++ destructors, and Go’s
defer f.Close() all hit. FOL does not copy any of them.
Instead, a lin value is never released implicitly. It must be consumed
exactly once, explicitly, on every path — which makes the release an
ordinary call whose error propagates like any other.
typ Handle()(lin, fin): rec = { descriptor: int };
fun (Handle)close(): int / int = {
when(self.descriptor) {
is(0) { report 7; }
* { }
};
return self.descriptor;
};
The two consumers
A linear value is consumed by transferring it out, or by discarding the failure on purpose:
var handle: Handle = { descriptor = 3 };
var code: int = [mov]handle.close() || 8; // the release, failure readable
var spare: Handle = { descriptor = 5 };
[fin]spare; // best-effort, failure discarded
[fin] runs the type’s finalizer, which is typed : non and so cannot report.
That is the point: throwing the failure away is allowed, but it has to be
spelled, and [fin] is greppable when auditing a codebase for ignored release
failures. A lin type that does not also claim fin has no finalizer to run,
so [fin] on it is refused.
Omitting both is a compile error.
What the compiler proves
Every path out of a scope is checked:
| Situation | Result |
|---|---|
| the scope ends still holding one | refused — the plain leak |
return while holding one | refused |
one when arm releases and another does not | refused — the join has no single answer |
| a resource from outside a loop is released inside it | refused — the second iteration would release it again |
| a call returns one and nobody binds the result | refused |
| released twice | refused by the ownership checker, at the first move |
[cpy] or [cln] of one | refused — a duplicate owes a release nothing tracks |
| captured by a closure or spawned task | refused — the obligation would leave the scope that owes it |
released inside dfr or edf | refused — those run at scope exit, with no caller for a failed release |
A borrow of a linear value carries no obligation, because the obligation
stayed with the owner. fun peek(h: Handle[bor]): int is an ordinary routine.
An owned lin parameter is the opposite: the caller transferred the resource,
so the routine now owes the release.
Reporting while holding one
A scope that still holds an unreleased linear resource may not report:
fun[] work(): int / int = {
var handle: Handle = { descriptor = 3 };
when(handle.descriptor) {
is(3) { report 9; } // refused: handle is still held
* { }
};
[fin]handle;
return 7;
};
Two errors would exist at once — the reported one and whatever the release returns — and a routine has one result channel. Picking a winner would discard the other, which is the data loss the capability exists to prevent. So the language refuses the case instead of choosing.
This is deliberately the most restrictive of the available answers. Relaxing it later to an error that can carry both is a widening, and widenings do not break existing programs; shipping “the body’s error wins” first would be a narrowing to undo.
Containment
A type holding a lin field must itself claim lin:
typ Holder()(lin, fin): rec = { inner: Handle };
Without that rule an ordinary record would be a hole in the analysis: wrapping a handle in a struct would hide it, and the release obligation would vanish at the moment the field was assigned. Propagating the claim outward keeps the obligation attached to whatever now owns the resource.
Examples
examples/v4_linear_handle— both consumers, and a readable release failureexamples/fail_v4_linear_leak— a scope ending while still holding oneexamples/fail_v4_linear_report—reportwhile holding oneexamples/fail_v4_linear_branch— one branch releases, the other does not
Pointers
FOL V3 has typed unique and shared pointers. Pointer construction allocates, so
it requires the memo capability model. A memo artifact with bundled std
remains heap-capable, but pointer construction does not itself require hosted
APIs.
Unique pointers
ptr[T] is a uniquely owned pointer to T:
pro[] main(): int = {
var value: int = 7;
var inner: ptr[int] = [ref]value;
var outer: ptr[ptr[int]] = [ref]inner;
var[mut] extracted: ptr[int] = [drf]outer;
[drf]extracted = 9;
return [drf]extracted;
};
[ref]value allocates the pointed-to value and produces a unique pointer. The
backend represents it as Box<T>. Unique pointers move on transfer, just like
other unique heap-owned values, and are freed when their owner leaves scope.
Constructing a pointer from a move-only value transfers that value into the new
allocation.
[drf]pointer is a by-value dereference to the T pointee:
- if
Tis clone-safe, dereference clonesTand leaves the pointer usable - if
Tis move-only, dereferencing a unique pointer transfersTout and consumes that pointer
The example consumes outer because its pointee is another unique pointer.
extracted then owns that inner pointer. A direct unique-pointer binding
declared with var[mut] supports write-through assignment such as
[drf]extracted = 9.
Direct unique-pointer bindings can be dereferenced, but a unique pointer reached
through a record field cannot be dereferenced in V3. That observation needs a
place-aware field projection in lowering; treating the field as an ordinary
value would partially move the pointer merely to read its pointee. This field
boundary also applies when T is clone-safe. Keep the unique pointer in a
direct binding, or use ptr[shared, T] with a clone-safe pointee when a
read-only pointer field is the intended shape.
Shared pointers
ptr[shared, T] is a reference-counted shared pointer:
var value: int = 7;
var first: ptr[shared, int] = [ref]value;
var second: ptr[shared, int] = first;
return [drf]first + [drf]second;
The backend represents shared pointers as Rc<T>. Assigning one clones the
reference count, so first and second refer to the same allocation. Shared
pointers are read-only; write-through is rejected.
A single [drf]p yields T for both unique and shared pointers. The reference
counting layer is not exposed as another pointer that needs a second
dereference. Because a shared pointer cannot remove the value from all of its
aliases, this read is available only when T is clone-safe. Dereferencing
ptr[shared, ptr[int]], for example, is rejected rather than cloning or moving
the unique inner pointer.
Borrowed pointers
A pointer can be borrowed like any other owned value:
fun[] read(pointer[bor]: ptr[int]): int = {
return [drf]pointer;
};
The borrowed pointer is a non-owning, read-only view. It can be passed directly
to another compatible [bor] parameter and reused for later calls. Dereference
can clone a clone-safe pointee such as int, but it cannot move a move-only
pointee through the borrow. A borrowed ptr[ptr[int]] therefore cannot produce
the inner ptr[int] by value. Write-through also requires a direct mutable
unique-pointer binding; a borrowed pointer is not such a binding.
Shared recursive graphs
Shared pointer indirection gives recursive graph edges a finite layout:
typ Node: rec = {
value: int,
next: opt ptr[shared, Node],
};
This lowers to an optional Rc<Node> edge. Shared recursion is legal, but V3
has no cycle collector: a cycle of shared pointers leaks unless a weak edge
breaks it.
Rc is not thread-safe and cannot cross a processor spawn boundary. The V3
processor pillar enforces that boundary; ptr[shared, sync, T] is the
synchronized (Arc-backed) shared owner for values that may cross it.
Weak pointers
ptr[weak, T] observes a shared allocation without keeping it alive.
[weak]shared creates the weak handle, and [upg]weak attempts to revive a
shared owner, producing opt[ptr[shared, T]] — nil when the allocation is
already gone. Neither operation consumes its operand.
pro[] main(): int = {
var value: int = 20;
var strong: ptr[shared, int] = [ref]value;
var observer: ptr[weak, int] = [weak]strong;
var revived: opt[ptr[shared, int]] = [upg]observer;
when(revived) {
on(alive) { return [drf]alive; }
* { return 0; }
}
};
Dereferencing a weak handle directly is rejected — upgrade first, then handle
the nil arm. Weak handles support explicit [cln], may live inside records,
and are the tool for breaking shared-pointer cycles
(examples/mem_ptr_weak_cycle_m3 breaks a parent/child cycle with a weak
back-edge).
Inner-place access
value[] reads the inner place uniformly across the pointer and shell families:
for a pointer it is a dereference, and for an opt[T] it is the present payload,
panicking if the option is nil.
var slot: ptr[shared, int] = [ref]count;
var maybe: opt[int] = lookup();
return slot[] + maybe[];
The same [] spelling works wherever a value wraps an inner place, so a
dereference and a shell unwrap share one surface.
Raw pointers are out
ptr[raw, T] is reserved but rejected with an explicit V4 interop diagnostic.
V3 does not provide raw pointer construction, manual .free(), or unsafe
delete. [end]x remains borrow give-back only; it never deletes a pointer.
Custom cleanup goes through the fin finalization capability instead.
Operations in core
Borrowing and pointer type declarations are legal in core: [bor]owner
creates a lexical borrow without allocation, and [end]borrow ends it early.
Constructing a pointer with [ref]value allocates, so it is rejected in core
even though the pointer’s type can still be analyzed there.
Concurrency
This section covers FOL’s first shipped V3 concurrency and asynchronous
execution subset. Every processor surface is hosted std-only and is
implemented with OS threads and Rust standard-library synchronization; FOL does
not use a separate async runtime.
Here std-only describes source capability: the artifact uses
fol_model = "memo" and the package explicitly declares the bundled internal
standard dependency. It does not mean FOL needs std merely to launch a
program. Host-compatible core and unhosted memo executables can run too;
they simply cannot use processor constructs.
The current chapter split is:
- eventuals
- tasks, channels,
select, and mutex parameters
Together they define the language-level model for task execution, coordination, and concurrent ownership boundaries.
The processor pillar is not complete at compiler acceptance. Each row below is
also guarded through lowering/runtime behavior, evaluated frontend capability
routing, structured diagnostics and explanations, formatter/tool commands, LSP
diagnostics/navigation/completion/tokens, Tree-sitter grammar/queries/corpus,
tests, docs, and the book. The exact cross-layer mapping lives in
Compiler Integration
and the repository-level docs/editor-sync.md matrix.
Shipped example inventory
This is the canonical processor example inventory. The milestone chapters and
the V3 processor plan link here instead of maintaining smaller lists that can
drift. Adding, removing, or renaming a processor example requires updating this
published list and the shared machine inventory in
test/v3_example_inventory.rs in the same change; compiler integration and
editor tests consume that shared machine inventory.
P1: spawn
Positive:
examples/proc_spawn_m1examples/proc_spawn_move_heap_m1examples/proc_spawn_canonical_m1examples/proc_spawn_detached_m1examples/proc_shared_sync_ptr_m1examples/proc_spawn_borrow_m1examples/proc_generic_send_spawn_m1
Negative:
examples/fail_proc_spawn_detached_borrow_m1examples/fail_proc_spawn_fin_m1examples/fail_proc_spawn_borrow_mutate_m1examples/fail_proc_generic_capture_send_m1examples/fail_proc_spawn_weak_m3examples/fail_proc_spawn_heap_use_after_move_m1examples/fail_proc_spawn_in_core_m1examples/fail_proc_spawn_indirect_m1examples/fail_proc_spawn_in_memo_m1examples/fail_proc_spawn_rc_cross_m1examples/fail_proc_spawn_recoverable_m1
P2: channels
Positive:
examples/proc_channel_capture_m2examples/proc_channel_loop_m2examples/proc_channel_m2examples/proc_channel_pull_m2examples/proc_sender_endpoint_m2examples/proc_receiver_endpoint_m2
Negative:
examples/fail_proc_channel_bare_send_m2examples/fail_proc_channel_capture_rx_m2examples/fail_proc_channel_in_core_m2examples/fail_proc_channel_in_memo_m2examples/fail_proc_channel_index_m2examples/fail_proc_channel_receive_bare_m2examples/fail_proc_channel_spawn_consumer_m2examples/fail_proc_clone_receiver_m2
P3: select and mutexes
Positive:
examples/proc_mutex_explicit_unlock_m3examples/proc_mutex_local_m3examples/proc_mutex_local_loop_m3examples/proc_mutex_guard_m3examples/proc_mutex_guard_end_m3examples/proc_mutex_m3examples/proc_select_m3examples/proc_receiver_select_m3examples/proc_receiver_loop_m3
Negative:
examples/fail_proc_mutex_deferred_m3examples/fail_proc_mutex_deferred_forward_m3examples/fail_proc_mutex_deferred_lock_m3examples/fail_proc_mutex_deferred_unlock_m3examples/fail_proc_mutex_guard_await_m3examples/fail_proc_mutex_guard_move_m3examples/fail_proc_mutex_in_core_m3examples/fail_proc_mutex_in_memo_m3examples/fail_proc_select_empty_m3examples/fail_proc_select_in_core_m3examples/fail_proc_select_in_memo_m3
P4: eventuals
Positive:
examples/proc_async_await_m4examples/proc_await_error_m4examples/proc_evt_named_m4examples/proc_evt_lifetime_m4
Negative:
examples/fail_proc_evt_return_elided_m4examples/fail_proc_evt_param_elided_m4examples/fail_proc_evt_detached_m4examples/fail_proc_evt_embedded_m4examples/fail_proc_async_in_core_m4examples/fail_proc_async_break_outer_m4examples/fail_proc_async_edf_await_m4examples/fail_proc_async_indirect_m4examples/fail_proc_async_in_memo_m4examples/fail_proc_async_nested_capture_m4examples/fail_proc_async_recoverable_discard_m4examples/fail_proc_async_recoverable_overwrite_m4examples/fail_proc_async_recoverable_unawaited_m4examples/fail_proc_await_in_core_m4examples/fail_proc_await_in_memo_m4examples/fail_proc_await_recoverable_discard_m4
Eventuals
Eventuals are a V3 processor feature and are std-only. They use operating-
system threads; FOL does not use Rust async/await, futures, Tokio,
continuations, or colored routines.
The package therefore selects fol_model = "memo" for the artifact and
declares the bundled internal standard dependency. That declaration enables
the processor API; it is not what makes the executable runnable.
The chosen pipe surface is:
var pending = calculate() | async;
var value = pending | await;
| async starts the call on an OS thread and produces a one-shot eventual.
| await blocks the current OS thread until that computation finishes. A local
binding may name the eventual with its lexical lifetime elided (V3_MEM §8.1):
evt[T] for an infallible call and evt[T / E] for a recoverable one, e.g.
var work: evt[int] = compute(7) | async. The public lifetime-carrying
evt[L, T] spelling is also a namable type, naming the region the eventual
belongs to. An eventual that crosses a routine signature must spell that
lifetime on both sides: a parameter or return type declares L: lif and
writes evt[L, T], and the lifetime name must resolve to a declared lifetime
parameter. The elided evt[T] form is local-declaration shorthand only.
This signature rule is what makes L enforceable without a region solver.
Handles cannot be embedded in aggregates or wrappers, sent through channels,
stored at module level, captured by routine values, or enter detached tasks —
so the only way a handle travels is through signatures and local moves.
Requiring the evt[L, T] spelling wherever a signature carries one means a
handle provably cannot outlive the parent scope L names.
The call to the left of | async must resolve directly to a named routine
declaration. Both calculate() and a qualified call such as
workers::calculate() are supported; qualification selects a declaration and
does not introduce runtime dispatch. Stored routine values, stored anonymous
routines, and routine parameters are indirect calls and are not async task
targets in V3. Receiver-method call syntax is also excluded from the task
target surface; call a free named routine directly instead.
Nested routine bodies cannot implicitly capture outer locals. Pass ordinary outer values through declared parameters instead of relying on a hidden closure environment. An outer eventual cannot use that workaround because generic crossings are forbidden; await and handle it in the outer routine.
Eventual bindings are move-only. A plain binding or assignment transfers the
eventual and makes the source binding unavailable. An eventual may be consumed
at most once: | await consumes the current binding, so a second await is a
use-after-consume error. An infallible eventual need not be awaited and is joined
at process exit; a recoverable eventual has the stronger must-handle rule below.
V3 does not embed eventuals in composite values or pass them through generic
parameters, because generic bodies do not yet carry a move-only contract. Await
the value before crossing either boundary.
Arguments sent into | async obey the same thread boundary as [>]: borrowed
values, ptr[shared, T], and unresolved generic parameters cannot cross it.
Omitted defaults are arguments too and are checked against that boundary before
the task starts. A generic call remains allowed when inference produces only
concrete thread-safe parameter types.
Thread-safe move-only results can cross back through an eventual. The producer
transfers the result into the eventual and | await transfers it to the
awaiting routine; neither step clones it. Unique pointers are one shipped
example of this rule. A result containing ptr[shared, T] is still rejected
because its Rc representation cannot cross the OS-thread boundary.
Error behavior stays identical to the synchronous call. An infallible call
awaits to T. A routine declared as T / E remains recoverable after await and
must be handled with the existing check(...) or || surfaces. Async and await
do not introduce a second error channel. A recoverable eventual is a must-handle
value: its final owner must await it and immediately handle the result. Moving it
to another binding moves that obligation. Lexical fallthrough and any break,
return, or report that exits a scope with a live obligation are rejected. At
a branch join, all continuing branches must leave compatible state: they may
all preserve the same owner for handling after the join, transfer consistently,
or discharge the obligation. Consuming or transferring on only some paths is
rejected. Dropping it as a statement, overwriting it while live, or discarding
the awaited result is also rejected.
| await is not allowed inside edf, and an existing eventual binding cannot
be accessed there. Error-only deferred cleanup does not run on normal exits, so
it cannot be used to discharge eventual ownership. This restriction remains in
force through nested blocks, including a dfr declared inside the edf. Await
or transfer the value in ordinary control flow instead.
Program exit joins outstanding async work just as it joins bare [>] tasks.
This includes an infallible eventual that was created and then never
awaited: it is not detached merely because no source-level binding consumes it.
Joining is not error handling, so a recoverable eventual cannot use that path to
discard its error. Cancellation, worker pools, and runtime scheduling controls
are not part of V3.
An eventual is a one-shot task result, not a resumable generator or coroutine.
V3 does not execute generator yield; that statement remains recognized by
the parser but is rejected by semantic analysis and lowering. async also does
not color the called routine or change its declaration.
The eventual slice is implemented end to end. Its exact positive (including the
namable evt[T] local), tier-failure, and must-handle failure example set is
maintained in the
canonical shipped processor inventory.
Tasks, Channels, and Mutexes
The processor surface is a V3 systems feature. Every processor construct is
std-only: a package must declare the bundled internal standard dependency.
Choosing core or memo alone does not provide threads or hosted services.
The artifact itself uses fol_model = "memo"; there is no std model.
This dependency gates processor APIs, not process execution: std-free core
and memo artifacts may still run on a compatible host.
Spawn
[>]call() starts one operating-system thread and lets the current routine
continue. FOL has no worker pool, scheduler settings, Rust async runtime, or
Tokio dependency. Every spawned task is registered with the process and the
program joins all outstanding tasks before its entry point exits.
use std: pkg = {"std"};
pro[] worker(): int = {
return std::io::echo_int(17);
};
pro[] main(): int = {
[>]worker();
return 0;
};
A bare spawn is always fire-and-forget: [>]call() creates no eventual and
cannot be awaited. It must therefore call an infallible routine. To run a
recoverable routine asynchronously, omit [>], write call() | async, then
consume the eventual with | await and handle the result with check(...) or
||.
The call form must resolve directly to a named routine declaration. Both an
unqualified call such as [>]worker() and a qualified call such as
[>]workers::worker() are supported. Stored routine values, stored anonymous
routines, and routine parameters remain indirect calls and are not spawn
targets in V3. The explicit zero-parameter anonymous spawn form carries an
explicit capture list: channel sender endpoints (c[tx]) and value operations
(data[mov], amount[cpy], record[cln]) thread their captures into the
task, and state[bor] lends the outer binding to the scoped task: the owner
stays readable but is frozen — no mutation, no transfer — until the scope
joins its tasks. Borrowed captures require a clone-safe, thread-safe owner. Receiver-method call
syntax is not a named spawn-target form; use a free routine name or qualified
path instead.
The spawn boundary follows the V3 memory rules:
- clone-safe values clone into the task
- thread-safe move-only values, including
@ownership and unique pointers, move into the task and leave the sender moved-out - borrowed values cross only as explicit
[bor]captures of a scoped task, which freeze their owner until the scope joins ptr[shared, T]values do not cross the boundary because theirRcbacking is not thread-safe- unresolved generic parameters do not cross until FOL has a thread-safety and lifetime contract for generics; concrete thread-safe instantiations can cross
- omitted defaults are checked as task arguments under the same rules as explicit arguments
Cross-thread shared mutation belongs to mux[T] parameters, not Rc.
The exact positive and negative spawn examples are maintained in the canonical shipped processor inventory.
Channels
Channels are an implemented processor surface. The contract is an unbounded
MPSC chn[T] backed by Rust’s std::sync::mpsc — not FOL’s own std::sync,
which is the atomic-counter module: c[tx] sends without blocking,
c[rx] performs a blocking pull that yields opt[T] — its present branch owns
a fresh payload and nil means every sender has closed — and receiver iteration
runs until all sender handles are dropped. Unwrap the result with c[rx][] or
bind it and inspect it with when ... on ... *. The old sequence-index spelling
c[rx][i] is not part of the contract.
A send value | c[tx] produces a must-handle err[T]: nil means the payload
was delivered, and the present branch owns the unsent payload when every
receiver has already closed. Bind it (var sent: err[int] = value | c[tx]),
inspect it with when ... on ... *, or propagate it; a bare send that discards
the result — and with it the unsent payload — is rejected.
A transmitter is a first-class value. c[tx] has type chn[tx, T], a
clone-capable sender endpoint that may be bound, passed to another routine, or
returned. Sending works through any sender value — value | sender — not only a
direct c[tx] access, so a producer can accept a chn[tx, T] parameter and emit
into it. The receiver endpoint is also a first-class chn[rx, T] value, but
unlike the cloneable sender it is unique and move-only: it may be bound, passed,
or returned, yet never duplicated, so a channel keeps exactly one receiver.
T may be a thread-safe move-only value. Sending consumes that value, and a
blocking receive, receiver iteration, or selected arm transfers the payload to
its destination without cloning it; the blocking receive delivers it inside the
opt[T] shell. Unique pointers are supported this way; values containing
ptr[shared, T] remain barred from OS-thread boundaries.
The first c[rx] acquisition relinquishes that channel binding’s local
transmitter capability. Clone or capture every needed c[tx] handle before
receiving. Sender handles acquired earlier remain valid and the channel closes
when the last of those handles is dropped; trying to acquire c[tx] after the
receiver is active is an ownership error, not a runtime panic. This explicit
endpoint lifecycle lets pull loops and select observe closure without keeping
an invisible transmitter alive.
Channel endpoint acquisition is not allowed inside dfr or edf, including
endpoint captures on anonymous spawned routines in a deferred body. Acquire all
sender handles before entering the deferred block, and keep receiver operations
in ordinary control flow; delayed endpoint acquisition cannot be ordered safely
against the first receiver acquisition.
V3 endpoint access is restricted to a direct local, parameter, or capture
binding owned by the current routine. Projected channel fields, channel
container elements, and implicit references to an outer routine’s channel are
not part of the shipped lifecycle model; keep the channel in a direct binding
before using [tx], [rx], iteration, or select. Top-level/global channel
bindings are also rejected; a channel belongs to the routine that owns its
receiver.
Full chn[T] values also cannot be embedded in records, entries, containers,
or ownership/error/optional wrappers in V3. This keeps the single receiver and
its endpoint lifecycle attached to one direct routine-local binding. Sender
handles that were acquired earlier remain independently cloneable.
Anonymous routines cannot declare chn[T] parameters in V3 because they do not
participate in named-routine sender/receiver effect refinement. Use a named
routine, or capture an already-existing sender explicitly with c[tx].
Spawned anonymous routines can clone a transmitter explicitly with
[>]fun()[c[tx]] = { ... }. Receiver endpoints are not cloned: MPSC retains a
single consuming side.
The exact positive, ownership-boundary, lifecycle, and tier-failure channel examples are maintained in the canonical shipped processor inventory.
Select
The chosen multiplexing form is a multi-arm statement:
select {
when first as value { consume(value); }
when second as value { consume(value); }
};
The old single-channel select(channel as name) { ... } form is not retained.
The runtime polls arms in source order with try_recv(). Closed arms are
skipped and a blocking select completes, continuing after the statement, when
all arms are closed. An optional * arm runs immediately when no receiver is
ready. Simultaneously-ready arms therefore have source-order bias in V3; no
fairness guarantee is promised.
A blocking select without * must contain at least one channel arm.
select {} is invalid and is rejected during typecheck rather than being left
for lowering. A default-only select is non-blocking because its * body runs
immediately.
Mutex parameters
The mutex is the first-class managed type mux[T]. The direct handle surface
locks and unlocks through the handle itself:
pro[] update(value: mux[Counter]): int = {
value.lock();
value.total = value.total + 1;
var result: int = value.total;
value.unlock();
return result;
};
mux[T] lowers to Arc<Mutex<T>>. A routine acquires the guard with .lock();
guarded fields are accessible only while that guard is active. The guard is
released automatically at the end of the lexical scope that acquired it, or
early with .unlock() in that same scope. Locking the same parameter twice is
rejected, as is unlocking without a guard acquired in the current lexical
scope.
Mutex field access and .lock()/.unlock() are not allowed inside dfr or
edf bodies in V3. Guard transitions are tracked for immediate lexical
execution and are not replayed as delayed effects at scope exit. Forwarding a
mutex handle from a deferred body to another mux[T] routine is rejected for
the same reason.
The guarded T cannot be copied, returned, embedded, or passed to an ordinary
T parameter as a whole value. Passing the mutex handle directly to another
mux[T] parameter is allowed, including through spawn; data access still
requires that receiving routine to acquire its own guard.
Wrapping an existing owner into a mux[T] parameter transfers it into the
mutex and consumes the binding: the call site must state [mov]owner, and the
original binding is unusable afterward. An implicit copy at that boundary
would silently fork the state between the caller’s binding and the guarded
value, so it is rejected even for copy-safe types. Fresh values (record
literals or call results) pass without an operation — there is no surviving
source to fork.
For a synchronous call, the caller must unlock a handle before forwarding it
to another mux[T] parameter; otherwise the callee could block trying to acquire
the caller’s guard. One call also cannot pass the same handle to two mux[T]
parameters because those aliases can self-deadlock. Spawn and async calls are
task boundaries and may receive the cloned handle while the caller still holds
its guard; the new task waits until the caller releases it.
Guard values
Locking a borrowed handle produces a named, lifetime-scoped mutable guard
bound with var[mut, bor]. Field access goes through the guard while the lock
is held:
pro[] bump(state: mux[Counter]): int = {
var[mut, bor] guard: Counter = ([bor]state).lock();
guard.value = guard.value + 1;
var snapshot: int = guard.value;
[end]guard;
return snapshot;
};
The guard releases at its last use (the same non-lexical rule as ordinary
loans), or early and explicitly with [end]guard. A guard value cannot be
moved, copied, or cloned, and it cannot be held across a spawn, an await, or a
blocking receive — the checker rejects those boundaries rather than attempting
static deadlock analysis. End the guard first, then cross the boundary
(examples/proc_mutex_guard_end_m3 shows the early-end pattern;
examples/fail_proc_mutex_guard_await_m3 and
examples/fail_proc_mutex_guard_move_m3 pin the rejections).
The mux[T] calling convention is currently available only on named routines
that are called directly, through either unqualified or qualified names. A
named routine with mux[T] parameters cannot be stored or passed as a
first-class routine value, and anonymous routines cannot declare mux[T]
parameters. Those routine-value forms do not yet retain the mutex ABI metadata
needed to preserve Arc<Mutex<T>>; use a named direct call instead.
Despite this chapter’s historical filename, the shipped surface is OS-thread
tasks, channels, select, and mutexes—not resumable coroutines or generators.
Generator yield is parser-recognized but remains rejected by typecheck and
lowering in V3.
The exact positive, removed-syntax, deferred-effect, and tier-failure examples
for select and mutexes are maintained in the
canonical shipped processor inventory.
Proofs
Implemented (
plan/FINISHED/V5_PROOF.md).fol code checkandfol code buildcheck every theorem of a package and its dependencies with a kernel that implements Lean 4’s type theory. Every proof in this chapter is checked by the book audit.
FOL has a prover in the style of Lean. Propositions are types, proofs are terms,
tactics build terms, and a small kernel checks every term. fol code check
rejects a program whose proofs do not check and prints the goal that is left.
Proofs, propositions, and proof-only definitions are erased before lowering, so
they cost nothing at run time: a program emits byte-identical Rust with and
without them.
Three modes
| Mode | Declarations | Reaches the backend | May call |
|---|---|---|---|
| exec | fun, pro, log, typ, var, con | yes | exec only |
| ghost | fun[gho], typ[gho], log[gho] | no | ghost, and reflectable exec fun |
| proof | thm | no | ghost, and exec fun (reflected) |
Executable code that names a ghost or proof declaration is error V1001. Ghost and proof declarations are never compiled; they exist for the checker alone.
Declarations
A ghost type with constructor fields is an inductive type, and it may be
recursive because it has no memory layout. A ghost fun is total and
expression-bodied; recursion on a constructor field is structural, and any
other recursion takes a measure, fun[gho, dec = m]. A ghost log is an
inductive predicate whose clauses are its constructors, named by label =>.
typ[gho] lst(T): ent = {
con nil;
con cons(head: T, tail: lst[T]);
};
fun[gho] len(T)(xs: lst[T]): nat = when(xs) {
is nil -> 0;
is cons(_, tail) -> len(tail) + 1;
};
log[gho] even(n: nat) = {
zero => n == 0;
step => exi k: nat, n == k + 2 and even(k);
};
A theorem states a proposition and proves it:
thm[exp] even_four: even(4) = prf {
app even::step;
app even::step;
app even::zero;
};
Its generic parameters and value parameters are universally quantified. prp
is the sort of propositions, nat the unbounded naturals, and big the
unbounded integers; all three exist only in proofs. thm[axm] states a
proposition without proof; it is the only way to skip one, and fol code check
reports every theorem that rests on it.
A ghost body names other declarations by path, the prelude’s included, as a theorem statement does; a path that nothing declares is V1007:
fun[gho] magnitude(x: big): nat = big::nat_abs(x);
thm magnitude_neg: magnitude(-3) == 3 = prf { evl; };
Propositions
Propositions reuse the expression grammar and add three looser levels on top:
| Level, loosest first | Form | Associativity |
|---|---|---|
| binder | all x: T, P and exi x: T, P | the body extends as far right as possible |
| iff | P <-> Q | none |
| implication | P -> Q | right |
| the expression ladder | or, xor, and, not, comparisons, arithmetic | as today |
In a proposition == is equality at any type and != its negation. Source is
ASCII only; editors may render all as ∀, exi as ∃, and -> as →.
Tactics
A proof block prf { ... } is a list of tactic statements. Every tactic has
one shape, a name followed by optional options and arguments, and the names are
looked up in a registry rather than reserved, so app, fix, and gen stay
ordinary identifiers outside prf.
thm[exp] zero_add(n: nat): 0 + n == n = prf {
ind n {
is zero -> rfl;
is succ(k, ih) -> { rew nat::add_succ, ih; };
};
};
thm[exp] and_swap(p, q: prp): p and q -> q and p = prf {
fix h;
cas h { is intro(hp, hq) -> { ctr; qed hq; qed hp; }; };
};
In ind arms the hypothesis comes after the constructor fields. An argument
can also bind a name: hav h: P = t adds the proof t of P as h, hav h: P
opens P as a new goal first, gen x = e names a term, and
ind h, odd = fun(n: big): prp => ... gives the motive of another member of a
mutual block (see Logicals in proofs).
thm[exp] modus(p, q: prp): p -> (p -> q) -> q = prf {
fix hp, hpq;
hav hq: q = hpq(hp);
qed hq;
};
The set is three-letter throughout: fix (intro), qed (exact), app
(apply), rfl, rew (rewrite), unf (unfold), cas (cases), ind
(induction), ctr (constructor), lft, rgt, wit (exists), hav (have),
shw (show), exf (exfalso), abs (contradiction), asm (assumption), trv,
spc, gen, rvt, spl, and the automation tier smp (simp), lia
(linear arithmetic over nat, big, and int), evl (decide), and clc
(calc).
lia reasons over the integers, not only over the rationals. Before and during
its elimination it divides each constraint by the gcd of its coefficients and
rounds the constant toward feasibility, so an equality whose constant the gcd
does not divide is refuted at once, and parity and divisibility facts are in
reach:
thm no_half(n: nat): n + n != 1 = prf { lia; };
thm third(x: int): 3 * x == 6 -> x == 2 = prf { lia; };
It does not split on the values a variable can take, as the Omega test’s dark
and grey shadows do. A system with no integer solution that only such a split
shows is out of reach: 27 <= 11 * x + 13 * y, 11 * x + 13 * y <= 45,
9 * y <= 7 * x + 10, and 7 * x <= 9 * y + 4 over nat.
Calculation chains
clc proves a goal from a chain of steps a R1 b, b R2 c, ..., y Rn z, each
relation one of ==, <=, and < over nat, big, or int, where every
step starts where the one before it ends. The steps compose by transitivity: the
chain is < when any step is, <= when any step is an order, and ==
otherwise. A goal the chain implies without spelling it, such as a <= z from
a < chain, is closed by lia from the chain. Each step is justified by the
first of rfl, asm, lia, and smp that closes it:
thm le_chain(a, b, c, d: nat): a <= b -> b <= c -> c < d -> a < d = prf {
fix hab, hbc, hcd;
clc a <= b, b <= c, c < d;
};
thm int_chain(x, y: int): x <= y -> x < y + 2 = prf {
fix h;
clc x <= y, y < y + 2;
};
An arm names a step by its number, from 1, and justifies it with its own tactics; the other steps stay automatic:
thm by_steps(a, b, c: nat): a == b -> b <= c -> a <= c = prf {
fix hab, hbc;
clc a == b, b <= c {
is 1 -> qed hab;
is 2 -> { qed hbc; };
};
};
A step that nothing justifies is V1004 at that step, with its goal:
tactic `clc` failed in `gap`: no tactic among `rfl`, `asm`, `lia`, and `smp`
proves the step `b <= c`; justify it with an arm `is <step> -> { ... };`
a, b, c: nat
hab: a <= b
|- b <= c
Theorems about exec code
A theorem may name an exec fun. The checker reflects it from the same lowered
code the backend compiles, so the proof is about the program that ships. A call
has three outcomes: it returns, it reports an error, or it breaks (overflow,
division by zero, an index out of bounds, assert, panic). An atomic
proposition over calls says every call returns and the relation holds of the
results; .ret(f(x)), .brk(f(x)), and .rpt(f(x), e) state an outcome
directly.
fun[exp] half_sum(a, b: int): int = {
return (a + b) / 2;
};
thm half_sum_breaks: .brk(half_sum(9223372036854775807, 1)) = prf { evl; };
thm half_sum_le(a, b: int): 0 <= a and a <= b and b <= 1000000 -> half_sum(a, b) <= b = prf {
fix h;
unf half_sum;
lia;
};
The upper bound on b is needed: without it a + b can overflow, and
half_sum breaks instead of returning. In a proposition, arithmetic on int is
exact; only the reflected exec code is checked.
A loop in a reflected routine needs a termination measure into nat that
falls on every iteration, written loop[dec = m]. The measure is proof-only and
erased like every ghost; lia proves that it falls when the routine is
reflected, and the error shows the goal when it cannot.
fun[exp] count_up(n: int): int = {
var[mut] i: int = 0;
loop[dec = big::nat_abs(n - i)](i < n) {
i = i + 1;
};
return i;
};
thm count_three: count_up(3) == 3 = prf { evl; };
A reflected loop is also named in proofs, as count_up::loop0, so a property
of every input is proven by induction over the loop. The showcase
test/apps/showcases/proven_nums proves this way that std::nums::clamp_int
stays in range, that std::nums::sign_int matches the sign, and that
std::nums::gcd is never negative when its inputs’ .abs fit.
A routine that cannot be reflected (a pro, an effect, flt, recursion, a loop
without a measure) is error V1003 when a theorem names it. A receiver routine
is reflected like any other, with the receiver as its first parameter, so
x.m(y) in a proposition is the routine T::m of x’s type T.
Reflected values are bol, every integer width, chr, str, records, opt,
and vec, arr, and seq, which are lists. A width’s value is a big with
the width’s range as hypotheses, and its arithmetic breaks outside that range:
i8 from -128 to 127, u64 from 0 to 18446744073709551615, and
int[arch] and int[uarch] at the 64 bits of every certified target.
.widen reflects, and so does .narrow from a width int holds, which
reports the value as an int. In a proposition, arithmetic on every width is
exact.
fun[exp] add_bytes(a, b: i8): i8 = {
return a + b;
};
thm add_bytes_fits: add_bytes(100, 27) == 127 = prf { evl; };
thm add_bytes_breaks: .brk(add_bytes(100, 28)) = prf { evl; };
thm byte_range(a: u8): a <= 255 = prf { lia; };
A chr compares by its code point, which .chr_to_int reads, and .len of a
str counts its UTF-8 bytes, as the compiled program does. A block that several branches reach outside every loop
is reflected once and shared, so a reflected routine grows with its code, not
with its paths.
fun[exp] tally(word: str): int = {
if (word == "") {
return 0;
} else {
};
return .len(word);
};
thm tally_two: tally("ab") == 2 = prf { evl; };
Lawful standards
A standard may state laws: thm members about its required routines and the
conforming type, which a law calls self, the way the required routines
have an implicit receiver. Every type that claims the standard takes on each
law as a proof obligation. It proves the law with a receiver theorem,
thm (T)law, whose statement must be the law with self and the standard’s
parameters instantiated at T; a law may also carry a default proof, which
is checked at each type that writes none.
std ordered(T): pro = {
fun le(other: T): bol;
thm refl: self.le(self) = prf {
unf le;
lia;
};
thm total(b: T): self.le(b) or b.le(self);
};
typ Money()(ordered[Money]): rec = {
var cents: int;
};
fun (Money)le(other: Money): bol = {
return self.cents <= other.cents;
};
thm (Money)total(b: Money): self.le(b) or b.le(self) = prf {
unf le;
lia;
};
Each obligation ends as the kernel theorem Money::ordered::total, whose type
is the law at Money and whose value is the proof, so the kernel itself checks
that the proof states the law. Inside thm (Money)..., and in a default
proof, the names of Money’s receiver routines resolve directly, which is why
unf le works. A law that is false for the type fails its proof with the
goal, like any theorem.
A law with neither a receiver theorem nor a default proof is tried
automatically: first smp over the type’s routines the law names, then lia
with those routines unfolded. When neither closes it, the claim is V1008, and
the message names the tactics that were tried; a proof of a different
statement is V1008 as well.
std tallied: pro = {
fun tally(): int;
thm capped: self.tally() <= 9;
};
typ Vote()(tallied): rec = {
var yes: int;
};
fun (Vote)tally(): int = {
return 2;
};
A required routine may come with a default body in the standard. A type that
writes no routine of its own takes the default, and the prover reflects the
default body as that type’s routine, T::m, with the type’s value as its first
parameter, so laws and theorems read x.m() the same way for either.
When two standards a type claims state laws of the same name, thm (T)law
would be ambiguous, so each is proved by its qualified name thm (T)S::law.
The qualified name is accepted without a clash too.
std short: pro = {
fun width(): int;
thm fits: self.width() <= 10;
};
std rounded: pro = {
fun twice(): int;
thm fits: self.twice() % 2 == 0;
};
typ Label()(short, rounded): rec = {
var text: str;
};
fun (Label)width(): int = {
return 4;
};
fun (Label)twice(): int = {
return 8;
};
thm (Label)short::fits: self.width() <= 10 = prf {
unf width;
lia;
};
thm (Label)rounded::fits: self.twice() % 2 == 0 = prf {
unf twice;
evl;
};
A law may take generics of its own, thm order(U: ord)(a, b: U): ..., and
the receiver theorem that proves it declares the same generics.
A lawful standard bounds a theorem’s generic parameter like ord does.
T: S brings S’s required routines and laws into the theorem: x.m(..) on
a value of T is S’s routine, and the law S::law is a hypothesis about
T. A type whose every law is certified gets an instance of S, so the
theorem applies to it. A standard whose parameter is the conforming type
itself, as ordered(T) is when Money claims ordered[Money], bounds as
X: ordered[X].
thm le_self(X: ordered[X])(a: X): a.le(a) = prf {
qed ordered::refl(a);
};
thm money_le_self(m: Money): m.le(m) = prf {
qed le_self(m);
};
The built-in ord and eq are lawful. A T: ord bound carries the proofs
that <= is reflexive (ord::refl), antisymmetric (ord::antisymm),
transitive (ord::trans), and total (ord::total); a T: eq bound carries
the proofs that its boolean equality eqs::beq is reflexive, symmetric, and
transitive (eqs::refl, eqs::symm, eqs::trans). The laws are proven once,
for nat, big, every integer width, bol, chr, and str, and <= on
bol (false below true), chr (by code point), and str (lexicographic by
code point) uses them.
thm le_both(T: ord)(a, b: T): a <= b -> b <= a -> a == b = prf {
fix h1, h2;
qed ord::antisymm(a, b, h1, h2);
};
thm chr_total(a, b: chr): a <= b or b <= a = prf {
qed ord::total(a, b);
};
thm str_trans(a, b, c: str): a <= b -> b <= c -> a <= c = prf {
fix h1, h2;
qed ord::trans(a, b, c, h1, h2);
};
thm u16_total(a, b: u16): a <= b or b <= a = prf {
qed ord::total(a, b);
};
Generic types
A generic record is one kernel structure over its generics: typ Shelf(T) is
ns::Shelf, and Shelf[int] in a proposition is that structure at int. A
generic receiver routine, fun (Shelf[T])room(T)(), is reflected once for
every T at ns::Shelf::room, with the generics as its leading arguments, so
s.room() on a Shelf[int] is Shelf::room at int and unf Shelf::room
opens it. Each instance the program monomorphizes is also reflected from the
code the binary runs, at ns::Shelf[int]::room, its type arguments spelled as
FOL types (Pair[int, str], Shelf[vec[int]]). The kernel checks that the
instance is the generic routine at those arguments, so a reflected caller of
the instance reads as the generic routine and the same unf proves facts
about it.
A generic type that claims a lawful standard, typ Shelf(T)(S), proves each
law once for every T: with a receiver theorem over the generic receiver,
thm (Shelf[T])law(T)(..), which declares the type’s generics before the
law’s own (thm (Shelf[T])order(T; U: ord)(a, b: U)), by the law’s default
proof, or automatically.
The certificate Shelf::S::law is the law at Shelf[T] for every T, and
Shelf::S::inst is an instance of S at every Shelf[T], so a theorem
bounded by X: S applies at any instance. Each instance the program uses,
Shelf[int], also gets its certificates Shelf[int]::S::law and its
instance Shelf[int]::S::inst, built from the instance’s own routines. A law
that is false for the generic type fails its receiver theorem with the goal.
std roomy: pro = {
fun room(): int;
thm spare: self.room() >= 0;
};
typ Shelf(T)(roomy): rec = {
var top: T;
var slots: int;
};
fun (Shelf[T])room(T)(): int = {
if (self.slots < 0) {
return 0;
} else {
};
return self.slots;
};
thm (Shelf[T])spare(T)(): self.room() >= 0 = prf {
unf room;
lia;
};
thm room_spare(X: roomy)(s: X): s.room() >= 0 = prf {
qed roomy::spare(s);
};
thm shelf_room(s: Shelf[str]): s.room() >= 0 = prf {
qed room_spare(s);
};
fun shelf_slots(s: Shelf[int]): int = {
return s.room();
};
thm shelf_slots_exact(s: Shelf[int]): s.slots >= 0 -> shelf_slots(s) == s.slots = prf {
fix h;
unf shelf_slots, Shelf::room;
lia;
};
A generic receiver routine is reflected for every T only when its body
never needs an operation of its generic type: a routine that calls a bound’s
routine on a value of that type is reflected per instance only, and a
proposition that calls it is V1003. A generic parameter that no field
mentions does not tell two instances apart in the compiled program, so they
share one reflected instance.
Checking
fol code check and fol code build run the prover after lowering. Verdicts
are cached per declaration in .fol/build/proof/, keyed by a fingerprint of the
declaration and everything it mentions, including the reflected routines and,
transitively, the routines they call, so a changed callee proves its callers’
theorems again. Cache replay elaborates the source statement, matches its
declaration kind, universe parameters and kernel type, then kernel-checks the
cached proof. Malformed or mismatched entries fall back to the source proof.
Entries with auxiliary declarations also re-run the proof instead of importing
names that are not bound to a source declaration.
--recheck ignores the cache.
| Code | Meaning |
|---|---|
| V1001 | exec code names a ghost or proof declaration |
| V1002 | goals are left when the proof ends; they are printed in FOL syntax |
| V1003 | a named exec routine cannot be reflected, or a named exec logical has no rule program the prover can read |
| V1004 | a tactic failed; the goal before it is printed |
| V1005 | fuel ran out; raise one theorem’s limit with thm[lim = N] |
| V1006 | a ghost inductive is not strictly positive, or its universes do not fit |
| V1007 | a statement or definition is ill-formed |
| V1008 | a type claims a standard but does not prove one of its laws |
| V9001 | the kernel refused an elaborated term, which is a prover bug |
Each has a fol code explain entry with a failing and a fixed example. Limits
are step counts, never time, so the verdict is the same on every machine.
fol tool proof axioms <theorem> lists every axiom a theorem rests on,
fol tool proof show <routine> prints a routine’s reflected definition, and
fol tool proof goals <file>:<line>:<col> prints the goals in front of the
tactic at a position. The language server answers the same question through
the fol/goals request.
Logicals in proofs
fol code check mounts the checked rule program of every package in the
prover, dependencies first, so a theorem names a log or a con relation by
its path, an imported package’s included. A rule that reads a dependency’s
relation names the dependency’s own predicate, and evl takes that
relation’s tuples and closed world from the dependency’s program. A con
relation is decidable membership in its tuples. An executable log is an
inductive predicate: each clause is a constructor, named by its label or, when
it has none, c0, c1, … in order; the alternatives of a labelled clause
that or splits are <label>_1, <label>_2, … in source order. Its exi
variables and one proof per conjunct are the constructor’s arguments. Integer
columns are big in the prover, str columns are strings, and bol and
chr columns are booleans and characters.
evl decides a ground query in both directions. The logicals engine answers
it, and the answer becomes a term the kernel checks: a derivation becomes
constructor applications, and an absent tuple is refuted by a case split over
the finite closed world. The engine is never trusted, so a wrong answer can
make evl fail but cannot prove a false query.
con parent: rel[str, str] = { { "albert", "bob" }, { "bob", "carl" } };
log grandparent(g, c: str) = {
via => exi p: str, parent(g, p) and parent(p, c);
};
thm carl: grandparent("albert", "carl") = prf { evl; };
thm not_reverse: not grandparent("carl", "albert") = prf { evl; };
A relation parameter is a parameter of the predicate, so a theorem over it
holds for every fact base. cas takes a derivation apart clause by clause,
and ind is induction over the derivations of a recursive log:
log dating(likes: rel[str, str]; a, b: str) = {
duo => likes(a, b) and likes(b, a);
};
thm dating_sym(likes: rel[str, str]; a, b: str):
dating(likes, a, b) -> dating(likes, b, a) = prf {
fix h;
cas h { is duo(ab, ba) -> { ctr; qed ba; qed ab; }; };
};
log reach(edges: rel[int, int]; a, b: int) = {
base => edges(a, b);
step => exi m: int, edges(a, m) and reach(edges, m, b);
};
thm reach_trans(edges: rel[int, int]; a, b, c: big):
reach(edges, a, b) -> reach(edges, b, c) -> reach(edges, a, c) = prf {
fix h1, h2;
ind h1 {
is base(x, y, e) -> { qed reach::step(x, c, y, e, h2); };
is step(x, y, m, e, r, ih) -> { qed reach::step(x, c, m, e, ih(h2)); };
};
};
con edge: rel[int, int] = { { 1, 2 }, { 2, 3 }, { 3, 4 } };
thm one_four: reach(edge, 1, 4) = prf { evl; };
thm not_four_one: not reach(edge, 4, 1) = prf { evl; };
In the ind arms each constructor’s fields come first, then the induction
hypothesis for each recursive premise.
A labelled clause that or splits is one constructor per alternative, and
cas names each:
con road: rel[str, str] = { { "ur", "kish" } };
con ferry: rel[str, str] = { { "kish", "lagash" } };
log link(a, b: str) = {
way => road(a, b) or ferry(a, b);
};
thm link_is_a_way(a, b: str): link(a, b) -> road(a, b) or ferry(a, b) = prf {
fix h;
cas h {
is way_1(r) -> { lft; qed r; };
is way_2(f) -> { rgt; qed f; };
};
};
A relation literal can stand for a relation argument. It is an anonymous fact
table, built as a con relation is, so evl decides queries over it in both
directions. Its tuples are constants; a tuple that names a variable is V1007.
thm lit_reach: reach({ { 1, 2 }, { 2, 3 } }, 1, 3) = prf { evl; };
thm lit_not_reach: not reach({ { 1, 2 } }, 2, 1) = prf { evl; };
Rule sets that name each other form one mutual block. cas takes a member
apart clause by clause, as it does any log. ind on a member also proves a
property of every member the induction reaches, so it takes a motive for each
of them by name, a predicate over that member’s columns, and has an arm for
every clause of each. A bare constructor name is the major premise’s own;
another member’s constructor is named by its path. A member the motives leave
out is V1004, with the block and the motive it needs.
con rung: rel[int, int] = { { 0, 1 }, { 1, 2 }, { 2, 3 } };
con ground: rel[int] = { 0 };
log climb(n: int) = {
base => ground(n);
up => exi m: int, rung(m, n) and climb(m);
};
log even_rung(n: int) = {
base => ground(n);
up => exi m: int, rung(m, n) and odd_rung(m);
};
log odd_rung(n: int) = {
up => exi m: int, rung(m, n) and even_rung(m);
};
thm odd_steps(n: big): odd_rung(n) -> exi m: big, rung(m, n) = prf {
fix h;
cas h { is up(k, m, r, e) -> { wit m; }; };
};
thm even_climbs(n: big): even_rung(n) -> climb(n) = prf {
fix h;
ind h, odd_rung = fun(k: big): prp => climb(k) {
is base(k, g) -> { qed climb::base(k, g); };
is up(k, m, r, o, ih) -> { qed climb::up(k, m, r, ih); };
is odd_rung::up(k, m, r, e, ih) -> { qed climb::up(k, m, r, ih); };
};
};
A clause may call an exec fun. The prover reflects it from the lowered code,
as for any theorem that names it, and models the call as the value it returns
where it returns; where it breaks, the comparison is false. The compiled query
reads the call the same way, in every build profile, so a theorem about the
relation holds of every run. The engine evaluates the same reflected
definition, and the kernel re-checks every answer:
fun[exp] triple(n: int): int = {
return n * 3;
};
con seeds: rel[int] = { 1, 2 };
log tripled(n, m: int) = {
seeds(n) and m == triple(n);
};
thm two_six: tripled(2, 6) = prf { evl; };
thm not_two_five: not tripled(2, 5) = prf { evl; };
A fun that returns opt[T] is modelled at T: the value where it returns
one, and a false comparison where it returns nil, as in the compiled query.
fun[exp] third_of(n: int): opt[int] = {
if (n % 3 == 0) {
return n / 3;
};
return nil;
};
con counts: rel[int] = { 3, 4 };
log thirds(n, m: int) = {
counts(n) and m == third_of(n);
};
thm three_one: thirds(3, 1) = prf { evl; };
thm four_none: not thirds(4, 1) and not thirds(4, 0) = prf { evl; };
What the bridge does not cover:
- a clause cannot call a
funthat is not reflectable; it is V1003 with the reason; indon a member of a mutual block does not infer the motives of the members it reaches, and each is given by name;- the engine reads a relation literal at the column types of the parameter it
is passed to, so a value outside them makes
evlfail.
The showcase test/apps/showcases/proven_logic proves ground queries over a
family tree, a negated rule, reachability with transitivity for every edge
relation, and a clause that calls exec code.
What is trusted
Only the kernel, and the one translator that reflects lowered exec code into
the logic, which a differential harness checks against the compiled program:
on the same inputs, the outcome and the value returned or reported must be
equal. The elaborator, the tactics, and the automation can fail to find a
proof but can never admit a false one, because every theorem ends as a term the
kernel checks. There is no way to leave a hole: the only skip is thm[axm],
which is always reported.
Interop Toolchain Boundary
FOL exports a real C ABI and imports real C libraries. A C program links a FOL
static or shared library and calls it through a generated header; a FOL package
calls a C provider through a manifest that fol tool bind c wrote from that
provider’s own header and archive. Both directions are proven by lanes in
make verify that compile and run the result, not by reading generated text.
What crosses each way is listed under What crosses, together with what is refused. The exclusions are as load-bearing as the inclusions: FOL rejects a construct it cannot model rather than approximating it.
FOL integrates three independently usable sibling crates and does not copy their native semantics:
build.fol executable + one C header/object import
-> PARC CompleteSourcePackage
-> LINC ValidatedLinkAnalysis
-> GERC GenerationBundle
-> fol-build generated-file action graph
-> fol-backend auxiliary Rust crates and exact rustc arguments
-> linked and executed FOL binary
The stages have fixed ownership:
- PARC is the only C preprocessor, parser, recovery engine, source extractor, provenance store, and source-contract owner.
- LINC is the only native artifact inspector, compiler/ABI probe runner, symbol/provider validator, and ordered link-evidence owner.
- GERC is the only closed-world raw Rust FFI projector and emitter.
- FOL owns language policy, target and build-graph routing, generated-file materialization, the narrow H7 call anchor, backend process invocation, diagnostics, and eventual safe language wrappers.
The handoff is typed. FOL does not use JSON shape conversion, copied sibling
models, a second provider resolver, a second raw extern "C" emitter, shell
splitting, or text link-argument parsing. GERC’s typed link atoms remain
individual native process arguments when they reach rustc.
Pinned inputs
lang/tooling/fol-interop/Cargo.toml is the machine authority: each component
is pinned there by git revision, and Cargo.lock records what cargo resolved
from those pins. H7 is certified against this exact snapshot:
| Stage | Package | Contract | Pinned revision |
|---|---|---|---|
| PARC | follang-parc 0.16.0 | source package schema 2 | 97a2dee3453219f928738a1e7f96aad830909e17 |
| LINC | follang-linc 0.1.0 with native-inspection | link-analysis schema 2 | 1a925fa07ce32a6cffa6814ddedafebebf1f22dc |
| GERC | follang-gerc 0.1.0 with pipeline-native | generation domain 1 | fedd86e77358a54cf2b72815dc69efc8305d72b0 |
Reading the host’s own system headers
By default the search inputs are exactly what the author wrote: §4.13 disables
ambient CPATH/SDK discovery, so a scan cannot quietly depend on the machine.
That is also why a header including <stdio.h> does not read – not because
the file is missing, but because stdint.h is written against the compiler’s
predefined macros (__INT8_TYPE__ and some four hundred others) and nothing
else supplies them.
--host-system-headers asks the C compiler for its own include roots and
predefines and expands them into explicit roots and defines before the scan
runs. The scan keeps its rule, the manifest records every root and macro, and
the fingerprint covers them – so two machines whose compilers disagree produce
visibly different identities rather than the same identity over different
headers. The author’s own --defines are written last and are never displaced.
It is off by default because it trades hermeticity for reach, and that trade should be a decision rather than a default.
A build.fol asks for the same thing with system_headers = "host" on its
add_c_import record, and reaches the same expansion – so a header that binds
by hand also builds from the graph. Any other value is refused rather than
ignored: a declaration nobody reads is one the author believes is in force.
The three components are git dependencies pinned by revision, not sibling path dependencies, so a fresh clone of this repository builds and tests without any of them checked out. A pinned revision is content-binding, which makes provenance a build-time property rather than something to re-observe at run time:
fol-interop/build.rsreads the resolved revisions back out ofCargo.lockand hands them to the crate, so the recorded provenance is whatever cargo actually built against.- compile-time assertions in
fol-interop/src/lib.rsprove those crates still expose the expected contract versions. - each component pins the components below it at these same revisions, because
two different
follang-parcrevisions in one graph would produce two incompatible sets of contract types — cargo resolves them as separate crates and every shared type stops matching.
tools/verify-interop-lock.sh checks that nothing loosens a pin to a branch or
a path, that no [patch] entry substitutes a component, and that this table
still quotes the revisions in force.
The earlier design shelled out to git at run time to check each sibling
checkout’s root, HEAD, worktree cleanliness, and origin. That could only pass
inside a source tree — a released binary carried the build machine’s paths — so
it verified nothing for users.
A provider’s own dependencies
Almost every shared library on Linux needs another one: libexpat.so carries a
DT_NEEDED on libm.so.6 and libc.so.6, and those carry more. The resolver
satisfies each one from the artifacts it was handed, so they have to be handed
to it:
app.add_c_import({
alias = "xp",
header = header,
provider = provider,
provider_kind = "shared",
annotations = overlay,
provider_dependencies = {
"/nix/store/.../lib/libm.so.6",
"/nix/store/.../lib/libc.so.6",
"/nix/store/.../lib/ld-linux-x86-64.so.2",
},
});
fol tool bind c takes the same thing as a repeatable --provider-dependency.
Each one is an exact path, and that is the whole distinction from
library_paths, which is refused. A search path asks the resolver to go
looking, and the certified analysis profile resolves exact paths only —
refusing it is what keeps the answer reproducible rather than dependent on what
happened to be installed. Naming the artifact is the opposite: it is precisely
the kind of input that profile accepts, and the build states it once.
The dependencies are digested into the manifest beside the provider, for the same reason the provider is: a swapped one decides what code actually runs, and a path alone would go on looking current.
This says nothing about the runtime loader. A shared provider still has to be
findable when the program starts, which is LD_LIBRARY_PATH, an RPATH, or an
installed library — the same as for any program that links one.
Certified platforms
Two lanes are promoted:
x86_64-unknown-linux-gnu ELF, LP64
x86_64-unknown-linux-musl ELF, LP64
explicit GCC or clang executable and observed compiler identity
one executable artifact with one C object provider
glibc and musl are the same System V AMD64 ABI — only the libc differs — and LINC measures every layout by compiling probes with the caller’s own compiler rather than modelling it, so the same evidence certifies both. Each lane has its own link-and-run smoke; neither stands in for the other.
The caller supplies normalized absolute paths for the compiler and the bounded LINC probe workspace. LINC observes and fingerprints the compiler rather than FOL guessing its identity, and accepts the GCC and clang families. The selected FOL target must equal every sibling target fingerprint before generated files or backend compilation are allowed.
Other Linux architectures, Apple targets, Windows targets, frameworks, import libraries, and multiple imports per artifact remain uncertified.
What crosses
The two directions are not symmetric, and the asymmetry is real rather than an
accident of what has been tested. Everything below is exercised by a lane in
make verify that compiles and runs it; nothing is listed on the strength of
the code appearing to support it.
Exporting, FOL to C — a C program links a FOL library and calls it:
| Shape | Crosses as |
|---|---|
integers int[8..64], unsigned, flt[32]/flt[64] | the exact-width C scalar |
bol | fol_bool_t (uint8_t); only 0 and 1 are valid, and imports validate |
chr | fol_char_t (uint32_t); validated as a Unicode scalar value |
| records | a C struct whose layout C agrees with, field order preserved |
| entries | a C enum with the discriminants the variants state |
| resources | an opaque fol_<domain>_t * token, released by a paired destroy; a second destroy, a use after destroy, or a pointer the library never produced is refused with FOL_STATUS_INVALID_ARGUMENT, and a handle C never releases shows up as a leak under LeakSanitizer |
| a routine parameter | a C function pointer plus its own void * context |
| recoverable errors | fol_status_t plus a typed error out-parameter |
| a FOL panic | contained and reported as FOL_STATUS_PANIC |
| borrowed text, inbound | fol_str_view_t, caller-owned and call-scoped |
Importing, C to FOL — FOL calls a C provider through a checked manifest:
| Shape | Crosses as |
|---|---|
scalars, including through typedef chains | the measured FOL scalar |
| named structs and enums, as parameters | a FOL record, and the enum’s measured storage scalar |
a C enum’s enumerators (enum color { RED, GREEN = 4 }) | constants of the import (prb::GREEN), typed at that scalar; a value naming no enumerator crosses unchanged |
| a struct the provider fills through a pointer | a FOL record passed as a mutable loan, its writes landing in FOL’s value |
a derived struct where C declares its base (uv_close(uv_handle_t *) handed a timer) | upcast / upcast_from: the derived record, accepted once its fields are checked to begin with every field of the base |
a tagged union behind a pointer (SDL_Event *) | a FOL record whose one named field is the tag, the rest opaque cells at the union’s size and alignment |
a record aligned past its fields (aligned(64), even under #pragma pack) | a FOL record whose struct carries the same alignment, built with {} when no field is worth naming |
| pointers and out-parameters | a FOL value on the success channel |
| a pointer/length pair | one borrowed FOL vector, its length derived |
| several pointer/length pairs in one routine | buffer = ["out", "in"] with buffer_length in the same order: each pair its own borrowed FOL vector |
a list of handles with its count (const git_commit *parents[]) | a buffer whose elements are a domain’s handles: a borrowed vec[D[bor]] of loans, crossing as an array of their addresses |
an output buffer whose written count comes back through a pointer (EVP_DigestFinal_ex), or whose count carries the room in and back under a status (zlib’s compress) | written_buffer / written_length / written_capacity (and written_length_in = "capacity"): a mutable loan of a FOL vector with at least the declared room, shortened to what the provider wrote |
| a provider-allocated buffer | a FOL vector, copied and released in the call |
| status codes | FOL’s ordinary or recoverable channel, per the overlay |
| opaque handles | a lin linear resource with a paired destroy routine |
a handle’s public fields (face->num_glyphs, face->glyph->outline) | fields on the domain: one getter per field through a borrowed handle – a scalar copied out, a pointer or embedded record handed back as a borrow-only domain’s handle |
| one synchronous callback shape | a FOL closure invoked by the provider |
a callback whose first and last parameters both have the context’s type (GLib’s GFunc) | callback_context_slot = "first" or "last": refused without it, because the type cannot say which end is the context; a context typed as something other than void * is handed to the provider at its own pointee type |
| a callback the provider keeps | a FOL closure owned by the handle that keeps it (callback_kept_by) |
a callback kept by a record the caller owns (uv_timer_t) | callback_kept_by naming a record parameter: the record’s address is the key, handed back as the callback’s first argument, and the closure is released after the routine the overlay names with releases_kept |
| a kept callback found by its keeper | callback_context = "keeper": the closure receives the keeping handle, borrowed |
| a kept callback found through user data | context_setter on the handle domain: FOL owns the slot and installs the keeper there |
| text inside a callback signature | callback_strings: a const char * position reaches the closure as its own str |
| a list of text inside a callback signature | callback_string_lists: a NULL-terminated const char ** position reaches the closure as its own vec[str] |
| several callbacks installed by one call | callback = ["start", "end"]: each gets its own trampoline; the context, keeper, and text positions are shared |
a struct of callbacks the caller fills (FT_Outline_Funcs) | callback_table naming the struct parameter: one FOL closure per named field, the struct built by the adapter with its other scalar fields zero |
Both directions now carry named aggregates, opaque handles, and the one callback shape. What is still refused, rather than approximated:
- Importing a self-referential struct’s pointed-to type. The pointer crosses as an opaque handle; the shape behind it does not.
- A struct field that is a pointer at something FOL cannot read – an
incomplete type, or a function pointer – crosses as an address token: the
record carries it at its offset, and FOL hands it back without reading it.
lua_Debug’s privateCallInfo *andsqlite3_vfs’s method pointers are the shape. - Variadics, bitfields, records
#pragma packorpackedactually narrows, flexible-array members, unions by value or without a lone scalar tag, C++ linkage, and unknown calling conventions. - A function pointer as a parameter: the adapter could hand the provider an
address only by reinterpreting it as a signature it was not built with. The
one reinterpretation this tree performs is narrower: a callback trampoline
whose context slot is
*mut c_voidhanded to a provider that declares that slot at another pointee type, which Rust’s ABI rules make the same call. As a result or a struct field it crosses as an address token FOL carries and never calls –Option<fn>casts to a raw pointer withas, which the parameter direction cannot do. - Adopting a provider’s allocation rather than copying it: FOL’s allocator did not make it and must not free it.
- Raw pointers in an ordinary export: a raw pointer with no declared ownership and destroy pairing is refused, not defaulted.
- An opaque handle inside a callback’s signature. A declared domain is read
for a routine’s own parameters and result, but not for the parameters and
result of a callback it takes, so a callback returning
Widget *is refused as incomplete while the sameWidget *binds as the routine’s own result. A callback returning a scalar beside it binds.
Evidence and failure policy
The required smoke test starts from the real build.fol graph route. It
compiles a C provider object, scans its header through PARC, certifies the
provider through LINC, projects raw Rust through GERC, materializes the raw and
FOL-owned anchor crates through fol-build, passes exact ordered link
arguments to fol-backend, and runs the linked executable. Its reported
evidence contains:
- the three locked sibling revisions;
- source, target, link-analysis, generation, and provider fingerprints;
- the exact certified target.
The checked build separately retains the exact generated raw-binding and anchor crate roots passed to the backend. The system test inspects the fixed anchor source, builds both crates, executes the final binary, and verifies the provider’s per-run return value.
Required negative cases prove that partial PARC source, unresolved LINC
providers, and GERC generation rejection stop before generated/backend files
are written. Target mismatch is rejected before compiler or output-directory
I/O. A skipped system test is not success: the required Make target sets
FOL_H7_REQUIRED=1 and supplies an explicit canonical GCC path.
The annotation overlay
C cannot say which of its declarations FOL may call, what a return code means, or who releases a pointer. The overlay is where a header author states those facts explicitly; the compiler never guesses them. It is a strict subset of TOML, and every key it does not recognize is refused rather than ignored.
version = 1
[routine.c_math_add_one]
error = "infallible"
[routine.c_math_checked_div]
error = "status"
status_ok = [0]
status_error = [1, 2]
out = "result"
effects = ["allocates"]
error admits exactly two conventions. errno, a last-error slot, an
undocumented sentinel, unwind, and longjmp are each refused by name, with
the reason, rather than falling through to “unknown value”: a convention FOL
cannot check is one FOL will get wrong.
Handle domains
A pointer to an incomplete type is C’s opaque handle, and the pointer itself carries no ownership information at all. A domain declares one:
[handle.Widget]
destroy = "widget_free"
[routine.widget_new]
error = "infallible"
handle = "Widget"
handle_role = "produces"
[routine.widget_size]
error = "infallible"
handle = "Widget"
handle_role = "borrows"
[routine.widget_free]
error = "infallible"
handle = "Widget"
handle_role = "consumes"
The role is per routine, not per type, because the same Widget * is produced
by one call, lent to many, and released by one. A producer’s handle is its
result; a borrower’s or consumer’s is its single pointer parameter, and a
routine with more than one pointer parameter is refused rather than having its
handle chosen by position.
A producer that reports a status instead of returning the handle writes it through an out-parameter, which is how most C libraries actually spell it:
int sqlite3_open(const char *filename, sqlite3 **ppDb);
That needs no extra key. error = "status" must already name its out
parameter, so that parameter is where the handle is taken from, and it must be
a pointer to the handle – a single pointer would be the handle itself, which
is what borrowing looks like. FOL never passes it: the adapter owns the
storage, and reads it only for a status the overlay called success.
examples/v4_c_sqlite is the whole path against a real database.
A routine that touches more than one domain names the extra ones. A
statement is prepared from a connection, so sqlite3_prepare_v2 is handed one
handle and produces another; libgit2 spells nearly its whole API that way:
int st_make(DB *db, ST **out);
[routine.st_make]
error = "status"
status_ok = [0]
out = "out"
handle = "ST"
handle_role = "produces"
handle_borrows = ["db"]
Only the parameters are named, never their domains. Which domain a pointer belongs to was measured from the header – a domain’s record is the pointee of its own destroy – so restating it would be a second spelling that could disagree with the first. What cannot be measured, and so is declared, is that the pointer is a handle at all rather than a struct FOL should read through. A parameter named here that is not a pointer to some domain’s record is refused, not guessed: the author has said “handle” about something that is not one, and treating it as an address anyway is how a destroy reaches the wrong thing.
Every handle named this way is borrowed. A routine may consume at most one,
and that one is the handle_role = "consumes" handle, so a release always has
exactly one place to look.
The domain is the identity. It becomes a distinct ABI type, so a handle
from one provider can never reach another provider’s destroy — that is a type
error rather than a runtime hazard. Four ways of making the identity incoherent
are refused: a domain whose destroy is not a selected routine, a destroy that
does not declare itself the consumer, a second consumer of one domain, and a
routine naming a domain no [handle.<Name>] table declares.
Which routine owes the release is part of the interface fingerprint, so
changing borrows to consumes invalidates every caller.
On the FOL side a handle is a linear resource:
consumed exactly once, explicitly, on every path. The domain becomes a FOL type
in the import’s namespace, so a program writes wid::Widget and the compiler
proves the release. examples/v4_c_opaque_handle is the whole path, and the
four examples/fail_v4_c_handle_* packages are the misuses C would compile.
A handle’s public fields
Some handles are not opaque at all: FreeType’s FT_Face points at a record
whose num_glyphs and glyph a program is meant to read. A domain lists them,
and names its record so the scan asks for the definition:
[handle.FT_Face]
destroy = "FT_Done_Face"
record = "FT_FaceRec_"
fields = ["num_glyphs", "glyph"]
[handle.FT_GlyphSlot]
record = "FT_GlyphSlotRec_"
fields = ["outline"]
Each field becomes a routine named <domain>_<field> that borrows the handle
and reads the field, with no provider call behind it:
var glyphs: i64 = ft::FT_Face_num_glyphs([bor]face);
var slot: ft::FT_GlyphSlot = ft::FT_Face_glyph([bor]face);
var outline: ft::FT_Outline = ft::FT_GlyphSlot_outline([bor]slot);
A scalar field is copied out. A pointer to another domain’s record is handed
back as that domain’s handle, and an embedded record as a handle to its
address – but only for a borrow-only domain: what a record points at is the
provider’s to free, so a domain with a destroy is refused as a field’s type. A
field that is neither a scalar nor such a record has no value FOL could copy,
and is refused too. See examples/v4_c_handle_fields.
A struct the provider fills in
stat(path, &st) is the shape: the caller supplies the storage and C writes
into it. It reaches FOL through the status convention, because that is what
says when the writes are worth reading:
int probe(int32_t v, struct S *out);
[routine.probe]
error = "status"
status_ok = [0]
status_error = [1]
out = "out"
The record comes back as FOL’s own value. The call site hands over the address of its own storage — FOL’s struct has the provider’s layout, checked at compile time — and the provider writes through it. The value is taken only on a code the overlay called success; on any other code it is discarded, because an unenumerated status means the provider did not say it wrote anything.
A record crosses by address, in every direction. FOL’s struct for an
imported record is emitted #[repr(C)] with its fields in the header’s
declaration order, so the address of FOL’s own value is an address of the
provider’s struct: an argument is passed as that address, an out-parameter is
written through it, and a value returned by C is written into storage the call
site owns. Nothing is copied field by field, nothing is rebuilt, and the
adapter never names FOL’s type.
A mutable struct T * is an out-parameter the provider writes through: the
routine gets a [mut, bor] of a FOL value, and the writes land in it – the
shape stat and lua_getinfo use. An imported record whose field FOL cannot
spell – an opaque pointer, a wide char array – is built with a partial
initializer: FOL names the fields it can, and the rest default, because the
value exists to be filled. When no field is worth naming, the initializer is
empty – {} – and every field defaults. This relaxation is
imported-record-only; FOL’s own records still require every field. See
examples/v4_c_out_record.
A derived struct where C declares its base
libuv declares uv_close(uv_handle_t *), and every handle type begins with the
same UV_HANDLE_FIELDS, so C code casts: uv_close((uv_handle_t *)&timer, cb).
The overlay says which record a parameter accepts instead:
[routine.uv_close]
error = "infallible"
upcast = ["handle"]
upcast_from = ["uv_timer_t"]
The bind checks that the derived record begins with every field of the base, by
name, offset, and size, and refuses it otherwise; the parameter then takes the
derived record, and the adapter hands C the same address typed as its base. See
examples/v4_c_record_upcast.
A state aligned past its fields
libsodium’s streaming hash takes a crypto_generichash_state the caller owns:
#pragma pack(push, 1)
typedef struct __attribute__((aligned(64))) state { unsigned char opaque[384]; } state;
#pragma pack(pop)
The aligned(64) raises the record’s alignment past anything its bytes need
and pads its size to a multiple of it, and the provider may rely on that
alignment for every address it is handed. FOL’s struct for the record carries
the same alignment – #[repr(C, align(64))] – so any value FOL owns is one
the provider accepts, and the size and alignment assertions above still compare
it with the provider’s own struct. #pragma pack is kept too: a record defined
under it is measured under it, and packing that narrows nothing – a byte array
– binds as ordinary layout. One that does narrow a field is refused, because
FOL reads fields by address and a packed field has none that is aligned.
var state: dg::digest_state = {};
var started: i32 = dg::digest_init([mut, bor]state);
See examples/v4_c_aligned_state, whose provider refuses any state not 64-byte
aligned.
That is a promise about layout, and it is checked rather than argued. The
adapter re-exports the provider’s own struct, and the generated crate asserts
its twin against it at compile time — size, alignment, and the offset of every
field. Size and alignment alone would pass two structs whose fields were merely
reordered, which is exactly the silent transposition this boundary produced
once before; offset_of! per field is the check that cannot. A layout that
drifted would fail the build naming the field, not hand C a wrong answer.
The declaration order is the part FOL’s type system does not keep — a checked record keys its fields by name — so it is carried down from the header separately, for imported records only. FOL’s own records stay Rust’s to lay out.
A field that is itself a struct needs nothing more: it is inline at its
offset, with the same guarantee one level down. A field that is a fixed
array needs nothing more either — char name[256] is 256 elements inline,
which is what FOL’s arr[chr, 256] is — and this is the reason the address
route was worth building: no flattening could have carried it.
An anonymous member is still refused, for a different reason. C makes its
fields part of the outer struct, so o.x is valid there, while the projection
puts them behind a generated name that is a content hash: FOL’s view of the
struct would not be C’s, and the name is not one a program could write. Give the
member a name, or lift it into a named struct.
An array parameter is refused as before: it decays to a pointer whose length C does not carry, and that is a different shape from an array inside a record.
Slots FOL does not pass
C carries parameters its own documentation tells callers to leave null:
optional out-parameters nobody wants the answer from, reserved slots kept for a
future version. sqlite3_prepare_v2 has one – pzTail is where the unused
tail of the SQL would go, and there is none when the string holds one
statement.
[routine.sqlite3_prepare_v2]
pass_null = ["pzTail"]
The parameter leaves FOL’s signature entirely. The adapter passes a null typed by the provider’s own declaration, which is the only place the pointee is named. Only a pointer may be declared this way – nothing else has a null a provider would recognise – and it is part of the interface, so adding or removing one invalidates every caller, exactly as unpairing a buffer does.
This is not a way to skip a parameter FOL cannot yet spell. It says the provider is being given nothing, and the provider has to be one that accepts nothing there.
Text coming back
A returned const char * is how every C library reports what went wrong:
sqlite3_errmsg, lua_tostring, curl_easy_strerror, git_error_last.
[routine.sqlite3_errmsg]
error = "infallible"
string_result = true
handle = "sqlite3"
handle_role = "borrows"
It is declared for the same reason a string parameter is: const char * is
how C spells text and equally how it spells a pointer to one byte, so nothing
measured tells them apart, and a declaration the header cannot bear – a result
that is not a pointer to characters – is refused rather than believed.
The difference from a parameter is ownership, and it is why this is a
distinct type rather than the same one read by position. A parameter is lent to
the provider for the length of one call. A result points into memory the
provider owns and may reuse the moment you call it again – SQLite documents
exactly that for sqlite3_errmsg – so lending it to FOL would be lending
something with no lifetime to bound it. FOL is handed a copy instead, made
before the call returns, and the question never arises. That is also why
sqlite3_libversion, whose string is static and immortal, needs no second
rule: copying makes the two lifetimes indistinguishable.
Two decisions the copy forces, both taken where C leaves them open. A NULL result is the empty string, the same reading a produced buffer gives it. And the bytes are decoded lossily, because C guarantees no encoding at all and one bad byte in an error message is not a reason to end a process.
Buffers
C carries a buffer as two parameters with nothing joining them:
checksum(const uint8_t *bytes, size_t count) could as easily be a pointer and
an unrelated tally. The overlay pairs them:
[routine.digest_sum]
error = "infallible"
buffer = "bytes"
buffer_length = "count"
reads = ["bytes"]
count then stops being a FOL parameter. The length is derived from the
value FOL passes, so there is no second number a caller can get wrong and no
way to describe a buffer longer than the one that exists. On FOL’s side it is a
borrowed vector – bor[vec[u8]] when the provider only reads, a mutable loan
when it writes.
A list of handles is a buffer whose elements point at a declared domain’s
record – git_commit_create(..., size_t parent_count, const git_commit *parents[]). The same two keys pair it, and on FOL’s side it is a vector of
loans, so each handle stays with the binding that owns it and is released
there:
var parents: vec[g::git_commit[bor]] = {[bor]parent};
var created: i32 = g::git_commit_create([mut, bor]made, [bor]repo, [bor]who,
[bor]who, [bor]message, [bor]tree, [bor]parents);
The call site builds an array of the handles’ addresses for the call and drops
it after; the provider only reads it. See examples/v4_c_handle_array.
A written buffer has no length going in, only a count coming out –
EVP_DigestFinal_ex(ctx, unsigned char *md, unsigned int *s) writes up to
EVP_MAX_MD_SIZE bytes and says through s how many. The overlay names the
buffer, the pointer the count returns through, and the room the provider needs:
[routine.EVP_DigestFinal_ex]
error = "infallible"
handle_borrows = ["ctx"]
written_buffer = "md"
written_length = "s"
written_capacity = 64
The caller passes a mutable loan of a vector with at least that much room; a
shorter one is refused before the call, since C would write past its end. The
adapter owns the count, refuses a report larger than the vector, and the vector
comes back shortened to exactly what was written. See
examples/v4_c_written_buffer.
When the count also carries the room in, as zlib’s
compress(Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
does, written_length_in = "capacity" starts the count at the vector’s length.
A written buffer may sit under a status convention; its out is then the
count, and the count is the success value:
[routine.compress]
error = "status"
status_ok = [0]
status_error = [-2, -4, -5]
out = "destLen"
written_buffer = "dest"
written_length = "destLen"
written_length_in = "capacity"
written_capacity = 1
buffer = "source"
buffer_length = "sourceLen"
var packed_length: u64 = zz::compress([mut, bor]packed, [bor]data) || 0;
The vector is shortened to the count only on a success status; on a failure it
comes back empty, because nothing the provider wrote may be read. See
examples/v4_c_zlib.
Direction is declared, not read off constness. reads, writes, and
reads_writes name the parameters they apply to. Constness stays the default,
but it is a poor witness: void *base in qsort is read and written, char *dst in strcpy is only written, and a mutable pointer a provider never
writes looks like either. A declaration C contradicts – writes on a const
pointee, or any direction on a by-value parameter – is refused.
An owned buffer is memory the provider allocated, and it gets a domain and a release, exactly like a handle:
[buffer.Bytes]
destroy = "digest_release"
[routine.digest_take]
error = "infallible"
buffer_domain = "Bytes"
buffer_role = "produces"
buffer_length = "out_len"
buffer_capacity = "out_capacity"
[routine.digest_release]
error = "infallible"
buffer_domain = "Bytes"
buffer_role = "consumes"
buffer_length = "count"
FOL never adopts that memory. Its allocator did not make the allocation and must not free it, so the adapter validates the report, copies out of it, and calls the release before returning. What FOL holds afterwards is its own vector pointing nowhere near the provider’s heap, and the destroy is not mountable: there is nothing left for a program to release, and no address to release it with.
Two ways a provider can contradict itself are refused rather than read: a null address with a nonzero length, which describes memory that does not exist, and a length past the capacity it reported, which describes memory it did not allocate. Copying on either reads whatever happened to be there. The capacity is what makes the second checkable – a length on its own is unfalsifiable.
The domain gets the same four cross-checks a handle domain does: a destroy that
is not a selected routine, a destroy that does not declare itself the consumer,
a domain with no producer or more than one, and a routine naming a domain no
[buffer.<Name>] table declares.
examples/v4_c_buffer runs all three shapes and asks the provider how many
allocations are outstanding afterwards – the answer is 0, and FOL cannot see
C’s heap any other way. examples/fail_v4_c_buffer_capacity and
fail_v4_c_buffer_null are the two contradictions.
C enums
A C enum crosses as the integer the provider’s compiler stores it in. That
storage is measured, not read off the spelling: GCC stores
enum color { RED, GREEN = 4, BLUE = 9 } as u32 because no enumerator is
negative, and an enum with a negative enumerator as i32. The enumerators are
constants of the import, so FOL code names them instead of writing their
numbers:
enum color { RED, GREEN = 4, BLUE = 9 };
int32_t paint(enum color c);
var painted: i32 = prb::paint(prb::GREEN);
prb::GREEN is a u32 holding 4, the type paint declares for its
parameter. Each value is the one the provider’s compiler measured – GERC
refuses an enumerator whose written value disagrees with the measurement – and
the manifest records it under constants, so a changed value moves the
interface fingerprint and a build against the old manifest is refused as stale.
A constant is a value, not a binding: assigning to one is refused.
The constants carried are those of every enum the bound surface reaches: one a
bound routine takes or returns, or one a field of a record it passes is
declared with. An enum no bound routine reaches is not carried, by the same
rule that keeps a header’s other declarations out of the surface. A routine
that declares int and documents an enum beside it, as libgit2’s error codes
are spelled, reaches no enum.
A value naming no enumerator crosses unchanged. C gives an enum no closed
set of values: any value of its storage type is a valid enum color, and
providers rely on that for flag combinations and for codes newer than the
caller’s header. So an imported enum is a FOL scalar, not an entry, and a value
outside its enumerators is neither refused nor clamped, in either direction:
prb::paint(42) hands C 42, and a provider returning (enum color)77 hands
FOL 77. A FOL entry is the opposite case: its variants are closed, so an
exported entry whose tag arrives from C naming no variant is refused with
FOL_STATUS_INVALID_ARGUMENT (below).
FOL names ignore case and underscores, so JSON_OBJECT and json_object are
one name. A bound routine keeps such a name and the enumerator is not mounted.
Two enumerators that fold to one name are both mounted, and a use of either is
reported as ambiguous, naming both. test/v4_c_shapes.rs runs all of this
against a provider.
Entry discriminants
An entry crosses as a C enum, and a C enum’s values are part of the ABI: they are written to files and sent over wires. So FOL will not pick them. Each variant states its own tag:
typ[exp] Lookup: ent = {
con[tag = 4] MISSING;
con[tag = 1] FOUND;
con[tag = 9] DENIED;
};
[tag = N] is not a default value. con NAME: int = 7 gives the variant a
default payload of 7, and var Ok: int = 1 beside var Err: str = "broken"
shows why that cannot double as a tag — both variants would land on 1. The two
are different things and are now spelled differently.
An entry with no tags is refused outbound with UnstableEntryTag, naming the
entry. Its variants are numbered by position, which is fine inside FOL and
cannot be promised to anyone holding a stored value: inserting a variant would
renumber every later one.
Three ways of tagging incoherently are refused at parse time: a duplicate tag, a tag outside the 32-bit range the discriminant carries, and a partially tagged entry, where the untagged variants would fall back to the position the tags exist to escape.
Because a tag is stated rather than positional, reordering the declaration is
a no-op: the manifest is byte-identical, and fol tool abi check reports the
surface unchanged. Changing a tag is the opposite — a breaking change, refused
without --allow-breaking. examples/v4_c_export_entry crosses both
directions; examples/fail_v4_c_entry_error is the untagged refusal.
Synchronous callbacks
A C routine that calls back needs a function pointer and somewhere to keep the
caller’s state. C cannot say which void * belongs to which function pointer,
so the overlay does:
[routine.tally_range]
error = "infallible"
callback = "step"
callback_context = "context"
Neither position is a FOL parameter. FOL passes a closure and fills the context itself, with that closure’s address, so the pairing cannot be got wrong:
var total: int[32] = tal::tally_range(4, fun(a: int[32], v: int[32]): int[32] = {
return a + v;
});
Bridging the two is a generated trampoline — a monomorphic extern "C" shim
nested inside the one call site, which recovers the closure from the context and
calls it. A Rust closure carries an environment and a C function pointer has
nowhere to put one; the trampoline is where that gap is closed.
Two shapes are imported. The function pointer hands the context back as its first parameter (expat, SQLite) or its last (libgit2, curl):
int tally_range(int upto,
int (*step)(void *context, int accumulator, int value),
void *context);
int tally_range(int upto,
int (*step)(int accumulator, int value, void *context),
void *context);
The context is the parameter whose type is the context argument’s own type, not
merely a pointer: git_reference_foreach_cb(git_reference *ref, void *payload)
hands back its payload last, and the reference first is an argument the closure
receives. A context anywhere else is refused at bind time rather than guessed
at, because guessing wrong hands the closure the wrong arguments –
examples/fail_v4_c_callback_shape.
The trampoline enforces two rules rather than documenting them. A null
context means the callback was invoked outside the call that lent the closure.
A fault inside the callback cannot travel further: unwinding out of
extern "C" is undefined, and a callback has no status channel — the provider
is mid-call and takes only a return value. Both end the process, naming the
symbol, rather than returning a value nobody computed.
What FOL does not enforce is what the provider does after the call returns. Retention, reentry, and cross-thread invocation are all provider behaviour that nothing on FOL’s side observes. FOL’s half of the contract holds structurally — the closure is a local, so the context cannot outlive the call — and the null-context check catches the one detectable case. A real guarantee would need a generation counter in the context and a provider-side destroyer, which V4 does not build.
See examples/v4_c_callback, examples/v4_c_callback_context_last,
examples/fail_v4_c_callback_panic, and examples/fail_v4_c_callback_shape.
A callback the provider keeps
The synchronous model has one window: the closure is reachable while the call that lent it is on the stack, and a provider that invokes it later finds the slot empty and is refused. Real libraries keep callbacks on purpose. SQLite’s busy handler and hooks, expat’s element handlers, and Lua’s C functions are all installed by one call and invoked by others, and every one of them binds today and ends the process on first use. The overlay says who keeps it:
[routine.relay_on]
error = "infallible"
handle_borrows = ["r"]
callback = "handler"
callback_context = "context"
callback_kept_by = "r"
A routine that installs several callbacks at once – expat’s
XML_SetElementHandler(parser, start, end) – names them as a list:
callback = ["start", "end"]. Each gets its own trampoline and, if kept, its
own slot on the keeper; the context, the keeper, and the text positions are
shared, and a text position one of them lacks is simply not that one’s.
callback_kept_by names a handle this routine borrows. Three things follow:
- The closure is moved, not lent. Its captures must be owned (
[mov],[cpy],[cln]); a closure holding[bor]captures is refused, because nothing bounds how long the provider will hold it. - The keeper owns it. FOL boxes the closure into storage keyed by the keeper’s address and passes that box’s address as the context. The trampoline reads the closure through the context, so there is no window: any later call on that handle may invoke it. Installing a second handler keeps both until the handle is released.
- The destroy releases it. The
consumescall on that domain drops every closure the handle kept, after the provider’s own destroy has run, so a destroy that invokes the handler one last time still finds it.
A kept callback needs a real context: callback_context = "none" with
callback_kept_by is refused, because without a context there is nothing the
provider hands back to find the closure by. A provider that keeps its context
somewhere other than the call that installs the callback — expat’s
XML_SetUserData — is not yet importable.
See examples/v4_c_callback_kept, and examples/v4_c_sqlite, whose progress
handler is one: SQLite keeps it on the connection and fires it from inside
sqlite3_step.
Found by its keeper
Some providers hand a kept callback no context at all, only the handle that
keeps it. Lua’s C functions are the shape: int (*)(lua_State *), installed
by lua_pushcclosure(L, fn, 0) and invoked with the same L. The overlay
says the keeper is the key:
[routine.lua_pushcclosure]
error = "infallible"
handle_borrows = ["L"]
callback = "fn"
callback_context = "keeper"
callback_kept_by = "L"
callback_context = "keeper" requires callback_kept_by, and the callback’s
first parameter must be a pointer to the keeper’s own record; it is refused
otherwise. Nothing is hidden from the closure: it receives that handle as a
borrowed lua_State[bor], because the provider still owns it, and reads
and writes the Lua stack through it. A handle handed to any callback is typed
as a loan for the same reason.
See examples/v4_c_lua, where Lua code calls twice(21) and the answer is
computed inside a FOL closure.
Found through user data a setter installs
expat is the third shape: its handlers receive a void *userData, but no
handler setter takes one – XML_SetUserData(parser, p) installs it once,
and the parser hands it to every handler. The overlay says the slot is FOL’s:
[handle.XML_Parser]
destroy = "XML_ParserFree"
context_setter = "XML_SetUserData"
[routine.XML_SetStartElementHandler]
error = "infallible"
handle_borrows = ["parser"]
callback = "handler"
callback_context = "keeper"
callback_kept_by = "parser"
context_setter names a selected routine that takes exactly the domain’s
handle and a void *; anything else is refused. Installing a kept handler
installs the keeper’s own address through it, before the installing call, and
the trampoline finds the closure by that address as it would through any
context. The setter itself is not mounted: a program that could call it could
overwrite the slot every kept handler on the parser is found through. The
handler’s void * is hidden from the closure, as a context always is.
See examples/v4_c_callback_user_data.
A struct of callbacks the caller fills
FreeType walks an outline through FT_Outline_Decompose(outline, const FT_Outline_Funcs *funcs, void *user): the callbacks are fields of a struct
the caller fills, all handed user back. callback_table names that
parameter, and callback then names its fields:
[routine.FT_Outline_Decompose]
error = "infallible"
handle_borrows = ["outline"]
callback_table = "func_interface"
callback = ["move_to", "line_to", "conic_to", "cubic_to"]
callback_context = "user"
FOL passes one closure per named field, in that order. The adapter builds the
struct around their trampolines, leaves every other field – which must be a
scalar – zero, and hands C its address. A callback’s const FT_Vector *
arrives as a borrowed handle of a declared domain, read through its fields:
var walked: i32 = ft::FT_Outline_Decompose([bor]outline,
pro(to: ft::FT_Vector[bor]): i32 = {
std::io::echo_int(ft::FT_Vector_x(to));
return 0;
}, ...);
The struct the adapter fills is its own repr(C) mirror of the provider’s,
asserted field by field against it: FOL spells a callback’s pointer arguments
its own way, and Rust casts no function pointer to another. See
examples/v4_c_callback_table.
Text inside a callback signature
A parser reports element names to its handler as const char *, and the
provider’s bytes are valid only during the callback. A function pointer’s
parameters have no names, so the overlay names the text by position in the C
signature, counting from zero with the context slot included:
[routine.XML_SetStartElementHandler]
error = "infallible"
handle_borrows = ["parser"]
callback = "handler"
callback_context = "keeper"
callback_kept_by = "parser"
callback_strings = [1]
A NULL-terminated list of text – expat’s attribute pairs, const char **
– is callback_string_lists, and reaches the closure as a vec[str] of its
own, each element copied; a null list is an empty one.
The closure receives that position as a str of its own, copied for the
invocation. Copied rather than lent, for the same reason a returned string
is: there is nothing to lend from once the provider reuses its buffer, and a
copy has no lifetime to spell. A position that is not const char *, or is
the hidden context, is refused; a provider that passes NULL where it declared
text ends the process, naming the routine.
See examples/v4_c_callback_text, and the expat lane in test/v4_c_expat.rs,
where a kept comment handler on a real libexpat.so receives the comment’s
text through all three keys at once.
Verification commands
Run these on GNU/Linux from the FOL root with parc, linc, and gerc as
sibling checkouts:
make interop-check interop-locked test-interop
make interop-checkruns the offline tier: every component pinned to a 40-character revision rather than a branch or a path, no[patch]entry substituting one, this page still quoting the revisions in force, and compilation of the typed integration. It needs no network.make interop-lockedadds--lockedresolution, proving the pins resolve exactly as committed with no network access and no manifest edit.make test-interopdepends on the locked check, requires Linux and GCC, and runs the positive and fail-closed native H7 tests without an optional-skip path.
CI checks out only FOL and invokes the same Make-owned locked smoke gate; cargo
fetches the pinned components. Moving a component means updating
fol-interop/Cargo.toml, Cargo.lock, and this snapshot together — the check
fails the moment the book stops quoting the revisions in force.
Working on a component locally without editing the pins:
# ~/.cargo/config.toml
[patch."https://github.com/fol-lang/parc"]
follang-parc = { path = "/absolute/path/to/parc" }
This boundary does not expose general foreign declaration syntax, general pointers or ownership, C++ ABI support, Rust facade generation, or a stable Rust binary ABI. C export and bounded header import are built on top of it and are described above.
ABI versioning
A library that other people link needs to say when its surface changed, and to distinguish that from having been rebuilt. An exporting artifact declares a version beside its exports:
lib.set_abi_version({ major = 1, minor = 0 });
lib.add_abi_export({ routine = "add_i32", symbol = "fol_slice_add_i32" });
The installed manifest carries two fingerprints, and the split is the whole point. The interface fingerprint covers what a caller can see: symbols, types, layouts, error contracts, ownership. The build fingerprint covers how the surface was produced — compiler, component revisions, link inputs. A new compiler moves the build fingerprint and leaves the interface fingerprint alone, so a toolchain upgrade does not read as an ABI event.
fol tool abi check --baseline <MANIFEST> --candidate <MANIFEST> compares a
checked-in baseline against a freshly built manifest and reports one of four
verdicts:
| Verdict | Meaning |
|---|---|
| unchanged | the interface is identical; if the build fingerprint moved, it says so |
| compatible | symbols were added and nothing existing changed |
| breaking | an existing symbol, type, layout, or contract changed |
| target mismatch | the two manifests describe different targets |
A break is accepted only with --allow-breaking, which says this break is
intended and belongs in the command that ran rather than in a file someone
edited. A target mismatch is never accepted by that flag: nothing about the
source changed, so treating it as an intended break would send a reader looking
for a change that is not there.
Both commands read written manifests and nothing else — no package root, no compilation — because an installed prefix and an extracted release archive are exactly where a consumer needs to ask what a library’s C surface is, and neither has a source tree. Reading recomputes both recorded fingerprints, so a hand-edited manifest is refused rather than compared.
fol tool abi package --prefix <DIR> --out <ARCHIVE> turns an installed prefix
into a release archive carrying the headers, libraries, manifests, a
CHECKSUMS.sha256 any consumer can verify with sha256sum -c, a PROVENANCE
record, and an SBOM naming the pinned components that measured the layouts.
It refuses a prefix containing generated Rust or a Cargo manifest rather than
filtering them out: that is implementation, not interface, and a prefix holding
it is a bug worth reporting rather than papering over.