Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 32 additions & 3 deletions lib/prism/translation/parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,35 @@ def initialize(message, level, reason, location)

Racc_debug_parser = false # :nodoc:

# By using the `:parser` keyword argument, you can translate in a way that is compatible with
# the Parser gem using any parser.
#
# For example, in RuboCop for Ruby LSP, the following approach can be used to improve performance
# by reusing a pre-parsed `Prism::ParseLexResult`:
#
# class PrismPreparsed
# def initialize(prism_result)
# @prism_result = prism_result
# end
#
# def parse_lex(source, **options)
# @prism_result
# end
# end
#
# prism_preparsed = PrismPreparsed.new(prism_result)
#
# Prism::Translation::Ruby34.new(builder, parser: prism_preparsed)
#
# In an object passed to the `:parser` keyword argument, the `parse` and `parse_lex` methods
# should be implemented as needed.
#
def initialize(builder = ::Parser::Builders::Default.new, parser: Prism)
@parser = parser

super(builder)
end

def version # :nodoc:
34
end
Expand All @@ -51,7 +80,7 @@ def parse(source_buffer)
source = source_buffer.source

offset_cache = build_offset_cache(source)
result = unwrap(Prism.parse(source, **prism_options), offset_cache)
result = unwrap(@parser.parse(source, **prism_options), offset_cache)

build_ast(result.value, offset_cache)
ensure
Expand All @@ -64,7 +93,7 @@ def parse_with_comments(source_buffer)
source = source_buffer.source

offset_cache = build_offset_cache(source)
result = unwrap(Prism.parse(source, **prism_options), offset_cache)
result = unwrap(@parser.parse(source, **prism_options), offset_cache)

[
build_ast(result.value, offset_cache),
Expand All @@ -83,7 +112,7 @@ def tokenize(source_buffer, recover = false)
offset_cache = build_offset_cache(source)
result =
begin
unwrap(Prism.parse_lex(source, **prism_options), offset_cache)
unwrap(@parser.parse_lex(source, **prism_options), offset_cache)
rescue ::Parser::SyntaxError
raise if !recover
end
Expand Down
Loading