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 via44
[Prism](https://github.com/ruby/prism) parsing and whole-program type inference.5-
Classes become C structs, methods become direct function calls, and numeric6-
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 dispatch9+
(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 Start1016
1117
```bash12-
# 1. Fetch and build the Prism parser library13-
make deps18+
# Build the compiler19+
make deps && make1420
15-
# 2. Build the spinel compiler16-
make17-
18-
# 3. Compile a Ruby program to C, then to a native binary21+
# Compile a Ruby program1922
./spinel --source=app.rb --output=app.c2023
cc -O2 app.c -lm -o app2124
22-
# For programs using Regexp, link with oniguruma:23-
cc -O2 app.c -lonig -lm -o app25+
# Run the full test suite26+
make test-all2427
```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
## Benchmarks2932
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-
```bash38-
make test # compile mandelbrot, run, verify output matches CRuby39-
```40-
4141
## How It Works4242
4343
```4444
Ruby Source (.rb)4545
|4646
v47-
Prism (libprism) -- parse to AST47+
Prism (libprism) -- parse to AST4848
|4949
v50-
Pass 1: Class Analysis -- find classes, methods, instance variables51-
|50+
Pass 1: Class Analysis -- classes, modules, inheritance, mixins,51+
| attr_accessor, Struct.new, yield detection,52+
| require_relative (multi-file)5253
v53-
Pass 2: Type Inference -- infer types for all variables, ivars, params54-
| (Integer, Float, Boolean, Object types)55-
v56-
Pass 3: Struct/Method Emit -- classes -> C structs57-
| methods -> C functions (direct calls)58-
| getters/setters -> inline field access54+
Pass 2: Type Inference -- whole-program: variables, ivars, params,55+
| returns. Cross-function inference.56+
| MONO (single type) vs POLY (union type)5957
v60-
Pass 4: Main Codegen -- top-level code -> main()61-
| while/for/times -> C loops62-
| arithmetic -> C operators63-
| puts/print/printf -> stdio58+
Pass 3: Code Generation -- MONO: classes → C structs, methods → direct calls59+
| POLY: sp_RbValue (8B NaN-boxed), 3-tier dispatch60+
| Closures, blocks, regexp, exceptions6461
v65-
Standalone C file62+
Standalone C file -- GC inline, exception handling inline6663
|6764
v68-
cc -O2 -lm -> native binary -- no mruby, no GC, just libc65+
cc -O2 -lm → native binary6966
```7067
71-
For `bm_ao_render.rb`, the compiler:72-
- Converts 6 Ruby classes (Vec, Sphere, Plane, Ray, Isect, Scene) into C structs73-
- Vec (3 floats) is passed/returned by value — no heap allocation74-
- All method calls are devirtualized to direct C function calls75-
- `Integer#times` blocks become C for loops76-
- `Math.sqrt/cos/sin` map directly to C math functions77-
- The Rand module's xorshift PRNG compiles to inline integer arithmetic78-
7968
## Supported Language Features8069
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+
## Architecture89+
90+
### 3-Tier Method Dispatch91+
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 + bitcast104+
- Bool/Nil: special constants105+
106+
Monomorphic code uses unboxed C types — zero overhead.137107
138-
## Benchmarks108+
## Test Suite139109
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+
```bash111+
make test-all # 44 tests, all pass112+
make test # quick: mandelbrot only113+
```148114
149115
## Project Structure150116
151117
```152118
spinel/153119
├── src/154-
│ ├── main.c # CLI, file reading, Prism parsing120+
│ ├── main.c # CLI, file reading, Prism parsing, require resolution155121
│ ├── codegen.h # Type system, class/method/module info structs156-
│ └── codegen.c # Multi-pass code generator (~7200 lines)157-
├── examples/ # 21 test programs158-
│ ├── 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 fibonacci162-
│ ├── bm_app_lc_fizzbuzz.rb # Lambda calculus (1201 closures, arena)163-
│ ├── bm_mandel_term.rb # Terminal Mandelbrot164-
│ ├── bm_yield.rb # yield/blocks, each/map/select165-
│ ├── bm_case.rb # case/when, unless, next, defaults166-
│ ├── bm_inherit.rb # Inheritance, super167-
│ ├── bm_rescue.rb # rescue/raise/ensure/retry168-
│ ├── bm_hash.rb # Hash operations169-
│ ├── bm_strings.rb # Symbol, basic string methods170-
│ ├── bm_strings2.rb # Advanced string methods, split171-
│ ├── bm_numeric.rb # Numeric methods, power172-
│ ├── bm_attr.rb # attr_accessor, for..in, loop, class methods173-
│ ├── bm_kwargs.rb # Keyword args, rest/splat174-
│ ├── 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.new122+
│ └── 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-
├── Makefile182-
├── PLAN.md # Implementation roadmap183-
└── ruby_aot_compiler_design.md # Detailed design document125+
│ └── tools/ # RBS extraction, LumiTrace prototype tools126+
├── Makefile # build, test, test-all127+
├── PLAN.md # Implementation roadmap & design docs128+
└── ruby_aot_compiler_design.md184129
```185130
186131
## Dependencies187132
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
## License193138