Skip to content

profMagija/dotnet-tree-sitter

Repository files navigation

dotnet-tree-sitter

Dotnet bindings for tree-sitter.

Cloning

Be sure to clone with --recurse-submodules, or run

git submodule update --init --recursive

if you have already cloned.

Building

To build everything, run the build.py script:

python build.py

This will use gcc for building native libraries, which are distributed as submodules.

Usage

(these examples are somewhat taken from the py-tree-sitter repo).

Basic parsing

Create a parser and set its language to a Python language instance.

using TreeSitter;
using TreeSitter.Python;

var language = PythonLanguage.Create();
var parser = new Parser {Language = language};

Parse some source code:

var tree = parser.Parse(@"
def foo():
    bar()
");

NOTE: Parsing a string will convert it into UTF-16 bytes, thus all byte indices will be double the character indices in the C# string.

Inspect the resulting tree:

Debug.Assert(tree.Root.ToString() == Trim(
    @"(module (function_definition
        name: (identifier)
        parameters: (parameters)
        body: (block (expression_statement (call
            function: (identifier)
            arguments: (argument_list))))))"));

(Trim is a utility function that replaces multiple whicespace characters with a single space).

Integrating with a new language

  1. Compile the language native modules, as a platform-dependant (.so/.dylib/.dll) shared library.
  2. Declare the [DllImport("...")] extern IntPtr tree_sitter_LANG(); function.
  3. The Language constructor must be passed the IntPtr result of calling that function.
  4. Take a look at CLanguage class to see how it is done for the C language, including the helper Create function.

About

Tree Sitter binding for .NET

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages