### Kotlin Loop Constructs Source: https://github.com/tree-sitter-grammars/tree-sitter-kotlin/blob/master/test/corpus/declarations.txt Examples of for, while, and do-while loops in Kotlin. ```kotlin fun Foo() { loop@ for (i in 0..10) { println(i) if (i == 5) { break@loop } } while (true) { println("Hello") break } do { println("World") break } while (true) } ``` ```lisp (source_file (function_declaration (identifier) (function_value_parameters) (function_body (block (for_statement (label) (variable_declaration (identifier)) (range_expression (number_literal) (number_literal)) (block (call_expression (identifier) (value_arguments (value_argument (identifier)))) (if_expression (binary_expression (identifier) (number_literal)) (block (labeled_expression (label) (identifier)))))) (while_statement (identifier) (block (call_expression (identifier) (value_arguments (value_argument (string_literal (string_content))))) (identifier))) (do_while_statement (block (call_expression (identifier) (value_arguments (value_argument (string_literal (string_content))))) (identifier)) (identifier)))))) ``` -------------------------------- ### Initialize and use the Kotlin parser in C Source: https://context7.com/tree-sitter-grammars/tree-sitter-kotlin/llms.txt Demonstrates the full lifecycle of a tree-sitter parser for Kotlin, including setup, parsing a source string, inspecting the syntax tree, and executing a query. ```c #include #include #include #include "tree-sitter-kotlin.h" int main() { // Create a parser TSParser *parser = ts_parser_new(); // Set the Kotlin language const TSLanguage *language = tree_sitter_kotlin(); ts_parser_set_language(parser, language); // Parse Kotlin source code const char *source_code = "package com.example\n" "\n" "object Singleton {\n" " val instance: Singleton get() = this\n" " \n" " fun doSomething() {\n" " println(\"Singleton action\")\n" " }\n" "}\n" "\n" "fun List.sum(): Int {\n" " var total = 0\n" " for (item in this) {\n" " total += item\n" " }\n" " return total\n" "}\n" "\n" "fun main() {\n" " Singleton.doSomething()\n" " val numbers = listOf(1, 2, 3, 4, 5)\n" " println(numbers.sum())\n" "}\n"; TSTree *tree = ts_parser_parse_string( parser, NULL, source_code, strlen(source_code) ); // Get the root node TSNode root_node = ts_tree_root_node(tree); printf("Root node type: %s\n", ts_node_type(root_node)); // Output: Root node type: source_file printf("Child count: %u\n", ts_node_child_count(root_node)); // Output: Child count: 4 // Check for syntax errors if (ts_node_has_error(root_node)) { printf("Syntax errors detected!\n"); } else { printf("No syntax errors\n"); } // Output: No syntax errors // Traverse children for (uint32_t i = 0; i < ts_node_child_count(root_node); i++) { TSNode child = ts_node_child(root_node, i); printf("Child %u: %s\n", i, ts_node_type(child)); } // Output: Child 0: package_header // Output: Child 1: object_declaration // Output: Child 2: function_declaration // Output: Child 3: function_declaration // Query using tree-sitter query API uint32_t error_offset; TSQueryError error_type; TSQuery *query = ts_query_new( language, "(function_declaration name: (identifier) @func)", strlen("(function_declaration name: (identifier) @func)"), &error_offset, &error_type ); if (query) { TSQueryCursor *cursor = ts_query_cursor_new(); ts_query_cursor_exec(cursor, query, root_node); TSQueryMatch match; while (ts_query_cursor_next_match(cursor, &match)) { for (uint16_t i = 0; i < match.capture_count; i++) { TSNode node = match.captures[i].node; uint32_t start = ts_node_start_byte(node); uint32_t end = ts_node_end_byte(node); printf("Function: %.*s\n", end - start, source_code + start); } } // Output: Function: sum // Output: Function: main ts_query_cursor_delete(cursor); ts_query_delete(query); } // Clean up ts_tree_delete(tree); ts_parser_delete(parser); return 0; } ``` -------------------------------- ### Kotlin Enum Classes Source: https://github.com/tree-sitter-grammars/tree-sitter-kotlin/blob/master/test/corpus/declarations.txt Example of an enum class with properties and methods. ```kotlin enum class Color { RED, GREEN, BLUE; override fun rgb() = when (this) { RED -> 0xFF0000 GREEN -> 0x00FF00 BLUE -> 0x0000FF } } ``` -------------------------------- ### Kotlin Type Casting Examples Source: https://github.com/tree-sitter-grammars/tree-sitter-kotlin/blob/master/test/corpus/expressions.txt Demonstrates various complex type casting scenarios in Kotlin, including function types, intersection types, and qualified types. ```kotlin x as Foo.(Z: Int) -> Bar ``` ```kotlin x as Foo & Bar ``` ```kotlin x as @Y Foo? & Bar? ``` ```kotlin x as Baz.Quux ``` -------------------------------- ### Example Kotlin Class Structure Parse Tree Source: https://context7.com/tree-sitter-grammars/tree-sitter-kotlin/llms.txt Illustrates the expected tree structure for a simple Kotlin class declaration, showing how node types like class_declaration, identifier, and function_declaration are nested. Useful for visualizing grammar output. ```javascript /* (source_file (class_declaration (modifiers (class_modifier)) name: (identifier) (primary_constructor (class_parameters (class_parameter (identifier) (user_type (identifier))))) (class_body (function_declaration name: (identifier) (function_value_parameters) (function_body (block ...)))))) */ ``` -------------------------------- ### Parse Kotlin Code with Tree Sitter in Python Source: https://context7.com/tree-sitter-grammars/tree-sitter-kotlin/llms.txt Utilize the Python binding to parse Kotlin source code and analyze its syntax tree. Ensure 'tree-sitter' and 'tree-sitter-kotlin' are installed. ```python import tree_sitter import tree_sitter_kotlin # Initialize the Kotlin language KOTLIN_LANGUAGE = tree_sitter.Language(tree_sitter_kotlin.language()) # Create parser parser = tree_sitter.Parser(KOTLIN_LANGUAGE) # Parse Kotlin source code source_code = b""" package com.example data class User( val id: Long, val name: String, val email: String? ) interface Repository { suspend fun findById(id: Long): T? suspend fun save(entity: T): T suspend fun delete(entity: T) } class UserRepository : Repository { private val users = mutableMapOf() override suspend fun findById(id: Long): User? = users[id] override suspend fun save(entity: User): User { users[entity.id] = entity return entity } override suspend fun delete(entity: User) { users.remove(entity.id) } } fun main() { val user = User(1, "John Doe", "john@example.com") println("Created user: ${user.name}") } """ tree = parser.parse(source_code) root_node = tree.root_node print(f"Root type: {root_node.type}") # Output: Root type: source_file print(f"Has errors: {root_node.has_error}") # Output: Has errors: False # Walk the syntax tree def walk_tree(node, depth=0): print(" " * depth + f"{node.type} [{node.start_point[0]}:{node.start_point[1]}]") for child in node.children: walk_tree(child, depth + 1) # Find all class declarations def find_classes(node): classes = [] if node.type == "class_declaration": name_node = node.child_by_field_name("name") if name_node: classes.append(name_node.text.decode()) for child in node.children: classes.extend(find_classes(child)) return classes classes = find_classes(root_node) print(f"Classes found: {classes}") # Output: Classes found: ['User', 'UserRepository'] ``` -------------------------------- ### Kotlin Modifiers and Class Structure Source: https://github.com/tree-sitter-grammars/tree-sitter-kotlin/blob/master/test/corpus/declarations.txt Examples of visibility, inheritance, and function modifiers applied to classes and objects. ```kotlin internal class Test(X: Int): Y(X) { abstract inline fun test() protected open fun test2() { println("Hello") } public fun test3() { println("World") } tailrec suspend fun test4() { println("!") } } public object Test2 { private companion object { fun test() { println("Hello") } } } ``` ```lisp (source_file (class_declaration (modifiers (visibility_modifier)) (identifier) (primary_constructor (class_parameters (class_parameter (identifier) (user_type (identifier))))) (delegation_specifiers (delegation_specifier (constructor_invocation (user_type (identifier)) (value_arguments (value_argument (identifier)))))) (class_body (function_declaration (modifiers (inheritance_modifier) (function_modifier)) (identifier) (function_value_parameters)) (function_declaration (modifiers (visibility_modifier) (inheritance_modifier)) (identifier) (function_value_parameters) (function_body (block (call_expression (identifier) (value_arguments (value_argument (string_literal (string_content)))))))) (function_declaration (modifiers (visibility_modifier)) (identifier) (function_value_parameters) (function_body (block (call_expression (identifier) (value_arguments (value_argument (string_literal (string_content)))))))) (function_declaration (modifiers (function_modifier) (function_modifier)) (identifier) (function_value_parameters) (function_body (block (call_expression (identifier) (value_arguments (value_argument (string_literal (string_content)))))))))) (object_declaration (modifiers (visibility_modifier)) (identifier) (class_body (companion_object (modifiers (visibility_modifier)) (class_body (function_declaration (identifier) (function_value_parameters) (function_body (block (call_expression (identifier) (value_arguments (value_argument (string_literal (string_content))))))))))))) ``` -------------------------------- ### Parse Kotlin Code with Tree Sitter in Node.js Source: https://context7.com/tree-sitter-grammars/tree-sitter-kotlin/llms.txt Use the Node.js binding to parse Kotlin source code and obtain a syntax tree. Requires installation of 'tree-sitter' and '@tree-sitter-grammars/tree-sitter-kotlin'. ```javascript const Parser = require("tree-sitter"); const Kotlin = require("@tree-sitter-grammars/tree-sitter-kotlin"); // Create a new parser instance const parser = new Parser(); parser.setLanguage(Kotlin); // Parse Kotlin source code const sourceCode = ` package com.example import kotlin.collections.List fun main(args: Array) { val message = "Hello, World!" println(message) val numbers = listOf(1, 2, 3, 4, 5) numbers.filter { it > 2 }.forEach { println(it) } } class Person(val name: String, var age: Int) { fun greet(): String = "Hello, I'm $name" } `; const tree = parser.parse(sourceCode); const rootNode = tree.rootNode; console.log("Root node type:", rootNode.type); // Output: Root node type: source_file console.log("Number of children:", rootNode.childCount); // Output: Number of children: 5 // Traverse the syntax tree function printTree(node, indent = 0) { console.log(" ".repeat(indent) + node.type); for (let i = 0; i < node.childCount; i++) { printTree(node.child(i), indent + 2); } } // Find all function declarations const functionQuery = `(function_declaration name: (identifier) @func-name)`); // Use with tree-sitter queries for advanced analysis // Access specific nodes const packageHeader = rootNode.children.find(c => c.type === "package_header"); console.log("Package:", packageHeader?.text); // Output: Package: package com.example // Find class declarations rootNode.children .filter(c => c.type === "class_declaration") .forEach(classNode => { const nameNode = classNode.childForFieldName("name"); console.log("Class found:", nameNode?.text); }); // Output: Class found: Person ``` -------------------------------- ### Parse Complex Kotlin Class and Function Structures Source: https://github.com/tree-sitter-grammars/tree-sitter-kotlin/blob/master/test/corpus/expressions.txt This example demonstrates the grammar for parsing more complex Kotlin constructs, including class declarations with delegation, property declarations within a class, and function declarations with various member access and method calls. ```tree-sitter (source_file (class_declaration (identifier) (delegation_specifiers (delegation_specifier (user_type (identifier)))) (class_body (property_declaration (variable_declaration (identifier)) (number_literal)) (property_declaration (variable_declaration (identifier)) (number_literal)) (property_declaration (variable_declaration (identifier)) (number_literal)) (property_declaration (variable_declaration (identifier)) (call_expression (identifier) (type_arguments (type_projection (user_type (identifier)))) (value_arguments))) (function_declaration (identifier) (function_value_parameters) (function_body (block (assignment (navigation_expression (this_expression (identifier)) ``` -------------------------------- ### Kotlin Import Statements Source: https://github.com/tree-sitter-grammars/tree-sitter-kotlin/blob/master/test/corpus/declarations.txt Demonstrates various import syntax patterns in Kotlin. ```kotlin import foo.bar import foo.baz.* import foo import bar ``` ```lisp (source_file (import (qualified_identifier (identifier) (identifier))) (import (qualified_identifier (identifier) (identifier))) (import (qualified_identifier (identifier))) (import (qualified_identifier (identifier)))) ``` -------------------------------- ### Parse Kotlin code with Go Source: https://context7.com/tree-sitter-grammars/tree-sitter-kotlin/llms.txt Initializes a tree-sitter parser with the Kotlin language and demonstrates tree traversal and node inspection. ```go package main import ( "fmt" tree_sitter "github.com/tree-sitter/go-tree-sitter" tree_sitter_kotlin "github.com/tree-sitter-grammars/tree-sitter-kotlin/bindings/go" ) func main() { // Create a parser with the Kotlin language language := tree_sitter.NewLanguage(tree_sitter_kotlin.Language()) parser := tree_sitter.NewParser() defer parser.Close() err := parser.SetLanguage(language) if err != nil { panic(err) } // Parse Kotlin source code sourceCode := []byte(` package com.example annotation class CustomAnnotation(val value: String) @CustomAnnotation("test") class AnnotatedClass { companion object { const val CONSTANT = "Hello" } var property: String by lazy { "Initialized" } fun String.extensionFunction(): Int = this.length operator fun plus(other: AnnotatedClass): AnnotatedClass { return AnnotatedClass() } } enum class Status(val code: Int) { ACTIVE(1), INACTIVE(0), PENDING(-1); fun isPositive() = code > 0 } typealias StringList = List fun main() { val obj = AnnotatedClass() val status = Status.ACTIVE println("Status: ${status.name}, Code: ${status.code}") } `) tree := parser.Parse(sourceCode, nil) defer tree.Close() rootNode := tree.RootNode() fmt.Printf("Root: %s\n", rootNode.Kind()) // Output: Root: source_file fmt.Printf("Children: %d\n", rootNode.ChildCount()) // Output: Children: 6 // Walk the tree recursively var walkTree func(node *tree_sitter.Node, depth int) walkTree = func(node *tree_sitter.Node, depth int) { indent := "" for i := 0; i < depth; i++ { indent += " " } fmt.Printf("%s%s\n", indent, node.Kind()) for i := uint(0); i < node.ChildCount(); i++ { child := node.Child(i) walkTree(child, depth+1) } } // Find class declarations var findClasses func(node *tree_sitter.Node) []string findClasses = func(node *tree_sitter.Node) []string { var classes []string if node.Kind() == "class_declaration" { nameNode := node.ChildByFieldName("name") if nameNode != nil { classes = append(classes, string(sourceCode[nameNode.StartByte():nameNode.EndByte()])) } } for i := uint(0); i < node.ChildCount(); i++ { child := node.Child(i) classes = append(classes, findClasses(child)...) } return classes } classes := findClasses(rootNode) fmt.Printf("Classes: %v\n", classes) // Output: Classes: [AnnotatedClass Status] } ``` -------------------------------- ### Parse Kotlin Code with Rust API Source: https://context7.com/tree-sitter-grammars/tree-sitter-kotlin/llms.txt Demonstrates how to use the tree-sitter Rust API to parse Kotlin source code. It includes setting up the parser, handling potential errors, and traversing the syntax tree to find specific node types like classes and functions. ```rust use tree_sitter::Parser; use tree_sitter_kotlin_ng::LANGUAGE; fn main() { // Create a parser and set the Kotlin language let mut parser = Parser::new(); parser .set_language(&LANGUAGE.into()) .expect("Error loading Kotlin grammar"); // Parse Kotlin source code let source_code = r#"# package com.example.app sealed class Result { data class Success(val data: T) : Result() data class Error(val exception: Exception) : Result() object Loading : Result() } inline fun genericFunction(value: T): String { return when (value) { is String -> "String: $value" is Int -> "Int: $value" else -> "Unknown: $value" } } suspend fun fetchData(): Result { return try { val data = apiCall() Result.Success(data) } catch (e: Exception) { Result.Error(e) } } fun main() { val result = genericFunction(42) println(result) } "#; let tree = parser.parse(source_code, None).unwrap(); let root_node = tree.root_node(); // Check for parse errors assert!(!root_node.has_error(), "Parse error in source code"); println!("Root node: {} with {} children", root_node.kind(), root_node.child_count()); // Traverse and find specific node types fn find_nodes_by_type<'a>(node: tree_sitter::Node<'a>, kind: &str) -> Vec> { let mut results = Vec::new(); if node.kind() == kind { results.push(node); } let mut cursor = node.walk(); for child in node.children(&mut cursor) { results.extend(find_nodes_by_type(child, kind)); } results } // Find all class declarations let classes = find_nodes_by_type(root_node, "class_declaration"); for class_node in &classes { if let Some(name_node) = class_node.child_by_field_name("name") { let name = &source_code[name_node.byte_range()]; println!("Found class: {}", name); } } // Find all function declarations let functions = find_nodes_by_type(root_node, "function_declaration"); println!("Total functions: {}", functions.len()); // Access node types information let node_types = tree_sitter_kotlin_ng::NODE_TYPES; println!("Node types JSON available: {} bytes", node_types.len()); } ``` -------------------------------- ### Use variable named constructor Source: https://github.com/tree-sitter-grammars/tree-sitter-kotlin/blob/master/test/corpus/semi.txt Illustrates usage of a variable named 'constructor' which shadows the constructor keyword context. ```kotlin fun Foo() { val constructor = Constructor() constructor.method() } ``` ```tree-sitter (source_file (function_declaration (identifier) (function_value_parameters) (function_body (block (property_declaration (variable_declaration (identifier)) (call_expression (identifier) (value_arguments))) (call_expression (navigation_expression (identifier) (identifier)) (value_arguments)))))) ``` -------------------------------- ### Define property with getter and setter Source: https://github.com/tree-sitter-grammars/tree-sitter-kotlin/blob/master/test/corpus/semi.txt Demonstrates a class property with explicit getter and setter definitions on new lines. ```kotlin class Foo { val bar: Int get() = 5 set(value) { field = value } } ``` ```tree-sitter (source_file (class_declaration (identifier) (class_body (property_declaration (variable_declaration (identifier) (user_type (identifier))) (getter (function_body (number_literal))) (setter (identifier) (function_body (block (assignment (identifier) (identifier))))))))) ``` -------------------------------- ### Parse Kotlin Annotations Source: https://github.com/tree-sitter-grammars/tree-sitter-kotlin/blob/master/test/corpus/expressions.txt Shows how various annotation styles, including constructor invocations and class references, are parsed. ```kotlin @Foo @Bar(1, 2, 3) val a = 1 @Baz(a = 1, b = 2) @Quux::class fun b() { } class C { @D @E @F val d = 1 } @G fun `hello world`() = true ``` ```sexp (source_file (property_declaration (modifiers (annotation (user_type (identifier))) (annotation (constructor_invocation (user_type (identifier)) (value_arguments (value_argument (number_literal)) (value_argument (number_literal)) (value_argument (number_literal)))))) (variable_declaration (identifier)) (number_literal)) (annotated_expression (annotation (constructor_invocation (user_type (identifier)) (value_arguments (value_argument (identifier) (number_literal)) (value_argument (identifier) (number_literal))))) (annotated_expression (annotation (user_type (identifier))) (callable_reference))) (function_declaration (identifier) (function_value_parameters) (function_body (block))) (class_declaration (identifier) (class_body (property_declaration (modifiers (annotation (user_type (identifier))) (annotation (user_type (identifier))) (annotation (user_type ``` -------------------------------- ### Kotlin Variable Declaration Syntax Source: https://github.com/tree-sitter-grammars/tree-sitter-kotlin/blob/master/test/corpus/expressions.txt Illustrates the structure of a variable declaration in Kotlin, including its identifier and type. ```kotlin val x: List = listOf(1, 2, 3) ``` -------------------------------- ### Parse Kotlin When Expressions Source: https://github.com/tree-sitter-grammars/tree-sitter-kotlin/blob/master/test/corpus/expressions.txt Demonstrates the grammar for parsing Kotlin's 'when' expressions, including simple value checks and type checks with 'is' and '!is'. ```tree-sitter (source_file (when_expression (when_subject (identifier)) (when_entry (number_literal) (number_literal)) (when_entry (number_literal) (number_literal))) ``` ```tree-sitter (when_expression (when_subject (identifier)) (when_entry (type_test (user_type (identifier))) (number_literal)) (when_entry (type_test (user_type (identifier))) (number_literal)) (when_entry (type_test (user_type (identifier))) (number_literal)) (when_entry (number_literal))) ``` -------------------------------- ### Use variable named set Source: https://github.com/tree-sitter-grammars/tree-sitter-kotlin/blob/master/test/corpus/semi.txt Illustrates usage of a variable named 'set' which shadows the setter keyword context. ```kotlin fun test() { val set = newSet() set.add(1) val a = set[0] set(a, b) } ``` ```tree-sitter (source_file (function_declaration (identifier) (function_value_parameters) (function_body (block (property_declaration (variable_declaration (identifier)) (call_expression (identifier) (value_arguments))) (call_expression (navigation_expression (identifier) (identifier)) (value_arguments (value_argument (number_literal)))) (property_declaration (variable_declaration (identifier)) (index_expression (identifier) (number_literal))) (call_expression (identifier) (value_arguments (value_argument (identifier)) (value_argument (identifier)))))))) ``` -------------------------------- ### Parse Kotlin Code with Swift API Source: https://context7.com/tree-sitter-grammars/tree-sitter-kotlin/llms.txt Initializes the Kotlin language parser and parses a given Kotlin source code string. Requires importing SwiftTreeSitter and TreeSitterKotlin. The parser can then be used to obtain a syntax tree. ```swift import SwiftTreeSitter import TreeSitterKotlin // Initialize the Kotlin language let language = Language(language: tree_sitter_kotlin()) // Create parser let parser = Parser() try parser.setLanguage(language) // Parse Kotlin source code let sourceCode = """ package com.example.mobile import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow interface DataSource { fun getData(): Flow> } data class Item( val id: String, val title: String, val description: String? ) class LocalDataSource : DataSource { override fun getData(): Flow> = flow { val items = listOf( Item("1", "First", "Description 1"), Item("2", "Second", null) ) emit(items) } } fun T?.orDefault(default: T): T = this ?: default """ let tree = parser.parse(sourceCode)! ``` -------------------------------- ### Define primary constructor on newline Source: https://github.com/tree-sitter-grammars/tree-sitter-kotlin/blob/master/test/corpus/semi.txt Shows a primary constructor with annotations defined on a new line. ```kotlin public class Foo @JvmOverloads constructor( val bar: Int = 5 ) ``` ```tree-sitter (source_file (class_declaration (modifiers (visibility_modifier)) (identifier) (primary_constructor (modifiers (annotation (user_type (identifier)))) (class_parameters (class_parameter (identifier) (user_type (identifier)) (number_literal)))))) ``` -------------------------------- ### Add comment after annotation Source: https://github.com/tree-sitter-grammars/tree-sitter-kotlin/blob/master/test/corpus/semi.txt Demonstrates a comment placed on the same line as an annotation. ```kotlin class Foo { val bar: Int @JvmOverloads // comment fun bar() {} } ``` ```tree-sitter (source_file (class_declaration (identifier) (class_body (property_declaration (variable_declaration (identifier) (user_type (identifier)))) (function_declaration ``` -------------------------------- ### Parse Keyword Operator Expressions Source: https://github.com/tree-sitter-grammars/tree-sitter-kotlin/blob/master/test/corpus/expressions.txt Demonstrates how Kotlin keyword operators like 'as', 'is', 'in', and '?:' are represented in the parse tree. ```kotlin fun Foo() { val a = 1 val b = a as Bar val c = b is Baz val d = c as? Qux val e = d !is Corge val f = e in Grault val g = f !in Garply val h = g ?: Waldo // Tricky case with this being a negation of a variable that starts with `is` // It is *not* `!is` followed by the rest of the identifier val i = !isFoo } ``` ```sexp (source_file (function_declaration (identifier) (function_value_parameters) (function_body (block (property_declaration (variable_declaration (identifier)) (number_literal)) (property_declaration (variable_declaration (identifier)) (as_expression (identifier) (user_type (identifier)))) (property_declaration (variable_declaration (identifier)) (is_expression (identifier) (user_type (identifier)))) (property_declaration (variable_declaration (identifier)) (as_expression (identifier) (user_type (identifier)))) (property_declaration (variable_declaration (identifier)) (is_expression (identifier) (user_type (identifier)))) (property_declaration (variable_declaration (identifier)) (in_expression (identifier) (identifier))) (property_declaration (variable_declaration (identifier)) (in_expression (identifier) (identifier))) (property_declaration (variable_declaration (identifier)) (binary_expression (identifier) (identifier))) (line_comment) (line_comment) (property_declaration (variable_declaration (identifier)) (unary_expression (identifier))))))) ``` -------------------------------- ### Tree-sitter Grammar for Kotlin As Expression Source: https://github.com/tree-sitter-grammars/tree-sitter-kotlin/blob/master/test/corpus/expressions.txt Details the Tree-sitter grammar for Kotlin's 'as' expression, covering function types, nullable types, and qualified names. ```tree-sitter-grammar (as_expression (identifier) (function_type (user_type (identifier)) (function_type_parameters (parameter (identifier) (user_type (identifier)))) (user_type (identifier)))) ``` ```tree-sitter-grammar (as_expression (identifier) (non_nullable_type (user_type (identifier)) (user_type (identifier)))) ``` ```tree-sitter-grammar (as_expression (identifier) (non_nullable_type (nullable_type (user_type (type_modifiers (annotation (user_type (identifier)))) (identifier) (type_arguments (type_projection (user_type (identifier)))))) (nullable_type (user_type (identifier) (type_arguments (type_projection (user_type (identifier)))))))) ``` ```tree-sitter-grammar (as_expression (identifier) (user_type (identifier) (identifier)))) ``` -------------------------------- ### Kotlin Function with If/Else Statement Source: https://github.com/tree-sitter-grammars/tree-sitter-kotlin/blob/master/test/corpus/semi.txt Demonstrates a simple Kotlin function containing an if-else conditional statement. The grammar shows the structure of the function, conditional expression, and string literals. ```kotlin fun test() { if (true) println("true") else println("false") } ``` ```tree-sitter-grammar (source_file (function_declaration (identifier) (function_value_parameters) (function_body (block (if_expression (identifier) (call_expression (identifier) (value_arguments (value_argument (string_literal (string_content))))) (call_expression (identifier) (value_arguments (value_argument (string_literal (string_content)))))))))) ``` -------------------------------- ### Parse Kotlin Reserved Identifiers Source: https://github.com/tree-sitter-grammars/tree-sitter-kotlin/blob/master/test/corpus/expressions.txt Shows how the grammar handles Kotlin's reserved identifiers, such as 'expect', 'constructor', and 'operator', in various contexts. ```tree-sitter (source_file (binary_expression (identifier) (number_literal)) ``` ```tree-sitter (property_declaration (variable_declaration (identifier)) (identifier)) ``` ```tree-sitter (property_declaration (variable_declaration (identifier)) (number_literal)) ``` ```tree-sitter (property_declaration (variable_declaration (identifier)) (call_expression (identifier) (value_arguments)))) ``` -------------------------------- ### Parse Simple Binary Expressions in Kotlin Source: https://github.com/tree-sitter-grammars/tree-sitter-kotlin/blob/master/test/corpus/expressions.txt This snippet shows the grammar for parsing simple arithmetic binary expressions in Kotlin, including addition, subtraction, multiplication, and division. ```tree-sitter (source_file (binary_expression (binary_expression (binary_expression (number_literal) (number_literal)) (binary_expression (number_literal) (number_literal))) (number_literal))) ``` -------------------------------- ### Query Kotlin Function Declarations Source: https://context7.com/tree-sitter-grammars/tree-sitter-kotlin/llms.txt Use a tree-sitter query to find function declarations, specifically capturing their names and parameters. This is useful for code analysis tools that need to identify functions. ```python query = KOTLIN_LANGUAGE.query(""" (function_declaration name: (identifier) @function-name (function_value_parameters) @params) """) captures = query.captures(root_node) for node, name in captures: if name == "function-name": print(f"Function: {node.text.decode()}") ``` -------------------------------- ### Define secondary constructor on newline Source: https://github.com/tree-sitter-grammars/tree-sitter-kotlin/blob/master/test/corpus/semi.txt Shows a secondary constructor defined within a class body. ```kotlin class Foo(bar: Int) { val a: Int public constructor() : this(-1) } ``` ```tree-sitter (source_file (class_declaration (identifier) (primary_constructor (class_parameters (class_parameter (identifier) (user_type (identifier))))) (class_body (property_declaration (variable_declaration (identifier) (user_type (identifier)))) (secondary_constructor (modifiers (visibility_modifier)) (function_value_parameters) (constructor_delegation_call (value_arguments (value_argument (unary_expression (number_literal))))))))) ``` -------------------------------- ### Parse Kotlin Comments and Strings Source: https://github.com/tree-sitter-grammars/tree-sitter-kotlin/blob/master/test/corpus/expressions.txt This snippet covers the grammar rules for parsing single-line comments, block comments, regular strings, multiline strings, and strings with interpolations and escape sequences. ```tree-sitter (source_file (line_comment) (block_comment) ``` ```tree-sitter (property_declaration (variable_declaration (identifier)) (string_literal (string_content))) ``` ```tree-sitter (property_declaration (variable_declaration (identifier) (user_type (identifier))) (string_literal (string_content))) ``` ```tree-sitter (property_declaration (variable_declaration (identifier)) (multiline_string_literal (string_content))) ``` ```tree-sitter (property_declaration (variable_declaration (identifier)) (string_literal (string_content) (interpolation (identifier)) (string_content) (escape_sequence))) ``` ```tree-sitter (property_declaration (variable_declaration (identifier)) (string_literal (string_content)))) ``` -------------------------------- ### Kotlin Null-Safe Navigation with Newlines Source: https://github.com/tree-sitter-grammars/tree-sitter-kotlin/blob/master/test/corpus/semi.txt Illustrates Kotlin's null-safe navigation operator (?.) used across multiple lines for property access. The grammar highlights the nested navigation expressions. ```kotlin fun test() { val a = b? .c ?.d } ``` ```tree-sitter-grammar (source_file (function_declaration (identifier) (function_value_parameters) (function_body (block (property_declaration (variable_declaration (identifier)) (navigation_expression (navigation_expression (identifier) (identifier)) (identifier))))))) ``` -------------------------------- ### Parse Kotlin Val and Var Declarations Source: https://github.com/tree-sitter-grammars/tree-sitter-kotlin/blob/master/test/corpus/expressions.txt Illustrates the grammar for parsing Kotlin variable declarations using 'val' (immutable) and 'var' (mutable), including destructuring declarations and custom getters. ```tree-sitter (source_file (property_declaration (variable_declaration (identifier)) (number_literal)) ``` ```tree-sitter (property_declaration (multi_variable_declaration (variable_declaration (identifier)) (variable_declaration (identifier))) (infix_expression (number_literal) (identifier) (number_literal))) ``` ```tree-sitter (property_declaration (user_type (identifier)) (variable_declaration (identifier)) (number_literal)) ``` ```tree-sitter (property_declaration (variable_declaration (identifier) (user_type (identifier))) (getter (function_body (string_literal (string_content)))))) ``` -------------------------------- ### Tree-sitter Grammar for Kotlin Property Declaration Source: https://github.com/tree-sitter-grammars/tree-sitter-kotlin/blob/master/test/corpus/expressions.txt Represents the Tree-sitter grammar structure for a Kotlin property declaration, including type arguments and call expressions. ```tree-sitter-grammar (source_file (property_declaration (variable_declaration (identifier) (user_type (identifier) (type_arguments (type_projection (user_type (identifier)))))) (call_expression (identifier) (value_arguments (value_argument (number_literal)) (value_argument (number_literal)) (value_argument (number_literal))))) ``` -------------------------------- ### Traverse and Print Syntax Tree Nodes Source: https://context7.com/tree-sitter-grammars/tree-sitter-kotlin/llms.txt Recursively traverses a syntax tree node and prints its type and children. Useful for understanding the structure of the parsed code. The function takes a Node object and an indentation level. ```swift // Recursively traverse the tree func printTree(_ node: Node, indent: Int = 0) { let indentStr = String(repeating: " ", count: indent) print("\(indentStr)\(node.nodeType ?? "unknown")") for i in 0.. [String] { var declarations: [String] = [] if node.nodeType == "class_declaration" || node.nodeType == "object_declaration" { if let nameNode = node.childByFieldName("name") { let startIndex = source.index(source.startIndex, offsetBy: Int(nameNode.startByte)) let endIndex = source.index(source.startIndex, offsetBy: Int(nameNode.endByte)) declarations.append(String(source[startIndex.. body } "as_expression", // type casting "is_expression", // type checking "range_expression", // 1..10, 1..<10 ]; ``` -------------------------------- ### Kotlin Types Node Types Source: https://context7.com/tree-sitter-grammars/tree-sitter-kotlin/llms.txt Defines type node types in the Kotlin grammar, including user-defined types, nullable types, function types, and type arguments/parameters. Crucial for analyzing type system information. ```javascript const types = [ "user_type", // User-defined types "nullable_type", // Type? "function_type", // (Int) -> String "type_arguments", // "type_parameters", // Generic parameters ]; ``` -------------------------------- ### Kotlin Modifiers Node Types Source: https://context7.com/tree-sitter-grammars/tree-sitter-kotlin/llms.txt Enumerate modifier node types in the Kotlin grammar, covering visibility, inheritance, class, function, member, and parameter modifiers. Helps in understanding code attributes and behavior. ```javascript const modifiers = [ "visibility_modifier", // public, private, protected, internal "inheritance_modifier", // abstract, final, open "class_modifier", // enum, sealed, annotation, data, inner, value "function_modifier", // tailrec, operator, infix, inline, external, suspend "member_modifier", // override, lateinit "parameter_modifier", // vararg, noinline, crossinline ]; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.