Commit 2bbda330

2bbda3308498Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 2 files · +1 added · ~1 modified

Description

docs: add AST format spec + update README for analyze/codegen split

README didn't reflect the analyze/codegen split that landed with #416; the pipeline diagram showed spinel_codegen doing both inference and emission, the bootstrap chain showed a 2-way fixpoint, and the architecture section listed only the legacy single-binary backend.

Changes:

  • Pipeline diagram now shows the four-stage shape (.rb -> .ast -> .ir -> .c) with spinel_analyze named explicitly. Links to docs/ANALYZE-IR.md and docs/AST.md for the per-stage contracts.
  • Self-Hosting section: 4-way fixpoint chain (IR + C dimensions for both analyze.rb and codegen.rb). The matching check names are the ones make bootstrap actually prints.
  • Architecture section: per-stage LoC counts, test count refreshed to 384, plus a "What spinel_analyze does" block enumerating the nine passes (collect_all, per-scope widening, iterative loop, post-loop fixups, refine_all_module_ivar_types, feature detection, precompute_all_scope_decls, annotate_all_node_types, dump_analysis_buf) and a matching "What spinel_codegen does" block.
  • Benchmarks line refreshed to 384 tests.

New docs/AST.md documents the .ast text format that spinel_parse (both .c and .rb implementations) emits and the backend stages consume. Sections cover:

  • File format (single-letter tag prefix, line-oriented).
  • Encoding rules for string payloads.
  • Node-type taxonomy by category (program / scopes, control flow, calls, literals, references & assignment, index access, pattern matching, forwarding).
  • Field-semantic conventions for the five non-N tags (S/I/F/R/A).
  • How spinel_analyze.rb / spinel_codegen.rb consume the file (the @nd_* flat-array model).
  • Limitations (integer overflow, source locations not preserved, ASCII/UTF-8 assumption).

The existing docs/ANALYZE-IR.md already covered the IR shape in detail; no edit needed there.

Details

Commit
2bbda3308498
Parent
c4275799dd46

README.mdmodifiedView file

@@ -16,12 +16,20 @@
1616 spinel_parse Parse with Prism (libprism), serialize AST
1717 | (C binary, or CRuby + Prism gem as fallback)
1818 v
19-AST text file
19+AST text file (.ast)
2020 |
2121 v
22-spinel_codegen Type inference + C code generation
23- | (self-hosted native binary)
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+ v
27+IR text file (.ir)
28+ |
2429 v
30+spinel_codegen C code generation (self-hosted)
31+ | Consumes .ast + .ir, emits one C file.
32+ v
2533 C source (.c)
2634 |
2735 v
@@ -31,6 +39,14 @@
3139 Native binary Standalone, no runtime dependencies
3240 ```
3341
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.
49+
3450 ## Quick Start
3551
3652 ```bash
@@ -69,19 +85,41 @@
6985
7086 ## Self-Hosting
7187
72-Spinel compiles its own backend. The bootstrap chain:
88+Spinel compiles its own backend. Both `spinel_analyze.rb` and
89+`spinel_codegen.rb` are written in a Ruby subset that compiles through
90+the same pipeline that compiles user code. The bootstrap chain
91+exercises each side in both dimensions (IR fixpoint, C fixpoint):
7392
7493 ```
75-CRuby + spinel_parse.rb → AST
76-CRuby + spinel_codegen.rb → gen1.c → bin1
77-bin1 + AST → gen2.c → bin2
78-bin2 + AST → gen3.c
79-gen2.c == gen3.c (bootstrap loop closed)
94+CRuby + spinel_parse(.rb) → analyze.ast / codegen.ast
95+CRuby + spinel_analyze.rb → analyze1.ir, codegen1.ir
96+CRuby + spinel_codegen.rb → analyze1.c, codegen1.c → bin1 (analyze + codegen)
97+
98+bin1 + analyze.ast → analyze2.ir
99+bin1 + analyze.ast + .ir → analyze2.c → bin2 (analyze)
100+bin1 + codegen.ast → codegen2.ir
101+bin1 + codegen.ast + .ir → codegen2.c → bin2 (codegen)
102+
103+bin2 + analyze.ast → analyze3.ir
104+bin2 + analyze.ast + .ir → analyze3.c
105+bin2 + codegen.ast → codegen3.ir
106+bin2 + codegen.ast + .ir → codegen3.c
107+
108+analyze2.ir == analyze3.ir (analyze.rb: IR fixpoint OK)
109+analyze2.c == analyze3.c (analyze.rb: C fixpoint OK)
110+codegen2.ir == codegen3.ir (codegen.rb: IR fixpoint OK)
111+codegen2.c == codegen3.c (codegen.rb: C fixpoint OK)
80112 ```
81113
114+All four `==` checks have to hold for `make bootstrap` to declare
115+success. Any change that affects deterministic output -- record order,
116+default-value handling, hash iteration -- breaks one of them, and the
117+bootstrap stops with a clear `analyze.rb: IR fixpoint FAIL` (or the
118+matching codegen / C variant) so the regression surfaces immediately.
119+
82120 ## Benchmarks
83121
84-290 tests pass. 52 benchmarks pass.
122+384 tests pass. 52 benchmarks pass.
85123 Geometric mean: **~11.6x faster** than miniruby (Ruby 4.1.0dev) across
86124 the 28 benchmarks below. Baseline is the latest CRuby `miniruby` build
87125 (without bundled gems), which is considerably faster than the system
@@ -266,23 +304,114 @@
266304
267305 ```
268306 spinel One-command wrapper script (POSIX shell)
269-spinel_parse.c C frontend: libprism → text AST (1_276 lines)
270-spinel_codegen.rb Compiler backend: AST → C code (30_795 lines)
271-lib/sp_runtime.h Runtime library header (1_089 lines)
272-lib/sp_bigint.c Arbitrary precision integers (5_394 lines)
273-lib/regexp/ Built-in regexp engine (1_866 lines)
274-test/ 290 feature tests
307+spinel_parse.c C frontend: libprism → text AST (1_608 lines)
308+spinel_analyze.rb Type inference: AST → IR (21_162 lines, self-hosted)
309+spinel_codegen.rb C emission: AST + IR → C (30_411 lines, self-hosted)
310+lib/sp_runtime.h Runtime library header (1_537 lines)
311+lib/sp_bigint.c Arbitrary precision integers (5_400 lines)
312+lib/regexp/ Built-in regexp engine
313+test/ 384 feature tests
275314 benchmark/ 52 benchmarks
315+docs/ Format specs (AST, IR, FFI, sp_Class design)
276316 Makefile Build automation
277317 ```
278318
279-The compiler backend (`spinel_codegen.rb`) is written in a Ruby subset
280-that Spinel itself can compile: classes, `def`, `attr_accessor`,
281-`if`/`case`/`while`, `each`/`map`/`select`, `yield`, `begin`/`rescue`,
282-String/Array/Hash operations, File I/O.
319+The two backend stages -- `spinel_analyze.rb` and `spinel_codegen.rb`
320+-- are both written in the Ruby subset that Spinel itself can compile:
321+classes, `def`, `attr_accessor`, `if`/`case`/`while`,
322+`each`/`map`/`select`, `yield`, `begin`/`rescue`, String/Array/Hash
323+operations, File I/O.
324+
325+No metaprogramming, no `eval`, no `require` in either backend.
283326
284-No metaprogramming, no `eval`, no `require` in the backend.
327+### What spinel_analyze does
328+
329+The analyze stage owns whole-program type inference. It's a sequence
330+of passes over the AST, each one filling in or refining one piece of
331+the static model:
285332
333+1. **`collect_all`** -- single walk that registers every class,
334+ module, top-level method, instance method, class method, ivar
335+ declaration, FFI declaration, regexp literal, and constant. After
336+ this pass the parallel tables (`@cls_names`, `@meth_names`,
337+ `@cls_ivar_names`, ...) carry every name the program defines.
338+
339+2. **Per-scope call-site widening** -- `infer_main_call_types`,
340+ `infer_function_body_call_types`, `infer_class_body_call_types`,
341+ `infer_ieval_body_call_types`. Walks each scope's call sites and
342+ feeds the arg types into the callee's param-type slots via
343+ `unify_call_types`. The unifier widens to `poly` only when two
344+ call sites disagree -- the conservative direction.
345+
346+3. **Iterative refinement loop (≤ 4 rounds)** --
347+ `infer_all_returns`, `infer_function_body_call_types`,
348+ `infer_class_body_call_types`, `infer_ivar_types_from_writers`,
349+ `infer_param_array_type_from_body`,
350+ `narrow_param_types_from_body_method_calls`,
351+ `narrow_param_hash_types_from_body_writes`,
352+ `widen_cmeths_via_hash_each_blocks` (#424),
353+ `detect_poly_params`. The loop terminates when
354+ `inference_signature` -- a fingerprint over return types, ivar
355+ types, param types, cmeth ptypes -- stops changing. Most programs
356+ converge in 1-2 rounds; the cap at 4 catches pathological cases
357+ without exploding compile time.
358+
359+4. **Post-loop fixups** -- `fix_nil_ivar_self_refs` (e.g. `@left =
360+ nil` on an attr_accessor inside `class Node` resolves to
361+ `obj_Node?`), `fix_lambda_return_types`, then re-run the inference
362+ passes so dependent types pick up the corrections.
363+
364+5. **`refine_all_module_ivar_types`** -- with stable param types in
365+ hand, module-level `@@h[k] = v` ivar writes can now refine the
366+ hash variant from the placeholder `str_int_hash` default to the
367+ actual key/value shape.
368+
369+6. **Feature detection** -- `pre_detect_bigint`, `detect_features`,
370+ `detect_value_types`, `recalc_needs_gc`, `collect_sym_names`,
371+ `scan_toplevel_ivars`, `compute_live_cls_methods`,
372+ `compute_live_instance_methods`. Sets the `@needs_*` flags that
373+ gate runtime helper emission and marks classes / methods for DCE.
374+
375+7. **`precompute_all_scope_decls`** -- runs the multi-pass local-decl
376+ refinement per method / cmeth / ieval / main scope and stores the
377+ result in `@nd_scope_names[bid]` / `@nd_scope_types[bid]` so
378+ codegen doesn't have to re-run `scan_locals`.
379+
380+8. **`annotate_all_node_types`** -- post-order walks every reachable
381+ AST node, calls `infer_type`, fills `@nd_inferred_type[nid]`.
382+ Codegen's own `infer_type` hits this cache > 99 % of the time at
383+ emit; only block-body expressions (whose scope is
384+ iterator-specific) and a few `@current_class_idx`-dependent arms
385+ fall through.
386+
387+9. **`dump_analysis_buf`** -- serializes the result. See
388+ [docs/ANALYZE-IR.md](docs/ANALYZE-IR.md) for the line-oriented
389+ text format that lands in the `.ir` file.
390+
391+### What spinel_codegen does
392+
393+The codegen stage reads `.ast` + `.ir`, then emits one C file:
394+
395+- `load_analysis_buf` reconstructs every analysis-derived ivar from
396+ the IR. After this, `@cls_names`, `@meth_return_types`,
397+ `@nd_inferred_type`, `@nd_scope_names`, etc. are populated as if
398+ the analyze passes had just run.
399+
400+- `generate_code` emits the standard preamble (`#include
401+ "sp_runtime.h"`, the per-program runtime helpers gated on
402+ `@needs_*` flags, the sp_Class tables for hierarchy-using
403+ programs, the symbol intern table, class structs and constructors,
404+ forward declarations), then walks every reachable method / cmeth
405+ body to emit its `static inline` definition, then emits
406+ `int main()`.
407+
408+- Per-program runtime helpers are gated. A `puts "hi"` program emits
409+ ~10 lines of C; a program that touches Method instances, hash
410+ literals, the class hierarchy, etc. gets the matching runtime
411+ blocks. The gating ladder is set by pre-scan passes in
412+ `generate_code` so the gates have the right value before the
413+ emission decisions land.
414+
286415 The runtime (`lib/sp_runtime.h`) contains GC, array/hash/string
287416 implementations, and all runtime support as a single header file.
288417 Generated C includes this header, and the linker pulls only the
@@ -300,10 +429,10 @@
300429
301430 ```bash
302431 make deps # fetch libprism into vendor/prism (one-time)
303-make # build parser + regexp library + bootstrap compiler
304-make test # run 290 feature tests (requires bootstrap)
432+make # build parser + regexp library + bootstrap analyze + codegen
433+make test # run 384 feature tests (requires bootstrap)
305434 make bench # run 52 benchmarks (requires bootstrap)
306-make bootstrap # rebuild compiler from source
435+make bootstrap # rebuild analyze + codegen from source (4-way fixpoint check)
307436 sudo make install # install to /usr/local (spinel in PATH)
308437 make clean # remove build artifacts
309438 ```