Commit 71ff060f

71ff060f3254Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 8 months ago · 1 file · ~1 modified

Description

Comprehensive README rewrite — 10500 lines, 47 examples, NaN-boxing

Full rewrite reflecting current state:

  • Polymorphism overview (MONO vs POLY, 3-tier dispatch, NaN-boxing)
  • Complete feature table (OOP, blocks, control flow, exceptions, params, polymorphism, types, collections, strings, regexp, numeric, I/O, introspection, multi-file, runtime)
  • Architecture: 3-tier dispatch + NaN-boxing explanation
  • Test suite: make test-all (44/44 pass)
  • Updated project structure (10500 lines, 47 examples)

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

Details

Commit
71ff060f3254
Parent
d13e349f9cb0

README.mdmodifiedView file

@@ -2,192 +2,137 @@
22
33 Spinel compiles Ruby source code to standalone C executables via
44 [Prism](https://github.com/ruby/prism) parsing and whole-program type inference.
5-Classes become C structs, methods become direct function calls, and numeric
6-operations compile to native C arithmetic with zero dynamic dispatch overhead.
7-Generated binaries have no runtime dependencies — no mruby, no GC, just libc and libm.
85
6+- **Monomorphic code** (statically typed): classes → C structs, methods → direct C calls,
7+ arithmetic → native C operators. 20-57x faster than CRuby.
8+- **Polymorphic code** (dynamically typed): 8-byte NaN-boxed values with 3-tier dispatch
9+ (monomorphic → bimorphic inline switch → megamorphic dispatch function).
10+- **No runtime dependencies**: generated binaries need only libc and libm.
11+ Mark-and-sweep GC is generated inline. Regexp programs link with libonig.
12+
13+~10500 lines of C. 47 test programs. 44/44 automated tests pass.
14+
915 ## Quick Start
1016
1117 ```bash
12-# 1. Fetch and build the Prism parser library
13-make deps
18+# Build the compiler
19+make deps && make
1420
15-# 2. Build the spinel compiler
16-make
17-
18-# 3. Compile a Ruby program to C, then to a native binary
21+# Compile a Ruby program
1922 ./spinel --source=app.rb --output=app.c
2023 cc -O2 app.c -lm -o app
2124
22-# For programs using Regexp, link with oniguruma:
23-cc -O2 app.c -lonig -lm -o app
25+# Run the full test suite
26+make test-all
2427 ```
2528
26-The generated C file includes a comment with the exact compile command needed.
29+The generated C file includes a comment with the exact compile command.
2730
2831 ## Benchmarks
2932
3033 | Benchmark | CRuby 3.2 | mruby | **Spinel AOT** | Speedup |
3134 |-----------|-----------|-------|----------------|---------|
32-| mandelbrot (600x600 PBM) | 1.14s | 3.18s | **0.02s** | **57x** |
33-| ao_render (64x64 AO raytracer) | 3.55s | 13.69s | **0.06s** | **59x** |
34-
35-Binary sizes: mandelbrot 16KB, ao_render 21KB (stripped).
35+| mandelbrot (600x600) | 1.14s | 3.18s | **0.02s** | **57x** |
36+| ao_render (64x64 AO) | 3.55s | 13.69s | **0.07s** | **51x** |
37+| so_lists (300x10K) | 0.44s | 2.01s | **0.02s** | **22x** |
38+| fib(34) recursive | 0.55s | 2.78s | **0.01s** | **55x** |
39+| lc_fizzbuzz (Church) | 28.96s | — | **1.55s** | **19x** |
3640
37-```bash
38-make test # compile mandelbrot, run, verify output matches CRuby
39-```
40-
4141 ## How It Works
4242
4343 ```
4444 Ruby Source (.rb)
4545 |
4646 v
47-Prism (libprism) -- parse to AST
47+Prism (libprism) -- parse to AST
4848 |
4949 v
50-Pass 1: Class Analysis -- find classes, methods, instance variables
51- |
50+Pass 1: Class Analysis -- classes, modules, inheritance, mixins,
51+ | attr_accessor, Struct.new, yield detection,
52+ | require_relative (multi-file)
5253 v
53-Pass 2: Type Inference -- infer types for all variables, ivars, params
54- | (Integer, Float, Boolean, Object types)
55- v
56-Pass 3: Struct/Method Emit -- classes -> C structs
57- | methods -> C functions (direct calls)
58- | getters/setters -> inline field access
54+Pass 2: Type Inference -- whole-program: variables, ivars, params,
55+ | returns. Cross-function inference.
56+ | MONO (single type) vs POLY (union type)
5957 v
60-Pass 4: Main Codegen -- top-level code -> main()
61- | while/for/times -> C loops
62- | arithmetic -> C operators
63- | puts/print/printf -> stdio
58+Pass 3: Code Generation -- MONO: classes → C structs, methods → direct calls
59+ | POLY: sp_RbValue (8B NaN-boxed), 3-tier dispatch
60+ | Closures, blocks, regexp, exceptions
6461 v
65-Standalone C file
62+Standalone C file -- GC inline, exception handling inline
6663 |
6764 v
68-cc -O2 -lm -> native binary -- no mruby, no GC, just libc
65+cc -O2 -lm → native binary
6966 ```
7067
71-For `bm_ao_render.rb`, the compiler:
72-- Converts 6 Ruby classes (Vec, Sphere, Plane, Ray, Isect, Scene) into C structs
73-- Vec (3 floats) is passed/returned by value — no heap allocation
74-- All method calls are devirtualized to direct C function calls
75-- `Integer#times` blocks become C for loops
76-- `Math.sqrt/cos/sin` map directly to C math functions
77-- The Rand module's xorshift PRNG compiles to inline integer arithmetic
78-
7968 ## Supported Language Features
8069
81-| Feature | Example |
82-|---------|---------|
83-| **Classes & OOP** | |
84-| Classes with instance variables | `class Vec; def initialize(x,y,z); @x=x; end; end` |
85-| Inheritance | `class Dog < Animal` |
86-| `super` | `super(name)` in child initialize/methods |
87-| `include` (mixin) | `class Widget; include Printable; end` |
88-| `attr_accessor/reader/writer` | `attr_accessor :x, :y` |
89-| Class methods | `def self.origin; Point.new(0,0); end` |
90-| Getters/setters (inlined) | auto-generated from attr or manual |
91-| Object construction | `Vec.new(1.0, 2.0, 3.0)` |
92-| Modules with state | `module Rand; @x = 123; def self.rand; ...; end; end` |
93-| **Blocks & Closures** | |
94-| `yield` | `def my_iter(n); yield i; end` |
95-| Blocks at call sites | `my_iter(10) do \|i\| total += i end` |
96-| `Array#each/map/select` | `arr.each { \|x\| puts x }` (inlined) |
97-| `Hash#each` | `h.each { \|k,v\| puts k }` |
98-| `Integer#times` with block | `n.times do \|i\| ... end` |
99-| Lambda/closures | `-> x { x + 1 }` with capture analysis |
100-| **Control Flow** | |
101-| `if`/`elsif`/`else`, `unless` | conditional branching |
102-| `case`/`when`/`else` | values, multiple values, ranges |
103-| `while`, `until`, `loop do`, `for..in` | loops |
104-| Ternary, `and`/`or`/`not` | boolean operators |
105-| `break`, `next`, `return` | loop/method exit |
106-| **Exception Handling** | |
107-| `begin`/`rescue`/`ensure`/`retry` | setjmp/longjmp based |
108-| `raise`, `rescue => e` | string exceptions |
109-| **Parameters** | |
110-| Positional, default values | `def foo(x, y = 10)` |
111-| Keyword arguments | `def greet(name:, greeting: "Hello")` |
112-| Rest/splat | `def sum(*nums)` |
113-| **Types & Collections** | |
114-| Integer, Float, Boolean, String, Symbol, nil | unboxed C types |
115-| Integer arrays | push/pop/shift/dup/reverse!/each/map/select |
116-| Hash (string→integer) | `[]=`, `[]`, `each`, `has_key?`, `delete` |
117-| **Strings** | |
118-| Literals, interpolation | `"hello #{name}"` → printf |
119-| 15+ methods | length, upcase, downcase, strip, reverse, gsub, sub, split, ... |
120-| Comparison, repetition | `==`, `<`, `"ha" * 3` |
121-| **Arithmetic** | |
122-| All operators | `+` `-` `*` `/` `%` `**` `<<` `\|` `^` `<` `>` `==` |
123-| Math module | `sqrt`, `cos`, `sin` |
124-| Numeric methods | `abs`, `even?`, `odd?`, `zero?`, `ceil`, `floor`, `round` |
125-| **I/O** | |
126-| `puts`/`print`/`printf`/`putc`/`p` | Int, Float, Bool, String |
127-| **Regexp** | |
128-| Regex literals, `=~`, captures | `/\d+/`, `$1`, `$2`, `$3` |
129-| `match?`, `gsub`, `sub`, `scan`, `split` | via oniguruma |
130-| **Introspection** | |
131-| `is_a?`, `respond_to?`, `nil?` | compile-time resolved |
132-| **Data Structures** | |
133-| `Struct.new(:x, :y)` | synthetic class with getters/setters |
134-| **Runtime** | |
135-| Mark-and-sweep GC | shadow stack roots, finalizers |
136-| Arena allocator | for closure-heavy programs |
70+| Category | Features |
71+|----------|----------|
72+| **OOP** | Classes, inheritance (`< Parent`), `super`, `include` (mixin), `attr_accessor`/`reader`/`writer`, class methods (`def self.foo`), `Struct.new`, `alias`, `Comparable` (operator methods) |
73+| **Blocks & Closures** | `yield`, `block_given?`, `&block`, `proc {}`, `Proc.new`, `Proc#call`, `method(:name)`, `Array#each/map/select/reject/reduce`, `Hash#each`, `Integer#times/upto/downto`, lambda `-> x { }`, `Enumerable` |
74+| **Control Flow** | `if`/`elsif`/`else`, `unless`, `case`/`when`, **`case`/`in` (pattern matching)**, `while`, `until`, `loop`, `for..in`, `break`, `next`, `return`, `catch`/`throw`, ternary, `and`/`or`/`not` |
75+| **Exceptions** | `begin`/`rescue`/`ensure`/`retry`, `raise "msg"`, `raise ClassName, "msg"`, `rescue ClassName => e` (class hierarchy), custom exception classes |
76+| **Parameters** | Positional, default values, keyword (`name:, greeting: "Hello"`), rest/splat (`*args`) |
77+| **Polymorphism** | Variables holding multiple types, heterogeneous arrays `[1, "two", 3.0]`, heterogeneous Hash `{name: "Alice", age: 30}`, duck typing (bimorphic + megamorphic dispatch), `case/in` pattern matching |
78+| **Types** | Integer, Float, Boolean, String (immutable `const char *` + mutable `sp_String`), Symbol, nil, Range, Time |
79+| **Collections** | Integer arrays (push/pop/shift/sort/min/max/sum/reduce/join/uniq), Hash (String→Int, heterogeneous), String arrays (split results) |
80+| **Strings** | 20+ methods: length, upcase, downcase, strip, reverse, gsub, sub, split, capitalize, chomp, include?, start\_with?, end\_with?, count, `+`, `<<`, `*`, `[]`, replace, clear, comparison (`==`/`<`) |
81+| **Regexp** | `/pattern/`, `=~`, `$1`-`$9`, `match?`, `gsub`, `sub`, `scan`, `split` (via oniguruma) |
82+| **Numeric** | `abs`, `even?`, `odd?`, `zero?`, `positive?`, `negative?`, `ceil`, `floor`, `round`, `**`, `to_f`, `to_i`, `to_s` |
83+| **I/O** | `puts`/`print`/`printf`/`putc`/`p`, `File.read/write/exist?/delete`, `ARGV`, `$stderr.puts`, `exit`, `sleep` |
84+| **Introspection** | `is_a?` (compile-time), `respond_to?` (compile-time), `nil?`, `defined?`, `__LINE__`, `__FILE__`, `__method__`, `freeze`/`frozen?` |
85+| **Multi-file** | `require_relative` (compile-time file resolution and merging) |
86+| **Runtime** | Mark-and-sweep GC (shadow stack), arena allocator (closures), NaN-boxed polymorphic values (8 bytes) |
87+
88+## Architecture
89+
90+### 3-Tier Method Dispatch
91+
92+| Polymorphism | Strategy | Speed |
93+|-------------|----------|-------|
94+| Monomorphic (1 type) | Direct C function call | Fastest |
95+| Bimorphic (2 types) | Inline if/else at call site | Fast |
96+| Megamorphic (3+ types) | Per-method dispatch function | Good |
97+
98+### NaN-boxing (8-byte values)
99+
100+Polymorphic values use favor-pointer NaN-boxing:
101+- Pointer: zero-cost extract (raw 48-bit address)
102+- Integer: shift + mask (48-bit signed, ±140 trillion)
103+- Double: subtract offset + bitcast
104+- Bool/Nil: special constants
105+
106+Monomorphic code uses unboxed C types — zero overhead.
137107
138-## Benchmarks
108+## Test Suite
139109
140-| Benchmark | CRuby 3.2 | mruby | **Spinel AOT** | Speedup |
141-|-----------|-----------|-------|----------------|---------|
142-| mandelbrot (600x600 PBM) | 1.14s | 3.18s | **0.02s** | **57x** |
143-| ao_render (64x64 AO raytracer) | 3.55s | 13.69s | **0.07s** | **51x** |
144-| so_lists (300x10K arrays) | 0.44s | 2.01s | **0.02s** | **22x** |
145-| fib(34) recursive | 0.55s | 2.78s | **0.01s** | **55x** |
146-| lc_fizzbuzz (Church encoding) | 28.96s | — | **1.55s** | **19x** |
147-| mandel_term (terminal art) | 0.05s | 0.05s | **~0s** | **50x+** |
110+```bash
111+make test-all # 44 tests, all pass
112+make test # quick: mandelbrot only
113+```
148114
149115 ## Project Structure
150116
151117 ```
152118 spinel/
153119 ├── src/
154-│ ├── main.c # CLI, file reading, Prism parsing
120+│ ├── main.c # CLI, file reading, Prism parsing, require resolution
155121 │ ├── codegen.h # Type system, class/method/module info structs
156-│ └── codegen.c # Multi-pass code generator (~7200 lines)
157-├── examples/ # 21 test programs
158-│ ├── bm_so_mandelbrot.rb # Mandelbrot (while, bitwise, PBM)
159-│ ├── bm_ao_render.rb # AO raytracer (6 classes, modules, GC)
160-│ ├── bm_so_lists.rb # Array operations (push/pop/shift, GC)
161-│ ├── bm_fib.rb # Recursive fibonacci
162-│ ├── bm_app_lc_fizzbuzz.rb # Lambda calculus (1201 closures, arena)
163-│ ├── bm_mandel_term.rb # Terminal Mandelbrot
164-│ ├── bm_yield.rb # yield/blocks, each/map/select
165-│ ├── bm_case.rb # case/when, unless, next, defaults
166-│ ├── bm_inherit.rb # Inheritance, super
167-│ ├── bm_rescue.rb # rescue/raise/ensure/retry
168-│ ├── bm_hash.rb # Hash operations
169-│ ├── bm_strings.rb # Symbol, basic string methods
170-│ ├── bm_strings2.rb # Advanced string methods, split
171-│ ├── bm_numeric.rb # Numeric methods, power
172-│ ├── bm_attr.rb # attr_accessor, for..in, loop, class methods
173-│ ├── bm_kwargs.rb # Keyword args, rest/splat
174-│ ├── bm_mixin.rb # include (mixin)
175-│ ├── bm_misc.rb # upto/downto, String <<
176-│ ├── bm_regexp.rb # Regexp (oniguruma)
177-│ ├── bm_introspect.rb # is_a?, respond_to?, nil?
178-│ └── bm_struct.rb # Struct.new
122+│ └── codegen.c # Multi-pass code generator (~10500 lines)
123+├── examples/ # 47 test programs (44 automated)
179124 ├── prototype/
180-│ └── tools/ # Step 0 prototype (RBS extraction, LumiTrace)
181-├── Makefile
182-├── PLAN.md # Implementation roadmap
183-└── ruby_aot_compiler_design.md # Detailed design document
125+│ └── tools/ # RBS extraction, LumiTrace prototype tools
126+├── Makefile # build, test, test-all
127+├── PLAN.md # Implementation roadmap & design docs
128+└── ruby_aot_compiler_design.md
184129 ```
185130
186131 ## Dependencies
187132
188133 - **Build time**: [Prism](https://github.com/ruby/prism) (fetched automatically by `make deps`)
189-- **Run time**: None for most programs. Generated binaries are standalone (libc + libm only).
190-- **Regexp**: Programs using regular expressions require [oniguruma](https://github.com/kkos/oniguruma) (`-lonig`). Install: `apt install libonig-dev` or equivalent.
134+- **Run time**: None for most programs. libc + libm only.
135+- **Regexp**: Programs using regex require [oniguruma](https://github.com/kkos/oniguruma) (`-lonig`).
191136
192137 ## License
193138