This module provides Python bindings to the tree-sitter parsing library.
Installation
The package has no library dependencies and provides pre-compiled wheels for all major platforms.
[!NOTE]
If your platform is not currently supported, please submit an issue on GitHub.
pip install tree-sitter
Usage
Setup
Install languages
Tree-sitter language implementations also provide pre-compiled binary wheels.
Let's take Python as an example.
pip install tree-sitter-python
Then, you can load it as a Language object:
import tree_sitter_python as tspython
from tree_sitter import Language, Parser
PY_LANGUAGE = Language(tspython.language())
Basic parsing
Create a Parser and configure it to use a language:
parser = Parser(PY_LANGUAGE)
Parse some source code:
tree = parser.parse(
bytes(
"""
def foo():
if bar:
baz()
""",
"utf8",
)
)
If you have your source code in some data structure other than a bytes object,
you can pass a "read" callable to the parse function.
The read callable can use either the byte offset or point tuple to read from
buffer and return source code as bytes object. An empty bytes object or None
terminates parsing for that line. The bytes must be encoded as UTF-8 or UTF-16.
For example, to use the byte offset with UTF-8 encoding:
src = bytes(
"""
def foo():
if bar:
baz()
""",
"utf8",
)
def read_callable_byte_offset(byte_offset, point):
return src[byte_offset : byte_offset + 1]
tree = parser.parse(read_callable_byte_offset, encoding="utf8")
And to use the point:
src_lines = ["\n", "def foo():\n", " if bar:\n", " baz()\n"]
def read_callable_point(byte_offset, point):
row, column = point
if row >= len(src_lines) or column >= len(src_lines[row]):
return None
return src_lines[row][column:].encode("utf8")
tree = parser.parse(read_callable_point, encoding="utf8")
Then, when you're ready to incorporate the changes into a new syntax tree,
you can call Parser.parse again, but pass in the old tree:
new_tree = parser.parse(new_src, tree)
This will run much faster than if you were parsing from scratch.
The Tree.changed_ranges method can be called on the old tree to return
the list of ranges whose syntactic structure has been changed:
for changed_range in tree.changed_ranges(new_tree):
print("Changed range:")
print(f" Start point {changed_range.start_point}")
print(f" Start byte {changed_range.start_byte}")
print(f" End point {changed_range.end_point}")
print(f" End byte {changed_range.end_byte}")
Pattern-matching
You can search for patterns in a syntax tree using a tree query:
matches = query_cursor.matches(tree.root_node)
assert len(matches) == 2
# first match
assert matches[0][1]["function.def"] == [function_name_node]
assert matches[0][1]["function.block"] == [function_body_node]
# second match
assert matches[1][1]["function.call"] == [function_call_name_node]
assert matches[1][1]["function.args"] == [function_call_args_node]
The difference between the two methods is that QueryCursor.matches() groups captures into matches,
which is much more useful when your captures within a query relate to each other.
To try out and explore the code referenced in this README, check out examples/usage.py.
Works well with
Use together with tree-sitter: extensions, drivers, servers and companion tools.
tree-sitter-typescriptPythie’s Index: 13TypeScript and TSX grammars for tree-sitter15.7M downloads/mo
tree-sitter-rustPythie’s Index: 36Rust grammar for tree-sitter8.5M downloads/mo
tree-sitter-goPythie’s Index: 20Go grammar for tree-sitter8.1M downloads/mo
tree-sitter-language-packPythie’s Index: 84Pre-compiled tree-sitter grammars for 371 programming languages6.3M downloads/mo
tree-sitter-cppPythie’s Index: 20C++ grammar for tree-sitter6.9M downloads/mo
tree-sitter-cPythie’s Index: 33C grammar for tree-sitter9.7M downloads/mo