Commit a6b3b81a

a6b3b81ac804Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 1 file · ~1 modified

Description

README: describe the C compiler reimplementation

master is now a single self-contained C binary (src/analyze*.c + src/codegen*.c) that parses via libprism, infers types and emits C in one process -- no IR file between stages, no Ruby at compile time. Update the intro, pipeline diagram, architecture, and analyze/codegen sections to match; reframe the self-hosting Ruby backend as the in-tree regression oracle under legacy/; fix the Portability/runtime-linking and CRuby notes (generated C links libspinel_rt.a); refresh the suite counts (886 tests, 57 benchmarks) and the History section.

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

Details

Commit
a6b3b81ac804
Parent
43d8d58768fb

README.mdmodifiedView file

@@ -4,8 +4,12 @@
44 It performs whole-program type inference and generates optimized C code,
55 achieving significant speedups over CRuby.
66
7-Spinel is **self-hosting**: the compiler backend is written in Ruby and
8-compiles itself into a native binary.
7+The compiler is a **single self-contained C binary**: it parses Ruby (via
8+libprism), infers types across the whole program, emits C, and invokes the
9+system `cc` to produce a native executable -- no Ruby runtime and no chained
10+helper binaries at compile time. (Spinel was previously written in a
11+self-hosting Ruby subset; that backend is preserved in-tree as a regression
12+oracle -- see [History](#history).)
913
1014 ## How It Works
1115
@@ -13,39 +17,34 @@
1317 Ruby (.rb)
1418 |
1519 v
16-spinel_parse Parse with Prism (libprism), serialize AST
17- | (C binary, or CRuby + Prism gem as fallback)
20+parse (libprism) Parse with Prism, linked in as a C library
21+ | (a CRuby + Prism-gem path produces the same AST)
1822 v
19-AST text file (.ast)
23+text AST -> NodeTable Loaded into an in-memory node table
2024 |
2125 v
22-spinel_analyze Whole-program type inference (self-hosted)
23- | Walks AST to fixpoint: param / return / ivar
24- | types, value-type detection, DCE markers,
25- | per-node inferred-type cache.
26+analyze Whole-program type inference (src/analyze*.c).
27+ | Walks the AST to a fixpoint: param / return / ivar
28+ | types, value-type detection, dead-code markers,
29+ | a per-node inferred-type cache.
2630 v
27-IR text file (.ir)
28- |
29- v
30-spinel_codegen C code generation (self-hosted)
31- | Consumes .ast + .ir, emits one C file.
31+codegen C code generation (src/codegen*.c). Reads the AST
32+ | plus the analysis just computed in the same process,
33+ | emits one C file.
3234 v
3335 C source (.c)
3436 |
3537 v
36-cc -O2 -Ilib -lm Standard C compiler + runtime header
38+cc -O2 -Ilib -lm System C compiler + runtime
3739 |
3840 v
3941 Native binary Standalone, no runtime dependencies
4042 ```
4143
42-The analyze / codegen split is by design -- they live in separate
43-binaries (`spinel_analyze`, `spinel_codegen`) that share no in-memory
44-state. Everything analyze decides is serialized through the IR file;
45-codegen reconstructs its inferred view from that contract. See
46-[docs/ANALYZE-IR.md](docs/ANALYZE-IR.md) for the per-record format
47-and [docs/AST.md](docs/AST.md) for the AST format the analyze stage
48-consumes.
44+Analyze and codegen run in one process and share the in-memory model:
45+codegen reads the types analyze just inferred directly, with no
46+serialization step in between. See [docs/AST.md](docs/AST.md) for the
47+text AST format the parser emits and the analyzer consumes.
4948
5049 ## Quick Start
5150
@@ -116,51 +115,39 @@
116115 ### RBS type signatures
117116
118117 Spinel can read RBS files to seed the analyzer. When invoked with
119-`--rbs DIR`, the `spinel` wrapper runs `spinel_rbs_extract` over a
120-directory of `*.rbs` files (the same layout `rbs` and Steep use) and
121-passes the resulting seed file to `spinel_analyze` as a positional
122-argument. Seeds are advisory — inference still runs on top and
118+`--rbs DIR`, `spinel` runs `spinel_rbs_extract` over a directory of
119+`*.rbs` files (the same layout `rbs` and Steep use) and feeds the
120+resulting seed into the analyzer. Seeds are advisory — inference still runs on top and
123121 widens on observed contradiction, so a wrong or unrepresentable seed
124122 is at worst a no-op. See [docs/RBS-EXTRACT.md](docs/RBS-EXTRACT.md)
125123 for the supported subset.
126124
127-## Self-Hosting
125+## Self-Hosting (legacy oracle)
128126
129-Spinel compiles its own backend. Both `spinel_analyze.rb` and
130-`spinel_codegen.rb` are written in a Ruby subset that compiles through
131-the same pipeline that compiles user code. The bootstrap chain
132-exercises each side in both dimensions (IR fixpoint, C fixpoint):
127+Spinel began as a compiler written in a Ruby subset that compiled
128+itself. The C compiler has since replaced that backend, but the
129+self-hosting Ruby implementation is kept in-tree (under `legacy/`) as a
130+**regression oracle**. `make bootstrap` exercises its 4-way self-host
131+fixpoint -- the Ruby backend, compiled by the previous generation,
132+must reproduce byte-identical IR and C across two generations of both
133+the analyze and codegen sides:
133134
134135 ```
135-CRuby + spinel_parse(.rb) → analyze.ast / codegen.ast
136-CRuby + spinel_analyze.rb → analyze1.ir, codegen1.ir
137-CRuby + spinel_codegen.rb → analyze1.c, codegen1.c → bin1 (analyze + codegen)
138-
139-bin1 + analyze.ast → analyze2.ir
140-bin1 + analyze.ast + .ir → analyze2.c → bin2 (analyze)
141-bin1 + codegen.ast → codegen2.ir
142-bin1 + codegen.ast + .ir → codegen2.c → bin2 (codegen)
143-
144-bin2 + analyze.ast → analyze3.ir
145-bin2 + analyze.ast + .ir → analyze3.c
146-bin2 + codegen.ast → codegen3.ir
147-bin2 + codegen.ast + .ir → codegen3.c
148-
149-analyze2.ir == analyze3.ir (analyze.rb: IR fixpoint OK)
150-analyze2.c == analyze3.c (analyze.rb: C fixpoint OK)
151-codegen2.ir == codegen3.ir (codegen.rb: IR fixpoint OK)
152-codegen2.c == codegen3.c (codegen.rb: C fixpoint OK)
136+analyze2.ir == analyze3.ir (analyze: IR fixpoint OK)
137+analyze2.c == analyze3.c (analyze: C fixpoint OK)
138+codegen2.ir == codegen3.ir (codegen: IR fixpoint OK)
139+codegen2.c == codegen3.c (codegen: C fixpoint OK)
153140 ```
154141
155-All four `==` checks have to hold for `make bootstrap` to declare
156-success. Any change that affects deterministic output -- record order,
157-default-value handling, hash iteration -- breaks one of them, and the
158-bootstrap stops with a clear `analyze.rb: IR fixpoint FAIL` (or the
159-matching codegen / C variant) so the regression surfaces immediately.
142+Any change that affects deterministic output -- record order,
143+default-value handling, hash iteration -- breaks one of these checks.
144+The bootstrap is no longer part of the standard gate (the C build is
145+checked by `make test` / `make bench` / `make optcarrot`); it remains
146+available for verifying the legacy backend still round-trips.
160147
161148 ## Benchmarks
162149
163-384 tests pass. 52 benchmarks pass.
150+886 tests pass. 57 benchmarks pass.
164151 Geometric mean: **~7.8x faster** than Ruby 4.0.4 with `--yjit` across
165152 the 28 benchmarks below. Baseline is CRuby 4.0.4 (stable), run with
166153 `--disable-gems` and with `--yjit` for the JIT column. Each timing is
@@ -344,13 +331,9 @@
344331 -fdata-sections` and linked with `--gc-sections`; each unused
345332 runtime function is stripped from the final binary.
346333 - **Iterative inference early exit**: the param/return/ivar fixed-point
347- loop stops as soon as a signature of the three refined arrays stops
348- changing. Most programs converge in 1-2 iterations instead of the
349- full 4, cutting bootstrap time by ~14%.
350-- **`parse_id_list` byte walk**: the AST-field list parser (called
351- ~120 K times during self-compile) walks bytes manually via
352- `s.bytes[i]` instead of `s.split(",")`, dropping N+1 allocations
353- per call to 2.
334+ loop stops as soon as a signature over the refined tables stops
335+ changing. Most programs converge in a couple of iterations, keeping
336+ compile time low.
354337 - **Warning-free build**: generated C compiles cleanly at the default
355338 warning level across every test and benchmark; the harness uses
356339 `-Werror` so regressions surface immediately.
@@ -358,129 +341,95 @@
358341 ## Architecture
359342
360343 ```
361-spinel Single binary: compiler + cc driver (symlink to build/spinel)
362-spinel_parse.c C frontend: libprism → text AST (1_608 lines)
363-spinel_analyze.rb Type inference: AST → IR (21_162 lines, self-hosted)
364-spinel_codegen.rb C emission: AST + IR → C (30_411 lines, self-hosted)
365-lib/sp_runtime.h Runtime library header (1_537 lines)
366-lib/sp_bigint.c Arbitrary precision integers (5_400 lines)
367-lib/regexp/ Built-in regexp engine
368-test/ 384 feature tests
369-benchmark/ 52 benchmarks
370-docs/ Format specs (AST, IR, FFI, sp_Class design)
344+spinel Single binary: parse + analyze + codegen + cc driver
345+ (repo-root symlink to build/spinel)
346+src/spinel_parse.c Frontend: libprism → text AST
347+src/node_table.c AST loader: text AST → in-memory NodeTable
348+src/analyze*.c Whole-program type inference
349+src/codegen*.c C code generation
350+src/main.c CLI driver: pipeline + cc invocation
351+lib/sp_runtime.h Runtime library header (GC, arrays, hashes, strings)
352+lib/sp_*.c Out-of-line runtime (bigint, GC, fiber, I/O, time, ...)
353+lib/regexp/ Built-in regexp engine; all linked into libspinel_rt.a
354+legacy/ Former self-hosting Ruby backend (regression oracle)
355+test/ 886 feature tests
356+benchmark/ 57 benchmarks
357+docs/ Format specs (AST, FFI, sp_Class design)
371358 Makefile Build automation
372359 ```
373360
374-The two backend stages -- `spinel_analyze.rb` and `spinel_codegen.rb`
375--- are both written in the Ruby subset that Spinel itself can compile:
361+The analyzer and code generator are C (`src/analyze*.c`,
362+`src/codegen*.c`) sharing a common `Compiler` over the in-memory
363+`NodeTable`. The pipeline accepts the Ruby subset Spinel targets:
376364 classes, `def`, `attr_accessor`, `if`/`case`/`while`,
377-`each`/`map`/`select`, `yield`, `begin`/`rescue`, String/Array/Hash
378-operations, File I/O.
365+`each`/`map`/`select`, `yield`, blocks (including `...` argument
366+forwarding), `begin`/`rescue`, String/Array/Hash operations, File I/O.
379367
380-No dynamic metaprogramming or `eval` in either backend. Compile-time class-body
368+No dynamic metaprogramming or `eval`. Compile-time class-body
381369 declarations with compile-time-known literal inputs are supported for
382370 Struct-style method synthesis.
383371
384-### What spinel_analyze does
385-
386-The analyze stage owns whole-program type inference. It's a sequence
387-of passes over the AST, each one filling in or refining one piece of
388-the static model:
389-
390-1. **`collect_all`** -- single walk that registers every class,
391- module, top-level method, instance method, class method, ivar
392- declaration, FFI declaration, regexp literal, and constant. After
393- this pass the parallel tables (`@cls_names`, `@meth_names`,
394- `@cls_ivar_names`, ...) carry every name the program defines.
395-
396-2. **Per-scope call-site widening** -- `infer_main_call_types`,
397- `infer_function_body_call_types`, `infer_class_body_call_types`,
398- `infer_ieval_body_call_types`. Walks each scope's call sites and
399- feeds the arg types into the callee's param-type slots via
400- `unify_call_types`. The unifier widens to `poly` only when two
401- call sites disagree -- the conservative direction.
402-
403-3. **Iterative refinement loop (≤ 4 rounds)** --
404- `infer_all_returns`, `infer_function_body_call_types`,
405- `infer_class_body_call_types`, `infer_ivar_types_from_writers`,
406- `infer_param_array_type_from_body`,
407- `narrow_param_types_from_body_method_calls`,
408- `narrow_param_hash_types_from_body_writes`,
409- `widen_cmeths_via_hash_each_blocks` (#424),
410- `detect_poly_params`. The loop terminates when
411- `inference_signature` -- a fingerprint over return types, ivar
412- types, param types, cmeth ptypes -- stops changing. Most programs
413- converge in 1-2 rounds; the cap at 4 catches pathological cases
414- without exploding compile time.
415-
416-4. **Post-loop fixups** -- `fix_nil_ivar_self_refs` (e.g. `@left =
417- nil` on an attr_accessor inside `class Node` resolves to
418- `obj_Node?`), `fix_lambda_return_types`, then re-run the inference
419- passes so dependent types pick up the corrections.
420-
421-5. **`refine_all_module_ivar_types`** -- with stable param types in
422- hand, module-level `@@h[k] = v` ivar writes can now refine the
423- hash variant from the placeholder `str_int_hash` default to the
424- actual key/value shape.
425-
426-6. **Feature detection** -- `pre_detect_bigint`, `detect_features`,
427- `detect_value_types`, `recalc_needs_gc`, `collect_sym_names`,
428- `scan_toplevel_ivars`, `compute_live_cls_methods`,
429- `compute_live_instance_methods`. Sets the `@needs_*` flags that
430- gate runtime helper emission and marks classes / methods for DCE.
431-
432-7. **`precompute_all_scope_decls`** -- runs the multi-pass local-decl
433- refinement per method / cmeth / ieval / main scope and stores the
434- result in `@nd_scope_names[bid]` / `@nd_scope_types[bid]` so
435- codegen doesn't have to re-run `scan_locals`.
436-
437-8. **`annotate_all_node_types`** -- post-order walks every reachable
438- AST node, calls `infer_type`, fills `@nd_inferred_type[nid]`.
439- Codegen's own `infer_type` hits this cache > 99 % of the time at
440- emit; only block-body expressions (whose scope is
441- iterator-specific) and a few `@current_class_idx`-dependent arms
442- fall through.
443-
444-9. **`dump_analysis_buf`** -- serializes the result. See
445- [docs/ANALYZE-IR.md](docs/ANALYZE-IR.md) for the line-oriented
446- text format that lands in the `.ir` file.
447-
448-### What spinel_codegen does
449-
450-The codegen stage reads `.ast` + `.ir`, then emits one C file:
451-
452-- `load_analysis_buf` reconstructs every analysis-derived ivar from
453- the IR. After this, `@cls_names`, `@meth_return_types`,
454- `@nd_inferred_type`, `@nd_scope_names`, etc. are populated as if
455- the analyze passes had just run.
456-
457-- `generate_code` emits the standard preamble (`#include
458- "sp_runtime.h"`, the per-program runtime helpers gated on
459- `@needs_*` flags, the sp_Class tables for hierarchy-using
460- programs, the symbol intern table, class structs and constructors,
461- forward declarations), then walks every reachable method / cmeth
462- body to emit its `static inline` definition, then emits
463- `int main()`.
464-
465-- Per-program runtime helpers are gated. A `puts "hi"` program emits
466- ~10 lines of C; a program that touches Method instances, hash
467- literals, the class hierarchy, etc. gets the matching runtime
468- blocks. The gating ladder is set by pre-scan passes in
469- `generate_code` so the gates have the right value before the
470- emission decisions land.
471-
472-The runtime (`lib/sp_runtime.h`) contains GC, array/hash/string
473-implementations, and all runtime support as a single header file.
474-Generated C includes this header, and the linker pulls only the
475-needed parts from `libspinel_rt.a` (bigint + regexp engine).
372+### What analyze does
373+
374+The analyze stage (`analyze_program`) owns whole-program type
375+inference. It's a sequence of passes over the AST, each one filling in
376+or refining one piece of the static model:
377+
378+1. **Registration** -- a walk that registers every class, module,
379+ top-level method, instance/class method, ivar, FFI declaration,
380+ regexp literal, and constant, then resolves parents, includes,
381+ prepends, attr/alias declarations and inherited members. After
382+ this the compiler's tables carry every name the program defines.
383+
384+2. **Call-site widening** -- each scope's call sites feed their arg
385+ types into the callee's param slots. The unifier widens to `poly`
386+ only when two call sites disagree -- the conservative direction.
387+
388+3. **Iterative refinement loop** -- return types, ivar types from
389+ writers, param types (array / hash / string specializations),
390+ block-param types, default-param types, and `for`/bigint loop
391+ locals are re-inferred to a fixpoint. The loop terminates when a
392+ signature over those tables stops changing; most programs converge
393+ in a couple of rounds.
394+
395+4. **Feature detection** -- value-type detection (which small
396+ immutable classes become stack structs), GC need, symbol
397+ collection, proc-capture marking, and reachability. These set the
398+ flags that gate runtime-helper emission and mark classes / methods
399+ for dead-code elimination.
400+
401+5. **Node-type annotation** -- a final pass fills a per-node
402+ inferred-type cache that codegen reads directly while emitting,
403+ avoiding any re-inference at emit time.
404+
405+### What codegen does
406+
407+The codegen stage runs in the same process on the same `Compiler`,
408+then emits one C file:
409+
410+- It emits the preamble (`#include "sp_runtime.h"`, the per-program
411+ runtime helpers gated on the analysis flags, the sp_Class tables for
412+ hierarchy-using programs, the symbol intern table, class structs and
413+ constructors, forward declarations), walks every reachable method /
414+ class-method body to emit its definition, then emits `int main()`.
415+
416+- Per-program runtime helpers are gated. A `puts "hi"` program emits a
417+ handful of lines of C; a program that touches Method instances, hash
418+ literals, the class hierarchy, etc. gets the matching runtime blocks.
419+
420+The runtime is split between a header (`lib/sp_runtime.h`: GC,
421+array/hash/string implementations, inline hot paths) and out-of-line
422+sources (`lib/sp_*.c`, `lib/regexp/`) archived into `libspinel_rt.a`.
423+Generated C includes the header and links the archive; `--gc-sections`
424+drops every unused runtime function from the final binary.
476425
477426 The parser has two implementations:
478-- **spinel_parse.c** links libprism directly (no CRuby needed)
427+- **src/spinel_parse.c** links libprism directly (no CRuby needed)
479428 - **spinel_parse.rb** uses the Prism gem (CRuby fallback)
480429
481-Both produce identical AST output. The `spinel` wrapper prefers the
482-C binary if available. `require_relative` is resolved at parse time
483-by inlining the referenced file.
430+Both produce identical AST output; the C path is the default.
431+`require_relative` is resolved at parse time by inlining the
432+referenced file.
484433
485434 ## Building
486435
@@ -509,8 +458,10 @@
509458 already have the prism gem installed, the build auto-detects it; you
510459 can also point at a custom location with `PRISM_DIR=/path/to/prism`.
511460
512-CRuby is needed only for the initial bootstrap. After `make`, the
513-entire pipeline runs without Ruby.
461+CRuby is not needed to build or run the C compiler -- only as an
462+optional parser fallback (the Prism-gem path), to run the legacy
463+self-host oracle, and in the test harness, which compares Spinel's
464+output against CRuby on the same source.
514465
515466 ## Portability
516467
@@ -524,9 +475,11 @@
524475 spinel app.rb -S # print the C to stdout
525476 ```
526477
527-The output is one self-contained `.c` file that compiles against
528-`lib/sp_runtime.h`. The two together are everything a downstream
529-consumer needs — no link to `libspinel`.
478+The output is one self-contained `.c` file. A downstream consumer
479+compiles it against the `lib/` headers (`sp_runtime.h` and friends) and
480+links `libspinel_rt.a` (the out-of-line runtime: bigint, regexp, GC,
481+fiber, I/O); `--gc-sections` then drops whatever the program doesn't
482+use. No CRuby and no `spinel` binary are needed on the target machine.
530483
531484 The runtime is POSIX-flavoured but covers every platform CI exercises:
532485
@@ -589,7 +542,7 @@
589542 in the commit message.
590543 - If the work was assisted by an AI, add a `Co-Authored-By:` trailer
591544 for the assistant alongside any human co-authors. The maintainer's
592- own AI-assisted commits use `Co-Authored-By: Claude Opus 4.7`.
545+ own AI-assisted commits use `Co-Authored-By: Claude Opus 4.8`.
593546
594547 Adjacent ecosystem (community-built, not part of this repo):
595548
@@ -599,9 +552,13 @@
599552
600553 ## History
601554
602-Spinel was originally implemented in C (18K lines, branch `c-version`),
603-then rewritten in Ruby (branch `ruby-v1`), and finally rewritten in a
604-self-hosting Ruby subset (current `master`).
555+Spinel was originally implemented in C (branch `c-version`), then
556+rewritten in Ruby (branch `ruby-v1`), then rewritten again in a
557+self-hosting Ruby subset (preserved on the `self-host` branch). The
558+current `master` is a fresh C implementation of the analyze and codegen
559+stages, which builds far faster than the self-hosted backend while
560+producing equivalent output; the self-hosting Ruby version remains
561+in-tree as a regression oracle (see [Self-Hosting](#self-hosting-legacy-oracle)).
605562
606563 ## License
607564