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 and8-
compiles itself into a native binary.7+
The compiler is a **single self-contained C binary**: it parses Ruby (via8+
libprism), infers types across the whole program, emits C, and invokes the9+
system `cc` to produce a native executable -- no Ruby runtime and no chained10+
helper binaries at compile time. (Spinel was previously written in a11+
self-hosting Ruby subset; that backend is preserved in-tree as a regression12+
oracle -- see [History](#history).)913
1014
## How It Works1115
@@ -13,39 +17,34 @@
1317
Ruby (.rb)1418
|1519
v16-
spinel_parse Parse with Prism (libprism), serialize AST17-
| (C binary, or CRuby + Prism gem as fallback)20+
parse (libprism) Parse with Prism, linked in as a C library21+
| (a CRuby + Prism-gem path produces the same AST)1822
v19-
AST text file (.ast)23+
text AST -> NodeTable Loaded into an in-memory node table2024
|2125
v22-
spinel_analyze Whole-program type inference (self-hosted)23-
| Walks AST to fixpoint: param / return / ivar24-
| 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 / ivar28+
| types, value-type detection, dead-code markers,29+
| a per-node inferred-type cache.2630
v27-
IR text file (.ir)28-
|29-
v30-
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 AST32+
| plus the analysis just computed in the same process,33+
| emits one C file.3234
v3335
C source (.c)3436
|3537
v36-
cc -O2 -Ilib -lm Standard C compiler + runtime header38+
cc -O2 -Ilib -lm System C compiler + runtime3739
|3840
v3941
Native binary Standalone, no runtime dependencies4042
```4143
42-
The analyze / codegen split is by design -- they live in separate43-
binaries (`spinel_analyze`, `spinel_codegen`) that share no in-memory44-
state. Everything analyze decides is serialized through the IR file;45-
codegen reconstructs its inferred view from that contract. See46-
[docs/ANALYZE-IR.md](docs/ANALYZE-IR.md) for the per-record format47-
and [docs/AST.md](docs/AST.md) for the AST format the analyze stage48-
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 no46+
serialization step in between. See [docs/AST.md](docs/AST.md) for the47+
text AST format the parser emits and the analyzer consumes.4948
5049
## Quick Start5150
@@ -116,51 +115,39 @@
116115
### RBS type signatures117116
118117
Spinel can read RBS files to seed the analyzer. When invoked with119-
`--rbs DIR`, the `spinel` wrapper runs `spinel_rbs_extract` over a120-
directory of `*.rbs` files (the same layout `rbs` and Steep use) and121-
passes the resulting seed file to `spinel_analyze` as a positional122-
argument. Seeds are advisory — inference still runs on top and118+
`--rbs DIR`, `spinel` runs `spinel_rbs_extract` over a directory of119+
`*.rbs` files (the same layout `rbs` and Steep use) and feeds the120+
resulting seed into the analyzer. Seeds are advisory — inference still runs on top and123121
widens on observed contradiction, so a wrong or unrepresentable seed124122
is at worst a no-op. See [docs/RBS-EXTRACT.md](docs/RBS-EXTRACT.md)125123
for the supported subset.126124
127-
## Self-Hosting125+
## Self-Hosting (legacy oracle)128126
129-
Spinel compiles its own backend. Both `spinel_analyze.rb` and130-
`spinel_codegen.rb` are written in a Ruby subset that compiles through131-
the same pipeline that compiles user code. The bootstrap chain132-
exercises each side in both dimensions (IR fixpoint, C fixpoint):127+
Spinel began as a compiler written in a Ruby subset that compiled128+
itself. The C compiler has since replaced that backend, but the129+
self-hosting Ruby implementation is kept in-tree (under `legacy/`) as a130+
**regression oracle**. `make bootstrap` exercises its 4-way self-host131+
fixpoint -- the Ruby backend, compiled by the previous generation,132+
must reproduce byte-identical IR and C across two generations of both133+
the analyze and codegen sides:133134
134135
```135-
CRuby + spinel_parse(.rb) → analyze.ast / codegen.ast136-
CRuby + spinel_analyze.rb → analyze1.ir, codegen1.ir137-
CRuby + spinel_codegen.rb → analyze1.c, codegen1.c → bin1 (analyze + codegen)138-
139-
bin1 + analyze.ast → analyze2.ir140-
bin1 + analyze.ast + .ir → analyze2.c → bin2 (analyze)141-
bin1 + codegen.ast → codegen2.ir142-
bin1 + codegen.ast + .ir → codegen2.c → bin2 (codegen)143-
144-
bin2 + analyze.ast → analyze3.ir145-
bin2 + analyze.ast + .ir → analyze3.c146-
bin2 + codegen.ast → codegen3.ir147-
bin2 + codegen.ast + .ir → codegen3.c148-
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 declare156-
success. Any change that affects deterministic output -- record order,157-
default-value handling, hash iteration -- breaks one of them, and the158-
bootstrap stops with a clear `analyze.rb: IR fixpoint FAIL` (or the159-
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 is145+
checked by `make test` / `make bench` / `make optcarrot`); it remains146+
available for verifying the legacy backend still round-trips.160147
161148
## Benchmarks162149
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` across165152
the 28 benchmarks below. Baseline is CRuby 4.0.4 (stable), run with166153
`--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 unused345332
runtime function is stripped from the final binary.346333
- **Iterative inference early exit**: the param/return/ivar fixed-point347-
loop stops as soon as a signature of the three refined arrays stops348-
changing. Most programs converge in 1-2 iterations instead of the349-
full 4, cutting bootstrap time by ~14%.350-
- **`parse_id_list` byte walk**: the AST-field list parser (called351-
~120 K times during self-compile) walks bytes manually via352-
`s.bytes[i]` instead of `s.split(",")`, dropping N+1 allocations353-
per call to 2.334+
loop stops as soon as a signature over the refined tables stops335+
changing. Most programs converge in a couple of iterations, keeping336+
compile time low.354337
- **Warning-free build**: generated C compiles cleanly at the default355338
warning level across every test and benchmark; the harness uses356339
`-Werror` so regressions surface immediately.@@ -358,129 +341,95 @@
358341
## Architecture359342
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 engine368-
test/ 384 feature tests369-
benchmark/ 52 benchmarks370-
docs/ Format specs (AST, IR, FFI, sp_Class design)344+
spinel Single binary: parse + analyze + codegen + cc driver345+
(repo-root symlink to build/spinel)346+
src/spinel_parse.c Frontend: libprism → text AST347+
src/node_table.c AST loader: text AST → in-memory NodeTable348+
src/analyze*.c Whole-program type inference349+
src/codegen*.c C code generation350+
src/main.c CLI driver: pipeline + cc invocation351+
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.a354+
legacy/ Former self-hosting Ruby backend (regression oracle)355+
test/ 886 feature tests356+
benchmark/ 57 benchmarks357+
docs/ Format specs (AST, FFI, sp_Class design)371358
Makefile Build automation372359
```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-memory363+
`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/Hash378-
operations, File I/O.365+
`each`/`map`/`select`, `yield`, blocks (including `...` argument366+
forwarding), `begin`/`rescue`, String/Array/Hash operations, File I/O.379367
380-
No dynamic metaprogramming or `eval` in either backend. Compile-time class-body368+
No dynamic metaprogramming or `eval`. Compile-time class-body381369
declarations with compile-time-known literal inputs are supported for382370
Struct-style method synthesis.383371
384-
### What spinel_analyze does385-
386-
The analyze stage owns whole-program type inference. It's a sequence387-
of passes over the AST, each one filling in or refining one piece of388-
the static model:389-
390-
1. **`collect_all`** -- single walk that registers every class,391-
module, top-level method, instance method, class method, ivar392-
declaration, FFI declaration, regexp literal, and constant. After393-
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 and399-
feeds the arg types into the callee's param-type slots via400-
`unify_call_types`. The unifier widens to `poly` only when two401-
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 when411-
`inference_signature` -- a fingerprint over return types, ivar412-
types, param types, cmeth ptypes -- stops changing. Most programs413-
converge in 1-2 rounds; the cap at 4 catches pathological cases414-
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 to418-
`obj_Node?`), `fix_lambda_return_types`, then re-run the inference419-
passes so dependent types pick up the corrections.420-
421-
5. **`refine_all_module_ivar_types`** -- with stable param types in422-
hand, module-level `@@h[k] = v` ivar writes can now refine the423-
hash variant from the placeholder `str_int_hash` default to the424-
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 that430-
gate runtime helper emission and marks classes / methods for DCE.431-
432-
7. **`precompute_all_scope_decls`** -- runs the multi-pass local-decl433-
refinement per method / cmeth / ieval / main scope and stores the434-
result in `@nd_scope_names[bid]` / `@nd_scope_types[bid]` so435-
codegen doesn't have to re-run `scan_locals`.436-
437-
8. **`annotate_all_node_types`** -- post-order walks every reachable438-
AST node, calls `infer_type`, fills `@nd_inferred_type[nid]`.439-
Codegen's own `infer_type` hits this cache > 99 % of the time at440-
emit; only block-body expressions (whose scope is441-
iterator-specific) and a few `@current_class_idx`-dependent arms442-
fall through.443-
444-
9. **`dump_analysis_buf`** -- serializes the result. See445-
[docs/ANALYZE-IR.md](docs/ANALYZE-IR.md) for the line-oriented446-
text format that lands in the `.ir` file.447-
448-
### What spinel_codegen does449-
450-
The codegen stage reads `.ast` + `.ir`, then emits one C file:451-
452-
- `load_analysis_buf` reconstructs every analysis-derived ivar from453-
the IR. After this, `@cls_names`, `@meth_return_types`,454-
`@nd_inferred_type`, `@nd_scope_names`, etc. are populated as if455-
the analyze passes had just run.456-
457-
- `generate_code` emits the standard preamble (`#include458-
"sp_runtime.h"`, the per-program runtime helpers gated on459-
`@needs_*` flags, the sp_Class tables for hierarchy-using460-
programs, the symbol intern table, class structs and constructors,461-
forward declarations), then walks every reachable method / cmeth462-
body to emit its `static inline` definition, then emits463-
`int main()`.464-
465-
- Per-program runtime helpers are gated. A `puts "hi"` program emits466-
~10 lines of C; a program that touches Method instances, hash467-
literals, the class hierarchy, etc. gets the matching runtime468-
blocks. The gating ladder is set by pre-scan passes in469-
`generate_code` so the gates have the right value before the470-
emission decisions land.471-
472-
The runtime (`lib/sp_runtime.h`) contains GC, array/hash/string473-
implementations, and all runtime support as a single header file.474-
Generated C includes this header, and the linker pulls only the475-
needed parts from `libspinel_rt.a` (bigint + regexp engine).372+
### What analyze does373+
374+
The analyze stage (`analyze_program`) owns whole-program type375+
inference. It's a sequence of passes over the AST, each one filling in376+
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. After382+
this the compiler's tables carry every name the program defines.383+
384+
2. **Call-site widening** -- each scope's call sites feed their arg385+
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 from389+
writers, param types (array / hash / string specializations),390+
block-param types, default-param types, and `for`/bigint loop391+
locals are re-inferred to a fixpoint. The loop terminates when a392+
signature over those tables stops changing; most programs converge393+
in a couple of rounds.394+
395+
4. **Feature detection** -- value-type detection (which small396+
immutable classes become stack structs), GC need, symbol397+
collection, proc-capture marking, and reachability. These set the398+
flags that gate runtime-helper emission and mark classes / methods399+
for dead-code elimination.400+
401+
5. **Node-type annotation** -- a final pass fills a per-node402+
inferred-type cache that codegen reads directly while emitting,403+
avoiding any re-inference at emit time.404+
405+
### What codegen does406+
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-program411+
runtime helpers gated on the analysis flags, the sp_Class tables for412+
hierarchy-using programs, the symbol intern table, class structs and413+
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 a417+
handful of lines of C; a program that touches Method instances, hash418+
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-line422+
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 the482-
C binary if available. `require_relative` is resolved at parse time483-
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 the432+
referenced file.484433
485434
## Building486435
@@ -509,8 +458,10 @@
509458
already have the prism gem installed, the build auto-detects it; you510459
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`, the513-
entire pipeline runs without Ruby.461+
CRuby is not needed to build or run the C compiler -- only as an462+
optional parser fallback (the Prism-gem path), to run the legacy463+
self-host oracle, and in the test harness, which compares Spinel's464+
output against CRuby on the same source.514465
515466
## Portability516467
@@ -524,9 +475,11 @@
524475
spinel app.rb -S # print the C to stdout525476
```526477
527-
The output is one self-contained `.c` file that compiles against528-
`lib/sp_runtime.h`. The two together are everything a downstream529-
consumer needs — no link to `libspinel`.478+
The output is one self-contained `.c` file. A downstream consumer479+
compiles it against the `lib/` headers (`sp_runtime.h` and friends) and480+
links `libspinel_rt.a` (the out-of-line runtime: bigint, regexp, GC,481+
fiber, I/O); `--gc-sections` then drops whatever the program doesn't482+
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:` trailer591544
for the assistant alongside any human co-authors. The maintainer's592-
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
## History601554
602-
Spinel was originally implemented in C (18K lines, branch `c-version`),603-
then rewritten in Ruby (branch `ruby-v1`), and finally rewritten in a604-
self-hosting Ruby subset (current `master`).555+
Spinel was originally implemented in C (branch `c-version`), then556+
rewritten in Ruby (branch `ruby-v1`), then rewritten again in a557+
self-hosting Ruby subset (preserved on the `self-host` branch). The558+
current `master` is a fresh C implementation of the analyze and codegen559+
stages, which builds far faster than the self-hosted backend while560+
producing equivalent output; the self-hosting Ruby version remains561+
in-tree as a regression oracle (see [Self-Hosting](#self-hosting-legacy-oracle)).605562
606563
## License607564