Commit 5e91f8cf

5e91f8cf8f28Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 7 months ago · 2 files · +2 added

Description

fix: pending_method_ref init, pattern match string concat

  • Add @pending_method_ref = "" to initialize (was missing, caused struct truncation at MAX_IVARS)
  • Use string interpolation instead of + for pattern match value comparison (avoids C binary + on char*/const char*)
  • Increase MAX_IVARS from 96 to 128 in C version codegen.h

55/59 tests pass. Self-compile 0 errors. Self-hosted binary runs but StatementsNode.body array not populated.

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

Details

Commit
5e91f8cf8f28
Parent
6b6d232ee24c

PLAN.mdaddedView file

1+# Spinel v2: Ruby Subset Self-Hosting Compiler
2+
3+## Goal
4+
5+Rewrite the Spinel AOT compiler in a Ruby subset that Spinel itself can
6+compile. The compiler takes Ruby source, parses it with Prism, infers
7+types, and generates standalone C code.
8+
9+## Architecture
10+
11+```
12+Ruby Source (.rb)
13+ |
14+ v
15+[Prism Frontend] -- CRuby + Prism gem (thin wrapper)
16+ | Parses Ruby, serializes AST to text format
17+ v
18+AST Text File (.ast)
19+ |
20+ v
21+[Spinel Backend] -- Written in Spinel-compilable Ruby subset
22+ | Reads AST, infers types, generates C
23+ v
24+C Source (.c)
25+ |
26+ v
27+cc -O2 -lm -- Native C compiler
28+ |
29+ v
30+Native Binary
31+```
32+
33+Two executables:
34+- `spinel-parse`: CRuby script (~700 lines), requires Prism. Outputs .ast file.
35+- `spinel-codegen`: Written in Ruby subset. Can run under CRuby OR as
36+ compiled native binary. Reads .ast, writes .c.
37+
38+One-command wrapper for convenience:
39+```bash
40+spinel input.rb -o output.c
41+# equivalent to:
42+spinel-parse input.rb > /tmp/ast && spinel-codegen /tmp/ast output.c
43+```
44+
45+## Ruby Subset ("Spinel Ruby")
46+
47+The compiler is written using ONLY these Ruby features:
48+
49+### Allowed
50+- `class`, `def`, `attr_accessor`, `attr_reader`
51+- `if`/`elsif`/`else`, `unless`, `case`/`when`, `while`, `until`
52+- `return`, `break`, `next`
53+- `begin`/`rescue`/`ensure`
54+- `yield`, `block_given?`, blocks with `do..end` or `{..}`
55+- Integer, Float, String (immutable `const char *`)
56+- Mutable string via `"".dup` + `<<`
57+- Array (homogeneous: Integer or String element)
58+- Hash (string keys, integer or string values)
59+- `puts`, `print`, `$stderr.puts`
60+- `File.read`, `File.write`
61+- `ARGV`, `ARGV.length`, `ARGV[i]`
62+- String methods: `length`, `+`, `==`, `!=`, `include?`, `start_with?`,
63+ `end_with?`, `index`, `split`, `gsub`, `sub`, `strip`, `chomp`,
64+ `to_i`, `to_f`, `[]`, `upcase`, `downcase`
65+- Integer methods: `+`, `-`, `*`, `/`, `%`, `==`, `<`, `>`, `to_s`
66+- Array methods: `push`, `pop`, `length`, `[]`, `[]=`, `include?`,
67+ `each`, `empty?`
68+- Hash methods: `[]`, `[]=`, `has_key?`, `length`, `each`, `delete`
69+- `nil` comparisons: `x == nil`, `x != nil`
70+- Constants: `FOO = value`
71+- String interpolation: `"hello #{x}"`
72+
73+### NOT Allowed
74+- `require` (except in parse frontend)
75+- `Struct.new`, `OpenStruct`
76+- `method_missing`, `respond_to_missing?`, `define_method`
77+- `eval`, `instance_eval`, `class_eval`, `send`
78+- `Symbol` literals (use strings: `"name"` not `:name`)
79+- `||=` (use explicit nil check)
80+- `lambda`, `->`, `proc {}`, `Proc.new`
81+- `Set`, `Comparable`, `Enumerable`
82+- `map`, `select`, `reject`, `reduce` (use `while` loops)
83+- `&:method` shorthand
84+- `.last`, `.first` (use `arr[arr.length - 1]`, `arr[0]`)
85+- Monkey patching, open classes on built-in types
86+- Multiple return values
87+- Splat args `*args`
88+- `freeze`, `frozen?`
89+- Regular expressions (in backend; parse frontend handles regex patterns)
90+
91+### Rationale
92+
93+Every feature in this subset has a direct, efficient C translation:
94+- `class` → C struct + functions
95+- `Array` → `sp_IntArray` or `sp_StrArray`
96+- `Hash` → `sp_StrIntHash` or `sp_StrStrHash`
97+- `while` → C `while`
98+- `yield` → function pointer callback
99+- `String` → `const char *`
100+
101+No dynamic dispatch, no metaprogramming, no closures needed.
102+
103+## AST Text Format
104+
105+Line-based, parseable with `split` and `to_i`:
106+
107+```
108+ROOT 0
109+N 0 ProgramNode
110+N 1 StatementsNode
111+N 2 CallNode
112+S 2 name puts
113+I 2 flags 0
114+R 2 receiver -1
115+R 2 arguments 3
116+N 3 ArgumentsNode
117+A 3 arguments 4
118+N 4 IntegerNode
119+I 4 value 42
120+A 1 body 2
121+R 0 statements 1
122+```
123+
124+Line types:
125+- `ROOT id` — root node ID
126+- `N id TypeName` — declare node
127+- `S id field value` — string field (percent-encoded)
128+- `I id field value` — integer field
129+- `F id field value` — float field
130+- `R id field ref_id` — node reference (-1 = nil)
131+- `A id field id1,id2,...` — array of node references
132+
133+## AST Node Class
134+
135+Single class with all possible fields:
136+
137+```ruby
138+class Node
139+ attr_accessor :type # String: "CallNode" etc
140+ attr_accessor :name # String
141+ attr_accessor :value # Integer or Float
142+ attr_accessor :content # String (for StringNode)
143+ attr_accessor :receiver # Node or nil
144+ attr_accessor :arguments # Node or nil (ArgumentsNode wrapper)
145+ attr_accessor :body # Node or nil
146+ attr_accessor :stmts # Array of Node (for StatementsNode.body)
147+ attr_accessor :args # Array of Node (for ArgumentsNode.arguments)
148+ attr_accessor :block # Node or nil
149+ attr_accessor :parameters # Node or nil
150+ attr_accessor :predicate # Node or nil
151+ attr_accessor :conditions # Array of Node
152+ attr_accessor :subsequent # Node or nil
153+ attr_accessor :else_clause # Node or nil
154+ attr_accessor :left # Node or nil
155+ attr_accessor :right # Node or nil
156+ attr_accessor :elements # Array of Node
157+ attr_accessor :parts # Array of Node
158+ attr_accessor :constant_path # Node or nil
159+ attr_accessor :superclass # Node or nil
160+ attr_accessor :requireds # Array of Node
161+ attr_accessor :optionals # Array of Node
162+ attr_accessor :keywords # Array of Node
163+ attr_accessor :rest # Node or nil
164+ attr_accessor :exceptions # Array of Node
165+ attr_accessor :rescue_clause # Node or nil
166+ attr_accessor :ensure_clause # Node or nil
167+ attr_accessor :expression # Node or nil
168+ attr_accessor :target # Node or nil
169+ attr_accessor :targets # Array of Node
170+ attr_accessor :pattern # Node or nil
171+ attr_accessor :key # Node or nil
172+ attr_accessor :reference # Node or nil
173+ attr_accessor :flags # Integer
174+ attr_accessor :depth # Integer
175+ attr_accessor :operator # String
176+ attr_accessor :binary_operator # String
177+ attr_accessor :call_operator # String
178+ attr_accessor :unescaped # String
179+ attr_accessor :collection # Node or nil
180+
181+ def initialize
182+ @type = ""
183+ @name = ""
184+ @value = 0
185+ @content = ""
186+ @flags = 0
187+ @depth = 0
188+ @operator = ""
189+ @binary_operator = ""
190+ @call_operator = ""
191+ @unescaped = ""
192+ end
193+end
194+```
195+
196+Note: Node-typed fields are initialized to nil by default in the
197+initializer (Spinel infers their type from external setter calls).
198+Array-typed fields are initialized to empty arrays `[]` when first
199+needed. This means Spinel needs to track that `node.receiver = x`
200+(where x is a Node) implies receiver's type is Node*.
201+
202+## Compiler Data Structures
203+
204+All written as regular classes with attr_accessor:
205+
206+```ruby
207+class VarInfo
208+ attr_accessor :name, :type, :c_name, :declared
209+end
210+
211+class ParamInfo
212+ attr_accessor :name, :type, :default_node
213+end
214+
215+class MethodInfo
216+ attr_accessor :name, :params, :return_type, :body_node
217+ attr_accessor :has_yield, :is_class_method
218+end
219+
220+class ClassInfo
221+ attr_accessor :name, :parent_name
222+ attr_accessor :ivar_names, :ivar_types # parallel arrays
223+ attr_accessor :method_names, :method_infos # parallel arrays
224+ attr_accessor :attr_readers, :attr_writers, :attr_accessors
225+ attr_accessor :includes # array of module names
226+end
227+```
228+
229+Key design: **NO hash-of-objects**. Use parallel arrays:
230+- `@class_names` + `@class_infos` instead of `@classes = {}`
231+- `method_names` + `method_infos` instead of `methods = {}`
232+- Lookup: `find_class(name)` scans `@class_names` array
233+
234+This avoids Spinel's type inference problem with Hash values being
235+`mrb_int` when they should be object pointers.
236+
237+## Compiler Structure
238+
239+```
240+spinel_codegen.rb
241+├── Node (AST node)
242+├── VarInfo, ParamInfo, MethodInfo, ClassInfo
243+├── Type module (constants: INTEGER, FLOAT, STRING, ...)
244+├── AstReader
245+│ └── read_text_ast(data) → Node
246+├── TypeInferrer
247+│ ├── infer(node) → type string
248+│ └── resolve_class_types()
249+├── ClassAnalyzer
250+│ ├── collect_classes(root)
251+│ ├── collect_methods(root)
252+│ └── collect_ivars()
253+├── CodeEmitter
254+│ ├── emit_header()
255+│ ├── emit_struct(class_info)
256+│ ├── emit_method(class_info, method_info)
257+│ └── emit_runtime_helpers()
258+├── ExprCompiler
259+│ └── compile(node) → string (C expression)
260+├── StmtCompiler
261+│ └── compile(node) (emits C statements)
262+└── main
263+ ├── read AST from file
264+ ├── analyze classes
265+ ├── infer types
266+ ├── generate C
267+ └── write output
268+```
269+
270+## Implementation Phases
271+
272+### Phase 1: Skeleton + fib (Day 1)
273+- Node class, AstReader (text format)
274+- ExprCompiler: IntegerNode, CallNode (+, -, <), LocalVariableReadNode
275+- StmtCompiler: LocalVariableWriteNode, IfNode, ReturnNode
276+- Top-level def: DefNode with parameters
277+- puts with integer
278+- Test: fib(34) = 5702887
279+- Self-compile test: compile spinel_codegen.rb → C → binary
280+
281+### Phase 2: Strings + control flow (Day 2)
282+- StringNode, InterpolatedStringNode, SymbolNode
283+- String methods: length, +, ==, include?, split, gsub, to_i
284+- case/when (with strcmp for strings)
285+- while, unless, for..in
286+- break, next
287+- Constants
288+- Tests: bm_strings, bm_case, bm_control
289+
290+### Phase 3: Classes + OOP (Day 3)
291+- ClassNode with constructor, instance variables
292+- attr_accessor/reader/writer
293+- Inheritance, super
294+- Type inference for class instances
295+- Class method calls: obj.method(args)
296+- Tests: bm_inherit, bm_attr, bm_comparable
297+
298+### Phase 4: Arrays + Hashes (Day 4)
299+- Array literals, push, pop, [], []=, length, each
300+- Hash literals, [], []=, has_key?, each, delete
301+- Type inference for collections
302+- for..in with arrays
303+- Integer#times, upto, downto
304+- Tests: bm_array2, bm_hash, bm_sort_reduce
305+
306+### Phase 5: Blocks + yield (Day 5)
307+- yield, block_given?
308+- Block parameter passing (function pointer + env)
309+- Array#each, map, select with block
310+- Tests: bm_yield, bm_block2, bm_enumerable
311+
312+### Phase 6: Exceptions + I/O (Day 6)
313+- begin/rescue/ensure, raise
314+- File.read, File.write, File.exist?
315+- ARGV processing
316+- system(), backtick
317+- Tests: bm_rescue, bm_fileio, bm_system
318+
319+### Phase 7: Advanced features (Day 7)
320+- Mutable strings (sp_String)
321+- Struct.new
322+- Pattern matching (case/in)
323+- catch/throw
324+- Regular expressions (via runtime)
325+- Tests: bm_struct, bm_pattern, bm_mutable_str
326+
327+### Phase 8: Polymorphism (Day 8)
328+- NaN-boxed values for mixed-type variables
329+- 3-tier dispatch (mono/bi/mega)
330+- Heterogeneous arrays and hashes
331+- Tests: bm_poly, bm_mega, bm_poly_hash
332+
333+### Phase 9: Self-hosting (Day 9)
334+- Compile spinel_codegen.rb with itself
335+- Fix type inference issues iteratively
336+- Verify: self-compiled binary produces identical output
337+- Performance comparison with CRuby-compiled binary
338+
339+### Phase 10: Polish (Day 10)
340+- Benchmark all 39 programs
341+- Fix remaining edge cases
342+- Performance optimization (conditional emission)
343+- README and documentation
344+
345+## Key Design Decisions
346+
347+### Parallel arrays instead of Hash-of-objects
348+```ruby
349+# NOT this (Spinel can't type-infer Hash values):
350+@classes = {} # string → ClassInfo
351+
352+# THIS:
353+@class_names = [] # Array of String
354+@class_infos = [] # Array of ClassInfo
355+
356+def find_class(name)
357+ i = 0
358+ while i < @class_names.length
359+ if @class_names[i] == name
360+ return @class_infos[i]
361+ end
362+ i = i + 1
363+ end
364+ nil
365+end
366+```
367+
368+### No iterators, use while loops
369+```ruby
370+# NOT this:
371+arr.each { |x| puts x }
372+arr.map { |x| x * 2 }
373+
374+# THIS:
375+i = 0
376+while i < arr.length
377+ puts arr[i]
378+ i = i + 1
379+end
380+```
381+
382+Exception: `yield` blocks ARE supported for user-defined iterators,
383+since the compiler emits them as C function pointers.
384+
385+### Explicit nil checks instead of ||=
386+```ruby
387+# NOT this:
388+@foo ||= []
389+
390+# THIS:
391+if @foo == nil
392+ @foo = []
393+end
394+```
395+
396+### String keys only in Hash
397+```ruby
398+# NOT this:
399+{name: "Alice", age: 30}
400+
401+# THIS:
402+h = {}
403+h["name"] = "Alice" # But value must be same type!
404+```
405+
406+Actually for mixed-value hashes, use parallel arrays:
407+```ruby
408+@const_names = []
409+@const_types = []
410+@const_values = []
411+```
412+
413+### Output buffering with StringIO
414+Spinel supports StringIO as built-in type:
415+```ruby
416+out = StringIO.new
417+out.puts "line 1"
418+out.puts "line 2"
419+result = out.string
420+```
421+
422+### Node type dispatch with case/when
423+```ruby
424+case node.type
425+when "IntegerNode"
426+ node.value.to_s
427+when "CallNode"
428+ compile_call(node)
429+when "StringNode"
430+ c_string_literal(node.content)
431+end
432+```
433+
434+## File Layout
435+
436+```
437+spinel-v2/
438+├── spinel_parse.rb # CRuby frontend (Prism → AST text)
439+├── spinel_codegen.rb # Compiler backend (Spinel Ruby subset)
440+├── test/ # Test programs
441+├── benchmark/ # Benchmark programs
442+└── PLAN.md # This file
443+```
444+
445+## Success Criteria
446+
447+1. All 59 tests produce identical output
448+2. All 38+ benchmarks produce correct output
449+3. spinel_codegen.rb compiles with Spinel (0 C errors)
450+4. Self-compiled binary produces identical output to CRuby-run version
451+5. Performance within 2x of C version on all benchmarks
452+6. Total code < 8,000 lines of Ruby