Tree-sitter C# Grammar

0.23.1 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to load the C# grammar provided by `tree-sitter-c-sharp`, create a `tree_sitter.Parser`, and parse a simple C# code snippet into a syntax tree. It then accesses basic information from the root node.

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')}")

view raw JSON →