Class: TreeHaver::Backends::Prism::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/tree_haver/backends/prism.rb

Overview

Prism parser wrapper

Wraps Prism to provide a tree-sitter-like API for parsing Ruby code.

Instance Method Summary collapse

Constructor Details

#initializeParser

Create a new Prism parser instance

Raises:



192
193
194
195
196
# File 'lib/tree_haver/backends/prism.rb', line 192

def initialize
  raise TreeHaver::NotAvailable, "prism not available" unless Prism.available?
  @language = nil
  @options = {}
end

Instance Method Details

#language=(lang) ⇒ void

This method returns an undefined value.

Set the language for this parser

Note: TreeHaver::Parser unwraps language objects before calling this method. This backend receives the Language wrapper (since Prism::Language stores options).



205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/tree_haver/backends/prism.rb', line 205

def language=(lang)
  case lang
  when Language
    @language = lang
    @options = lang.options
  when Symbol, String
    if lang.to_sym == :ruby
      @language = Language.ruby
      @options = {}
    else
      raise ArgumentError,
        "Prism only supports Ruby parsing. Got: #{lang.inspect}"
    end
  else
    raise ArgumentError,
      "Expected Prism::Language or :ruby, got #{lang.class}"
  end
end

#parse(source) ⇒ Tree

Parse source code

Raises:



229
230
231
232
233
234
235
# File 'lib/tree_haver/backends/prism.rb', line 229

def parse(source)
  raise TreeHaver::NotAvailable, "No language loaded (use parser.language = :ruby)" unless @language

  # Use Prism.parse with options
  prism_result = ::Prism.parse(source, **@options)
  Tree.new(prism_result, source)
end

#parse_string(old_tree, source) ⇒ Tree

Parse source code (compatibility with tree-sitter API)

Prism doesn’t support incremental parsing, so old_tree is ignored.



244
245
246
# File 'lib/tree_haver/backends/prism.rb', line 244

def parse_string(old_tree, source) # rubocop:disable Lint/UnusedMethodArgument
  parse(source)  # Prism doesn't support incremental parsing
end