iter operator-routing-eq-ord.1 (DONE 13/13): drop comparator builtins, route through Eq/Ord

Closes Gitea #1. Realises the "P2 follow-up" called out in
examples/prelude.ail:9 — removes the surface comparator names
`==` / `!=` / `<` / `<=` / `>` / `>=` from the language entirely,
routes the LLM-author's `(app eq …)` / `(app compare …)` /
`(app ne|lt|le|gt|ge …)` through prelude.Eq / prelude.Ord class-
dispatch, ships six named Float-comparison fns
(`float_eq`/`float_ne`/`float_lt`/`float_le`/`float_gt`/`float_ge`)
so Float keeps comparability without an Eq/Ord instance, and emits
primitive instance bodies with `alwaysinline` so the -O0 IR shape
stays at one instruction per comparison.

Plan-task journal (13 tasks, single atomic iter per Approach A):

  Task 1 — Bootstrap: 4 new fixtures (eq_user_adt_smoke.ail,
    eq_float_must_fail.ail, float_compare_smoke.ail,
    operator_unbound_check.ail) + 5 new E2E/pin tests as RED
    starting state. All 5 confirmed RED at start: north-star
    fixed `NoInstance Eq Unit` (preserved by Unit-eq opening line
    intentionally added in plan-self-review); float_compare unknown
    `float_eq`; operator-name typechecked (== still polymorphic);
    must-fail diagnostic lacked `float_eq`; alwaysinline absent
    from IR.

  Task 2 — Codegen alwaysinline + intercept arms: introduced
    `intercept_emit_wants_alwaysinline` allowlist + appended
    ` alwaysinline` between `)` and `{` of the `define` line in
    `emit_fn`; added 9 new intercept arms to
    `try_emit_primitive_instance_body` — `eq__Int`/`eq__Bool`/
    `eq__Unit` + the six `float_*` arms.

  Task 3 — Prelude reshape: `instance Eq Unit` added; Eq Int/Bool
    bodies become placeholder-`false` (intercept overrides); six
    `float_*` free fns added; line-9 P2-follow-up comment removed.
    Lockstep hash re-pins: prelude_module_hash_pin (3abe0d3fa3c11c99
    → new), mono_hash_stability six body-hash literals
    (eq__Int/Bool/Str + compare__Int/Bool/Str all shifted because
    placeholder body changes the canonical hash). IR-snapshot
    regen (hello/list/max3/sum/ws_main) rolled forward into this
    task at orchestrator's pragmatic call — prelude shift forces
    the snapshots immediately.

  Task 4 — Fixture migration: 58 .ail fixtures rewritten
    (`(app == …)` → `(app eq …)`, etc.; Float-typed operand sites
    to `(app float_eq …)` / `(app float_lt …)`). eq_ord_user_adt.ail:21
    inner `==` → `eq` migration with lockstep eq_ord_e2e.rs:134
    body-hash re-pin (3c4cf040cb4e8bb2 → new). Two prose snapshots
    accepted; deps test + 5 hash_pin literals updated as cascading
    consequences.

  Task 5 — Test-scaffold migration: all 8 in-source
    `#[cfg(test)] mod tests` AST-literal sites threaded
    (desugar.rs:2414, check/lib.rs:5656/6092/6220, codegen/lib.rs
    sites). 7 obsolete in-source tests deleted (5 eq_typechecks +
    2 lower_eq ADT/Fn rejection — coverage moves to E2E
    eq_user_adt_smoke + eq_float_must_fail). 2 additional letrec
    tests deleted (single-module check env can't resolve eq/ge
    without prelude auto-import; covered by workspace E2E).

  Task 6 — Lit-pattern desugar: build_eq emits
    `Term::Var { name: "eq" }` instead of `"=="` at desugar.rs:1109;
    doc-comment rewritten to describe class-dispatch.

  Task 7 — Dead-machinery deletion sweep (compile-gated): typchecker
    builtins (install + list comparator entries deleted); codegen
    builtin_binop_typed (10 comparator arms deleted from synth.rs,
    table reduced to arithmetic core); lower_eq fn entirely
    deleted; `==` short-circuit in lower_app deleted;
    `is_static_callee` `==` clause deleted;
    `is_arithmetic_or_comparison_op` renamed to `is_arithmetic_op`
    + caller-update at codegen/lib.rs:2152 + :2529. Dead
    `poly_a_a_to_bool` helpers also removed. Workspace build green
    after compile gate — every caller of the deleted surface was
    migrated by Tasks 4-6.

  Task 8 — Float-aware NoInstance diagnostic: check/lib.rs:856-880
    addendum extended to name `float_eq` / `float_lt` as the
    explicit alternative for Eq/Ord at Float;
    eq_float_noinstance.rs:32-44 assertion extended.

  Task 9 — IR snapshot regen: subsumed by Task 3 (prelude shift
    forced immediate snapshot regen; deferring to Task 9 would
    have left the workspace red between tasks).

  Task 10 — Prose-projection cleanup: 6 comparator arms deleted
    from binop_info; 3 in-source mod-tests updated/deleted
    (comparator-infix rendering would be dishonest now that the
    operators are no longer language identifiers).

  Task 11 — Contract updates: 5 design files rewritten to the
    class-dispatch present —
      float-semantics.md (arithmetic guarantees retained on
        +/-/*/; comparison guarantees transferred from ==/!=/<
        to float_eq/float_ne/float_lt/etc.);
      prelude-classes.md (Eq Unit added to instance list;
        new paragraph on six float_* fns; Float-no-Eq/Ord clause
        gains `→ use float_eq` cross-reference);
      str-abi.md (clause "REMAIN primitive operators" rewritten
        to describe class-method dispatch);
      scope-boundaries.md (multiple operator-name and
        Pattern::Lit-desugar clauses rewritten);
      authoring-surface.md (==, <= dropped from operator-example
        list).

  Task 12 — Initial acceptance gate: workspace 638/0 GREEN;
    bench/compile_check + cross_lang 0 regressed; bench/check.py
    flagged 4 regressions on bench_closure_chain (+29% bump_s,
    +47% rc_s, +29% bump_rss_kb, +48% rc_rss_kb). Orchestrator
    initially classified as DONE-with-concerns; Boss reclassified
    as PARTIAL-via-acceptance-#8-fail after independent re-run,
    extended iter scope to Task 13.

  Task 13 — Direct icmp intercept arms (Boss-extension):
    try_emit_primitive_instance_body gains direct-icmp arms for
    lt__Int / le__Int / gt__Int / ge__Int / ne__Int, bypassing
    the compare__Int → Ordering → match indirection that allocated
    one Ordering ctor per call in tight loops. Each new arm
    inherits `alwaysinline` via the existing allowlist (extended
    accordingly). New IR pin test `ord_int_intercept_ir_pin.rs`
    + smoke fixture `ord_int_intercept_smoke.ail` ratify the
    optimization — opt -O2 -S confirms zero `call
    @ail_prelude_lt__Int` in optimized IR; the icmp folds directly
    at every use site. Bool variants (lt__Bool/etc.) deliberately
    NOT added — no bench/example calls Ord at Bool; spec-extension
    permits skipping if unreachable at bench level. Family can be
    extended symmetrically when first Bool-ordered perf workload
    appears.

Bench-gate post-Task-13: bench_closure_chain bump_s -6.05%,
rc_s -2.67%, bump_rss_kb -0.77%, rc_rss_kb +0.46% — all four
previously-regressed metrics back inside tolerance. Full bench
corpus: 36 metrics, 0 regressed, 0 improved beyond tolerance,
36 stable. bench/check.py exit 0 ✓; bench/compile_check.py exit
0 ✓; bench/cross_lang.py exit 0 ✓.

Workspace: 640 passed, 0 failed across all binaries (delta vs.
milestone start: +5 new E2E/pin tests added in Task 1 + 1 IR pin
added in Task 13 − 9 in-source mod tests deleted as obsolete net
≈ −3). The eq_user_adt_smoke fixture's Unit-opening line was
the deliberate RED-first device added in planner self-review so
the north-star wouldn't accidentally GREEN at start (user-ADT-Eq
on Point with hand-written instance was already operable today;
the milestone's actual delivery is operator-name death + Eq Unit
+ Float-named-fns + cleanup of the two-pathy primitive
comparator machinery).

Net delta: 96 files changed, 1760 insertions, 1101 deletions;
12 net-new files (6 new fixtures, 5 new E2E/pin tests, 1 stats
file). main passes-test-count: 640 (was 633 pre-iter, accounting
for the deletions).

Spec-vs-acceptance addendum: spec §Testing strategy anticipated
the bench-gate-regression case with two recovery paths
(`alwaysinline` investigation or "spec needs revisiting toward α").
Task 13 is the third path — direct intercept arms for `lt`/etc.
that bypass the compare→match path entirely. The spec's contingency
clause was thus generous enough to absorb Task 13 without spec
revision, but a future iter that hits a class-method primitive
where the body shape introduces a similar codegen cost (Ordering
allocation, RC tax, deferred-init) should expect a parallel
extension. The pattern is "primitive instance whose canonical body
indirects through other class methods that allocate" → add a
direct-emit intercept arm + alwaysinline + IR-shape pin.

Concerns absorbed:
  - Codegen lower_app / resolve_top_level_fn gained a
    prelude-fallback lookup so bare monomorphic prelude fns
    (`float_eq` etc.) resolve from non-prelude modules without
    explicit `prelude.float_eq` qualifier. Mirrors the
    typechecker's implicit prelude import — not in plan but
    necessary infra for the named-fn surface to be callable.
  - Recon's "≈10 fixtures" estimate was 6× too low — 58 actual.
    Mechanical migration; no design impact.
  - Recon caught 4 in-source AST-literal sites the spec missed
    (lib.rs:5656 `>=` site + three codegen/lib.rs sites);
    Task 5 covered all.
  - Recon caught 2 contract files outside the spec's update set
    that directly contradicted the milestone (str-abi.md +
    scope-boundaries.md "REMAIN primitive operators" /
    "Pattern::Lit desugar to ==" clauses); Task 11 covered all 5.

Stats file:
`bench/orchestrator-stats/2026-05-21-iter-operator-routing-eq-ord.1.json`.

closes #1
This commit is contained in:
2026-05-21 01:16:21 +02:00
parent 400ad7c067
commit 5170b6abd1
96 changed files with 1759 additions and 1100 deletions
+24 -16
View File
@@ -7,28 +7,35 @@ no `f32` variant. The runtime / codegen contract:
**Guaranteed:**
- Every individual builtin (`+`/`-`/`*`/`/`/`neg`/`<`/`==`/...) lowers
to a single LLVM IR instruction on the Float arm:
`fadd/fsub/fmul/fdiv double`, `fneg double`, `fcmp olt/ole/ogt/oge
double`, `fcmp oeq double`, `fcmp une double` (for `!=`). On a
fixed `(target triple, LLVM version)` pair, the bit pattern of
the result of any single op is reproducible.
- Every individual arithmetic builtin (`+`/`-`/`*`/`/`/`neg`) lowers
to a single LLVM IR instruction on the Float arm: `fadd / fsub /
fmul / fdiv double`, `fneg double`. Float comparison goes through
the named prelude fns `float_eq` / `float_ne` / `float_lt` /
`float_le` / `float_gt` / `float_ge` (Float has no Eq/Ord instance
— see [Prelude (built-in) classes](prelude-classes.md)); each fn
lowers to a single `fcmp` instruction (`oeq` / `une` / `olt` /
`ole` / `ogt` / `oge` respectively) via the codegen intercept
`try_emit_primitive_instance_body`, with the `alwaysinline`
attribute on the generated `define` so the call folds to one
instruction at every use site. On a fixed `(target triple, LLVM
version)` pair, the bit pattern of the result of any single op is
reproducible.
- NaN and ±Inf propagate per IEEE 754 — no silent collapse to zero,
no trap. Arithmetic on a NaN operand produces NaN; division by
zero produces ±Inf; `0.0 / 0.0` produces NaN.
- `-0.0` and `+0.0` are distinct bit patterns at the canonical-JSON
hash level (`{"bits":"0000000000000000",...}` vs
`{"bits":"8000000000000000",...}` — distinct `def_hash`s) but
compare equal via `==` per IEEE (`fcmp oeq double` returns true
for `+0 == -0`). This asymmetry is the correct IEEE behaviour;
it does mean `def_hash`-equality is finer than `==`-equality on
Float.
- `==` returns `false` whenever either operand is NaN
compare equal via `float_eq` per IEEE (`fcmp oeq double` returns
true for `+0 == -0`). This asymmetry is the correct IEEE
behaviour; it does mean `def_hash`-equality is finer than
`float_eq` on Float.
- `float_eq` returns `false` whenever either operand is NaN
(`fcmp oeq` is the ordered-equal predicate; ordered = both
operands non-NaN).
- `!=` returns `true` whenever either operand is NaN (`fcmp une`
is the unordered-or-not-equal predicate). This matches Rust
`f64::ne` and IEEE-`!=` exactly.
- `float_ne` returns `true` whenever either operand is NaN
(`fcmp une` is the unordered-or-not-equal predicate). This matches
Rust `f64::ne` and IEEE-`!=` exactly.
- `is_nan` (`fcmp uno double %x, %x`) returns `true` iff `x` is
NaN. Bit-pattern-based NaN detection without dependence on the
payload bits.
@@ -95,8 +102,9 @@ This bits-hex encoding is what keeps Floats inside the
[Data model](data-model.md) for the pattern schema) is hard-
rejected at typecheck (`CheckError::FloatPatternNotAllowed`). IEEE
semantics make Float patterns semantically dubious — NaN never
matches via IEEE-`==`, and bit-exact equality is rarely what an
LLM-author wants. Use ordering operators (`<`, `>`, ...) and
matches via `float_eq` (its `fcmp oeq` lowering is `false` for
NaN), and bit-exact equality is rarely what an LLM-author wants.
Use the explicit comparison fns (`float_lt`, `float_gt`, ...) and
`is_nan` to discriminate Floats.
`float_to_str` (Float → Str) and `int_to_str` (Int → Str) are
+27 -7
View File
@@ -3,14 +3,34 @@
## Prelude (built-in) classes
The prelude ships the `Ordering` ADT, the `Eq` and `Ord`
[classes](typeclasses.md), primitive `Eq Int/Bool/Str` and
[classes](typeclasses.md), primitive `Eq Int/Bool/Str/Unit` and
`Ord Int/Bool/Str` instances, and the five polymorphic free-fn
helpers `ne`/`lt`/`le`/`gt`/`ge`. Float has neither `Eq` nor `Ord`
instance per [Float semantics](float-semantics.md); a polymorphic
helper invoked at Float fires `NoInstance` at typecheck with a
Float-aware diagnostic cross-referencing this section. The lookup
machinery that turns a `show x` call site into the right monomorphic
instance is documented in [method dispatch](method-dispatch.md).
helpers `ne`/`lt`/`le`/`gt`/`ge`. The primitive `Eq` / `Ord`
instance bodies are placeholder lambdas in `examples/prelude.ail`;
the codegen intercept `try_emit_primitive_instance_body` overrides
them with single-instruction bodies (`icmp eq i64` for `eq__Int`,
`icmp eq i1` for `eq__Bool`, `@ail_str_eq` for `eq__Str`,
`ret i1 1` for `eq__Unit`; a three-way `icmp` ladder constructing
`LT`/`EQ`/`GT` for `compare__T`) and attaches `alwaysinline` so
the call folds to the single instruction at every use site.
Float has neither `Eq` nor `Ord` instance per [Float semantics](
float-semantics.md); a polymorphic helper invoked at Float fires
`NoInstance` at typecheck with a Float-aware diagnostic that names
the explicit `float_eq` / `float_lt` alternatives and
cross-references this section. The lookup machinery that turns a
`show x` call site into the right monomorphic instance is
documented in [method dispatch](method-dispatch.md).
Float comparison is a separate surface: the six monomorphic prelude
fns `float_eq` / `float_ne` / `float_lt` / `float_le` / `float_gt`
/ `float_ge` each carry the type `(Float, Float) -> Bool` without
a class constraint. They lower via the same intercept machinery as
the primitive `Eq` instances (single `fcmp` instruction with the
matching predicate `oeq` / `une` / `olt` / `ole` / `ogt` / `oge`,
plus `alwaysinline`). They replace what would otherwise be a
polymorphic `==` / `<` on Float — Float gets full comparability
via explicit named fns, not via an implicit class instance.
The prelude ships `class Show a where show : (a borrow) -> Str` and
primitive `Show Int`, `Show Bool`, `Show Str`, `Show Float`
+34 -29
View File
@@ -39,9 +39,7 @@ What **is** supported (and used as the smoke test for the pipeline):
- **Builtins.** Arithmetic operators (`+`, `-`, `*`, `/`) of type
`forall a. (a, a) -> a` (codegen-restricted to `{Int, Float}`);
`%` of type `(Int, Int) -> Int` (Int-only — `fmod` semantics for
Float deferred); ordering operators and `!=` (`!=`, `<`, `<=`,
`>`, `>=`) of type `forall a. (a, a) -> Bool` (codegen-restricted
to `{Int, Float}`); polymorphic `neg : forall a. (a) -> a`
Float deferred); polymorphic `neg : forall a. (a) -> a`
(codegen-restricted to `{Int, Float}`; Float arm uses LLVM
`fneg double` for correct `-0.0` handling); logical
`not : (Bool) -> Bool`; conversions
@@ -55,25 +53,28 @@ What **is** supported (and used as the smoke test for the pipeline):
`fcmp uno`); Float bit-pattern constants `nan : Float`,
`inf : Float`, `neg_inf : Float` (resolved as bare values, lower
to direct hex-float `double` SSA constants at use site); the IO
effect op `io/print_str`; **`==` : forall a.
(a, a) -> Bool**; and **`__unreachable__ : forall a. a`**.
- **`==` is polymorphic.** The typechecker accepts
`==` at any type whose two sides agree (the rigid `a` of the
`Forall` is unified by HM at the use site). Codegen
monomorphises and dispatches on the resolved AIL arg type:
`Int` `icmp eq i64`; `Bool``icmp eq i1`;
`Str` `call @strcmp(ptr, ptr)` then `icmp eq i32 0`
(`@strcmp` is declared in the LLVM IR header alongside
`@printf` / `@ailang_rc_alloc`); `Unit` → constant `i1 true`
(Unit has a single inhabitant; both sides are still
evaluated for any side effects); `Float``fcmp oeq double`.
ADT and `Fn` arg types are rejected at codegen with a
`CodegenError::Internal` mentioning `==` and the offending
type — neither has a canonical structural-equality scheme
yet, and the language deliberately does not silently elide
the check. **`!=` for Float uses `fcmp UNE double` (NOT
`one`)** — `one` is "ordered and not equal" and would return
false for `nan != nan`, violating IEEE-`!=`.
effect op `io/print_str`; and **`__unreachable__ : forall a. a`**.
- **Equality + ordering** are not builtins. The class method
`eq` (`prelude.Eq`) dispatches via the per-type Eq instance;
the class method `compare` (`prelude.Ord`) dispatches via the
per-type Ord instance, returning a three-ctor `Ordering` ADT
(`LT` / `EQ` / `GT`). The five free helpers `ne` / `lt` /
`le` / `gt` / `ge` are defined in the prelude in terms of
`eq` / `compare`. The primitive Eq/Ord instance bodies are
emitted by the codegen intercept
`try_emit_primitive_instance_body`: Eq Int → `icmp eq i64`,
Eq Bool → `icmp eq i1`, Eq Str → `call @ail_str_eq(...)`,
Eq Unit → `ret i1 1`, Ord Int / Bool / Str → three-way
`icmp slt` / `icmp eq` ladder constructing the `Ordering`
ctor; every primitive instance body carries the
`alwaysinline` attribute so the call folds at every use site.
Float has no Eq / Ord instance (see
[Float semantics](float-semantics.md)); explicit comparison
is via the named fns `float_eq` / `float_ne` / `float_lt` /
`float_le` / `float_gt` / `float_ge`, each lowering to a
single `fcmp` with the matching predicate. `float_ne` uses
`fcmp une double` (NOT `one`) so `nan != nan` returns `true`
per IEEE.
- **`__unreachable__`** is a polymorphic bottom value: a use of
`__unreachable__` typechecks against any expected type at
the use site and codegens to the LLVM `unreachable`
@@ -88,15 +89,19 @@ What **is** supported (and used as the smoke test for the pipeline):
- **ADTs + pattern matching.** Sub-patterns of a Ctor pattern may be `Var`, `Wild`,
another `Ctor`, or a literal. The desugar pass flattens
nested Ctor patterns into a chain of let + match and rewrites every
`Pattern::Lit` (top-level or sub-) to a `Term::If` on `==` before
typecheck/codegen — see [desugar](../../crates/ailang-core/src/desugar.rs) and [Pipeline](../models/pipeline.md).
`Pattern::Lit` (top-level or sub-) to a `Term::If` on `eq` (the
class method `prelude.Eq.eq`) before typecheck/codegen — see
[desugar](../../crates/ailang-core/src/desugar.rs) and
[Pipeline](../models/pipeline.md).
- Literal patterns at top level and inside Ctor sub-patterns (via desugar).
`(pat-lit 0)` and `(pat-ctor Cons (pat-lit 0) _)` both
parse and lower; the rewrite is to `Term::If { cond = (== sv lit) }`,
so any literal kind whose `==` is supported is authorable. With `==`
polymorphic over `Int`/`Bool`/`Str`/`Unit`, that
covers every lit kind the AST ships — including `(pat-lit "hi")`
over a `Str` scrutinee, exercised by `examples/eq_demo.ail.json`.
parse and lower; the rewrite is to `Term::If { cond = (eq sv lit) }`,
so any literal kind whose `eq` dispatch resolves to a known
primitive Eq instance is authorable. The primitive instances
cover `Int` / `Bool` / `Str` / `Unit`; `Float` lit-patterns are
hard-rejected at typecheck (`CheckError::FloatPatternNotAllowed`,
see [float-semantics](float-semantics.md)). `(pat-lit "hi")` over
a `Str` scrutinee is exercised by `examples/eq_demo.ail.json`.
- **Imports + qualified cross-module references** via dotted names.
Extends to **types and constructors**: a foreign
module's ADT is referenced as `(con std_pair.Pair a b)`, its ctors as
+11 -4
View File
@@ -37,11 +37,18 @@ directly; values of other primitive types route through the
polymorphic `print` helper (see [prelude classes](prelude-classes.md)),
which feeds the heap-Str result of `show x` into `io/print_str`.
`==`, `<`, `<=`, `>`, `>=` REMAIN primitive operators. Class methods
are accessed by name (`eq x y`, `lt x y`, …), not via these
operators.
Equality on `Str` dispatches via `prelude.Eq.eq` (Str instance,
lowered by `try_emit_primitive_instance_body::eq__Str` to a call
into `@ail_str_eq` with the `alwaysinline` attribute). Ordering on
`Str` dispatches via `prelude.Ord.compare` (Str instance, lowered
by `try_emit_primitive_instance_body::compare__Str` to a call into
`@ail_str_compare` then a three-way branch ladder constructing
`LT`/`EQ`/`GT`). The polymorphic helpers `ne` / `lt` / `le` / `gt`
/ `ge` resolve via the class layer on top of `eq` / `compare`.
There are no primitive operator names `==` / `<` / `!=` / etc. in
the language.
Arithmetic operators (`+`, `-`, `*`, `/`) stay primitive and
Arithmetic operators (`+`, `-`, `*`, `/`, `%`) stay primitive and
per-type.
**Str ABI.** A `Str` is a pointer to a structure with `i64 len` at