Skip to content

examples: rewritten to the current spec (D55 ruling 4) + examples-tests lane in the battery (#1150) - #1308

Merged
ehartford merged 12 commits into
mainfrom
examples-v72
Sep 22, 2026
Merged

ehartford merged 12 commits into
mainfrom
examples-v72

Conversation

@ehartford

Copy link
Copy Markdown
Contributor

Implements Eric's ruling 4 of 2026-09-22 (D55, #1150): examples track the current spec, and get a CI lane so they cannot rot again. Scope per Eric: the failing examples are rewritten the way an application developer writes With today (spec is the authority; idioms from docs/with_for_ai.md and the passing examples), keeping each example's purpose and observable output. One commit per example, spec sections cited in each.

Examples

Example Verdict Verified with Depends on
hello.w, async-collection-await.w, async-tuple-await.w, idiomatic/, bench_demo.w left as-is (already pass) installed compiler —
fizzbuzz.w touched lightly: last arm f"{i}" (§18.2, ruling 6) printd stage1 (print over Display) the print-over-Display PR (not yet opened)
ephemerality-and-lowering/ rewritten: async main awaits the scope demo; tracked tasks bound and awaited (§14.7, the let _ = task spelling is retired); Atomic globals in the async test (§9.1c) installed compiler; with test 4/4 —
nebula/ rewritten: move fn drop() (§2.4), fn Database.open (§3.1), implicit Ok(()), async fn main -> Result + error AppError from ... (§10.9), &str parsers (§3.8), rx.recv() ?? break, tracked results awaited, sleeping select loser (§14.10) stage1 of this tree (post-#1284): runs end to end #1290 for the two batch/stats counts
json_test.w rewritten over std.json's safe surface: JsonDocument.parse, field views, Deserialize incl. @[derive(Serialize, Deserialize)], JsonWriter round trip; no unsafe/&raw installed compiler: 21/21 PASS —
service/ rewritten: move fn builder chain, mut fn handlers on AppState, &T observers, var-base field moves (D32), Copy enums; 27 pub marks (§18.3) installed compiler: original output —
json-parser/ rewritten: mut fn receivers, Unit, consuming advance() lookahead, Option[&JsonValue] views (D27), byte literals installed compiler: original output —
ecs/ rewritten: one generic DenseStorage[T] (extend[T]), views + remove transfers (D27), mut fn systems on World, &T readers, Copy components; 68 pub marks installed compiler: original output #1290 for the spawn builders (despawn demo prints nothing until then)
async-auction.w rewritten: tx.clone() per bidder (§14.15, ruling 5), Atomic counters (§9.1c), the stale "BUG DISCOVERED" workarounds replaced by .await?, is_err, cancel, select await biased, await_all/await_first stage1 of this tree (post-#1283/#1284) and the lane: all 14 phases, prints ok —
channels/pipeline.w touched: demo 3 read 5 items from a channel that receives 3 and hung (the issue's "run hangs"); now a fan-in through cloned senders (§14.15) stage1 of this tree and the lane: fan-in prints 100 101 0 1 2 —
package tests (ecs, service, nebula) touched: top-level constructors, &T params, record update (D32) installed compiler: all pass —

pub counts for the pub(package) argument (Eric asked): service 27, ecs 68, nebula 0 new, json-parser 0. Note the compiler does not enforce §18.3 inside a package today (a probe with no pub at all built), so these are what the spec requires, not what the compiler demanded.

The four committed Mach-O binaries (examples/hello, channels/pipeline, json-parser/json, service/src/main) are removed.

Lane

build/examples.w + examples-tests target in build.w, wired into :test. It checks bench_demo.w, builds and runs the ten single-file examples, builds and runs the three packages, and runs the six package test files, with per-step timeouts and captured stdout/stderr under out/test-graph/examples-tests. The example list is the lane's contract, so examples/spiral/ (untracked user work) is not touched. WITH=$PWD/src/main src/main build :examples-tests on the rebased tree: 19 of 20 steps green; the one red step is examples_fizzbuzz.build, exactly the print-over-Display dependency above, so the lane stays red until that PR merges (it is also the proof the lane bites). :dev green (263 s). Note: main was unbuildable while I ran this (#1284 vs #1283, fixed by #1306); I applied that one-line pub to my working tree only for the run and reverted it — nothing under rt/ or src/ is in this PR.

Compiler defects the rewrite exposed (all filed, with smallest repros)

Not run here (per instructions): :fixpoint, :test, the battery. Run: :dev and :examples-tests (results above).

Eric Hartford added 12 commits September 22, 2026 09:46
…D55 ruling 6; #1150)

A match whose arms do not share a Display type yields nothing joinable;
the spec's fix-it is the f-string. Example updated under the examples
policy (D55 ruling 4). Compiles against the print-over-Display stage1;
the installed compiler still rejects the str/&str join.
…es its globals (§14.7, §9.1c; #1150)

The `let _ = task` detach spelling was retired (§14.7: statement position
already means detach; a bound task must be observed). The example now
demonstrates the replacement: an async main awaits the scope demo, the
tracked tasks are bound and awaited, and the package test is itself
async. The test's defer-order probes become Atomic counters, since the
async test makes the program concurrent (§9.1c rule 2). Typed bindings
feed the Atomic stores until #1287 is fixed. Rewritten under the
examples policy (D55 ruling 4); the README's Zig-bootstrap commands are
replaced with `with check`/`with test`.
…t spec (§3.1, §3.8, §7.4, D32; #1150)

Constructors with no receiver move out of the extend block to top-level
`fn Type.new` (§3.1 location rule); functions that only observe an array
or a struct take `&T` (§3.8, the signature states ownership); the
record-update test spells the record update it claims to test
(`{ base with port }`, §7.4) instead of moving fields out one by one
(D32, §2.2). Updated under the examples policy (D55 ruling 4).
…2, §10.2, §10.9, §14.7, §14.10; #1150)

- `move fn drop()` is the destructor receiver (§2.4); the Database
  constructor is a function of the type (`fn Database.open`, §3.1
  location rule) and the methods use the keyword receiver forms.
- Result[Unit, E] functions end with implicit Ok(()) (§10 happy path);
  main is `async fn main -> Result[Unit, AppError]` and propagates with
  `?` through `error AppError from DbError, SessionError` (§10.9)
  instead of hand-written wrapper variants and .expect().
- Functions that observe take `&T` (§3.8): parse_telemetry(&str) clones
  the bytes it keeps; parse_batch/compute_stats borrow their Vec; the
  status helpers borrow.
- Tracked tasks are bound and awaited (§14.7); a receive uses
  `rx.recv() ?? break` (§10.4); insert_bulk is generic over SqlRecord.
- The select-await race sleeps on the analyzer side so the shutdown
  branch wins (§14.10); a loser parked in recv() deadlocks the runtime
  (#1293). Needs #1284 for `Duration`.
- The derives on Status/Telemetry are parked with a comment until #1288
  (Debug on f64) and #1289 (derive on enums) are fixed; the batch and
  final-stats builders read 0 until #1290 (#1294) lands.
- Package test: record update instead of field-by-field moves (D32).

Rewritten under the examples policy (D55 ruling 4). pub marks needed:
0 new (the package already exported its cross-module names).
…1, §11.8; #1150)

The example drove the raw jsmn token API with `unsafe { json_parse(...) }`,
`&raw mut` and a *mut JsonToken buffer — an application never writes
unsafe (CLAUDE.md, `:user-programs-safe`). It now uses what std.json
exports for applications: JsonDocument.parse, field views (.field/.raw),
Deserialize for primitives and for @[derive(Serialize, Deserialize)]
types (nested), and a JsonWriter round trip. The two incomplete-input
cases are gone: the safe parse panics on malformed input instead of
returning JSON_ERROR_PART. The source copy the round-trip compares
against is spelled (`js.clone()`; parse takes an owned str).

Rewritten under the examples policy (D55 ruling 4); 21 checks pass on
the installed compiler.
….2, §11.8, D32; #1150)

- Builder setters are `move fn` and chain
  (`UserService.builder().with_config(cfg).build()`, §3.1); the
  constructors with no receiver are functions of the type
  (`fn UserService.builder`, `fn HttpResponse.ok` ...).
- Mutating methods are `mut fn` (create_user, bump_*); request
  handling is `mut fn` on AppState instead of `&mut AppState` params.
- Functions that observe take `&T` (§3.8): validate_create(&req) so the
  caller keeps the request for create_user; make_welcome_notification,
  describe_changes borrow their users.
- A consumed request's fields vacate from a `var` base with `move`
  (§2.2, D32); Role and Priority opt into Copy (§11.8) since they are
  passed by value everywhere.
- `pub` on every cross-module name (§18.3): 27 marks (types, methods,
  constructors, functions) across service.w and http.w; the compiler
  does not enforce §18.3 within a package today.
- describe_changes and the postgres SET builder use the `var`
  desugaring of §7.2 until #1298 accepts a trailing `if`.

Rewritten under the examples policy (D55 ruling 4); the demo prints its
original output. Package test updated separately (d3bd2a8f).
…, §10, D22, D27; #1150)

- `mut fn` receivers replace `self: &mut Self` (§3.1); the constructors
  are functions of the type (`fn Tokenizer.new`, `fn Parser.new`).
- `Unit` replaces `void`; happy paths return the value and `?`/
  `return Err(...)` carry the sad path (§10.2), with .Variant spelling.
- The parser consumes its lookahead explicitly: `advance()` moves the
  current token out of the receiver (§2.2 vacate from a mut fn) and
  loads the next, and parse_value dispatches on the consumed token; the
  loops peek through `&self.current`. (A `match self.current:` moves
  the field out and blanks it, #1302.)
- The tree is observed, never consumed (§3.8): json_to_string and the
  lookups take `&JsonValue`; json_get_field/json_get_index return
  Option[&JsonValue] views (D27) and the demo reads them with
  `if let`. A one-line kv_value helper stands in for `&entry.value`
  until #1297.
- Byte literals replace the ASCII magic numbers, as match guards until
  a byte literal is accepted as a pattern (#1295); `-1.0` replaces
  `0.-1.0`; `bump` keeps an explicit Ok(()) until #1296.

Rewritten under the examples policy (D55 ruling 4); the demo prints its
original output (the error-case positions are the more precise ones the
consuming parser reports). pub marks: 0 (single module).
…§11.8, §18.3, D22, D27; #1150)

- One generic DenseStorage[T] (`extend[T]`) replaces five copies; `get`
  returns a view (Option[&T]) and `remove` transfers the component out
  (D27: element access observes, remove transfers). Vec has no swap, so
  the hole is closed with `Vec.remove` and a re-index.
- Systems state what they touch in their signatures (§3.8): the writers
  (input, player controller, movement, run_frame, spawning) are `mut fn`
  on World; the readers (collision, render, response, queries) take
  `&DenseStorage[...]`/`&World`, and run_collision returns its events.
- Constructors are functions of the type (`fn World.new`, `fn Vec2.new`,
  `fn Entity.new`; pub ones with explicit return types); components and
  math types opt into Copy (§11.8); views that must survive a mutation
  are taken as typed independent copies (§3.4, D22 contextual Copy);
  entity_name returns Option[&str].
- `pub` on every cross-module name (§18.3): 68 marks across the six
  modules (the compiler does not enforce §18.3 within a package today).
- World.spawn is spelled spawn_entity until #1303 (a user `spawn`
  method is intercepted by the scope builtin); DenseStorage.insert
  carries `-> Unit` until #1296; the spawn helpers return `with ... as
  mut` builders (§7.2) and so hand back empty Vecs until #1290 (#1294)
  lands, which is why the despawn demo currently prints nothing after
  its header. Package test updated separately (d3bd2a8f).

Rewritten under the examples policy (D55 ruling 4); the demo otherwise
prints its original output.
…§14.7, §14.10, §14.11, §14.15; #1150)

- Every bidder gets its own sender: `tx.clone()` per tracked task, the
  channel closes when the last sender drops (§14.15, D55 ruling 5).
- The verification counters are Atomic[i32] (§9.1c rule 2): the program
  is concurrent, so bare mutated globals are not safe.
- The stale "BUG DISCOVERED" workarounds are gone: `.await?` chains,
  Result.is_err(), task.cancel(), `select await biased` (§14.10) and
  await_all/await_first over a Vec of tasks (§14.11) are written the
  way the spec says; a receive is `rx.recv() ?? break`; Bid is Copy.

Rewritten under the examples policy (D55 ruling 4). Needs #1283 and
#1284 (both merged 2026-09-22); verified against a stage1 of the
rebased tree.
… (§14.15; #1150)

Demo 3 read five values from a channel that only ever receives three,
so the program hung (the survey's 'run hangs'). It now shows the thing
its title promised: two producers feeding one channel through their own
clones of the sender (§14.15, D55 ruling 5), and a consumer draining
it. std.channel is imported so the Clone impl is in scope. Verified with
a stage1 of this tree (post-#1283). Updated under the examples policy
(D55 ruling 4).
…n the battery (#1150, D55 ruling 4)

build/examples.w declares the lane's contract: the single-file examples
are built with the release compiler and run, the packages are built in
their directory and run, the package tests run under `with test`, and
bench_demo.w is checked. Each step has a timeout and its stdout/stderr
captured under out/test-graph/examples-tests; one red step fails the
target, and the target is a dependency of :test, so a rotted example
turns the battery red. The list is explicit, so untracked user work
beside the examples (examples/spiral) is not on it.

The four committed Mach-O build outputs (examples/hello,
channels/pipeline, json-parser/json, service/src/main) are removed:
the lane builds them under out/.
…(§3.8, D32; #1150)

`match (req.method, req.path)` moves two fields out of a request the
handler still needs; main's D32 rule (#1301) now says so. The router
matches `(&req.method, &req.path)` and hands the whole request on.
@ehartford
ehartford merged commit bbb9c5b into main Sep 22, 2026
0 of 5 checks passed
@ehartford
ehartford deleted the examples-v72 branch September 22, 2026 14:11
ehartford added a commit that referenced this pull request Sep 22, 2026
…mpiler defects (#1338)

* examples: ephemerality-and-lowering stores the element directly, store(order[2], ...) (#1287 fixed in #1311)

The typed-binding detour around #1287 (Atomic intrinsics passed an element view's address as the value) is gone with its comment. Package test output unchanged on a release compiler built from ae609cd.

* examples: json-parser matches byte literals as patterns and returns &entry.value inline (#1295, #1297 fixed)

Byte arms are Some(b'{') patterns, not guards (#1295, fixed in #1312); json_get_field returns Some(&entry.value) from a for loop over the entries, and the kv_value helper is gone (#1297, fixed in #1327). Workaround comments removed. Demo and package test output unchanged on a release compiler built from ae609cd.

* examples: nebula's Status and Telemetry carry @[derive(Debug, Clone)] again (§11.8; #1288, #1289 fixed in #1311)

The parking comment is removed. Demo and package test output unchanged on a release compiler built from ae609cd.

* examples: service builds its change list and SET clause with the §7.2 builder (#1298 fixed in #1319)

describe_changes and PgUserRepo.update spell with Vec.new() as mut ...: with a trailing if; the var desugaring and its comments are gone. Demo and package test output unchanged on a release compiler built from ae609cd (neither function is reached by the demo; the same shape was run separately under --debug-alloc: correct result, zero leaks).

* examples: ecs cites D43 for DenseStorage.insert's -> Unit, not #1296

insert's tail if has an assignment arm (a value of type T) and a push arm (Unit): two meanings remain, so -> Unit is the spelling D43 requires, not a workaround. The compiler currently infers Unit without it because the assignment arm is a multi-statement block (#1337); the one-statement spellings of the same arm are rejected as D43 requires.

---------

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