Module: TreeSitter::Mixins::Language

Included in:
TreeSitter, TreeStand::Parser
Defined in:
lib/tree_sitter/mixins/language.rb

Overview

Language Mixin.

Instance Method Summary collapse

Instance Method Details

#extString

The platform-specific extension of the parser.

Returns:

  • (String)

    ‘dylib` or `so` for mac or linux.



100
101
102
103
104
105
# File 'lib/tree_sitter/mixins/language.rb', line 100

def ext
  case Gem::Platform.local.os
  in   /darwin/ then 'dylib'
  else               'so'
  end
end

#language(name) ⇒ TreeSitter:language

Note:

the name is case sensitive, but library lookup is not: if your parser is defined as ‘COBOL`, then you have to call `language(’COBOL’)‘, but the parser can be `cobol.so/COBOL.so/…`.

Load a language from configuration or default lookup paths.

Examples:

Load java from default paths

# This will look for:
#
#   .vendor/tree-sitter-parsers/(java/)?(libtree-sitter-)?java.{ext}
#   .vendor/parsers/(java/)?(libtree-sitter-)?java.{ext}
#   vendor/tree-sitter-parsers/(java/)?(libtree-sitter-)?java.{ext}
#   vendor/parsers/(java/)?(libtree-sitter-)?java.{ext}
#   parsers/(java/)?(libtree-sitter-)?java.{ext}
#   tree-sitter-parsers/(java/)?(libtree-sitter-)?java.{ext}
#   /opt/local/lib/(java/)?(libtree-sitter-)?java.{ext}
#   /opt/lib/(java/)?(libtree-sitter-)?java.{ext}
#   /usr/local/lib/(java/)?(libtree-sitter-)?java.{ext}
#   /usr/lib/(java/)?(libtree-sitter-)?java.{ext}
#
java = TreeSitter.language('java')

(TreeStand) Load java from a configured path

# This will look for:
#
#   /my/path/(java/)?(libtree-sitter-)?java.{ext}
#
TreeStand.config.parser_path = '/my/path'
java = TreeStand::Parser.language('java')

(TreeStand) Load java from environment variables

# This will look for:
#
#   /my/forced/env/path/(java/)?(libtree-sitter-)?java.{ext}
#   /my/path/(java/)?(libtree-sitter-)?java.{ext}
#
# … and the same works for the default paths if `TreeStand.config.parser_path`
# was `nil`
ENV['TREE_SITTER_PARSERS'] = '/my/forced/env/path'
TreeStand.config.parser_path = '/my/path'
java = TreeStand::Parser.language('java')

Parameters:

  • name (String)

    the name of the parser. This name is used to load the symbol from the compiled parser, replacing ‘-` with `_`.

Returns:

  • (TreeSitter:language)

    a language object to use in your parsers.

Raises:

  • (RuntimeError)

    if the parser was not found.

See Also:

  • #search_for_lib


82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/tree_sitter/mixins/language.rb', line 82

def language(name)
  lib = search_for_lib(name)

  if lib.nil?
    raise ::TreeSitter::ParserNotFoundError, <<~MSG.chomp
      Failed to load a parser for #{name}.

      #{search_lib_message}
    MSG
  end

  # We know that the bindings will accept `lib`, but I don't know how to tell sorbet
  # the types in ext/tree_sitter where `load` is defined.
  TreeSitter::Language.load(name.tr('-', '_'), lib)
end