Debian Codegraph @

lib/prism/pattern.rb

raw symbols SCIP
1 # frozen_string_literal: true
2 # :markup: markdown
3
4 module Prism
5 # A pattern is an object that wraps a Ruby pattern matching expression. The
6 # expression would normally be passed to an `in` clause within a `case`
7 # expression or a rightward assignment expression. For example, in the
8 # following snippet:
9 #
10 # case node
11 # in ConstantPathNode[ConstantReadNode[name: :Prism], ConstantReadNode[name: :Pattern]]
12 # end
13 #
14 # the pattern is the <tt>ConstantPathNode[...]</tt> expression.
15 #
16 # The pattern gets compiled into an object that responds to #call by running
17 # the #compile method. This method itself will run back through Prism to
18 # parse the expression into a tree, then walk the tree to generate the
19 # necessary callable objects. For example, if you wanted to compile the
20 # expression above into a callable, you would:
21 #
22 # callable = Prism::Pattern.new("ConstantPathNode[ConstantReadNode[name: :Prism], ConstantReadNode[name: :Pattern]]").compile
23 # callable.call(node)
24 #
25 # The callable object returned by #compile is guaranteed to respond to #call
26 # with a single argument, which is the node to match against. It also is
27 # guaranteed to respond to #===, which means it itself can be used in a `case`
28 # expression, as in:
29 #
30 # case node
31 # when callable
32 # end
33 #
34 # If the query given to the initializer cannot be compiled into a valid
35 # matcher (either because of a syntax error or because it is using syntax we
36 # do not yet support) then a Prism::Pattern::CompilationError will be
37 # raised.
38 class Pattern
39 # Raised when the query given to a pattern is either invalid Ruby syntax or
40 # is using syntax that we don't yet support.
41 class CompilationError < StandardError
42 # Create a new CompilationError with the given representation of the node
43 # that caused the error.
44 def initialize(repr)
45 super(<<~ERROR)
46 prism was unable to compile the pattern you provided into a usable
47 expression. It failed on to understand the node represented by:
48
49 #{repr}
50
51 Note that not all syntax supported by Ruby's pattern matching syntax
52 is also supported by prism's patterns. If you're using some syntax
53 that you believe should be supported, please open an issue on
54 GitHub at https://github.com/ruby/prism/issues/new.
55 ERROR
56 end
57 end
58
59 # The query that this pattern was initialized with.
60 attr_reader :query
61
62 # Create a new pattern with the given query. The query should be a string
63 # containing a Ruby pattern matching expression.
64 def initialize(query)
65 @query = query
66 @compiled = nil
67 end
68
69 # Compile the query into a callable object that can be used to match against
70 # nodes.
71 def compile
72 result = Prism.parse("case nil\nin #{query}\nend")
73
74 case_match_node = result.value.statements.body.last
75 raise CompilationError, case_match_node.inspect unless case_match_node.is_a?(CaseMatchNode)
76
77 in_node = case_match_node.conditions.last
78 raise CompilationError, in_node.inspect unless in_node.is_a?(InNode)
79
80 compile_node(in_node.pattern)
81 end
82
83 # Scan the given node and all of its children for nodes that match the
84 # pattern. If a block is given, it will be called with each node that
85 # matches the pattern. If no block is given, an enumerator will be returned
86 # that will yield each node that matches the pattern.
87 def scan(root)
88 return to_enum(:scan, root) unless block_given?
89
90 @compiled ||= compile
91 queue = [root]
92
93 while (node = queue.shift)
94 yield node if @compiled.call(node) # steep:ignore
95 queue.concat(node.compact_child_nodes)
96 end
97 end
98
99 private
100
101 # Shortcut for combining two procs into one that returns true if both return
102 # true.
103 def combine_and(left, right)
104 ->(other) { left.call(other) && right.call(other) }
105 end
106
107 # Shortcut for combining two procs into one that returns true if either
108 # returns true.
109 def combine_or(left, right)
110 ->(other) { left.call(other) || right.call(other) }
111 end
112
113 # Raise an error because the given node is not supported.
114 def compile_error(node)
115 raise CompilationError, node.inspect
116 end
117
118 # in [foo, bar, baz]
119 def compile_array_pattern_node(node)
120 compile_error(node) if !node.rest.nil? || node.posts.any?
121
122 constant = node.constant
123 compiled_constant = compile_node(constant) if constant
124
125 preprocessed = node.requireds.map { |required| compile_node(required) }
126
127 compiled_requireds = ->(other) do
128 deconstructed = other.deconstruct
129
130 deconstructed.length == preprocessed.length &&
131 preprocessed
132 .zip(deconstructed)
133 .all? { |(matcher, value)| matcher.call(value) }
134 end
135
136 if compiled_constant
137 combine_and(compiled_constant, compiled_requireds)
138 else
139 compiled_requireds
140 end
141 end
142
143 # in foo | bar
144 def compile_alternation_pattern_node(node)
145 combine_or(compile_node(node.left), compile_node(node.right))
146 end
147
148 # in Prism::ConstantReadNode
149 def compile_constant_path_node(node)
150 parent = node.parent
151
152 if parent.is_a?(ConstantReadNode) && parent.slice == "Prism"
153 name = node.name
154 raise CompilationError, node.inspect if name.nil?
155
156 compile_constant_name(node, name)
157 else
158 compile_error(node)
159 end
160 end
161
162 # in ConstantReadNode
163 # in String
164 def compile_constant_read_node(node)
165 compile_constant_name(node, node.name)
166 end
167
168 # Compile a name associated with a constant.
169 def compile_constant_name(node, name)
170 if Prism.const_defined?(name, false)
171 clazz = Prism.const_get(name)
172
173 ->(other) { clazz === other }
174 elsif Object.const_defined?(name, false)
175 clazz = Object.const_get(name)
176
177 ->(other) { clazz === other }
178 else
179 compile_error(node)
180 end
181 end
182
183 # in InstanceVariableReadNode[name: Symbol]
184 # in { name: Symbol }
185 def compile_hash_pattern_node(node)
186 compile_error(node) if node.rest
187 compiled_constant = compile_node(node.constant) if node.constant
188
189 preprocessed =
190 node.elements.to_h do |element|
191 key = element.key
192 if key.is_a?(SymbolNode)
193 [key.unescaped.to_sym, compile_node(element.value)]
194 else
195 raise CompilationError, element.inspect
196 end
197 end
198
199 compiled_keywords = ->(other) do
200 deconstructed = other.deconstruct_keys(preprocessed.keys)
201
202 preprocessed.all? do |keyword, matcher|
203 deconstructed.key?(keyword) && matcher.call(deconstructed[keyword])
204 end
205 end
206
207 if compiled_constant
208 combine_and(compiled_constant, compiled_keywords)
209 else
210 compiled_keywords
211 end
212 end
213
214 # in nil
215 def compile_nil_node(node)
216 ->(attribute) { attribute.nil? }
217 end
218
219 # in /foo/
220 def compile_regular_expression_node(node)
221 regexp = Regexp.new(node.unescaped, node.closing[1..])
222
223 ->(attribute) { regexp === attribute }
224 end
225
226 # in ""
227 # in "foo"
228 def compile_string_node(node)
229 string = node.unescaped
230
231 ->(attribute) { string === attribute }
232 end
233
234 # in :+
235 # in :foo
236 def compile_symbol_node(node)
237 symbol = node.unescaped.to_sym
238
239 ->(attribute) { symbol === attribute }
240 end
241
242 # Compile any kind of node. Dispatch out to the individual compilation
243 # methods based on the type of node.
244 def compile_node(node)
245 case node
246 when AlternationPatternNode
247 compile_alternation_pattern_node(node)
248 when ArrayPatternNode
249 compile_array_pattern_node(node)
250 when ConstantPathNode
251 compile_constant_path_node(node)
252 when ConstantReadNode
253 compile_constant_read_node(node)
254 when HashPatternNode
255 compile_hash_pattern_node(node)
256 when NilNode
257 compile_nil_node(node)
258 when RegularExpressionNode
259 compile_regular_expression_node(node)
260 when StringNode
261 compile_string_node(node)
262 when SymbolNode
263 compile_symbol_node(node)
264 else
265 compile_error(node)
266 end
267 end
268 end
269 end