Commit 93530674

93530674539eMerged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 17 files · +8 added · ~5 modified

Description

Add C compiler scaffold (M0): single-binary parse -> codegen

Stand up the C reimplementation of the Spinel compiler under src/, per the plan in C-SPINEL.md. The Ruby analyzer/codegen move to legacy/ as the regression oracle; the new compiler is a single binary that holds the AST and compiler state in memory with no on-disk intermediates.

  • Reuse spinel_parse.c's Prism walk: extract the parse core into sp_parse_emit(FILE*), guard the standalone main() behind !SPINEL_PARSE_AS_LIB, and expose sp_parse_file_to_text() which writes the text AST to an in-memory stream. Standalone parser output is byte-identical (verified).
  • src/node_table.{c,h}: in-memory AST node table mirroring the text schema (N/S/I/F/R/A), loaded directly from the parser's text output (C port of node_table_loader.rb).
  • src/codegen.{c,h}: M0 vertical slice -- puts, integer literals, and the +,-,* operators -- emitting the same prologue and sp_* runtime calls as legacy. Unsupported constructs abort loudly.
  • src/main.c: CLI driver (parse -> load -> codegen), emits C to stdout or -o file, plus --dump-ast.
  • Makefile: build build/spinelc from src/ + the parser-as-lib object; add a legacy target for the Ruby oracle; repoint test/bench/optcarrot at the C compiler (optcarrot links with --int-overflow=wrap).

make spinelc builds; puts 1 + 2 compiles, links against libspinel_rt.a, and prints 3. Baseline make test: 0 pass / 844 error (expected -- the climb starts here).

Co-Authored-By: Claude Opus 4.8 (1M context) [email protected]

Details

Commit
93530674539e
Parent
931b98e6276c

C-SPINEL.mdaddedView file

1+# C-SPINEL: Reimplementing the Spinel compiler in C
2+
3+## Why
4+
5+Spinel is an AOT Ruby-to-C compiler that is **self-hosted**: the analyzer and
6+code generator are written in Ruby (`legacy/spinel_analyze.rb`,
7+`legacy/spinel_codegen.rb`) and are themselves compiled to C by Spinel. The
8+problem is build time. Bootstrapping compiles ~93k lines of Ruby through the
9+whole pipeline into multi-megabyte C files, and the `-O3 -flto` link of that
10+generated C dominates the dev loop (the reason the memory keeps a "use LTO=0"
11+note). Every inference change risks a stage-2 self-host cascade because the
12+compiler is written in the very subset it compiles.
13+
14+Rewriting the analyzer and code generator **directly in C** removes both costs:
15+the compiler becomes a small, fast-to-build native program, and an entire class
16+of self-host hazards disappears (see "What gets easier" below).
17+
18+## Goal (definition of done)
19+
20+1. A single C binary in `src/` that compiles a `.rb` file end to end.
21+2. New Makefile targets `test`, `bench`, `optcarrot` driving that binary, plus
22+ a `legacy` target that builds the Ruby compiler as a regression oracle.
23+3. `make test` passes (the 844-case `test/` golden corpus).
24+4. `make bench` and `make optcarrot` pass.
25+
26+The ordering in the request is deliberate: stand up the targets (`test`,
27+`bench`, `optcarrot`, `legacy`), then drive them to green starting with `test`.
28+
29+## Architecture
30+
31+### One binary, no intermediate files
32+
33+Today the pipeline is three programs talking through files on disk:
34+
35+```
36+app.rb --[spinel_parse (C)]--> app.ast --[spinel_analyze (Ruby)]--> app.ir --[spinel_codegen (Ruby)]--> app.c --[cc]--> app
37+```
38+
39+The C rewrite collapses analyze+codegen into **one process** that holds the
40+shared compiler state in memory and never serializes the AST or IR for normal
41+operation:
42+
43+```
44+app.rb --[Prism walk]--> node table (in mem) --[analyze]--> Compiler state (in mem) --[codegen]--> app.c --[cc]--> app
45+```
46+
47+C source is split across ~8-15 translation units (TUs) for fast incremental
48+builds, but they **link into one binary**. "Split the source, not the program."
49+
50+### The front end is already done — reuse it
51+
52+`spinel_parse.c` (~2500 lines) already walks the full Prism AST and emits the
53+text node-table format. It parses everything the test corpus needs. We refactor
54+it to **populate an in-memory node table** (the same node schema) instead of
55+printing text. That makes the front end ~100% complete on day one.
56+
57+**Consequence: the entire port surface and all the risk is analyze + codegen.**
58+The plan below is almost entirely about those two.
59+
60+### Reuse the runtime library unchanged
61+
62+`lib/` already contains the full C runtime the generated programs link against:
63+`sp_runtime.h` (the big header the emitted C `#include`s), `libspinel_rt.a`
64+(bigint, regexp engine, GC, fiber, pack, strscan, time, net, io, crypto —
65+~10k lines of C). The generated C is unchanged in shape, so **the runtime is
66+reused as-is**. Our code generator must emit the same `sp_*` calls the legacy
67+generator emits (e.g. `sp_int_add`, `SP_GC_SAVE`, the `needs_*` prologue).
68+
69+### The IR dump is the schema of the central struct
70+
71+The legacy `.ir` file is a serialization of the analyzer's `@ivar` state — the
72+whole-program tables the code generator reads back: `needs_*` capability flags,
73+`@meth_names` / `@meth_param_types` / per-class method tables, inferred node
74+types, etc. In one binary those stages stop serializing and **share one
75+`Compiler` struct**. That struct's field inventory is exactly the set of lines
76+in a representative `.ir` dump.
77+
78+Design this struct first; it is the backbone of the whole program. Derive its
79+fields by dumping the IR of a *rich* program (not the 13-line `puts 1+2` case)
80+and cataloguing every `INT/STR/SA/...` key.
81+
82+## Type system (highest-risk foundation — design before code)
83+
84+Spinel's lattice is a set of **string tags**, ported verbatim as interned type
85+ids (an enum for the closed core, plus parameterized container tags). From the
86+analyzer the live tag vocabulary is:
87+
88+- Scalars: `int`, `float`, `string`, `symbol`/`sym`, `bool`, `nil`, `bigint`
89+- Nullable scalars: `int?`, `string?`, `float?` (sentinel-encoded; see memory)
90+- Typed arrays: `int_array`, `float_array`, `str_array`, `poly_array`,
91+ `ptr_array`
92+- Typed hashes: `int_int_hash`, `str_int_hash`, `str_str_hash`, `int_str_hash`,
93+ `sym_int_hash`, `sym_str_hash`, ... (key_value naming)
94+- Other: `range`, `regexp`, `proc`, `lambda`, `class`, `void`
95+- `poly` — the union / top type (a value whose static type widened)
96+
97+`base_type(t)` strips nullability/decoration to the core tag and is called
98+everywhere; `infer_type(nid)` is the central query. **Before writing the
99+type module, read the actual representation in `legacy/compiler_helpers.rb`
100+(`compiler_state_field_type`, `compile_time_literal_type`,
101+`infer_nil_guard_narrow_type`, `poly_dispatch_*`, `base_type`) and the type
102+constants in `spinel_analyze.rb`.** This is the foundation and the area where a
103+wrong model costs the most.
104+
105+Representation plan: a small `sp_type` value = interned id. Containers and
106+hashes get a compact encoding (enum kind + element/key/value tags). Provide the
107+helper surface the passes need: `base_type`, `is_nullable`, `nullable_of`,
108+`unify`/widen-to-poly, `array_of`, `hash_of`, tag<->string for `--dump-ir`.
109+
110+## CLI / cc contract
111+
112+The binary's job for the harness is **`.rb -> C`**; a thin wrapper (or the
113+binary itself) invokes `cc` to link against `libspinel_rt.a`, mirroring the
114+existing `spinel` shell script so harness edits stay minimal. Scope for `make
115+test`:
116+
117+- Required modes: emit-C-to-file and emit-C-to-stdout; the cc-and-link step.
118+- Required overflow modes: **`raise`** (default, used by `test`) and **`wrap`**
119+ (used by `optcarrot`, which routes through `spinel --int-overflow=wrap`).
120+ `promote` is deferred.
121+- **Not needed for `make test`** and explicitly out of initial scope: `-e`/`-E`
122+ run mode, `--emit-rbs`, `--emit-types`, `--emit-symbol-map`, RBS seeding,
123+ FFI link/cflag scraping, `--debug`/`#line` line-mapping. Add later only if a
124+ target needs them. (optcarrot/bench/test do not.)
125+
126+`docs/INCOMPATIBILITIES.md` is part of the behavioral spec — intentional
127+divergences from CRuby (e.g. `Integer#**` negative exponent = RangeError) must
128+be preserved, not "fixed."
129+
130+## Verification strategy
131+
132+The ratchet is **output equivalence**, exactly what the harness already does:
133+parse → analyze → codegen → cc → run, then `diff` against `test/<name>.rb.expected`
134+(and against CRuby for `bench`/`optcarrot`). We do **not** need bit-exact IR
135+parity with legacy, nor legacy's inference precision, nor its speed — only
136+inference precise enough to compile and to match *observable* semantics
137+(nil/nullable behavior, overflow mode, hash defaults, `INCOMPATIBILITIES.md`).
138+
139+Debugging lens (keep, but never gate on it): retain optional `--dump-ast` /
140+`--dump-ir` text output in the legacy format. Two payoffs on a 93k-line port:
141+
142+1. **Localization** — diff our analyzer's IR against legacy's at the stage
143+ boundary ("node 412 got `poly` not `int_array`") instead of "test N fails
144+ somewhere downstream."
145+2. **Cross-execution** — feed legacy's IR into our codegen, or our IR into
146+ legacy's codegen, to isolate *which stage* diverged.
147+
148+Bit-exact IR is too brittle to gate on (counters, hash iteration order), so it
149+stays a lens, not a gate.
150+
151+`make legacy` builds the Ruby oracle (`spinel_analyze`/`spinel_codegen` via the
152+existing bootstrap path) so it stays available for these diffs and for any test
153+whose `.expected` needs regenerating.
154+
155+## What gets easier (and what doesn't)
156+
157+Roughly half the hazards in the project memory exist **only because the
158+compiler was written in the subset it compiles**: stage-2 self-host cascades,
159+node-id/seed "poison" (`get_args` widening, node-id-as-poly), "widening breaks
160+bootstrap," the MRI-harness-vs-self-host divergences. In hand-written C these
161+are **gone** — write the inference straightforwardly, no placeholder-parity or
162+post-fixpoint re-narrow gymnastics needed to keep a bootstrap alive.
163+
164+What does **not** get easier: over-widening still changes program output (a
165+value typed `poly` when it should be `int_array` can pick a different runtime
166+path), and nullable/overflow/default semantics still have to match. "Relaxed"
167+is not "free." Correctness is still judged by the goldens.
168+
169+## Source layout (`src/`)
170+
171+Target ~8-15 TUs, each budgeted to ~2-3k lines so no single `.c` dominates
172+compile time. Initial split (will be refined as codegen grows):
173+
174+| File | Responsibility |
175+|------|----------------|
176+| `main.c` | CLI parsing, mode dispatch, cc invocation |
177+| `node_table.{c,h}` | AST node storage (parallel arrays: type, string/int/ref/array fields), the schema Prism populates |
178+| `parse.c` | Prism walk → node table (adapted from `spinel_parse.c`) |
179+| `compiler.{c,h}` | the shared `Compiler` state struct (= IR schema) + lifecycle |
180+| `types.{c,h}` | type lattice: tags, `base_type`, unify, container/hash encoding, tag<->string |
181+| `analyze.c` + `analyze_*.c` | inference passes, split by area (literals, methods, classes, hashes/containers, fixpoint driver) |
182+| `codegen.c` + `codegen_*.c` | C emission, split by area (expr, stmt, class/method, builtins: string / array / hash, runtime prologue & `needs_*`) |
183+| `emit.{c,h}` | output buffer + formatting helpers shared by codegen |
184+| `irdump.c` | optional `--dump-ast`/`--dump-ir` (debug lens) |
185+
186+Build: per-module `.o`, relink-only-changed. Modular incremental compilation is
187+**the deliverable's actual value** and a first-class design constraint, not an
188+afterthought.
189+
190+## Build / Makefile changes
191+
192+Confirmed directional decisions (2026-06-08):
193+
194+- **Front end:** reuse `spinel_parse.c`'s Prism walk, refactored to fill the
195+ in-memory node table; keep its text output as `--dump-ast`.
196+- **CLI/cc:** the C binary does `.rb -> C` only; a thin driver (the existing
197+ `spinel` script, repointed) invokes `cc`/link. Minimal harness change.
198+- **Targets:** repoint `test`/`bench`/`optcarrot` at the C binary **from the
199+ start** — no interim parallel target. The trade-off is accepted: these main
200+ targets are red until parity is reached. `legacy` is added for the oracle.
201+
202+Concretely:
203+
204+- **`test`/`bench`/`optcarrot`** are repointed at the new C binary immediately.
205+ Until M4 they will report failures; that is the expected state during the
206+ climb, and the failing-test count is the progress metric.
207+- **New `legacy` target:** build the Ruby `spinel_analyze`/`spinel_codegen`
208+ oracle (the current bootstrap path), used for IR diffs and `.expected` regen.
209+ This preserves access to the oracle even after the main targets move.
210+- New `src/`-driven object rules with a per-file size budget; one final link.
211+- Keep `parse`/`regexp`/runtime rules as-is (reused unchanged).
212+
213+## Milestone ladder (test-driven, vertical slices)
214+
215+Each milestone is gated by a growing subset of the 844-test corpus; the legacy
216+oracle localizes any regression.
217+
218+- **M0 — Scaffolding.** `src/` builds and links one binary against Prism +
219+ `libspinel_rt.a`. Refactor `spinel_parse.c`'s Prism walk to fill the
220+ in-memory node table. Stub analyze + a trivial codegen that handles
221+ `puts <int>` and integer arithmetic, emitting the same prologue/`sp_*` calls
222+ as legacy. Wire `make legacy` and repoint `test`/`bench`/`optcarrot` at the C
223+ binary (they go red — expected). **Exit:** `puts 1 + 2` compiles, links, and
224+ prints `3`.
225+- **M1 — Core expressions & statements.** Locals, conditionals, loops,
226+ string/float/bool/nil/symbol literals, method calls on core types, `def`/
227+ return. Climb the easy slice of `test/`. **Exit:** a few hundred scalar tests
228+ green.
229+- **M2 — Type inference parity where it affects output.** Containers (typed
230+ arrays/hashes), nullable scalars, the fixpoint driver, `poly` dispatch.
231+ Localize divergences via `--dump-ir` against legacy. **Exit:** container &
232+ inference tests green.
233+- **M3 — Classes, modules, blocks, exceptions.** Method tables, `attr_*`,
234+ inheritance/`include`, blocks/`yield`, `begin/rescue` (setjmp model, matching
235+ legacy), regexp. **Exit:** the structural slice green.
236+- **M4 — Full `test` green** (the targets are already pointed here), then
237+ `bench` (vs CRuby) and `optcarrot` (`--int-overflow=wrap`, `checksum: 59662`).
238+ Close the long tail of builtins.
239+- **M5 — Cleanup.** Document the new build in README; decide the fate of the
240+ legacy Ruby sources / bootstrap path now that the C compiler is primary.
241+
242+## Open risks
243+
244+- **Scale.** ~37k lines of analyzer + ~54k of codegen of behavior to
245+ reproduce. Mitigation: vertical slices, the golden corpus as a ratchet, and
246+ the legacy oracle for localization. We reproduce *observable behavior*, not
247+ source structure — large stretches of the Ruby (self-host workarounds,
248+ defensive poly handling) have no C counterpart.
249+- **Inference precision drift.** Too narrow → miscompiles; too wide → wrong
250+ runtime path. Caught by output diffs; localized by IR diffs.
251+- **Builtin breadth.** The string/array/hash/enumerable method surface is
252+ large. Drive it demand-first from failing tests rather than enumerating
253+ upfront.