Commit 03239254

03239254a1d7Merged

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

Description

docs: update AST.md / ANALYZE-IR.md for the single-binary C compiler

Both docs described the retired Ruby self-host pipeline (separate spinel_parse / spinel_analyze / spinel_codegen binaries communicating through .ast and .ir files, consumed into @nd_ arrays).

AST.md: the text AST format is still the parser->NodeTable contract, so keep the record/encoding/taxonomy spec, but fix the pipeline to the single binary (sp_parse_file_to_text -> nt_load_text -> NodeTable, no on-disk .ast), document the SOURCE_FILE / FILE records and per-node node_line / node_file / node_col source positions (so "source locations not emitted" is no longer true), and replace the @nd_* ivar consumer section with the nt_* accessor API.

ANALYZE-IR.md: the .ir file no longer exists -- analyze and codegen are one binary sharing the Compiler struct in memory. Rewrite the doc to describe that in-memory contract (the per-node type cache read via comp_ntype, the scope/class/method/FFI tables), with a historical note on the removed .ir serialization.

Co-Authored-By: Claude Opus 4.8 [email protected]

Details

Commit
03239254a1d7
Parent
7ef977f75a5c

docs/ANALYZE-IR.mdmodifiedView file

@@ -1,411 +1,109 @@
1-# Analyze ↔ Codegen IR
1+# Analyze ↔ Codegen contract
22
3-The Spinel compiler runs in three stages, each as a separate binary:
3+Spinel runs analysis and code generation as two phases of a **single
4+binary**, sharing one in-memory state object:
45
56 ```
6-.rb ──[spinel_parse]──▶ .ast ──[spinel_analyze]──▶ .ir ──[spinel_codegen]──▶ .c
7+.rb ──[sp_parse_file_to_text]──▶ text AST ──[nt_load_text]──▶ NodeTable
8+ ──[analyze_program(c)]──▶ Compiler (filled) ──[codegen emits]──▶ .c
79 ```
810
9-`spinel_analyze` produces `.ir`; `spinel_codegen` consumes it. This file
10-documents that contract: the file format, every tag, every ivar that
11-crosses the boundary, and the constraints either side relies on.
11+`codegen_program(nt)` (`src/codegen.c`) builds a `Compiler`, calls
12+`analyze_program(c)` to populate it, then walks the AST emitting C. The
13+analyzer and code generator are the same process and share heap state;
14+nothing is serialized between them.
1215
13-The IR is the only artefact the two binaries share. They do not share
14-heap state, do not share an in-memory `Compiler` instance, and do not
15-re-derive each other's results. If a piece of analysis state is not in
16-the IR, codegen does not have it.
16+> **Historical note.** The retired Ruby self-host ran `spinel_analyze`
17+> and `spinel_codegen` as *separate* binaries that communicated through a
18+> text `.ir` file (`SPINEL-IR v1`, with `INT` / `STR` / `SA` / `IA` / `T`
19+> / `NM` / `SN` / `ST` records). That file no longer exists. The C
20+> rewrite folded both stages into one binary, so the `.ir` round-trip,
21+> its percent-encoding, and the four-way bootstrap fixpoint it backed are
22+> all gone. `src/compiler.h` keeps the lineage explicit: *"its field set
23+> corresponds to the legacy .ir dump."*
1724
18-## File format
25+## The shared object: `Compiler`
1926
20-Plain UTF-8 text, line-oriented (`\n`-terminated). The first line is the
21-literal version stamp:
27+`src/compiler.h` defines `Compiler` -- the modern equivalent of the old
28+`.ir`. Everything analysis derives and codegen consumes is a field on it.
29+The pieces that cross the analyze → codegen boundary:
2230
23-```
24-SPINEL-IR v1
25-```
31+### Per-node arrays (indexed by AST node id)
2632
27-Every subsequent line is a single record:
33+| Field | Meaning |
34+|------------------|------------------------------------------------------------------|
35+| `ntype[id]` | Inferred `TyKind` for the node. Read via `comp_ntype(c, id)`, the type cache codegen consults instead of re-inferring. |
36+| `nscope[id]` | Owning scope index (`comp_scope_of`). |
37+| `node_cbody[id]` | Enclosing class/module-body class id, or -1. |
2838
29-```
30-<tag> <name-or-nid> [<count>] <payload>
31-```
39+`comp_ntype` is the contract codegen relies on most: `infer_type`
40+(`src/analyze*.c`) fills `ntype[]` during analysis, and codegen reads it
41+back as the static type of every expression. (`TY_STRBUF`, a codegen-only
42+mutable-string storage refinement, is normalized to `TY_STRING` on read;
43+codegen consults the raw scope-local type where the distinction matters.)
3244
33-Fields are space-separated. Payload encoding rules below depend on tag.
34-A line is one whole record — newlines never appear inside payload values
35-(they are percent-encoded).
45+### Scopes and locals
3646
37-### Tags
47+`scopes[]` holds one `Scope` per `def` / class method / lambda / block
48+body plus the top-level scope (`scopes[0]`). Each `Scope` carries its
49+parameter list, inferred return type (`ret`), yield/block metadata, and a
50+`LocalVar[]` of params + body locals with their inferred `type`. Codegen
51+emits C function signatures, local declarations, and call dispatch
52+straight from these.
3853
39-| Tag | Shape | Carries |
40-|------|--------------------------------|--------------------------------------------------------------------------|
41-| `INT`| `INT @ivar <integer>` | scalar integer ivar (counters, feature-need flags) |
42-| `STR`| `STR @ivar <encoded-string>` | scalar string ivar (`@cls_meth_live`, `@cls_cmeth_live`) |
43-| `SA` | `SA @ivar <count> <pipe-strs>`| length-prefixed `Array<String>` (every analysis-derived parallel array) |
44-| `IA` | `IA @ivar <count> <csv-ints>` | length-prefixed `Array<Int>` (body ids, sizes, offsets, flags) |
45-| `T` | `T <nid> <encoded-type>` | per-AST-node inferred type (the cache that lets codegen skip `infer_type`) |
46-| `NM` | `NM <nid> <encoded-name>` | per-AST-node `@nd_name` override (`__sp_ieval_<N>` rewrites) |
47-| `NB` | `NB <nid> <int>` | per-AST-node `@nd_block` override (rewritten ieval call sites) |
48-| `SN` | `SN <nid> <pipe-strs>` | per-scope local-decl names (one entry per scope body) |
49-| `ST` | `ST <nid> <pipe-strs>` | per-scope local-decl types (paired with SN) |
54+### Program tables
5055
51-`INT`, `STR`, `SA`, `IA` mirror compiler-instance state by ivar name.
52-`T`, `NM`, `NB`, `SN`, `ST` are sparse per-node records — they only emit
53-for nodes whose value differs from the default, so codegen fills the
54-rest with the default at load time.
56+`classes[]` (ivars + types, attr readers/writers, prepend chains, value-type
57+flag, `compiler_state` fields, …), `consts[]`, `gvars[]` (+ aliases),
58+`symbols[]` (intern table), `toplevel_includes[]`, and the FFI registry
59+(`ffi_funcs` / `ffi_consts` / `ffi_bufs` / `ffi_readers` / `ffi_libs` /
60+`ffi_cflags`). These are queried through the `comp_*` accessors declared
61+in `compiler.h` (`comp_class_index`, `comp_method_in_chain`,
62+`comp_reader_in_chain`, `comp_resolve_alias`, …).
5563
56-### Encoding
64+Feature gating (which runtime helper blocks to emit, the class-machinery
65+tables, the `main()` prologue) is not stored as `@needs_*` flags the way
66+the legacy IR did; codegen recomputes it from the analyzed program via
67+scan passes (`scan_prologue_features`, `program_needs_class_machinery`,
68+…) immediately before emission.
5769
58-Strings (the payload of `STR`, the elements of `SA` / `T` / `NM` / `SN`
59-/ `ST`) are percent-encoded for the four characters that would
60-otherwise collide with the line-and-pipe split:
70+## What analyze does
6171
62-| Char | Encoded |
63-|--------|---------|
64-| space | `%20` |
65-| `\n` | `%0A` |
66-| `\r` | `%0D` |
67-| `\t` | `%09` |
68-| `%` | `%25` |
69-| `\|` | `%7C` |
72+`analyze_program(c)` registers the program's declarations, then runs type
73+inference to a fixpoint and fills the per-node type cache. Conceptually:
7074
71-`SA` payloads are `<count> <e1>|<e2>|…|<en>`. The leading `<count>`
72-distinguishes `[]` (count 0, body empty) from `[""]` (count 1, body
73-empty after pipe split) — both serialise to identical bodies, so the
74-loader uses the count to pad with empty strings.
75+1. **Collect** -- walk the AST registering classes, modules, methods,
76+ constants, ivars, globals, and FFI declarations into the tables above
77+ (`walk_scope` and friends in `src/analyze_scope.c`).
78+2. **Infer to fixpoint** -- iterate the inference passes
79+ (`src/analyze_infer.c`, `src/analyze_pass.c`): return types, ivar
80+ types from writers, parameter types narrowed from bodies, poly
81+ locals/params, hash/array variant selection, bigint loop promotion,
82+ etc. The loop repeats until the derived types stop changing.
83+3. **Finalize** -- post-fixpoint refinements (value-type detection,
84+ nullable re-narrowing, live-method marking) and then fill `ntype[]`
85+ for every reachable node so codegen reads cached types.
7586
76-`IA` payloads are `<count> <e1>,<e2>,…,<en>`. Same count guarantee.
87+Because the two phases share memory, codegen can also call `infer_type`
88+directly for the few nodes whose type is context-dependent at emit time
89+(block-body expressions whose iterator-derived param types are not
90+pre-cached, `super` arms that need the current class). The cache covers
91+the overwhelming majority; these are the deliberate exceptions.
7792
78-## Pipeline contract
93+## Adding analysis state
7994
80-### What analyze populates
95+Add a field to the relevant struct in `src/compiler.h` (`Compiler`,
96+`Scope`, `ClassInfo`, …), populate it in the analysis pass that derives
97+it, and read it in codegen. There is no serializer to update, no encoding
98+to round-trip, and no IR fixpoint to keep stable -- the value is just a
99+struct field both phases see. Verify with `make check` (test) plus
100+`make optcarrot` / `make bench` when the change touches type inference
101+(see [the gates](../README.md)).
81102
82-`Compiler#analyze_phase` (spinel_analyze.rb) runs to fixpoint:
83-
84-1. `collect_all` — walks the AST, registers classes, methods, modules,
85- constants, ivars, FFI declarations.
86-2. `infer_main_call_types` / `infer_function_body_call_types` /
87- `infer_class_body_call_types` / `infer_ieval_body_call_types` —
88- per-scope call-site widening.
89-3. `detect_poly_locals`.
90-4. Iterative loop (≤ 4 rounds): `infer_all_returns`,
91- `infer_*_call_types`, `infer_ivar_types_from_writers`,
92- `infer_param_array_type_from_body`,
93- `narrow_param_types_from_body_method_calls`,
94- `narrow_param_hash_types_from_body_writes`, `detect_poly_params`.
95- Loop terminates when `inference_signature` (a fingerprint over
96- return-types, ivar-types, param-types, cmeth-ptypes) is unchanged.
97-5. `fix_nil_ivar_self_refs`, then re-run inference passes.
98-6. `refine_all_module_ivar_types` (uses now-stable param types to
99- refine module-ivar hash / array specialisation), then re-run.
100-7. `fix_lambda_return_types`.
101-8. `pre_detect_bigint`, `detect_features`.
102-9. `detect_value_types`, `recalc_needs_gc`, `collect_sym_names`,
103- `scan_toplevel_ivars`, `compute_live_cls_methods`,
104- `compute_live_instance_methods`.
105-10. Sets `@analysis_frozen = 1`.
106-11. `precompute_all_scope_decls` — walks every method / cmeth / ieval /
107- main scope, runs the full multi-pass local-decl refinement (used
108- to be re-derived in `emit_main` and `declare_method_locals`),
109- stores the result in `@nd_scope_names[bid]` /
110- `@nd_scope_types[bid]` (pipe-joined per body).
111-12. `annotate_all_node_types` (`walk_and_cache`) — post-order walks
112- every reachable AST node, calls `infer_type`, fills
113- `@nd_inferred_type[nid]`. Targets non-block-body nodes (block
114- iteration scope is iterator-specific and resolved at emit time).
103+## See also
115104
116-After step 12 the compiler dumps state via `dump_analysis_buf`.
117-
118-### What codegen consumes
119-
120-`spinel_codegen.rb`:
121-
122-1. Parses the AST file (same `read_text_ast` as analyze; fresh
123- `Compiler` instance with empty tables).
124-2. Calls `load_analysis_buf` on the IR to overwrite scalar / array
125- ivars and per-node caches.
126-3. Calls `generate_code`, which assumes the compiler is in the same
127- "post-analysis" shape analyze left it in:
128- - `@cls_is_value_type`, `@needs_gc`, `@sym_names`,
129- `@toplevel_ivar_*`, `@cls_meth_live`, `@cls_cmeth_live` are
130- pre-populated. `generate_code` does not re-run
131- `detect_value_types`, `compute_live_*`, etc.
132- - `@nd_inferred_type[nid]` is the cache `infer_type` consults
133- before running the dispatch tree (>99 % hit rate at emit).
134- - `@nd_scope_names[bid]` / `@nd_scope_types[bid]` are read by
135- `declare_method_locals`, `emit_main`, and the inline-yield body
136- emitters in lieu of re-running `scan_locals`.
137-4. Walks AST, emits C, writes to stdout or `out.c`.
138-
139-### What stays in codegen by design
140-
141-Some helpers conceptually belong to analysis but their results are
142-consumed only at emit time, so they stayed in `spinel_codegen.rb`:
143-
144-- `infer_array_elem_type`, `infer_hash_val_type`, `unify_call_types` —
145- used inside `compile_array_literal_from_ids`, `compile_hash_literal`,
146- `body_yield_arg_types`. The values they compute are emit-site-local
147- and are not part of any per-program table.
148-- `cls_meth_is_live`, `cls_cmeth_is_live` — read the pipe-joined
149- `@cls_meth_live` / `@cls_cmeth_live` strings analyze produced. The
150- membership-test wrappers stay codegen-side because they are pure
151- consumers.
152-- Block-iteration scope: `infer_type` for nodes inside a block body
153- does its own dispatch since the iterator-derived block-param types
154- (`each` / `map` / `each_with_index` / `each_pair` / `tap` / `scan` /
155- `Fiber.new` / etc.) are not pre-cached. `walk_and_cache` skips block
156- bodies for exactly this reason; codegen's own `infer_type` does the
157- iterator-specific scope push when it traverses into one.
158- `proc` / `lambda` / `Proc.new` blocks are also intentionally skipped
159- — their param type is determined by the runtime caller and
160- `compile_lambda_def` hardcodes `int` for the param.
161-
162-## Per-ivar contract
163-
164-Every ivar listed below is round-tripped through the IR. Codegen has
165-no analysis-side derivers for any of them — if analyze does not write
166-the record, codegen sees the default value (`0`, `""`, `[]`).
167-
168-### Compiler-state declaration metadata (`SA`)
169-
170-`@compiler_state_classes`, `@compiler_state_kinds`, and
171-`@compiler_state_names` describe class-body `compiler_state_*`
172-declarations. Each position is one field: class name, kind (`int`,
173-`str`, `sa`, `ia`), and bare field name.
174-
175-These metadata records are emitted before the declared compiler state
176-itself. Codegen uses them while loading the following `INT` / `STR` /
177-`SA` / `IA` rows through the synthetic typed setters, and later while
178-emitting the synthetic `init_compiler_state`, `dump_compiler_state_ir`,
179-and setter bodies.
180-
181-### Counters / scalars (`INT`)
182-
183-| Ivar | Meaning |
184-|-------------------|-------------------------------------------------------------------------|
185-| `@nd_count` | Total AST node count. Codegen sizes its parallel arrays from this. |
186-| `@root_id` | Root ProgramNode id (entry into AST traversal). |
187-| `@analysis_frozen`| Set to `1` after `analyze_phase` finishes (advisory; codegen ignores). |
188-| `@ieval_counter` | Counter used to mint `__sp_ieval_<N>` synthetic method names. |
189-
190-### Feature-need flags (`INT`, all default `0`)
191-
192-`@needs_gc`, `@needs_system`, `@needs_int_array`, `@needs_float_array`,
193-`@needs_str_array`, `@needs_str_int_hash`, `@needs_str_str_hash`,
194-`@needs_int_str_hash`, `@needs_sym_int_hash`, `@needs_sym_str_hash`,
195-`@needs_sym_intern`, `@needs_setjmp`, `@needs_mutable_str`,
196-`@needs_rb_value`, `@needs_regexp`, `@needs_rand`, `@needs_stringio`,
197-`@needs_lambda`, `@needs_fiber`, `@needs_bigint`, `@needs_poly_array`,
198-`@needs_poly_poly_hash`, `@needs_str_poly_hash`, `@needs_sym_poly_hash`,
199-`@needs_ptr_array`, `@needs_file_io`. Each toggle gates an emit of the
200-corresponding runtime helper block.
201-
202-### Live-method tables (`STR`)
203-
204-| Ivar | Meaning |
205-|--------------------|---------------------------------------------------------------------------|
206-| `@cls_meth_live` | `;`-joined `<ClassName>::<method>` entries for live instance methods. |
207-| `@cls_cmeth_live` | `;`-joined entries for live class methods. Both used by DCE stub emit. |
208-
209-### Top-level methods (`SA` / `IA`)
210-
211-`@meth_names`, `@meth_param_names`, `@meth_param_types`,
212-`@meth_param_empty`, `@meth_return_types`, `@meth_body_ids` (IA),
213-`@meth_has_defaults`, `@meth_rest_index` (IA), `@meth_has_yield` (IA).
214-
215-These are the parallel arrays codegen reads in `emit_toplevel_method`,
216-`compile_no_recv_call_expr`, the bare-call dispatch paths, etc.
217-
218-### Class tables (`SA` / `IA`)
219-
220-`@cls_names`, `@cls_parents`, `@cls_ivar_names`, `@cls_ivar_types`,
221-`@cls_ivar_init_definite`, `@cls_ivar_observed_types`,
222-`@cls_meth_names`, `@cls_meth_params`, `@cls_meth_ptypes`,
223-`@cls_meth_returns`, `@cls_meth_bodies`, `@cls_meth_defaults`,
224-`@cls_meth_ptypes_empty`, `@cls_attr_readers`, `@cls_attr_writers`,
225-`@cls_cmeth_names`, `@cls_cmeth_params`, `@cls_cmeth_ptypes`,
226-`@cls_cmeth_returns`, `@cls_cmeth_bodies`, `@cls_cmeth_defaults`,
227-`@cls_is_value_type` (IA), `@cls_is_sra` (IA), `@cls_meth_has_yield`,
228-`@cls_method_adapters`.
229-
230-The per-class entries inside each `SA` are joined by `;` (between
231-methods of one class) and `|` (between classes). Joining and splitting
232-is consistent with the helper API (`cls_meth_pnames_get`,
233-`cls_meth_ptypes_get`, etc.) on both sides.
234-
235-### Constants / cvars / gvars (`SA` / `IA`)
236-
237-`@const_names`, `@const_types`, `@const_expr_ids` (IA),
238-`@const_scope_names`, `@cvar_names`, `@cvar_types`,
239-`@cvar_init_values`, `@gvar_names`, `@gvar_types`,
240-`@multi_const_inits`.
241-
242-### Modules (`SA` / `IA`)
243-
244-`@module_names`, `@module_body_ids` (IA), `@module_acc_keys`,
245-`@module_acc_consts`.
246-
247-### FFI (`SA` / `IA`)
248-
249-`@ffi_modules`, `@ffi_module_libs`, `@ffi_module_cflags`,
250-`@ffi_func_modules`, `@ffi_func_names`, `@ffi_func_arg_types`,
251-`@ffi_func_ret_types`, `@ffi_func_arg_specs`, `@ffi_func_ret_specs`,
252-`@ffi_buf_modules`, `@ffi_buf_names`, `@ffi_buf_sizes` (IA),
253-`@ffi_reader_modules`, `@ffi_reader_names`, `@ffi_reader_kinds`,
254-`@ffi_reader_offsets` (IA).
255-
256-### Regexp / dyn-regex / local-regex (`SA` / `IA`)
257-
258-`@regexp_patterns`, `@regexp_flags`, `@dyn_regex_node_ids` (IA),
259-`@dyn_regex_flags`, `@local_regex_names`, `@local_regex_idx` (IA).
260-
261-### Misc (`SA` / `IA`)
262-
263-`@open_class_names`, `@method_ref_vars`, `@method_ref_names`,
264-`@galias_new`, `@galias_old`, `@undef_class_idx` (IA), `@undef_method`,
265-`@sym_names`, `@tuple_types`, `@poly_funcs`, `@poly_param_types`,
266-`@ieval_class_idxs` (IA), `@ieval_body_ids` (IA),
267-`@pre_execution_blocks` (IA), `@post_execution_blocks` (IA),
268-`@toplevel_ivar_names`, `@toplevel_ivar_types`,
269-`@lambda_var_ret_names`, `@lambda_var_ret_types`,
270-`@compile_time_subst_keys`, `@compile_time_subst_vals`.
271-
272-`@compile_time_subst_keys` / `@compile_time_subst_vals` carry literal substitutions
273-for compile-time class-body declarations. Keys have the form
274-`<class_idx>:<method_name>:<body_id>:<blockvar>`; values are tagged
275-literal payloads such as `sym:draft`, `str:name`, or `int:3`.
276-
277-## Per-AST-node records
278-
279-These records are sparse — a record is emitted only when the value
280-differs from the default, so the count is bounded by the size of the
281-analysis result, not by `@nd_count`.
282-
283-### `T <nid> <type>` — inferred-type cache
284-
285-Filled by `annotate_all_node_types` for every reachable node outside
286-block bodies. Codegen's `infer_type(nid)` checks `@nd_inferred_type[nid]`
287-first; non-empty cache hit returns immediately, otherwise it runs the
288-dispatch tree (still kept in codegen for block-body expressions and
289-the `SuperNode` / `ForwardingSuperNode` arms that need
290-`@current_class_idx` context).
291-
292-### `NM <nid> <name>` — `@nd_name` override
293-
294-Emitted only for `rewrite_instance_eval_calls` rewrites that re-stamp
295-a CallNode's name to `__sp_ieval_<N>`. The matching `NB` record below
296-clears the call's block. Codegen does not re-run the rewrite; the IR
297-ports the result.
298-
299-### `NB <nid> <int>` — `@nd_block` override
300-
301-Emitted alongside `NM` when an ieval call's block was lifted into
302-`@ieval_body_ids` and the AST callsite's block is now `-1`.
303-
304-### `SN <nid> <pipe-names>` and `ST <nid> <pipe-types>` — scope locals
305-
306-One pair per scope body whose local declarations are non-empty. The
307-ids are body-node ids (top-level main, top-level method bodies,
308-instance method bodies, class method bodies, ieval bodies). Codegen
309-calls `declare_method_locals(bid, pnames)` which short-circuits on
310-`@nd_scope_names[bid]` instead of re-running the multi-pass
311-`scan_locals` refinement.
312-
313-The pairing is positional — `SN` element `i` declares the local whose
314-type is `ST` element `i`. Both arrays have the same length.
315-
316-## Loading order
317-
318-`load_analysis_buf` processes records in the order they appear in the
319-file. Order matters in two places:
320-
321-1. The `@compiler_state_classes`, `@compiler_state_kinds`, and
322- `@compiler_state_names` records must precede any compiler-state row
323- declared by `compiler_state_*`. The generic IR loader dispatches
324- those rows through generated typed setters, which need the metadata
325- loaded first.
326-2. `INT @nd_count` must precede any per-node record (`T`, `NM`, `NB`,
327- `SN`, `ST`). The loader bound-checks `nid < @nd_count` and silently
328- drops records out of range; with `@nd_count` not yet set, every
329- per-node record would be dropped. `dump_analysis_buf` emits
330- `@nd_count` as the first scalar after the version stamp for this
331- reason.
332-3. Class / method tables (`SA`) load before any `T` record that names
333- a class or method type (`obj_<C>`, `class`, etc.) — codegen does
334- not re-validate types at load, so a downstream consumer that calls
335- `find_class_idx` against an unloaded `@cls_names` would miss. In
336- practice the dump order keeps the parallel-array tables ahead of
337- per-node records, so this is not a problem with the current
338- serialiser, but reordering the SA / IA emit block requires
339- matching loader awareness.
340-
341-## Statistics
342-
343-For the bootstrap input `spinel_codegen.rb` (~28.9 K Ruby lines, ~123 K
344-AST nodes):
345-
346-| Category | Count | Notes |
347-|------------|---------|------------------------------------------------------------------|
348-| `T` | ~101 K | Per-node inferred-type cache, ~99 % hit rate at emit |
349-| `SN` / `ST`| ~370 each | Scope-body local-decl pairs |
350-| `SA` | ~73 | Analysis-derived parallel arrays |
351-| `INT` | ~30 | Counters + feature-need flags |
352-| `IA` | ~16 | Body-id arrays, flag arrays |
353-| `STR` | ~2 | Live-method tables |
354-| File size | ~1.5 MB | Round-trip fixpoint stable (`gen2.ir == gen3.ir`) |
355-
356-## Gotchas
357-
358-- **Length-prefixed split** is non-negotiable for `SA` / `IA`. The
359- empty array and the single-empty-element array serialise to the
360- same body; only the `<count>` distinguishes them. `ir_split_strs_n`
361- / `ir_split_ints_n` pad up to the recorded count when the body
362- parses to fewer elements.
363-- **Percent-encoding** must round-trip — the encoder escapes ` `, `\n`,
364- `\r`, `\t`, `%`, `|`, but downstream consumers may rely on other
365- characters surviving. Adding new escape rules requires updating both
366- `ir_escape` (analyze) and `ir_unescape` (codegen).
367-- **Two-string `O(N²)` trap**: the original `dump_analysis_buf`
368- appended T-records with `buf = buf + line` in a loop; for the ~150 K
369- T-records in spinel_codegen.rb's self-host, that quadratic
370- reallocation pattern blew the heap to 60 GB on the spinel-compiled
371- analyze binary. The current implementation accumulates record
372- strings into a `StrArray` and joins once at the end. Any new
373- per-node record loop should follow the same pattern.
374-- **Block-body type cache is empty by design**. Codegen's
375- `infer_type` is the authoritative path for block-body expressions
376- because the iterator-derived block-param types are not pre-cached
377- by `walk_and_cache`. Adding `T` records for block-body nids is not
378- a no-op — it would override the iterator-specific scope codegen
379- pushes during traversal.
380-- **Bootstrap fixpoint is 4-way**, not 2-way. `make bootstrap`
381- verifies both `analyze.rb` and `codegen.rb` round-trip through the
382- pipeline in both the IR (`analyze.rb: IR fixpoint OK`) and C
383- (`codegen.rb: C fixpoint OK`) dimensions. A change that affects
384- either side's deterministic output (record order, string
385- formatting, default-value handling) breaks the fixpoint and the
386- bootstrap fails.
387-
388-## Format version
389-
390-`SPINEL-IR v1` is the only version recognised. The loader treats the
391-literal version line as a comment — any other text on the first
392-non-empty line is silently ignored, so a future v2 format that
393-extends the tag set must change the version stamp and matching loader
394-logic together.
395-
396-## Adding a new ivar
397-
398-1. Decide tag: scalar int → `INT`, scalar string → `STR`, array of
399- strings → `SA`, array of ints → `IA`, per-node attribute → `T` /
400- `NM` / `NB` / `SN` / `ST`.
401-2. Add the emit line in `dump_analysis_buf`
402- (spinel_analyze.rb#dump_analysis_buf).
403-3. Add the matching loader arm in `ir_set_int_ivar` /
404- `ir_set_str_ivar` / `ir_set_sa_ivar` / `ir_set_ia_ivar`
405- (spinel_codegen.rb).
406-4. Initialise the ivar to its default value in
407- `Compiler#initialize` on **both** sides — codegen relies on the
408- ivar existing as a struct field for self-host typing.
409-5. Run `make bootstrap` and verify all four fixpoints
410- (`analyze.rb: IR fixpoint OK`, `analyze.rb: C fixpoint OK`,
411- `codegen.rb: IR fixpoint OK`, `codegen.rb: C fixpoint OK`).
105+- [docs/AST.md](AST.md) -- the text AST format and the `NodeTable` the
106+ analyzer and code generator both read.
107+- `src/compiler.h` -- the `Compiler` / `Scope` / `ClassInfo` structs and
108+ the `comp_*` accessor API.
109+- `src/analyze.h` -- `analyze_program` / `infer_type` entry points.