tree-sitter-kotlin

1.1.0 · active · verified Thu Apr 16

tree-sitter-kotlin provides a Kotlin grammar for the Tree-sitter parsing library. Tree-sitter is an incremental parsing system designed for text editors, enabling fast and robust syntax tree generation and updates. This Python package provides pre-compiled binaries of the Kotlin grammar, allowing developers to parse Kotlin code and build Abstract Syntax Trees (ASTs) in Python applications. The library maintains an active development status, with recent releases indicating a cadence of a few updates per year.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to load the `tree-sitter-kotlin` grammar and use `tree_sitter.Parser` to parse a basic Kotlin code snippet, then access the root node of the generated Abstract Syntax Tree.

import tree_sitter_kotlin as tskt
from tree_sitter import Language, Parser

# Load the Kotlin grammar
KOTLIN_LANGUAGE = Language(tskt.language())

# Create a parser and set the language
parser = Parser()
parser.set_language(KOTLIN_LANGUAGE)

# Sample Kotlin code to parse
kotlin_code = b'''
fun main() {
    val greeting = "Hello, Tree-sitter!"
    println(greeting)
}
'''

# Parse the code
tree = parser.parse(kotlin_code)

# Get the root node of the AST
root_node = tree.root_node

print(f"Root node type: {root_node.type}")
print(f"Root node children count: {len(root_node.children)}")
# Example: Find a function declaration
function_node = root_node.children[0] # Assuming 'fun main()' is the first child
if function_node.type == 'function_declaration':
    print(f"Found function: {function_node.text.decode('utf8').split('(')[0]}")

view raw JSON →