Debian Codegraph @

lib/prism/translation/parser.rb

raw symbols SCIP
1 # frozen_string_literal: true
2 # :markup: markdown
3
4 begin
5 required_version = ">= 3.3.7.2"
6 gem "parser", required_version
7 require "parser"
8 rescue LoadError
9 warn(<<~MSG)
10 Error: Unable to load parser #{required_version}. \
11 Add `gem "parser"` to your Gemfile or run `bundle update parser`.
12 MSG
13 exit(1)
14 end
15
16 module Prism
17 module Translation
18 # This class is the entry-point for converting a prism syntax tree into the
19 # whitequark/parser gem's syntax tree. It inherits from the base parser for
20 # the parser gem, and overrides the parse* methods to parse with prism and
21 # then translate.
22 #
23 # Note that this version of the parser always parses using the latest
24 # version of Ruby syntax supported by Prism. If you want specific version
25 # support, use one of the version-specific subclasses, such as
26 # `Prism::Translation::Parser34`. If you want to parse using the same
27 # version of Ruby syntax as the currently running version of Ruby, use
28 # `Prism::Translation::ParserCurrent`.
29 class Parser < ::Parser::Base
30 Diagnostic = ::Parser::Diagnostic # :nodoc:
31 private_constant :Diagnostic
32
33 # The parser gem has a list of diagnostics with a hard-coded set of error
34 # messages. We create our own diagnostic class in order to set our own
35 # error messages.
36 class PrismDiagnostic < Diagnostic
37 # This is the cached message coming from prism.
38 attr_reader :message
39
40 # Initialize a new diagnostic with the given message and location.
41 def initialize(message, level, reason, location)
42 @message = message
43 super(level, reason, {}, location, [])
44 end
45 end
46
47 Racc_debug_parser = false # :nodoc:
48
49 # The `builder` argument is used to create the parser using our custom builder class by default.
50 #
51 # By using the `:parser` keyword argument, you can translate in a way that is compatible with
52 # the Parser gem using any parser.
53 #
54 # For example, in RuboCop for Ruby LSP, the following approach can be used to improve performance
55 # by reusing a pre-parsed `Prism::ParseLexResult`:
56 #
57 # class PrismPreparsed
58 # def initialize(prism_result)
59 # @prism_result = prism_result
60 # end
61 #
62 # def parse_lex(source, **options)
63 # @prism_result
64 # end
65 # end
66 #
67 # prism_preparsed = PrismPreparsed.new(prism_result)
68 #
69 # Prism::Translation::Ruby34.new(builder, parser: prism_preparsed)
70 #
71 # In an object passed to the `:parser` keyword argument, the `parse` and `parse_lex` methods
72 # should be implemented as needed.
73 #
74 def initialize(builder = Prism::Translation::Parser::Builder.new, parser: Prism)
75 if !builder.is_a?(Prism::Translation::Parser::Builder)
76 warn(<<~MSG, uplevel: 1, category: :deprecated)
77 [deprecation]: The builder passed to `Prism::Translation::Parser.new` is not a \
78 `Prism::Translation::Parser::Builder` subclass. This will raise in the next major version.
79 MSG
80 end
81 @parser = parser
82
83 super(builder)
84 end
85
86 def version # :nodoc:
87 41
88 end
89
90 # The default encoding for Ruby files is UTF-8.
91 def default_encoding
92 Encoding::UTF_8
93 end
94
95 def yyerror # :nodoc:
96 end
97
98 # Parses a source buffer and returns the AST.
99 def parse(source_buffer)
100 @source_buffer = source_buffer
101 source = source_buffer.source
102
103 offset_cache = build_offset_cache(source)
104 result = unwrap(@parser.parse(source, **prism_options), offset_cache)
105
106 build_ast(result.value, offset_cache)
107 ensure
108 @source_buffer = nil
109 end
110
111 # Parses a source buffer and returns the AST and the source code comments.
112 def parse_with_comments(source_buffer)
113 @source_buffer = source_buffer
114 source = source_buffer.source
115
116 offset_cache = build_offset_cache(source)
117 result = unwrap(@parser.parse(source, **prism_options), offset_cache)
118
119 [
120 build_ast(result.value, offset_cache),
121 build_comments(result.comments, offset_cache)
122 ]
123 ensure
124 @source_buffer = nil
125 end
126
127 # Parses a source buffer and returns the AST, the source code comments,
128 # and the tokens emitted by the lexer.
129 def tokenize(source_buffer, recover = false)
130 @source_buffer = source_buffer
131 source = source_buffer.source
132
133 offset_cache = build_offset_cache(source)
134 result =
135 begin
136 unwrap(@parser.parse_lex(source, **prism_options), offset_cache)
137 rescue ::Parser::SyntaxError
138 raise if !recover
139 end
140
141 program, tokens = result.value
142 ast = build_ast(program, offset_cache) if result.success?
143
144 [
145 ast,
146 build_comments(result.comments, offset_cache),
147 build_tokens(tokens, offset_cache)
148 ]
149 ensure
150 @source_buffer = nil
151 end
152
153 # Since prism resolves num params for us, we don't need to support this
154 # kind of logic here.
155 def try_declare_numparam(node)
156 node.children[0].match?(/\A_[1-9]\z/)
157 end
158
159 private
160
161 # This is a hook to allow consumers to disable some errors if they don't
162 # want them to block creating the syntax tree.
163 def valid_error?(error)
164 true
165 end
166
167 # This is a hook to allow consumers to disable some warnings if they don't
168 # want them to block creating the syntax tree.
169 def valid_warning?(warning)
170 true
171 end
172
173 # Build a diagnostic from the given prism parse error.
174 def error_diagnostic(error, offset_cache)
175 location = error.location
176 diagnostic_location = build_range(location, offset_cache)
177
178 case error.type
179 when :argument_block_multi
180 Diagnostic.new(:error, :block_and_blockarg, {}, diagnostic_location, [])
181 when :argument_formal_constant
182 Diagnostic.new(:error, :argument_const, {}, diagnostic_location, [])
183 when :argument_formal_class
184 Diagnostic.new(:error, :argument_cvar, {}, diagnostic_location, [])
185 when :argument_formal_global
186 Diagnostic.new(:error, :argument_gvar, {}, diagnostic_location, [])
187 when :argument_formal_ivar
188 Diagnostic.new(:error, :argument_ivar, {}, diagnostic_location, [])
189 when :argument_no_forwarding_amp
190 Diagnostic.new(:error, :no_anonymous_blockarg, {}, diagnostic_location, [])
191 when :argument_no_forwarding_star
192 Diagnostic.new(:error, :no_anonymous_restarg, {}, diagnostic_location, [])
193 when :argument_no_forwarding_star_star
194 Diagnostic.new(:error, :no_anonymous_kwrestarg, {}, diagnostic_location, [])
195 when :begin_lonely_else
196 location = location.copy(length: 4)
197 diagnostic_location = build_range(location, offset_cache)
198 Diagnostic.new(:error, :useless_else, {}, diagnostic_location, [])
199 when :class_name, :module_name
200 Diagnostic.new(:error, :module_name_const, {}, diagnostic_location, [])
201 when :class_in_method
202 Diagnostic.new(:error, :class_in_def, {}, diagnostic_location, [])
203 when :def_endless_setter
204 Diagnostic.new(:error, :endless_setter, {}, diagnostic_location, [])
205 when :embdoc_term
206 Diagnostic.new(:error, :embedded_document, {}, diagnostic_location, [])
207 when :incomplete_variable_class, :incomplete_variable_class_3_3
208 location = location.copy(length: location.length + 1)
209 diagnostic_location = build_range(location, offset_cache)
210
211 Diagnostic.new(:error, :cvar_name, { name: location.slice }, diagnostic_location, [])
212 when :incomplete_variable_instance, :incomplete_variable_instance_3_3
213 location = location.copy(length: location.length + 1)
214 diagnostic_location = build_range(location, offset_cache)
215
216 Diagnostic.new(:error, :ivar_name, { name: location.slice }, diagnostic_location, [])
217 when :invalid_variable_global, :invalid_variable_global_3_3
218 Diagnostic.new(:error, :gvar_name, { name: location.slice }, diagnostic_location, [])
219 when :module_in_method
220 Diagnostic.new(:error, :module_in_def, {}, diagnostic_location, [])
221 when :numbered_parameter_ordinary
222 Diagnostic.new(:error, :ordinary_param_defined, {}, diagnostic_location, [])
223 when :numbered_parameter_outer_scope
224 Diagnostic.new(:error, :numparam_used_in_outer_scope, {}, diagnostic_location, [])
225 when :parameter_circular
226 Diagnostic.new(:error, :circular_argument_reference, { var_name: location.slice }, diagnostic_location, [])
227 when :parameter_name_repeat
228 Diagnostic.new(:error, :duplicate_argument, {}, diagnostic_location, [])
229 when :parameter_numbered_reserved
230 Diagnostic.new(:error, :reserved_for_numparam, { name: location.slice }, diagnostic_location, [])
231 when :regexp_unknown_options
232 Diagnostic.new(:error, :regexp_options, { options: location.slice[1..] }, diagnostic_location, [])
233 when :singleton_for_literals
234 Diagnostic.new(:error, :singleton_literal, {}, diagnostic_location, [])
235 when :string_literal_eof
236 Diagnostic.new(:error, :string_eof, {}, diagnostic_location, [])
237 when :unexpected_token_ignore
238 Diagnostic.new(:error, :unexpected_token, { token: location.slice }, diagnostic_location, [])
239 when :write_target_in_method
240 Diagnostic.new(:error, :dynamic_const, {}, diagnostic_location, [])
241 else
242 PrismDiagnostic.new(error.message, :error, error.type, diagnostic_location)
243 end
244 end
245
246 # Build a diagnostic from the given prism parse warning.
247 def warning_diagnostic(warning, offset_cache)
248 diagnostic_location = build_range(warning.location, offset_cache)
249
250 case warning.type
251 when :ambiguous_first_argument_plus
252 Diagnostic.new(:warning, :ambiguous_prefix, { prefix: "+" }, diagnostic_location, [])
253 when :ambiguous_first_argument_minus
254 Diagnostic.new(:warning, :ambiguous_prefix, { prefix: "-" }, diagnostic_location, [])
255 when :ambiguous_prefix_ampersand
256 Diagnostic.new(:warning, :ambiguous_prefix, { prefix: "&" }, diagnostic_location, [])
257 when :ambiguous_prefix_star
258 Diagnostic.new(:warning, :ambiguous_prefix, { prefix: "*" }, diagnostic_location, [])
259 when :ambiguous_prefix_star_star
260 Diagnostic.new(:warning, :ambiguous_prefix, { prefix: "**" }, diagnostic_location, [])
261 when :ambiguous_slash
262 Diagnostic.new(:warning, :ambiguous_regexp, {}, diagnostic_location, [])
263 when :dot_dot_dot_eol
264 Diagnostic.new(:warning, :triple_dot_at_eol, {}, diagnostic_location, [])
265 when :duplicated_hash_key
266 # skip, parser does this on its own
267 else
268 PrismDiagnostic.new(warning.message, :warning, warning.type, diagnostic_location)
269 end
270 end
271
272 # If there was a error generated during the parse, then raise an
273 # appropriate syntax error. Otherwise return the result.
274 def unwrap(result, offset_cache)
275 result.errors.each do |error|
276 next unless valid_error?(error)
277 diagnostics.process(error_diagnostic(error, offset_cache))
278 end
279
280 result.warnings.each do |warning|
281 next unless valid_warning?(warning)
282 diagnostic = warning_diagnostic(warning, offset_cache)
283 diagnostics.process(diagnostic) if diagnostic
284 end
285
286 result
287 end
288
289 # Prism deals with offsets in bytes, while the parser gem deals with
290 # offsets in characters. We need to handle this conversion in order to
291 # build the parser gem AST.
292 #
293 # If the bytesize of the source is the same as the length, then we can
294 # just use the offset directly. Otherwise, we build an array where the
295 # index is the byte offset and the value is the character offset.
296 def build_offset_cache(source)
297 if source.bytesize == source.length
298 -> (offset) { offset }
299 else
300 offset_cache = []
301 offset = 0
302
303 source.each_char do |char|
304 char.bytesize.times { offset_cache << offset }
305 offset += 1
306 end
307
308 offset_cache << offset
309 end
310 end
311
312 # Build the parser gem AST from the prism AST.
313 def build_ast(program, offset_cache)
314 program.accept(Compiler.new(self, offset_cache))
315 end
316
317 # Build the parser gem comments from the prism comments.
318 def build_comments(comments, offset_cache)
319 comments.map do |comment|
320 ::Parser::Source::Comment.new(build_range(comment.location, offset_cache))
321 end
322 end
323
324 # Build the parser gem tokens from the prism tokens.
325 def build_tokens(tokens, offset_cache)
326 Lexer.new(source_buffer, tokens, offset_cache).to_a
327 end
328
329 # Build a range from a prism location.
330 def build_range(location, offset_cache)
331 ::Parser::Source::Range.new(
332 source_buffer,
333 offset_cache[location.start_offset],
334 offset_cache[location.end_offset]
335 )
336 end
337
338 # Options for how prism should parse/lex the source.
339 def prism_options
340 options = {
341 filepath: @source_buffer.name,
342 version: convert_for_prism(version),
343 partial_script: true,
344 }
345 # The parser gem always encodes to UTF-8, unless it is binary.
346 # https://github.com/whitequark/parser/blob/v3.3.6.0/lib/parser/source/buffer.rb#L80-L107
347 options[:encoding] = false if @source_buffer.source.encoding != Encoding::BINARY
348
349 options
350 end
351
352 # Converts the version format handled by Parser to the format handled by Prism.
353 def convert_for_prism(version)
354 case version
355 when 33
356 "3.3.1"
357 when 34
358 "3.4.0"
359 when 35, 40
360 "4.0.0"
361 when 41
362 "4.1.0"
363 else
364 "latest"
365 end
366 end
367
368 require_relative "parser/builder"
369 require_relative "parser/compiler"
370 require_relative "parser/lexer"
371
372 private_constant :Compiler
373 private_constant :Lexer
374 end
375 end
376 end