Tree-sitter Elixir
View SourceThis package provides Elixir bindings for the Tree-sitter parsing library.
Installation
- Install the Tree-sitter C library:
# On macOS
brew install tree-sitter
# On Ubuntu/Debian
apt-get install libtree-sitter-dev
# On Fedora
dnf install tree-sitter-devel
- Add the package to your dependencies:
def deps do
[
{:tree_sitter, "~> 0.1"}
]
end
Usage
# Create a parser
parser = TreeSitter.new()
# Load a language (provides the path to the shared library and function name)
language = TreeSitter.new_language("/path/to/tree-sitter-elixir.so", "tree_sitter")
# Set the language on the parser
:ok = TreeSitter.set_language(parser, language)
# Parse a string
tree = TreeSitter.parse_string(parser, "defmodule Test do\n def hello, do: :world\nend")
# Create a query
{:ok, query} = TreeSitter.new_query(language, """
(
(call_expression
function: (identifier) @function_name
)
)
""")
# Execute the query against the tree
{:ok, matches} = TreeSitter.exec_query(query, tree)
Helper Functions
You can also use the helper functions for a simpler workflow:
# Parse a string with a given language in one step
tree = TreeSitter.parse("/path/to/lang.so", "tree_sitter_lang", "source code...")
# Run a query in one step
{:ok, matches} = TreeSitter.query(language, tree, """
(identifier) @id
""")
Building Languages
To use this library, you'll need shared libraries (.so, .dylib, or .dll files) for each Tree-sitter language you want to use. You can build these from the language repositories:
git clone https://github.com/tree-sitter/tree-sitter-elixir
cd tree-sitter-elixir
make
# The shared library will be in the build/ directory
License
MIT