Top-level fn names are now usable as values, fn-typed parameters can be called as `f(args)`. KISS slice of "closures + HOFs + TIR": no TIR, no heap, no ABI shift — that bundle stays in Iter 8 where closure-with-capture and lambdas land together. Codegen: - Type::Fn lowers to LLVM `ptr`; sig travels via a per-fn-body `ssa_fn_sigs` sidetable on `Emitter`. - Term::Var falls through to `resolve_top_level_fn` when the name is not a local; emits `@ail_<m>_<def>` and registers the sig. - Term::App splits: static callee (builtin / current-module / qualified) keeps the existing direct path; otherwise lower the callee, look up the sig, emit indirect `call <ret> (<param-tys>) %fn(args...)`. - emit_fn registers fn-typed params in the sidetable on entry. - If branches propagate a fn-pointer sig to their phi when both arms match. Typechecker: unchanged. It already accepted `synth(callee)` against Type::Fn; the only blocker was codegen rejecting non-Var callees. Tests: 48 green (was 47). New `examples/hof.ail.json` and e2e `higher_order_apply_inc` exercise `apply(inc, 41) == 42` end-to-end. DESIGN.md: "What is not (yet) supported" rewritten — closures-with- capture and lambdas remain pending, first-class fn-refs added as positive bullet. Smoke-test list extended with `hof.ail.json`. JOURNAL.md: Iter 7 entry with rationale, scope choice, architecture self-check, Iter 8 plan. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
10 KiB
AILang — design decisions
This document records the core decisions for AILang. It is my contract with myself across future iterations. Prefer cuts over growth.
Goal
AILang is a programming language for LLM authors. It compiles to LLVM IR. Performance: native, no GC for the MVP.
Optimised for:
- Machine readability over human ergonomics. The source is structured.
- Local reasoning. Every definition carries its full type and effects.
- Provability. Pure core language, explicit effects, optional refinements.
- Robustness against hallucinations. Symbols are hashable; tools can verify existence without spending context window.
Project ecosystem
AILang is not just a language but an ecosystem. The language on its own is only valuable when its surroundings make it usable, checkable, and extensible for its target user (LLM authors). The repo therefore contains several equally important components — none of them optional, all of them evolving in lockstep with the language:
- Language core (
crates/ailang-core,crates/ailang-check,crates/ailang-codegen): AST, type system, codegen. - CLI (
crates/ail): toolchain for tooling consumers —manifest,describe,deps,check,build, etc., preferably with--jsonfor machine consumption. - Examples (
examples/): canonical.ail.jsonprograms. They are specification anchors, not demos — the E2E suite hangs off them. - Agents (
agents/): specialised sub-prompts (implementer, architect, tester, debugger) that form the project's own LLM tooling. They are a versioned part of the repo. Seeagents/README.md. - Docs (
docs/): DESIGN.md (what and why), JOURNAL.md (history). - Tests: unit tests per crate plus E2E in
crates/ail/tests/e2e.rs. Every new compiler path needs a test, otherwise the feature does not count as done.
When the language grows, these components grow with it. New tools that
strengthen the LLM tooling (e.g. ail diff, IR snapshot diffs, new agents)
explicitly belong in the ecosystem inventory of this section and are added
here as soon as they are established.
Project language: English
All in-tree content is written in English: source code (identifiers,
comments, string literals, CLI help), design documents, the journal, agent
prompts, READMEs, commit messages, examples, and CLAUDE.md. The live
conversation between user and me stays German for ergonomic reasons;
everything that lands in git is English. This keeps diffs and tooling output
uniform and matches the audience for AILang (LLM authors), for whom English
is the default.
Decision 1: source = data, not text
A module is a JSON object with a fixed schema. There is no parser for free-form text. Typos in identifiers turn into hash-lookup errors that the compiler proposes a fix for directly.
A textual form exists (.ail, S-expression-like), but only as a
bidirectional projection of the JSON form. It is intended for human reviews
and diffs.
Canonical format: .ail.json with deterministic key order.
Decision 2: content-addressed definitions
Every top-level definition has a hash value (BLAKE3 over canonical JSON
without the hash field itself). References between definitions go primarily
by name — names are for readability. The hash is the canonical identity.
Advantages:
- Refactoring by adding new defs, not by in-place change. Old versions stay callable until manually removed.
- Caching of typecheck results and codegen per hash.
- Diffs show exactly which def has changed.
Decision 3: pure core language + algebraic effects
The default is total, pure functions. Effects are declared as a set in the
function type: (Int) -> Int ![IO]. The effect set is row-polymorphic
(![IO | r]). In the MVP only the effects IO and Diverge (for infinite
loops) are wired up.
This is the most important LLM property: when I read a function, I can trust its signature without reading the body.
Decision 4: Hindley-Milner + optional refinements
MVP: HM with let-polymorphism. All types are inferable, but at the top level they must always be explicitly annotated (for local reasoning).
Later: refinement annotations that escalate to SMT. (i: Int | i >= 0). They
are reserved in the AST from the start, but in the MVP they are simply passed
through as opaque strings.
Decision 5: emit LLVM IR as text
Instead of inkwell or llvm-sys: AILang produces .ll files as strings
and hands them to clang for linking.
Rationale:
- The LLVM IR text syntax is largely stable across versions.
- No build dependency on a specific libllvm version.
- Generated code is trivially inspectable, which makes debugging much easier.
- An LLM can read the generated IR directly, which is harder with opaque library calls.
Trade-off: no inline optimisations through the LLVM API. We rely on
clang -O2 as the standard pipeline.
Mangling scheme (Iter 5c)
All AILang functions are mangled to @ail_<module>_<def> — even in the
single-module case. Constants likewise (@ail_<module>_<const>). Global
string literals carry a short hint for readability:
@.str_<module>_<hint>_<idx> (e.g. @.str_sum_fmt_int_0). The entry point
is a define i32 @main() trampoline (C / LLVM ABI) that calls
@ail_<entry-module>_main(). source_filename exists exactly once per
workspace and carries the entry-module name (<entry-module>.ail).
Convention: qualified cross-module references (Iter 5b)
Cross-module calls use no new AST node. Instead, a Term::Var { name }
with exactly one dot in the name is a qualified reference: <prefix>.<def>.
<prefix>is an import alias (import { module: "X", as: "<prefix>" }) or, when imported without an alias, the module name itself.<def>is the name of a top-level definition in the target module.- Def names MUST NOT contain a dot — the typechecker reports
invalid-def-namewithctx: { "reason": "contains-dot" }. - The workspace loader (Iter 5a) finds all reachable modules; the
typechecker (Iter 5b,
check_workspace) resolves dotted names through the import map. Diagnostic codes:unknown-module(prefix not imported),unknown-import(module found, def not).
Hash stability: no new AST node, no renamed fields — all previous module hashes stay bit-identical.
Data model (MVP)
Module
{
"schema": "ailang/v0",
"name": "<id>",
"imports": [{ "module": "<id>", "as": "<id>" }],
"defs": [Def...]
}
Def
kind ∈ { "fn", "type", "effect", "const" }. In the MVP only fn and const.
{
"kind": "fn",
"name": "<id>",
"type": Type,
"params": ["<id>"...],
"body": Term,
"doc": "<optional string>"
}
Term (expression)
{ "t": "lit", "lit": { "kind": "int" | "bool" | "unit", "value": ... } }
{ "t": "var", "name": "<id>" }
{ "t": "app", "fn": Term, "args": [Term...] }
{ "t": "let", "name": "<id>", "value": Term, "body": Term }
{ "t": "if", "cond": Term, "then": Term, "else": Term }
{ "t": "do", "op": "<eff>/<op>", "args": [Term...] }
In the MVP, do is only a direct call to a built-in effect op (no handler).
Type
{ "k": "con", "name": "Int" }
{ "k": "con", "name": "Bool" }
{ "k": "con", "name": "Unit" }
{ "k": "fn", "params": [Type...], "ret": Type, "effects": ["IO"...] }
{ "k": "var", "name": "a" }
{ "k": "forall", "vars": ["a"...], "body": Type }
Pipeline
.ail.json ─┐
├─ load + validate schema
├─ resolve names + assign hashes
├─ typecheck (HM, effect rows)
├─ lower to MIR (SSA-like, named SSA values)
├─ emit LLVM IR (.ll)
└─ clang -O2 *.ll -o binary
CLI
ail check <module.ail.json> — loads, validates, typechecks
ail manifest <module.ail.json> — table: name :: type !effects [hash]
ail describe <module> <name> — detail of a definition
ail render <module> — JSON → pretty-print
ail parse <module.ail> — pretty-print → JSON (for bootstrapping)
ail emit-ir <module> — writes .ll
ail build <module> — full pipeline → binary
Verification and correctness (across cycles)
- Snapshot tests for the pretty-printer and IR emit. The diff makes regressions visible immediately.
- Property tests for the JSON ↔ pretty-print roundtrip.
- End-to-end tests for
examples/with expected program output. - Hash stability: a test ensures the same def always produces the same hash.
- CI pin of the outputs in
tests/expected/.
What is not (yet) supported
Snapshot of the boundary at the end of Iter 7. Items move out of this list as iterations land; the JOURNAL records the exact iteration.
- No closures with capture / no anonymous lambdas. Both will require a typed IR stage (TIR) and closure conversion in lowering. First-class function references (top-level fns as values, fn-typed parameters, indirect calls) are supported as of Iter 7 — see below.
- No effect handlers — only the built-in IO and Diverge ops.
- No refinements / SMT escalation.
- No cross-module ADTs. ADTs are local to a module; ctor names must be unique within their module but may collide across modules.
- No visibility rules in imports. Every top-level def of an imported module
is reachable; there is no
pub/priv. - No GC. The
Ctorheap layout leaks. Acceptable for current example programs; required before any longer-running program.
What is supported (and used as the smoke test for the pipeline):
- Int, Bool, Unit, Str as primitive types.
if,let, function calls, recursion.- Effects on function signatures, with
do op(args)for direct effect ops (io/print_int,io/print_bool,io/print_str). - ADTs + flat pattern matching (Iter 3). Sub-patterns of a Ctor
pattern are restricted to
Var/Wild. - Imports + qualified cross-module references via dotted names (Iter 5).
- First-class function references (Iter 7). A top-level fn name (or
qualified
prefix.def) used as aTerm::Varis a fn-pointer value of AILang typeType::Fn { ... }and LLVM typeptr. Fn-typed parameters may be called directly asf(args). No capture, no lambdas — the only way to construct a fn-value is to refer to a top-level def.
Pipeline regression smoke tests:
examples/sum.ail.json→ prints 55 (recursion, arithmetic).examples/list.ail.json→ prints 42 (ADTs + match).examples/hof.ail.json→ prints 42 (first-class fn-refs, indirect call).