Skip to content

Commit 986bfbf

Browse files
committed
Support custom parser in Prism::Translation::Parser
Follow-up to Shopify/ruby-lsp#1849. This is an extension of `Prism::Translation::Parser` to implement Shopify/ruby-lsp#1849. It is based on the comments in Shopify/ruby-lsp#1849 (review), but also adds a default argument for delegation to `Parser::Base` super class.
1 parent 8d04d59 commit 986bfbf

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

lib/prism/translation/parser.rb

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,35 @@ def initialize(message, level, reason, location)
3333

3434
Racc_debug_parser = false # :nodoc:
3535

36+
# By using the `:parser` keyword argument, you can translate in a way that is compatible with
37+
# the Parser gem using any parser.
38+
#
39+
# For example, in RuboCop for Ruby LSP, the following approach can be used to improve performance
40+
# by reusing a pre-parsed `Prism::ParseLexResult`:
41+
#
42+
# class PrismPreparsed
43+
# def initialize(prism_result)
44+
# @prism_result = prism_result
45+
# end
46+
#
47+
# def parse_lex(source, **options)
48+
# @prism_result
49+
# end
50+
# end
51+
#
52+
# prism_proxy = ParserProxy.new(prism_result)
53+
#
54+
# Prism::Translation::Ruby34.new(builder, parser: prism_proxy)
55+
#
56+
# In an object passed to the `:parser` keyword argument, the `parse` and `parse_lex` methods
57+
# should be implemented as needed.
58+
#
59+
def initialize(builder = ::Parser::Builders::Default.new, parser: Prism)
60+
@parser = parser
61+
62+
super(builder)
63+
end
64+
3665
def version # :nodoc:
3766
34
3867
end
@@ -51,7 +80,7 @@ def parse(source_buffer)
5180
source = source_buffer.source
5281

5382
offset_cache = build_offset_cache(source)
54-
result = unwrap(Prism.parse(source, **prism_options), offset_cache)
83+
result = unwrap(@parser.parse(source, **prism_options), offset_cache)
5584

5685
build_ast(result.value, offset_cache)
5786
ensure
@@ -64,7 +93,7 @@ def parse_with_comments(source_buffer)
6493
source = source_buffer.source
6594

6695
offset_cache = build_offset_cache(source)
67-
result = unwrap(Prism.parse(source, **prism_options), offset_cache)
96+
result = unwrap(@parser.parse(source, **prism_options), offset_cache)
6897

6998
[
7099
build_ast(result.value, offset_cache),
@@ -83,7 +112,7 @@ def tokenize(source_buffer, recover = false)
83112
offset_cache = build_offset_cache(source)
84113
result =
85114
begin
86-
unwrap(Prism.parse_lex(source, **prism_options), offset_cache)
115+
unwrap(@parser.parse_lex(source, **prism_options), offset_cache)
87116
rescue ::Parser::SyntaxError
88117
raise if !recover
89118
end

0 commit comments

Comments
 (0)