Skip to content

Phase 4: BTreeMap and BTreeSet over the M*LIB B+tree (D151); D152; D112 enforced - #2572

Merged
ehartford merged 11 commits into
mainfrom
mlib-phase4
Oct 23, 2026
Merged

ehartford merged 11 commits into
mainfrom
mlib-phase4

Conversation

@ehartford

Copy link
Copy Markdown
Contributor

Phase 4 of docs/proposals/stdlib_sourcing_plan.md: BTreeMap/BTreeSet become facades over MLIB's B+tree (D151), the MLIB corpus joins std.engines, and D112 is enforced in the build.

Corpus. build/mlib.w: m-core.h + m-bptree.h pinned at 93cddfb56c32976d8aeefd45ef9094167f64b285, migrated with M_USE_STDIO=0 and M_RAISE_FATAL(...)=abort(), <stdio.h> forced (forced_includes, a new Corpus field); the facade shapes unit instantiates BPTREE_DEF(mlib_slot_tree, 16, mlib_slot, …) over slot pointers with M_USE_DECL/M_USE_DEF so the engine's functions are exported; upstream's multimap example is the drift harness (mlib-test, mlib-test-fresh). Promoted through the pipeline (corpus.stamp, promoted_for first promotion).

Migrator rules it exposed, each general with a fixture in build/selfhost.w: typedef'd arrays and pointers; case A: default:; call arguments translated once per level (the 2^depth tower); discarded sizeof/compound literals; (T){0} = v; an anonymous record a compound literal instantiates; an enum is one With type everywhere (i32 when its enumerators fit int: the D147 getter and enum_constants expectations follow); a field of a value read directly; strlen's size_t; std.libc's strtoll family + the strtold runtime seam; a demotion comment's location goes through --macro-prefix-map, which the corpus pipeline now passes for every corpus (a promoted corpus names no staging directory).

Compiler. The BTreeMap/BTreeSet List-layout knowledge is retired (traversal by iter(), literals and comprehensions from the recorded new() contract). An extern fn is its module's view of a C symbol (Sema.get_sig consults the declaring module, then a direct import, then a reachable one), so corpora of different migrator generations coexist; the bundle interface emits an extern from its own declaration; the frontend keeps same-named externs across tiers. Codegen reads a bound type parameter from Sema's substitution, never llvm_type_to_sema_type (TotalF64 lowers to a double).

D112 enforced. corpus_promote_trigger: a promotion states its trigger (first promotion, pin moved, WITH_CORPUS_PROMOTE=migrator-pin:#N | ruling:DN | inputs:<what>); the refusal cites D112; the stamp records promoted_for; corpus-promote-guard-check in the gate. CLAUDE.md carries the law (20,000 corpora).

Facades. BTreeMap[K: Ord + Clone, V], BTreeSet[T: Ord + Clone] over std.collections.mlib_slot; entries facade-owned, the engine owns key-slot clones (its separators keep copies, proven with a native probe); iterators, Clone impls, set algebra. Complexity rows btree-* PASS (XFAIL #937 before); drop-audit cells btree_map_*/btree_set_*; behav_btree_engine.w, behav_extern_module_views.w. Benchmark (n=100000 i32, ns/op insert/lookup/remove): BTreeSet 945/444/617, BTreeMap 936/438/611, OrderedSet (STC sset) 195/107/223, HashSet 75/26/25.

Ceremony census. Two grants in build/ceremony-allowances.tsv: clone-call lib (element clones through views in Clone impls and set algebra; nine D63 fn-value clones) and move-arg lib (D32 explicit vacates of entry records); one lit-ptr-len in ClangBridge.

Open, filed: #2567 (declared return type as the demand), #2568, #2569 (collection demand leaks into a comprehension literal), #2570 (cancel poll resets live temps), #2571 (bounded Drop impl on a std generic is not drop glue). Needs Eric: the D120 fixture line var n = m on a BTreeMap (brief: resource + .clone()). Upstream tests/test-mbptree.c under With is the next step (needs m-string.h + test-obj.h).

D152 (ruled 2026-10-23). A collection's copy class is part of its interface: List, HashMap, HashSet copy with a count; every engine-backed collection is a resource, by D45 (a count-copy is O(1), a tree copy walks the nodes). The D120 fixture's var n = m on a BTreeMap is a migration to var n = m.clone(), a breaking change the release runbook's notes checklist carries; the moved-value diagnostic on an engine-backed collection names the class and the clone's cost. HashMap keeps its value class on any engine (its engine facade must support the count-copy).

Battery fixes on the way. get_sig refines only a cross-module extern resolution (a program's manual extern and a module's pub fn free win as before); a from self clause states an engine facade's view origin to callers (BTreeMap.get, the D22 cell holds); emit-C declares structs a fn type names through a pointer and orders records after their array members' element, and clones a fn value; the libc surface list gains C99's strtoll family.

Eric Hartford added 11 commits October 22, 2026 20:18
A C unit instantiating `BPTREE_DEF2` over m-core.h now migrates, type-checks,
builds and runs. Every rule is a C rule, none knows M*LIB:

- a typedef of an array (`typedef struct s_s s_t[1]`) is an array: the
  canonical type decides, so `s_t t; f(t)` decays and `t->f` is `t[0].f`;
- a typedef of a pointer (`typedef struct n_s *node_t`) is the pointer its
  text spells, so a malloc result converts to it and `n->f` dereferences;
- a `case A: default:` label run is the default arm;
- a call nested in a call argument is translated once per level (it was
  twice, 2^depth: `M_INC(M_INC(...))` towers spent the #1387 scan budget on
  every macro; the budget report now names the macro);
- a discarded `sizeof` is a constant with no effect (`(void) sizeof(struct {
  _Static_assert(..); })`), and a discarded compound literal or initializer
  list is its elements' effects;
- `(T){init} = v` (C99 6.5.2.5, M_ASSIGN_CAST) is `v` converted to T;
- a record with no tag a compound literal instantiates (M_CONST_CAST's
  union) is named `<fn>_literal_anon` and declared beside the function, as
  a local's record is (#1878);
- an enum is one With type everywhere: `i32` when its enumerators fit int
  (its alias, its signatures, its locals), else its underlying type; a
  return's mismatch reads the operand's C type when the IR has none;
- a field of a value (a literal, a call result) reads directly: `&raw const`
  of a value is no address (#2551);
- the preamble's strlen returns `u64`, C's size_t (every corpus casts it).

std.libc gains strtoll, strtoull, strtof and strtold; strtold is a runtime
seam (`with_libc_strtold`): f64 where C's long double is 8 bytes (Darwin
arm64, Windows), strtod's correctly rounded double elsewhere (#2176).

Fixtures in build/selfhost.w: switch_case_then_default, strtoll_family,
nested_call_tower, typedef_array_decay, discarded_sizeof,
array_arrow_member, compound_literal_assign, enum_one_type,
compound_literal_anon_record, pointer_typedef_local.

Filed on the way: #2567 (a literal at a distinct-integer demand), #2568 (a
default argument resolves in the caller's scope: a program's `src` captures
panic's `loc = src()`).
…orced

The corpus `mlib` (build/mlib.w, lib/std/engines/mlib): m-core.h and
m-bptree.h at 93cddfb5, the facade shapes unit instantiating the B+tree of
rank 16 over slot pointers (D148), upstream's multimap example as the drift
harness and the mlib-test lanes. `M_USE_STDIO=0`, `M_RAISE_FATAL=abort()`,
`<stdio.h>` forced (the corpus model's forced_includes).

`BTreeMap[K: Ord + Clone, V]` and `BTreeSet[T: Ord + Clone]` are facades over
that shape (std.collections.mlib_slot). A B+tree copies keys into its
internal nodes as separators, so the engine owns its slots: INIT_SET clones
through a With callback, CLEAR drops, every slot points back at the facade's
entry (a native probe of the pointer-copying shape tripped M*LIB's own
contract after erases). A map is a resource: a copy is `.clone()`. The
sorted-List implementation (#937) is gone; btree-map-*/btree-set-* rows
PASS; drop-audit cells btree_map_*/btree_set_* (the audit's record type
gets an identity-free clone); behav_btree_engine.w; benchmark rows (plan).

The compiler no longer knows the two types' layout (D65): traversal is the
facade's iter() under §13.5 (Sema's btree_traversal_element_type and MIR's
lower_for_btreemap are gone); a literal or comprehension starts from the
facade's new(), specialized by Sema (record_btree_new_contract) and called
by MIR (btree_storage_list_type, the aggregate, lower_btree_new, BTreeNew
are gone).

D112 enforced after it was broken once (the five corpora were re-promoted
to agree with a preamble change; Eric: a migrator change never re-migrates
a corpus; build everything as for 20,000 corpora): a promote states its
trigger or refuses (the pin moved, migrator-pin:#N, ruling:DN, inputs:...),
the stamp records it, the integrity check fails a moved pin that was not
promoted, corpus-promote-guard-check in the gate asserts the rule and that
no target reaches a promote; CLAUDE.md states the law. And the coordination
point that forced it is gone: an `extern fn` is its module's view of a C
symbol (Sema.extern_view_sig: own declaration, then a directly imported
module's, then a reachable one), the frontend never drops a lower tier's
extern for a higher tier's same-named one, and an interface's declaration
keeps its own signature beside a source owner's; the preamble's strlen is
`u64` for new corpora only (behav_extern_module_views.w).

Also: TotalF64 is Clone; the migrated enum alias and uses agree, and a named
enum is spelled by its name (the D147 getter expectation, red on main).

Filed: #2569 (a collection demand leaks into a comprehension's iterable
literal), #2570 (a cancel poll between argument calls resets live argument
temporaries), #2571 (a bounded Drop impl on a std generic is not drop
glue). Open for Eric: the D120 fixture copies a BTreeMap by assignment (the
brief in the session notes).
…from its LLVM type

The analysis audit re-derives a type node from the AST to compare with
the owner's answer. For a bound type parameter the derivation went
through the binding's LLVM type and `llvm_type_to_sema_type`: `TotalF64`
lowers to a bare double, a double reads back as `f64`, and
`sizeof[MlibSlot[K]]` in `BTreeSet[TotalF64]`'s cloner looked up
`MlibSlot[f64]`, an instance Sema never made ("BUG: generic struct type
`MlibSlot` ... names no instance Sema created" under `with analyze
'select:kind=operator'` on behav_2182_total_f64.w, the gate's
analyze-operator-route fixture).

The type-binding frame now carries Sema's type id beside the LLVM type
(`type_binding_sema`, from the specialization's substitution and the
impl's trait arguments), and the AST derivation of an identifier reads
the bound parameter from it first (D65: the LLVM representation never
decides a type). Found with lldb on stage1: the breakpoint at the BUG
report, then `Sema.find_generic_inst_type(base_sym=255 MlibSlot,
args=[12 f64])` while Sema's only instance is tid 702 (WITH_TRACE_INST).
… pipeline maps the staging directory

The first pipeline promotion of the M*LIB corpus wrote
`// /Users/.../out/tmp/action-scratch/mlib-migrate/source/m-core.h:5610:8:
demoted to opaque` into defs.w: the migrator spells a declaration's
location as the path clang was given, and the pipeline gives it the
staging directory's absolute path. A promoted corpus must be the same on
every host (D50), so the location now goes through the same
`--macro-prefix-map` maps a `__FILE__` does (`migrate_map_output_path`),
and `corpus_run_migration` passes `<staging>/=` for every corpus, as
build/stc.w already did by hand for its per-program units. Fixture:
`demotion_comment_mapped` (c-migrator-basic-tests).
… Clone has no spelled receiver

The ceremony census found the branch above main's bar. What was
ceremony is removed: the pipeline cloned `str` paths and `&str` views on
the way into a call (D111: a str is a value), the facade cloned the slot
prefix's fn values read through a reference, and the slot head wrapped
its callbacks in `Some()` at an Option demand (D103). What the language
requires is granted in build/ceremony-allowances.tsv and said here: a fn
value read through a raw-pointer deref is `.clone()`d because `fn(A) -> R`
is not Copy (D63, three sites); the facades' Clone impls and set algebra
copy each element through a view (§2.3, the engine owns no second copy);
a replaced, removed, popped or drained entry's key and value are vacated
with D32's explicit `move`; ClangBridge names a compound literal's
anonymous record through the existing anon_join seam (one lit-ptr-len).
`impl Clone for TotalF64` spelled `self: &Self`, the one explicit receiver
the receiver-surface audit found outside the D7 carve-out; it reads as the
integer impls do.
…n follows the one-type rule

The facade shapes unit now defines `M_USE_DECL`/`M_USE_DEF`, so M*LIB
emits its instance functions as exported definitions instead of `static
inline` ones: the corpus's 88 engine functions are `pub` and reach the
bundle interface, where `std.collections` calls them (drop-audit's btree
cells and the analyze operand-type fixture compiled against private
names). The corpus is re-migrated for that reason alone (D112:
`inputs:` the shapes unit changed).

D147's fixture expected an enum member's getter to spell `-> color`; the
enum rule in the previous commit makes an enum one With type everywhere
(`i32` when its enumerators fit int), and D147's own wording is "returns
the integer", so the expectation reads `-> i32`.
…ed collections are resources, by D45

Eric's ruling on the D120 fixture: `var n = m` on a BTreeMap copied
under D120 because the map was a struct over a List, an implementation
fact a fixture elevated into semantics (the §4.10 pattern). Now §2.3
names the classes: List, HashMap and HashSet copy with a count; every
engine-backed collection (BTreeMap, BTreeSet and D148's) is a resource,
because a count-copy is O(1) and a tree copy walks the nodes (D45).
Changing a type's class is an interface break with its own ruling; a
HashMap keeps its value class on any engine, so its engine facade must
support the count-copy (decided now, constraining the hash engine
choice).

The fixture line is a migration (`var n = m.clone()`), a breaking change
the release runbook's notes checklist carries; the moved-value diagnostic
on an engine-backed collection names the class and the clone's cost,
since that error is the first thing a program upgrading hits. The
decision log and docs/meetings/2026-10-23-D152-… record the brief and
the ruling.
…`from` clause states a view's origin to callers

Two battery reds, one cause each:

- `get_sig` consulted the extern view before the name's resolution: a
  program's manual `extern fn atoi` after its c_import's lost to the
  c_import's (spec_ss16's `unsafe {}` became vacuous), and a module's
  `pub fn free` lost to a corpus's `extern fn free` reached through an
  import (the issue59 demos). The view now refines only a resolution that
  is an extern declared by another module; within a module the latest
  declaration wins as before, and a function with a body is never
  re-read through it. The dead strlen trace in extern_view_sig is gone.

- The D22 cell err_d22_btreemap_origin_after_clear lost its rejection:
  the facade's `get` returns the entry's value through a local raw
  pointer, which no inference roots at `self`, so the view had no origin.
  §21.1 rule 6's `from self` clause now states the origin on the
  signature at the body merge (EFF_ESCAPE_VIEW and the origin bit, read
  from the declaration node the check holds, the template for a
  specialization), so every caller reads it; the judge checks the clause
  against the direct effects the body derived, and accepts it for a body
  that reads through a raw pointer, which derives what no inference can
  see. A lazily-skipped std declaration resolves its clause at its body
  check. BTreeMap.get declares `from self`.

Fixture: err_1903c_from_self_states_the_origin_of_an_engine_view.w. The
ceremony grant for plain-bits annotations rises by the one seed-blocked
site this adds.
…ders a record after its array members' element

The prelude's M*LIB engine broke 33 of 34 emit-C cases: a callback
field's type `fn(*mut m_string_s) -> i32` named an opaque record no
typedef declared (the struct collector read bodies, locals and
signatures, never a fn type's parameters), and
`m_bptr33_transaction_record_t tab[265]` sat in a record emitted before
its element's definition (the dependency test saw an array, not a
struct). The collector walks every used fn type's parameters and return,
and a by-value member's dependency is the struct under its arrays.
…heir rules

libc-surface-check's standard list gains strtoll, strtoull and strtof
(C99 <stdlib.h>, on every target). err_1362's expectation reads the
candidates form the diagnostic takes once two corpora export the
preamble helper. behav_migrate_unexposed_operators' refused discarded
arm uses a call with no translation: a discarded compound literal is its
elements' effects now, so a two-arm union initializer there no longer
fails.
@ehartford

Copy link
Copy Markdown
Contributor Author

Battery GREEN on 65302f9 (seed nightly-20261020-local-3, 369 s wall; logs out/battery/ in the worktree). Gate green.

@ehartford
ehartford marked this pull request as ready for review October 23, 2026 05:50
@ehartford
ehartford merged commit fe877f3 into main Oct 23, 2026
@ehartford
ehartford deleted the mlib-phase4 branch October 23, 2026 06:02
ehartford added a commit that referenced this pull request Oct 23, 2026
…der the view is refused (#2573)

The D148 facades (OrderedMap, OrderedSet, UnorderedMap, UnorderedSet,
Deque, PriorityQueue, BinaryHeap, SortedList, Trie, HashIndex) return a
view through the engine's slot pointer exactly as BTreeMap.get did before
#2572: no inference roots it at `self`, so `let view = m.get(1).unwrap();
m.remove(1); print(*view)` compiled for every one of them (twelve probes,
twelve accepted). Each accessor (`get`, `first`, `last`, `front`, `back`,
`peek`) now declares `from self` under §21.1 rule 6, as BTreeMap.get does,
and the D22 cells err_d22_<facade>_<accessor>_origin_after_mutation.w pin
the rejection; a view used before the mutation still compiles.

Co-authored-by: Eric Hartford <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant