[Python] How to load custom language in python tree-sitter version 0.23.0

Discussão em 'Python' iniciado por Stack, Maio 9, 2025.

  1. Stack

    Stack Membro Participativo

    Python tree-sitter version 0.21.3 or earlier

    from tree_sitter import Language, Parser

    lang_path = "tree-sitter-test-lang/test-lang.so"

    # Load the language
    TESTLANG_LANGUAGE = Language(lang_path, 'testlang')

    # Initialize the parser with the languages
    parser = Parser()
    parser.set_language(TESTLANG_LANGUAGE)

    # Parse some code
    source_code = b"""
    let x = 10;
    print x;
    """

    tree = parser.parse(source_code)

    # Explore the tree
    root_node = tree.root_node

    def print_node(node, indent=""):
    print(f"{indent}{node.type}: {node.text.decode('utf-8')}")
    for child in node.children:
    print_node(child, indent + " ")

    print_node(root_node)


    Python tree-sitter version 0.23.0

    In latest python version the definition of Language and Parser is changed. Language expects one argument of type tree-sitter.language and Parser is initialized directly with the output of Parser. Build_libary, set_language are removed and set_language

    import tree_sitter_python as tspython
    from tree_sitter import Language, Parser

    PY_LANGUAGE = Language(tspython.language())

    parser = Parser(PY_LANGUAGE)
    tree = parser.parse(
    bytes(
    """
    def foo():
    if bar:
    baz()
    """,
    "utf8"
    )
    )


    The essence of my questions is how to use tree-sitter version 0.23.0 to load and parser with a custom-generated parser such as tree-sitter-test-lang/test-lang.so shared-object

    lang_path = "tree-sitter-simple-lang/simple-lang.so"
    # Load the language grammar

    # Load the compiled language from the shared object file
    my_language = ctypes.cdll.LoadLibrary(lang_path)
    ...

    Continue reading...

Compartilhe esta Página