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) withspinel_analyzenamed 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 bootstrapactually 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.rbconsume 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 AST1717
| (C binary, or CRuby + Prism gem as fallback)1818
v19-
AST text file19+
AST text file (.ast)2020
|2121
v22-
spinel_codegen Type inference + C code generation23-
| (self-hosted native binary)22+
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+
v27+
IR text file (.ir)28+
|2429
v30+
spinel_codegen C code generation (self-hosted)31+
| Consumes .ast + .ir, emits one C file.32+
v2533
C source (.c)2634
|2735
v@@ -31,6 +39,14 @@
3139
Native binary Standalone, no runtime dependencies3240
```3341
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.49+
3450
## Quick Start3551
3652
```bash@@ -69,19 +85,41 @@
6985
7086
## Self-Hosting7187
72-
Spinel compiles its own backend. The bootstrap chain:88+
Spinel compiles its own backend. Both `spinel_analyze.rb` and89+
`spinel_codegen.rb` are written in a Ruby subset that compiles through90+
the same pipeline that compiles user code. The bootstrap chain91+
exercises each side in both dimensions (IR fixpoint, C fixpoint):7392
7493
```75-
CRuby + spinel_parse.rb → AST76-
CRuby + spinel_codegen.rb → gen1.c → bin177-
bin1 + AST → gen2.c → bin278-
bin2 + AST → gen3.c79-
gen2.c == gen3.c (bootstrap loop closed)94+
CRuby + spinel_parse(.rb) → analyze.ast / codegen.ast95+
CRuby + spinel_analyze.rb → analyze1.ir, codegen1.ir96+
CRuby + spinel_codegen.rb → analyze1.c, codegen1.c → bin1 (analyze + codegen)97+
98+
bin1 + analyze.ast → analyze2.ir99+
bin1 + analyze.ast + .ir → analyze2.c → bin2 (analyze)100+
bin1 + codegen.ast → codegen2.ir101+
bin1 + codegen.ast + .ir → codegen2.c → bin2 (codegen)102+
103+
bin2 + analyze.ast → analyze3.ir104+
bin2 + analyze.ast + .ir → analyze3.c105+
bin2 + codegen.ast → codegen3.ir106+
bin2 + codegen.ast + .ir → codegen3.c107+
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 declare115+
success. Any change that affects deterministic output -- record order,116+
default-value handling, hash iteration -- breaks one of them, and the117+
bootstrap stops with a clear `analyze.rb: IR fixpoint FAIL` (or the118+
matching codegen / C variant) so the regression surfaces immediately.119+
82120
## Benchmarks83121
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) across86124
the 28 benchmarks below. Baseline is the latest CRuby `miniruby` build87125
(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 tests307+
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 engine313+
test/ 384 feature tests275314
benchmark/ 52 benchmarks315+
docs/ Format specs (AST, IR, FFI, sp_Class design)276316
Makefile Build automation277317
```278318
279-
The compiler backend (`spinel_codegen.rb`) is written in a Ruby subset280-
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/Hash323+
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 does328+
329+
The analyze stage owns whole-program type inference. It's a sequence330+
of passes over the AST, each one filling in or refining one piece of331+
the static model:285332
333+
1. **`collect_all`** -- single walk that registers every class,334+
module, top-level method, instance method, class method, ivar335+
declaration, FFI declaration, regexp literal, and constant. After336+
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 and342+
feeds the arg types into the callee's param-type slots via343+
`unify_call_types`. The unifier widens to `poly` only when two344+
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 when354+
`inference_signature` -- a fingerprint over return types, ivar355+
types, param types, cmeth ptypes -- stops changing. Most programs356+
converge in 1-2 rounds; the cap at 4 catches pathological cases357+
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 to361+
`obj_Node?`), `fix_lambda_return_types`, then re-run the inference362+
passes so dependent types pick up the corrections.363+
364+
5. **`refine_all_module_ivar_types`** -- with stable param types in365+
hand, module-level `@@h[k] = v` ivar writes can now refine the366+
hash variant from the placeholder `str_int_hash` default to the367+
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 that373+
gate runtime helper emission and marks classes / methods for DCE.374+
375+
7. **`precompute_all_scope_decls`** -- runs the multi-pass local-decl376+
refinement per method / cmeth / ieval / main scope and stores the377+
result in `@nd_scope_names[bid]` / `@nd_scope_types[bid]` so378+
codegen doesn't have to re-run `scan_locals`.379+
380+
8. **`annotate_all_node_types`** -- post-order walks every reachable381+
AST node, calls `infer_type`, fills `@nd_inferred_type[nid]`.382+
Codegen's own `infer_type` hits this cache > 99 % of the time at383+
emit; only block-body expressions (whose scope is384+
iterator-specific) and a few `@current_class_idx`-dependent arms385+
fall through.386+
387+
9. **`dump_analysis_buf`** -- serializes the result. See388+
[docs/ANALYZE-IR.md](docs/ANALYZE-IR.md) for the line-oriented389+
text format that lands in the `.ir` file.390+
391+
### What spinel_codegen does392+
393+
The codegen stage reads `.ast` + `.ir`, then emits one C file:394+
395+
- `load_analysis_buf` reconstructs every analysis-derived ivar from396+
the IR. After this, `@cls_names`, `@meth_return_types`,397+
`@nd_inferred_type`, `@nd_scope_names`, etc. are populated as if398+
the analyze passes had just run.399+
400+
- `generate_code` emits the standard preamble (`#include401+
"sp_runtime.h"`, the per-program runtime helpers gated on402+
`@needs_*` flags, the sp_Class tables for hierarchy-using403+
programs, the symbol intern table, class structs and constructors,404+
forward declarations), then walks every reachable method / cmeth405+
body to emit its `static inline` definition, then emits406+
`int main()`.407+
408+
- Per-program runtime helpers are gated. A `puts "hi"` program emits409+
~10 lines of C; a program that touches Method instances, hash410+
literals, the class hierarchy, etc. gets the matching runtime411+
blocks. The gating ladder is set by pre-scan passes in412+
`generate_code` so the gates have the right value before the413+
emission decisions land.414+
286415
The runtime (`lib/sp_runtime.h`) contains GC, array/hash/string287416
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
```bash302431
make deps # fetch libprism into vendor/prism (one-time)303-
make # build parser + regexp library + bootstrap compiler304-
make test # run 290 feature tests (requires bootstrap)432+
make # build parser + regexp library + bootstrap analyze + codegen433+
make test # run 384 feature tests (requires bootstrap)305434
make bench # run 52 benchmarks (requires bootstrap)306-
make bootstrap # rebuild compiler from source435+
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 artifacts309438
```docs/AST.mdaddedView file
Loading diff…