Parsing Ruby code with Prism
suggest changePrism is a Ruby parser written in C, with a Ruby API, that turns Ruby source code into a syntax tree. It shipped with Ruby 3.3 as a default gem (you only need require "prism"), and since Ruby 3.4 it is the parser Ruby itself uses to compile your programs. RuboCop, Sorbet, ruby-lsp, IRB's type completion and syntax_suggest use it too.
Use Prism when you want to read Ruby code as data: find all method definitions, write a small linter, rewrite code automatically (a codemod), check syntax without running anything, or highlight source code.
Examples were run with Ruby 4.0, which bundles Prism 1.8:
require "prism"
p Prism::VERSION
p RUBY_DESCRIPTION
"1.8.1"
"ruby 4.0.7 (2026-09-15 revision 229531a6cf) +PRISM [x64-mingw-ucrt]"
The +PRISM in the version string says the interpreter compiles code with Prism.
Parsing a string
Prism.parse returns a Prism::ParseResult. Its value is the root of the tree, always a Prism::ProgramNode:
require "prism"
result = Prism.parse("total = price * 2 # double it")
p result.success?
p result.value.class
p result.comments
puts result.value.inspect
true
Prism::ProgramNode
[#<Prism::InlineComment @location=#<Prism::Location @start_offset=18 @length=11 start_line=1>>]
@ ProgramNode (location: (1,0)-(1,17))
├── flags: ∅
├── locals: [:total]
└── statements:
@ StatementsNode (location: (1,0)-(1,17))
├── flags: ∅
└── body: (length: 1)
└── @ LocalVariableWriteNode (location: (1,0)-(1,17))
├── flags: newline
├── name: :total
├── depth: 0
├── name_loc: (1,0)-(1,5) = "total"
├── value:
│ @ CallNode (location: (1,8)-(1,17))
│ ├── flags: ∅
│ ├── receiver:
│ │ @ CallNode (location: (1,8)-(1,13))
│ │ ├── flags: variable_call, ignore_visibility
│ │ ├── receiver: ∅
│ │ ├── call_operator_loc: ∅
│ │ ├── name: :price
│ │ ├── message_loc: (1,8)-(1,13) = "price"
│ │ ├── opening_loc: ∅
│ │ ├── arguments: ∅
│ │ ├── closing_loc: ∅
│ │ ├── equal_loc: ∅
│ │ └── block: ∅
│ ├── call_operator_loc: ∅
│ ├── name: :*
│ ├── message_loc: (1,14)-(1,15) = "*"
│ ├── opening_loc: ∅
│ ├── arguments:
│ │ @ ArgumentsNode (location: (1,16)-(1,17))
│ │ ├── flags: ∅
│ │ └── arguments: (length: 1)
│ │ └── @ IntegerNode (location: (1,16)-(1,17))
│ │ ├── flags: static_literal, decimal
│ │ └── value: 2
│ ├── closing_loc: ∅
│ ├── equal_loc: ∅
│ └── block: ∅
└── operator_loc: (1,6)-(1,7) = "="
inspect on a node prints the whole subtree, which is the quickest way to find out which node classes and fields you need. Some things to notice:
- Every node type is its own class:
LocalVariableWriteNode,CallNode,IntegerNode. Prism 1.8 has 151 of them. - Operators are method calls.
price * 2is aCallNodenamed:*withpriceas the receiver. pricealone is also aCallNode, flaggedvariable_call: Prism doesn't know a local variableprice, so it must be a method call with no arguments.- Comments are not nodes. They are collected in
result.comments.
Other entry points: Prism.parse_file(path) reads and parses a file, and Prism.parse_success?(source) only tells you whether the code is valid.
require "prism"
p Prism.parse_success?("def x; end")
p Prism.parse_success?("def x;")
true
false
You can see the same tree from the command line with ruby --dump=parsetree file.rb.
Navigating nodes
Each field from the inspect output is a method on the node:
require "prism"
program = Prism.parse("total = price * 2").value
assign = program.statements.body.first
p assign.class
p assign.name
p assign.type
call = assign.value
p call.name
p call.receiver.name
p call.arguments.arguments.first.value
p call.slice
p call.message_loc.slice
p assign.child_nodes.map(&:class)
Prism::LocalVariableWriteNode
:total
:local_variable_write_node
:*
:price
2
"price * 2"
"*"
[Prism::CallNode]
slice returns the exact source text of a node. child_nodes returns the direct children (with nil for empty fields), compact_child_nodes skips the nils and each_child_node yields them.
Nodes support pattern matching, which is the most readable way to check a shape that spans several nodes:
case assign
in Prism::LocalVariableWriteNode[name:, value: Prism::CallNode[name: :*]]
puts "#{name} = something times something"
end
total = something times something
To find the first node that matches a condition anywhere in a tree, use breadth_first_search:
p program.breadth_first_search { |n| n.is_a?(Prism::IntegerNode) }&.value
2
Walking the tree with Prism::Visitor
Usually you want every node of some kind, wherever it is. Subclass Prism::Visitor and define visit_<type> methods for the nodes you care about. The default implementation of each visit_* method visits the children, so call super to keep going deeper.
We'll use this file in the next examples:
# shop.rb
# Shopping cart helpers
class Cart
TAX = 0.2
def initialize
@items = []
end
# Adds an item to the cart
def add(name, price)
@items << [name, price]
puts "added #{name}"
self
end
def total
sum = @items.sum { |_, price| price }
sum + sum * TAX
end
def self.empty = new
end
A visitor that lists methods with their parameters and line numbers:
require "prism"
class MethodCollector < Prism::Visitor
attr_reader :methods
def initialize
@methods = []
@class_name = nil
end
def visit_class_node(node)
@class_name = node.constant_path.slice
super
end
def visit_def_node(node)
sep = node.receiver ? "." : "#"
params = node.parameters&.requireds&.map(&:name) || []
@methods << "#{@class_name}#{sep}#{node.name}(#{params.join(", ")}) line #{node.location.start_line}"
super
end
end
result = Prism.parse_file("shop.rb")
collector = MethodCollector.new
result.value.accept(collector)
puts collector.methods
Cart#initialize() line 5
Cart#add(name, price) line 10
Cart#total() line 16
Cart.empty() line 21
node.accept(visitor) starts the walk. def self.empty has a receiver (self), which is how you tell singleton methods apart. The endless def self.empty = new is a DefNode like any other.
Several listeners in one pass: Prism::Dispatcher
When several independent checks need the same tree, Prism::Dispatcher walks it once and calls on_<type>_enter / on_<type>_leave on every registered listener. Listeners are plain objects:
require "prism"
class MethodCounter
attr_reader :count
def initialize = @count = 0
def on_def_node_enter(node) = @count += 1
end
class ConstantLister
attr_reader :names
def initialize = @names = []
def on_constant_write_node_enter(node) = @names << node.name
end
methods = MethodCounter.new
constants = ConstantLister.new
dispatcher = Prism::Dispatcher.new
dispatcher.register(methods, :on_def_node_enter)
dispatcher.register(constants, :on_constant_write_node_enter)
dispatcher.dispatch(Prism.parse_file("shop.rb").value)
p methods.count
p constants.names
4
[:TAX]
ruby-lsp is built this way: each feature (hover, document symbols, folding ranges) is a listener on one shared dispatcher.
Locations and comments
Every node has a location (a Prism::Location), and many nodes have extra locations for their parts, like name_loc for the name of a method or message_loc for the method name in a call. Lines start at 1, columns at 0:
require "prism"
result = Prism.parse_file("shop.rb")
result.comments.each do |c|
puts "#{c.location.start_line}: #{c.slice} (#{c.class.name.split("::").last})"
end
result.attach_comments!
add = result.value.breadth_first_search { |n| n.is_a?(Prism::DefNode) && n.name == :add }
p add.location.leading_comments.map(&:slice)
loc = add.name_loc
p [loc.start_line, loc.start_column, loc.end_column]
p [loc.start_offset, loc.end_offset, loc.length]
p loc.slice
p add.location.end_line
p add.location.slice_lines.lines.first
1: # Shopping cart helpers (InlineComment)
9: # Adds an item to the cart (InlineComment)
["# Adds an item to the cart"]
[10, 6, 9]
[123, 126, 3]
"add"
14
" def add(name, price)\n"
By default comments are only in result.comments. attach_comments! assigns each comment to the nearest node as a leading or trailing comment, which is what you need to read documentation comments for a method. =begin/=end blocks are Prism::EmbDocComment; Prism.parse_comments(source) returns only the comments, which is faster than a full parse.
slice_lines returns the full lines a location covers, handy for printing context in error messages.
Offsets are in bytes
start_offset, end_offset and start_column count bytes, not characters. For ASCII it makes no difference; with other characters it does:
require "prism"
node = Prism.parse('"Zoë"; total').value.statements.body.last
p node.slice
p [node.start_offset, node.start_column]
p [node.start_character_offset, node.start_character_column]
"total"
[8, 8]
[7, 7]
ë takes 2 bytes in UTF-8. Use the byte offsets to slice or edit the source as a binary string (see the codemod below), and the *_character_* variants when you show a column to a human. There are also *_code_units_* variants for editors that count UTF-16 code units, as LSP does.
Tokens with Prism.lex
Prism.lex returns the tokens instead of a tree. Each element is a pair of a Prism::Token and the lexer state:
require "prism"
tokens = Prism.lex('puts "hi #{name}" if ok').value
tokens.each do |token, _lex_state|
printf "%-22s %-10p %s\n", token.type, token.value, token.location.start_column
end
IDENTIFIER "puts" 0
STRING_BEGIN "\"" 5
STRING_CONTENT "hi " 6
EMBEXPR_BEGIN "\#{" 9
IDENTIFIER "name" 11
EMBEXPR_END "}" 15
STRING_END "\"" 16
KEYWORD_IF_MODIFIER "if" 18
IDENTIFIER "ok" 21
EOF "" 23
Tokens are what you want for syntax highlighting: the lexer knows that if here is a modifier and that #{ starts interpolation. Prism.lex_compat returns tokens in the same format as Ripper.lex, to ease porting Ripper-based code.
Error-tolerant parsing
Prism doesn't stop at the first syntax error. It reports all the errors it finds and still builds a tree, inserting "missing" nodes where needed. This is what editors need: the file you are typing is invalid most of the time, but you still want an outline and completion.
require "prism"
source = <<~RUBY
class Report
def title
"Sales"
end
def total(rows
rows.sum
end
def rows = [1, 2, 3]
end
RUBY
result = Prism.parse(source)
p result.success?
result.errors.each do |e|
puts "line #{e.location.start_line}:#{e.location.start_column} #{e.type}: #{e.message}"
end
names = []
result.value.breadth_first_search { |n| names << n.name if n.is_a?(Prism::DefNode); false }
p names
false
line 7:4 def_params_term_paren: unexpected local variable or method; expected a `)` to close the parameters
[:title, :total, :rows]
Despite the missing ), all three methods are in the tree. (The block returns false so breadth_first_search keeps going through the whole tree.) e.type is a stable symbol you can match on; e.message is for humans. result.warnings has warnings, such as unused variables, in the same form.
errors_format renders errors the way Ruby shows them:
require "prism"
result = Prism.parse("def total(rows\n rows.sum\nend\n")
puts result.errors_format
def total(rows
rows.sum
^~~~ unexpected local variable or method; expected a `)` to close the parameters
end
Parsing for a specific Ruby version or scope
Prism can parse code as an older Ruby would. In Ruby 3.4 a bare it inside a block became the implicit block parameter; with version: "3.3" it is a method call:
require "prism"
src = "[1, 2].map { it * 2 }"
p Prism.parse(src, version: "3.3").value.statements.body.first.block.body.body.first.receiver.class
p Prism.parse(src, version: "3.4").value.statements.body.first.block.body.body.first.receiver.class
Prism::CallNode
Prism::ItLocalVariableReadNode
When you parse a snippet that will run inside an existing scope (as eval does, see Evaluating a String), pass the local variables that already exist with scopes:, otherwise foo is parsed as a method call:
p Prism.parse("foo", scopes: [[:foo]]).value.statements.body.first.class
p Prism.parse("foo").value.statements.body.first.class
Prism::LocalVariableReadNode
Prism::CallNode
A tiny linter
Let's find debugging leftovers: p, pp, puts and print called without a receiver, and binding.irb. The code to check:
# app.rb
def checkout(cart, user)
p cart
return if cart.items.length == 0
binding.irb if user.admin?
logger.puts "checkout #{user.id}"
pp user unless cart.items.size == 0
charge(user, cart.total)
end
The linter:
# lint.rb
require "prism"
class DebugCallLinter < Prism::Visitor
DEBUG_METHODS = %i[p pp puts print].freeze
Offense = Struct.new(:line, :column, :message)
attr_reader :offenses
def initialize
@offenses = []
end
def visit_call_node(node)
if node.receiver.nil? && DEBUG_METHODS.include?(node.name)
add(node, "remove debug call `#{node.name}`")
elsif node.name == :irb && (node.receiver in Prism::CallNode[name: :binding])
add(node, "remove `binding.irb`")
end
super
end
private
def add(node, message)
@offenses << Offense.new(node.start_line, node.start_column + 1, message)
end
end
ARGV.each do |path|
result = Prism.parse_file(path)
unless result.success?
result.errors.each { |e| puts "#{path}:#{e.location.start_line}: syntax error: #{e.message}" }
next
end
linter = DebugCallLinter.new
result.value.accept(linter)
linter.offenses.each { |o| puts "#{path}:#{o.line}:#{o.column}: #{o.message}" }
end
$ echo 'x = 1 +' > bad.rb
$ ruby lint.rb app.rb bad.rb
app.rb:2:3: remove debug call `p`
app.rb:4:3: remove `binding.irb`
app.rb:6:3: remove debug call `pp`
bad.rb:1: syntax error: unexpected end-of-input; expected an expression after the operator
bad.rb:1: syntax error: unexpected end-of-input, assuming it is closing the parent top level context
logger.puts has a receiver, so it's not reported. This is the advantage over a regular expression: the parser knows the difference between puts the method call, puts inside a string and a local variable called p. We add 1 to the column because editors count columns from 1.
A tiny codemod
A codemod rewrites source code. The safe approach with Prism is to never regenerate code from the tree: find the nodes to change, record their byte ranges, and replace only those ranges in the original source. Everything else (formatting, comments) stays exactly as it was.
This one rewrites x.length == 0 and x.size == 0 to x.empty?:
# codemod.rb
require "prism"
class EmptyCheckRewriter < Prism::Visitor
attr_reader :edits
def initialize
@edits = []
end
def visit_call_node(node)
case node
in Prism::CallNode[
name: :==,
receiver: Prism::CallNode[name: :length | :size, receiver: Prism::Node => collection, arguments: nil],
arguments: Prism::ArgumentsNode[arguments: [Prism::IntegerNode[value: 0]]]
]
@edits << [node.start_offset, node.end_offset, "#{collection.slice}.empty?"]
else
super
end
end
end
def rewrite(source)
result = Prism.parse(source)
raise "cannot rewrite code with syntax errors" if result.failure?
rewriter = EmptyCheckRewriter.new
result.value.accept(rewriter)
output = source.b
rewriter.edits.sort_by(&:first).reverse_each do |from, to, text|
output[from...to] = text.b
end
output.force_encoding(source.encoding)
end
puts rewrite(File.read(ARGV.fetch(0)))
$ ruby codemod.rb app.rb
def checkout(cart, user)
p cart
return if cart.items.empty?
binding.irb if user.admin?
logger.puts "checkout #{user.id}"
pp user unless cart.items.empty?
charge(user, cart.total)
end
Details that matter:
receiver: Prism::Node => collectionrequires a receiver, so a barelength == 0(callingself.length) is left alone, and binds it so we can reuse its source withslice.arguments: nilskipsx.size(1) == 0.- Edits are applied from the end of the file backwards, so earlier offsets stay valid.
- Offsets are byte offsets, so we edit a binary copy (
source.b) and restore the encoding at the end. This works with non-ASCII source too. - We don't call
superafter a match, so nested matches inside the matched expression aren't recorded twice.
Prism, parse.y, Ripper and RubyVM::AbstractSyntaxTree
Before Prism, Ruby's parser was parse.y, a Bison grammar. It is still in the source tree, and you can switch back to it if you hit a Prism bug:
$ ruby --parser=parse.y -e 'p RUBY_DESCRIPTION'
"ruby 4.0.7 (2026-09-15 revision 229531a6cf) [x64-mingw-ucrt]"
(+PRISM is gone.) In Ruby 3.3, where parse.y was the default, --parser=prism was the opt-in.
Two older standard library APIs give you a syntax tree, and both still use parse.y no matter which parser runs your program:
require "ripper"
require "prism"
src = "total = price * 2"
pp RubyVM::AbstractSyntaxTree.parse(src)
pp Ripper.sexp(src)
pp Prism::Translation::Ripper.sexp(src)
(SCOPE@1:0-1:17
tbl: [:total]
args: nil
body:
(LASGN@1:0-1:17 :total
(OPCALL@1:8-1:17 (VCALL@1:8-1:13 :price) :*
(LIST@1:16-1:17 (INTEGER@1:16-1:17 2) nil))))
[:program,
[[:assign,
[:var_field, [:@ident, "total", [1, 0]]],
[:binary,
[:vcall, [:@ident, "price", [1, 8]]],
:*,
[:@int, "2", [1, 16]]]]]]
[:program,
[[:assign,
[:var_field, [:@ident, "total", [1, 0]]],
[:binary,
[:vcall, [:@ident, "price", [1, 8]]],
:*,
[:@int, "2", [1, 16]]]]]]
RubyVM::AbstractSyntaxTreeexposes CRuby's internal parse.y nodes. It is CRuby-only, its node types change between versions, and it can't map Prism-compiled code back to a tree:RubyVM::AbstractSyntaxTree.of(method(:foo))raisesRuntimeError: cannot get AST for ISEQ compiled by prismunder the default parser.Ripperis an event-based parser on top of parse.y that produces S-expressions made of nested arrays. Many older tools were built on it. Its trees are hard to work with: no classes, positions only on tokens.Prism::Translation::Ripperis a drop-in replacement forRipperbuilt on Prism, as the identical output above shows. Prism also hasPrism::Translation::Parser, which produces the AST of theparsergem so tools like RuboCop could switch without rewriting their rules (it needs theparsergem installed).
For new code use the Prism API directly: it's the same parser that compiles your program, it works the same way on CRuby, JRuby and TruffleRuby, and its node classes are documented and stable across Ruby versions.
To get from a method to its node, parse the file it came from and search for a DefNode on the right line:
require "prism"
def double(x) = x * 2
def node_for(meth)
file, line = meth.source_location
Prism.parse_file(file).value.breadth_first_search do |n|
n.is_a?(Prism::DefNode) && n.name == meth.name && n.start_line == line
end
end
p node_for(method(:double)).slice
"def double(x) = x * 2"
For more on inspecting live objects instead of source code, see Introspection and Metaprogramming.