go-ruby-prism
go-ruby-prism is a Go library that leverages the Ruby Prism parser compiled to WebAssembly, enabling Ruby code parsing and analysis without the need for CGO bindings. This solution provides native and efficient integration for Ruby code analysis in Go applications.
Table of Contents
Features
- ๐ CGO-Free: Uses the Ruby Prism parser compiled to WebAssembly, completely eliminating the need for CGO bindings
- โก High Performance: Leverages WebAssembly efficiency for fast and efficient Ruby code parsing
- ๐ Simplified Integration: Seamless integration into Go applications with minimal configuration
- ๐ Cross-Platform: Works on any platform supported by Go, ensuring universal compatibility
- ๐ฏ Flexible API: Offers multiple ways to work with the generated AST (Abstract Syntax Tree)
- ๐ Complete Ruby Support: Compatible with Ruby versions 3.3 and 3.4
- ๐ ๏ธ Advanced Configuration: Support for encoding, scopes, frozen string literals, and other Ruby options
Installation
Prerequisites
Installation via go get
go get github.com/danielgatis/go-ruby-prism
Manual installation
git clone https://github.com/danielgatis/go-ruby-prism.git
cd go-ruby-prism
make all
Rebuilding from prism
prism.wasm and the generated parser sources are committed, so using the
library needs nothing beyond Go. Rebuilding them is only necessary when the
prism submodule moves:
make wasm_build # compiles prism.wasm in Docker; needs Docker, not Ruby
make config # copies config.yml out of the submodule
make generate # regenerates the parser sources with the Go generator
Code generation reads prism's config.yml directly, so neither Ruby nor the
WASI SDK has to be installed. go generate ./... runs the same generator.
Quick Start
Basic Example
package main
import (
"context"
"fmt"
"log"
parser "github.com/danielgatis/go-ruby-prism/parser"
)
func main() {
ctx := context.Background()
// Create a new parser instance
p, err := parser.NewParser(ctx)
if err != nil {
log.Fatal(err)
}
defer p.Close(ctx)
// Ruby code to analyze
source := "puts 'Hello, World!'"
// Parse the code
result, err := p.Parse(ctx, []byte(source))
if err != nil {
log.Fatal(err)
}
fmt.Printf("AST Root: %T\n", result.Value)
fmt.Printf("Errors: %d\n", len(result.Errors))
fmt.Printf("Warnings: %d\n", len(result.Warnings))
}
Detailed Examples
1. Converting AST to JSON
package main
import (
"context"
"encoding/json"
"fmt"
"log"
parser "github.com/danielgatis/go-ruby-prism/parser"
)
func main() {
ctx := context.Background()
p, err := parser.NewParser(ctx)
if err != nil {
log.Fatal(err)
}
defer p.Close(ctx)
source := `
class User
attr_reader :name, :email
def initialize(name, email)
@name = name
@email = email
end
def greet
puts "Hello, #{@name}!"
end
end
`
result, err := p.Parse(ctx, []byte(source))
if err != nil {
log.Fatal(err)
}
// Convert to JSON
jsonResult, err := json.MarshalIndent(result, "", " ")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(jsonResult))
}
2. Using the Visitor Pattern
package main
import (
"context"
"fmt"
"log"
"github.com/danielgatis/go-ruby-prism/parser"
)
type CodeAnalyzer struct {
parser.DefaultVisitor
methodCount int
classCount int
}
func (v *CodeAnalyzer) Visit(node parser.Node) {
switch node.(type) {
case *parser.DefNode:
v.methodCount++
fmt.Printf("๐ Found method at line %d\n", node.StartLine())
case *parser.ClassNode:
v.classCount++
fmt.Printf("๐ Found class at line %d\n", node.StartLine())
}
v.DefaultVisitor.Visit(node)
}
func (v *CodeAnalyzer) Analyze(node parser.Node) {
for _, child := range node.ChildNodes() {
v.Visit(child)
if len(child.ChildNodes()) > 0 {
v.Analyze(child)
}
}
}
func main() {
ctx := context.Background()
p, err := parser.NewParser(ctx)
if err != nil {
log.Fatal(err)
}
defer p.Close(ctx)
source := `
class Calculator
def add(a, b)
a + b
end
def multiply(a, b)
a * b
end
end
class MathUtils
def self.pi
3.14159
end
end
`
result, err := p.Parse(ctx, []byte(source))
if err != nil {
log.Fatal(err)
}
analyzer := &CodeAnalyzer{}
analyzer.Analyze(result.Value)
fmt.Printf("\n๐ Analysis complete:\n")
fmt.Printf(" Classes found: %d\n", analyzer.classCount)
fmt.Printf(" Methods found: %d\n", analyzer.methodCount)
}
3. Rails Application Analysis
The project includes a complete example that downloads and analyzes the entire Rails codebase:
go run example/parse_rails/main.go
This example demonstrates:
- Automatic Rails source code download
- Parsing thousands of Ruby files
API Reference
Parser
NewParser(ctx context.Context, options ...ParserOption) (*Parser, error)
Creates a new parser instance with the specified options.
Parse(ctx context.Context, source []byte) (*ParseResult, error)
Parses the provided Ruby code and returns the resulting AST.
A single parser can be reused for any number of Parse calls, including across
different files, and this is the recommended way to process a batch of sources โ
creating a parser instantiates the WebAssembly module, which costs far more than
a parse.
Parse is safe to call from multiple goroutines. A parser holds a pool of
WebAssembly instances and each call runs on its own instance, so parses proceed
in parallel rather than queueing behind one another. The pool is filled on
demand, so a program that only ever parses one file at a time pays for a single
instance.
WithPoolSize(size int) ParserOption
Sets how many instances the pool may hold, which caps how many parses can run
at once. It defaults to GOMAXPROCS. Each instance carries its own linear
memory, so a larger pool trades memory for concurrency; a size of 1 serializes
every parse onto one instance.
Close(ctx context.Context) error
Releases WebAssembly runtime resources. Should always be called when the parser is no longer needed.
Configuration Options
// Configure source file
parser.WithFilePath("app/models/user.rb")
// Configure starting line
parser.WithLine(10)
// Configure encoding
parser.WithEncoding("UTF-8")
// Enable frozen string literals
parser.WithFrozenStringLiteral(true)
// Configure Ruby version
parser.WithVersion(parser.SyntaxVersionV3_4)
// Configure as main script
parser.WithMainScript(true)
// Configure local variable scopes
parser.WithScopes([][][]byte{{[]byte("local_var")}})
// Configure how many parses can run at once (defaults to GOMAXPROCS)
parser.WithPoolSize(16)
// Configure custom logger
parser.WithLogger(customLogger)
ParseResult
The ParseResult structure contains:
type ParseResult struct {
Value Node // Root AST node
Errors []Error // Parsing errors
Warnings []Warning // Parser warnings
Source []byte // Original source code
}
Supported Syntax Versions
const (
SyntaxVersionLatest SyntaxVersion = iota // Latest version
SyntaxVersionV3_3 // Ruby 3.3
SyntaxVersionV3_4 // Ruby 3.4
)
Advanced Configuration
Custom Logging
type CustomLogger struct{}
func (l *CustomLogger) Debug(format string, args ...interface{}) {
log.Printf("[DEBUG] "+format, args...)
}
// Use custom logger
p, err := parser.NewParser(ctx, parser.WithLogger(&CustomLogger{}))
Rails Code Configuration
p, err := parser.NewParser(ctx,
parser.WithMainScript(true),
parser.WithVersion(parser.SyntaxVersionV3_4),
parser.WithFrozenStringLiteral(true),
parser.WithEncoding("UTF-8"),
)
Parsing with File Context
p, err := parser.NewParser(ctx,
parser.WithFilePath("app/controllers/users_controller.rb"),
parser.WithLine(1),
parser.WithMainScript(true),
)
Project Structure
go-ruby-prism/
โโโ example/ # Usage examples
โ โโโ json/ # JSON conversion
โ โโโ parse_rails/ # Rails application analysis
โ โโโ visitor/ # Visitor pattern
โโโ parser/ # Main parser API
โ โโโ parser.go # Main interface
โ โโโ gen_nodes.go # Generated AST nodes
โ โโโ gen_visitor.go # Generated visitor pattern
โ โโโ parsing_options.go # Configuration options
โโโ prism/ # Ruby Prism submodule
โโโ wasm/ # WebAssembly runtime
โโโ templates/ # Code generation templates
Build and Development
Available Make Commands
# Complete build (recommended for first time)
make all
# Generate Go code only
make generate
# Build WASM only
make wasm_build
# Format code
make format
# Clean temporary files
make clean
Development Dependencies
- Ruby with Bundler (for Prism build)
- WASI SDK (downloaded automatically)
- Go 1.23+
Build Process
- Initialization:
git submodule update --init --recursive
- Prism Compilation: Compiles Ruby parser to WebAssembly
- Code Generation: Generates Go structs from Prism schema
- Formatting: Applies
go fmt to all files
Optimizations
- Parser pools for concurrent usage
- Instance reuse when possible
- Automatic WebAssembly memory management
Parser Pool Example
type ParserPool struct {
parsers chan *parser.Parser
ctx context.Context
}
func NewParserPool(ctx context.Context, size int) *ParserPool {
pool := &ParserPool{
parsers: make(chan *parser.Parser, size),
ctx: ctx,
}
for i := 0; i < size; i++ {
p, _ := parser.NewParser(ctx)
pool.parsers <- p
}
return pool
}
func (p *ParserPool) Parse(source []byte) (*parser.ParseResult, error) {
parser := <-p.parsers
defer func() { p.parsers <- parser }()
return parser.Parse(p.ctx, source)
}
Practical Examples
All examples are available in the /example directory:
- JSON Export (
example/json/): Converts AST to JSON format
- Visitor Pattern (
example/visitor/): Demonstrates custom AST traversal
- Rails Analysis (
example/parse_rails/): Complete Rails application analysis
To run any example:
go run example/[example-name]/main.go
Development
# Set up development environment
git clone https://github.com/danielgatis/go-ruby-prism.git
cd go-ruby-prism
make all
# Run tests
go test ./...
# Check linting
golangci-lint run
License
Copyright (c) 2024-present Daniel Gatis
Licensed under MIT License