Tree-sitter C# Grammar
The `tree-sitter-c-sharp` library provides a C# grammar definition for the `tree-sitter` universal parsing system. It allows Python applications to parse C# source code into a concrete syntax tree (CST) efficiently. The current version is 0.23.1, and releases typically track updates to the C# language specification and bug fixes for the grammar.
Warnings
- gotcha The `tree-sitter` Python library (PyPI package `tree-sitter`) is a required dependency but is NOT automatically installed with `tree-sitter-c-sharp`. You must install both separately.
- gotcha The C# grammar evolves to support new language features (e.g., C# 10, C# 11). Older versions of `tree-sitter-c-sharp` might not correctly parse syntax from newer C# language versions, leading to `ERROR` nodes in the parse tree.
- gotcha When working with `tree-sitter`, always pass byte strings (e.g., `bytes(code, 'utf8')`) to the parser's `parse` method. Passing a regular Python string will raise a `TypeError`.
Install
-
pip install tree-sitter tree-sitter-c-sharp
Imports
- language
import tree_sitter_c_sharp from tree_sitter import Language, Parser
- Language
from tree_sitter import Language
- Parser
from tree_sitter import Parser
Quickstart
import tree_sitter_c_sharp
from tree_sitter import Language, Parser
# Load the C# grammar from the installed package
C_SHARP_LANGUAGE = Language(tree_sitter_c_sharp.language())
# Create a parser instance
parser = Parser()
parser.set_language(C_SHARP_LANGUAGE)
# C# source code to parse
code = """
using System;
namespace MyNamespace
{
class MyClass
{
static void Main(string[] args)
{
Console.WriteLine("Hello, Tree-sitter C#!");
}
}
}
"""
# Parse the code
tree = parser.parse(bytes(code, "utf8"))
# Print a snippet of the AST
root_node = tree.root_node
print(f"Root node type: {root_node.type}")
print(f"Number of children: {len(root_node.children)}")
if root_node.children:
first_child = root_node.children[0]
print(f"First child type: {first_child.type}")
print(f"First child text: {first_child.text.decode('utf8')}")