From 5d95e5333a24afb27a3b1ccb00c218142f6033ae Mon Sep 17 00:00:00 2001 From: Earlopain <14981592+Earlopain@users.noreply.github.com> Date: Tue, 21 Jan 2025 10:03:46 +0100 Subject: [PATCH] Add a custom builder class for the parser translator I want to add new node types to the parser translator, for example `itblock`. The bulk of the work is already done by prism itself. In the `parser` builder, this would be a 5-line change at most but we don't control that here. Instead, we can add our own builder and either overwrite the few methods we need, or just inline the complete builder. I'm not sure yet which would be better. `rubocop-ast` uses its own builder for `parser`. For this to correctly work, it must explicitly choose to extend the prism builder and use it, same as it currently chooses to use a different parser when prism is used. I'd like to enforce that the builder for prism extends its custom one since it will lead to some pretty weird issues otherwise. But first, I'd like to change `rubocop-ast` to make use of this. --- lib/prism/translation/parser.rb | 5 +++++ lib/prism/translation/parser/builder.rb | 13 +++++++++++++ test/prism/ruby/parser_test.rb | 1 + 3 files changed, 19 insertions(+) create mode 100644 lib/prism/translation/parser/builder.rb diff --git a/lib/prism/translation/parser.rb b/lib/prism/translation/parser.rb index 6b417be423..6cf762e959 100644 --- a/lib/prism/translation/parser.rb +++ b/lib/prism/translation/parser.rb @@ -31,6 +31,10 @@ def initialize(message, level, reason, location) end end + def initialize(builder = Parser::Builder.new) + super + end + Racc_debug_parser = false # :nodoc: def version # :nodoc: @@ -313,6 +317,7 @@ def convert_for_prism(version) end end + require_relative "parser/builder" require_relative "parser/compiler" require_relative "parser/lexer" diff --git a/lib/prism/translation/parser/builder.rb b/lib/prism/translation/parser/builder.rb new file mode 100644 index 0000000000..ee3da1ee67 --- /dev/null +++ b/lib/prism/translation/parser/builder.rb @@ -0,0 +1,13 @@ +# frozen_string_literal: true + +module Prism + module Translation + class Parser + # A builder that knows how to convert more modern Ruby syntax + # into whitequark/parser gem's syntax tree. + class Builder < ::Parser::Builders::Default + + end + end + end +end diff --git a/test/prism/ruby/parser_test.rb b/test/prism/ruby/parser_test.rb index 2ec5af0777..cbf61f3d77 100644 --- a/test/prism/ruby/parser_test.rb +++ b/test/prism/ruby/parser_test.rb @@ -16,6 +16,7 @@ # First, opt in to every AST feature. Parser::Builders::Default.modernize +Prism::Translation::Parser::Builder.modernize # The parser gem rejects some strings that would most likely lead to errors # in consumers due to encoding problems. RuboCop however monkey-patches this