Class: TreeStand::Parser

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/tree_stand/parser.rb

Overview

Wrapper around the TreeSitter parser. It looks up the parser by filename in the configured parsers directory.

Examples:

TreeStand.configure do
  config.parser_path = "path/to/parser/folder/"
end

# Looks for a parser in `path/to/parser/folder/sql.{so,dylib}`
sql_parser = TreeStand::Parser.new("sql")

# Looks for a parser in `path/to/parser/folder/ruby.{so,dylib}`
ruby_parser = TreeStand::Parser.new("ruby")

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(language) ⇒ void

Parameters:

  • language (String)


27
28
29
30
31
32
33
34
35
36
# File 'lib/tree_stand/parser.rb', line 27

def initialize(language)
  @language_string = language
  @ts_language = TreeSitter::Language.load(
    language,
    "#{TreeStand.config.parser_path}/#{language}.so"
  )
  @ts_parser = TreeSitter::Parser.new.tap do |parser|
    parser.language = @ts_language
  end
end

Instance Attribute Details

#ts_languageTreeSitter::Language (readonly)

Returns:

  • (TreeSitter::Language)


21
22
23
# File 'lib/tree_stand/parser.rb', line 21

def ts_language
  @ts_language
end

#ts_parserTreeSitter::Parser (readonly)

Returns:

  • (TreeSitter::Parser)


23
24
25
# File 'lib/tree_stand/parser.rb', line 23

def ts_parser
  @ts_parser
end

Instance Method Details

#parse_string(document, tree: nil) ⇒ TreeStand::Tree

Parse the provided document with the TreeSitter parser.

Parameters:

  • document (String)
  • tree (TreeStand::Tree, nil) (defaults to: nil)

    providing the old tree will allow the parser to take advantage of incremental parsing and improve performance by re-useing nodes from the old tree.

Returns:



43
44
45
46
47
# File 'lib/tree_stand/parser.rb', line 43

def parse_string(document, tree: nil)
  # @todo There's a bug with passing a non-nil tree
  ts_tree = @ts_parser.parse_string(nil, document)
  TreeStand::Tree.new(self, ts_tree, document)
end

#parse_string!(document, tree: nil) ⇒ TreeStand::Tree

Note:

Like #parse_string, except that if the tree contains any parse errors, raises an InvalidDocument error.

Parameters:

Returns:

Raises:

See Also:



56
57
58
59
60
61
62
63
64
# File 'lib/tree_stand/parser.rb', line 56

def parse_string!(document, tree: nil)
  tree = parse_string(document, tree: tree)
  return tree unless tree.any?(&:error?)

  raise(InvalidDocument, <<~ERROR)
    Encountered errors in the document. Check the tree for more details.
      #{tree}
  ERROR
end