Skip to content

Commit ae50da6

Browse files
mameclaude
andcommitted
Prefer Ruby::Prism, the parser built into the interpreter
Ruby 4.1 will expose the prism parser built into the interpreter as Ruby::Prism, and the prism gem becomes a bundled gem (https://bugs.ruby-lang.org/issues/22379). Ruby::Prism is the very parser that compiled the code, so use it for spotting nodes; the prism gem is not needed and may not be available under bundler. On older Rubies keep using the prism gem as before. The constant-path checks use Node#type instead of class comparisons so that they work with nodes of either module. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent e7da36e commit ae50da6

1 file changed

Lines changed: 19 additions & 6 deletions

File tree

‎lib/error_highlight/base.rb‎

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def self.spot(obj, **opts)
5858

5959
Spotter.new(node, **opts).spot
6060

61-
when RubyVM::AbstractSyntaxTree::Node, Prism::Node
61+
when RubyVM::AbstractSyntaxTree::Node, prism::Node
6262
Spotter.new(obj, **opts).spot
6363

6464
else
@@ -93,18 +93,31 @@ def self.find_node_from_loc(loc)
9393
# Accepts a Thread::Backtrace::Location object and returns a Prism::Node
9494
# corresponding to the backtrace location in the source code.
9595
def self.prism_find(location)
96-
require "prism"
97-
return nil if Prism::VERSION < "1.0.0"
96+
return nil if prism::VERSION < "1.0.0"
9897

9998
absolute_path = location.absolute_path
10099
return unless absolute_path
101100

102101
node_id = RubyVM::AbstractSyntaxTree.node_id_for_backtrace_location(location)
103-
Prism.parse_file(absolute_path).value.breadth_first_search { |node| node.node_id == node_id }
102+
prism.parse_file(absolute_path).value.breadth_first_search { |node| node.node_id == node_id }
104103
end
105104

106105
private_class_method :prism_find
107106

107+
# Returns the prism module: Ruby::Prism, the parser built into the
108+
# interpreter (Ruby 4.1+), whose nodes always correspond to the compiled
109+
# code; or the prism gem on older Rubies.
110+
def self.prism
111+
if defined?(Ruby::Prism)
112+
Ruby::Prism
113+
else
114+
require "prism"
115+
::Prism
116+
end
117+
end
118+
119+
private_class_method :prism
120+
108121
class Spotter
109122
class NonAscii < Exception; end
110123
private_constant :NonAscii
@@ -167,9 +180,9 @@ def spot
167180

168181
begin
169182
subnodes << node if node.name == @name
170-
end while (node = node.parent).is_a?(Prism::ConstantPathNode)
183+
end while (node = node.parent)&.type == :constant_path_node
171184

172-
if node.is_a?(Prism::ConstantReadNode) && node.name == @name
185+
if node&.type == :constant_read_node && node.name == @name
173186
subnodes << node
174187
end
175188

0 commit comments

Comments
 (0)