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 Compiler2+
3+
## Goal4+
5+
Rewrite the Spinel AOT compiler in a Ruby subset that Spinel itself can6+
compile. The compiler takes Ruby source, parses it with Prism, infers7+
types, and generates standalone C code.8+
9+
## Architecture10+
11+
```12+
Ruby Source (.rb)13+
|14+
v15+
[Prism Frontend] -- CRuby + Prism gem (thin wrapper)16+
| Parses Ruby, serializes AST to text format17+
v18+
AST Text File (.ast)19+
|20+
v21+
[Spinel Backend] -- Written in Spinel-compilable Ruby subset22+
| Reads AST, infers types, generates C23+
v24+
C Source (.c)25+
|26+
v27+
cc -O2 -lm -- Native C compiler28+
|29+
v30+
Native Binary31+
```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 as36+
compiled native binary. Reads .ast, writes .c.37+
38+
One-command wrapper for convenience:39+
```bash40+
spinel input.rb -o output.c41+
# equivalent to:42+
spinel-parse input.rb > /tmp/ast && spinel-codegen /tmp/ast output.c43+
```44+
45+
## Ruby Subset ("Spinel Ruby")46+
47+
The compiler is written using ONLY these Ruby features:48+
49+
### Allowed50+
- `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 Allowed74+
- `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` shorthand84+
- `.last`, `.first` (use `arr[arr.length - 1]`, `arr[0]`)85+
- Monkey patching, open classes on built-in types86+
- Multiple return values87+
- Splat args `*args`88+
- `freeze`, `frozen?`89+
- Regular expressions (in backend; parse frontend handles regex patterns)90+
91+
### Rationale92+
93+
Every feature in this subset has a direct, efficient C translation:94+
- `class` → C struct + functions95+
- `Array` → `sp_IntArray` or `sp_StrArray`96+
- `Hash` → `sp_StrIntHash` or `sp_StrStrHash`97+
- `while` → C `while`98+
- `yield` → function pointer callback99+
- `String` → `const char *`100+
101+
No dynamic dispatch, no metaprogramming, no closures needed.102+
103+
## AST Text Format104+
105+
Line-based, parseable with `split` and `to_i`:106+
107+
```108+
ROOT 0109+
N 0 ProgramNode110+
N 1 StatementsNode111+
N 2 CallNode112+
S 2 name puts113+
I 2 flags 0114+
R 2 receiver -1115+
R 2 arguments 3116+
N 3 ArgumentsNode117+
A 3 arguments 4118+
N 4 IntegerNode119+
I 4 value 42120+
A 1 body 2121+
R 0 statements 1122+
```123+
124+
Line types:125+
- `ROOT id` — root node ID126+
- `N id TypeName` — declare node127+
- `S id field value` — string field (percent-encoded)128+
- `I id field value` — integer field129+
- `F id field value` — float field130+
- `R id field ref_id` — node reference (-1 = nil)131+
- `A id field id1,id2,...` — array of node references132+
133+
## AST Node Class134+
135+
Single class with all possible fields:136+
137+
```ruby138+
class Node139+
attr_accessor :type # String: "CallNode" etc140+
attr_accessor :name # String141+
attr_accessor :value # Integer or Float142+
attr_accessor :content # String (for StringNode)143+
attr_accessor :receiver # Node or nil144+
attr_accessor :arguments # Node or nil (ArgumentsNode wrapper)145+
attr_accessor :body # Node or nil146+
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 nil149+
attr_accessor :parameters # Node or nil150+
attr_accessor :predicate # Node or nil151+
attr_accessor :conditions # Array of Node152+
attr_accessor :subsequent # Node or nil153+
attr_accessor :else_clause # Node or nil154+
attr_accessor :left # Node or nil155+
attr_accessor :right # Node or nil156+
attr_accessor :elements # Array of Node157+
attr_accessor :parts # Array of Node158+
attr_accessor :constant_path # Node or nil159+
attr_accessor :superclass # Node or nil160+
attr_accessor :requireds # Array of Node161+
attr_accessor :optionals # Array of Node162+
attr_accessor :keywords # Array of Node163+
attr_accessor :rest # Node or nil164+
attr_accessor :exceptions # Array of Node165+
attr_accessor :rescue_clause # Node or nil166+
attr_accessor :ensure_clause # Node or nil167+
attr_accessor :expression # Node or nil168+
attr_accessor :target # Node or nil169+
attr_accessor :targets # Array of Node170+
attr_accessor :pattern # Node or nil171+
attr_accessor :key # Node or nil172+
attr_accessor :reference # Node or nil173+
attr_accessor :flags # Integer174+
attr_accessor :depth # Integer175+
attr_accessor :operator # String176+
attr_accessor :binary_operator # String177+
attr_accessor :call_operator # String178+
attr_accessor :unescaped # String179+
attr_accessor :collection # Node or nil180+
181+
def initialize182+
@type = ""183+
@name = ""184+
@value = 0185+
@content = ""186+
@flags = 0187+
@depth = 0188+
@operator = ""189+
@binary_operator = ""190+
@call_operator = ""191+
@unescaped = ""192+
end193+
end194+
```195+
196+
Note: Node-typed fields are initialized to nil by default in the197+
initializer (Spinel infers their type from external setter calls).198+
Array-typed fields are initialized to empty arrays `[]` when first199+
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 Structures203+
204+
All written as regular classes with attr_accessor:205+
206+
```ruby207+
class VarInfo208+
attr_accessor :name, :type, :c_name, :declared209+
end210+
211+
class ParamInfo212+
attr_accessor :name, :type, :default_node213+
end214+
215+
class MethodInfo216+
attr_accessor :name, :params, :return_type, :body_node217+
attr_accessor :has_yield, :is_class_method218+
end219+
220+
class ClassInfo221+
attr_accessor :name, :parent_name222+
attr_accessor :ivar_names, :ivar_types # parallel arrays223+
attr_accessor :method_names, :method_infos # parallel arrays224+
attr_accessor :attr_readers, :attr_writers, :attr_accessors225+
attr_accessor :includes # array of module names226+
end227+
```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` array233+
234+
This avoids Spinel's type inference problem with Hash values being235+
`mrb_int` when they should be object pointers.236+
237+
## Compiler Structure238+
239+
```240+
spinel_codegen.rb241+
├── Node (AST node)242+
├── VarInfo, ParamInfo, MethodInfo, ClassInfo243+
├── Type module (constants: INTEGER, FLOAT, STRING, ...)244+
├── AstReader245+
│ └── read_text_ast(data) → Node246+
├── TypeInferrer247+
│ ├── infer(node) → type string248+
│ └── resolve_class_types()249+
├── ClassAnalyzer250+
│ ├── collect_classes(root)251+
│ ├── collect_methods(root)252+
│ └── collect_ivars()253+
├── CodeEmitter254+
│ ├── emit_header()255+
│ ├── emit_struct(class_info)256+
│ ├── emit_method(class_info, method_info)257+
│ └── emit_runtime_helpers()258+
├── ExprCompiler259+
│ └── compile(node) → string (C expression)260+
├── StmtCompiler261+
│ └── compile(node) (emits C statements)262+
└── main263+
├── read AST from file264+
├── analyze classes265+
├── infer types266+
├── generate C267+
└── write output268+
```269+
270+
## Implementation Phases271+
272+
### Phase 1: Skeleton + fib (Day 1)273+
- Node class, AstReader (text format)274+
- ExprCompiler: IntegerNode, CallNode (+, -, <), LocalVariableReadNode275+
- StmtCompiler: LocalVariableWriteNode, IfNode, ReturnNode276+
- Top-level def: DefNode with parameters277+
- puts with integer278+
- Test: fib(34) = 5702887279+
- Self-compile test: compile spinel_codegen.rb → C → binary280+
281+
### Phase 2: Strings + control flow (Day 2)282+
- StringNode, InterpolatedStringNode, SymbolNode283+
- String methods: length, +, ==, include?, split, gsub, to_i284+
- case/when (with strcmp for strings)285+
- while, unless, for..in286+
- break, next287+
- Constants288+
- Tests: bm_strings, bm_case, bm_control289+
290+
### Phase 3: Classes + OOP (Day 3)291+
- ClassNode with constructor, instance variables292+
- attr_accessor/reader/writer293+
- Inheritance, super294+
- Type inference for class instances295+
- Class method calls: obj.method(args)296+
- Tests: bm_inherit, bm_attr, bm_comparable297+
298+
### Phase 4: Arrays + Hashes (Day 4)299+
- Array literals, push, pop, [], []=, length, each300+
- Hash literals, [], []=, has_key?, each, delete301+
- Type inference for collections302+
- for..in with arrays303+
- Integer#times, upto, downto304+
- Tests: bm_array2, bm_hash, bm_sort_reduce305+
306+
### Phase 5: Blocks + yield (Day 5)307+
- yield, block_given?308+
- Block parameter passing (function pointer + env)309+
- Array#each, map, select with block310+
- Tests: bm_yield, bm_block2, bm_enumerable311+
312+
### Phase 6: Exceptions + I/O (Day 6)313+
- begin/rescue/ensure, raise314+
- File.read, File.write, File.exist?315+
- ARGV processing316+
- system(), backtick317+
- Tests: bm_rescue, bm_fileio, bm_system318+
319+
### Phase 7: Advanced features (Day 7)320+
- Mutable strings (sp_String)321+
- Struct.new322+
- Pattern matching (case/in)323+
- catch/throw324+
- Regular expressions (via runtime)325+
- Tests: bm_struct, bm_pattern, bm_mutable_str326+
327+
### Phase 8: Polymorphism (Day 8)328+
- NaN-boxed values for mixed-type variables329+
- 3-tier dispatch (mono/bi/mega)330+
- Heterogeneous arrays and hashes331+
- Tests: bm_poly, bm_mega, bm_poly_hash332+
333+
### Phase 9: Self-hosting (Day 9)334+
- Compile spinel_codegen.rb with itself335+
- Fix type inference issues iteratively336+
- Verify: self-compiled binary produces identical output337+
- Performance comparison with CRuby-compiled binary338+
339+
### Phase 10: Polish (Day 10)340+
- Benchmark all 39 programs341+
- Fix remaining edge cases342+
- Performance optimization (conditional emission)343+
- README and documentation344+
345+
## Key Design Decisions346+
347+
### Parallel arrays instead of Hash-of-objects348+
```ruby349+
# NOT this (Spinel can't type-infer Hash values):350+
@classes = {} # string → ClassInfo351+
352+
# THIS:353+
@class_names = [] # Array of String354+
@class_infos = [] # Array of ClassInfo355+
356+
def find_class(name)357+
i = 0358+
while i < @class_names.length359+
if @class_names[i] == name360+
return @class_infos[i]361+
end362+
i = i + 1363+
end364+
nil365+
end366+
```367+
368+
### No iterators, use while loops369+
```ruby370+
# NOT this:371+
arr.each { |x| puts x }372+
arr.map { |x| x * 2 }373+
374+
# THIS:375+
i = 0376+
while i < arr.length377+
puts arr[i]378+
i = i + 1379+
end380+
```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+
```ruby387+
# NOT this:388+
@foo ||= []389+
390+
# THIS:391+
if @foo == nil392+
@foo = []393+
end394+
```395+
396+
### String keys only in Hash397+
```ruby398+
# 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+
```ruby408+
@const_names = []409+
@const_types = []410+
@const_values = []411+
```412+
413+
### Output buffering with StringIO414+
Spinel supports StringIO as built-in type:415+
```ruby416+
out = StringIO.new417+
out.puts "line 1"418+
out.puts "line 2"419+
result = out.string420+
```421+
422+
### Node type dispatch with case/when423+
```ruby424+
case node.type425+
when "IntegerNode"426+
node.value.to_s427+
when "CallNode"428+
compile_call(node)429+
when "StringNode"430+
c_string_literal(node.content)431+
end432+
```433+
434+
## File Layout435+
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 programs441+
├── benchmark/ # Benchmark programs442+
└── PLAN.md # This file443+
```444+
445+
## Success Criteria446+
447+
1. All 59 tests produce identical output448+
2. All 38+ benchmarks produce correct output449+
3. spinel_codegen.rb compiles with Spinel (0 C errors)450+
4. Self-compiled binary produces identical output to CRuby-run version451+
5. Performance within 2x of C version on all benchmarks452+
6. Total code < 8,000 lines of Rubyspinel_parse.rbaddedView file
Loading diff…