### Install dependencies Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/CONTRIBUTING.md Initializes the project environment by installing required Node.js packages. ```bash npm install ``` -------------------------------- ### Install tree-sitter-kotlin for Node.js Source: https://context7.com/fwcd/tree-sitter-kotlin/llms.txt Install the tree-sitter and tree-sitter-kotlin packages using npm for use in JavaScript/Node.js applications. ```bash npm install tree-sitter tree-sitter-kotlin ``` -------------------------------- ### Install Dependencies and Run Tests Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/tools/README.md Install project dependencies, fetch fixtures, generate corpus tests, and run all tree-sitter tests. ```bash npm install npm run vendor-fixtures npm run vendor-jetbrains npm test npm run cross-validate npm run cross-validate:test ``` -------------------------------- ### Kotlin JVM Multifile Package Annotation Example Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/topJvmPackageNameMultifile.txt Example of a Kotlin file using JvmMultifileClass and JvmPackageName annotations. ```kotlin // LIBRARY_PLATFORMS: JVM @file:Suppress("UNCHECKED_CAST", "NOTHING_TO_INLINE", "INVISIBLE_MEMBER", "INVISIBLE_REFERENCE") @file:JvmName("OtherKt") @file:JvmMultifileClass @file:kotlin.jvm.JvmPackageName("some.other.jvm") package some.other @SinceKotlin("1.2") fun foo() {} ``` -------------------------------- ### Install tree-sitter-kotlin for Python Source: https://context7.com/fwcd/tree-sitter-kotlin/llms.txt Install the tree-sitter-kotlin package for Python applications using pip. ```bash pip install tree-sitter-kotlin ``` -------------------------------- ### Tree-Sitter CST for Local Class Example Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/localClass.txt The concrete syntax tree generated by the Tree-Sitter Kotlin grammar for the provided local class example. ```scheme (source_file (line_comment) (package_header (identifier (simple_identifier))) (class_declaration (type_identifier) (class_body (function_declaration (modifiers (visibility_modifier)) (simple_identifier) (function_value_parameters) (function_body (call_expression (simple_identifier) (call_suffix (annotated_lambda (lambda_literal (statements (class_declaration (type_identifier)) (call_expression (simple_identifier) (call_suffix (value_arguments)))))))))) (property_declaration (modifiers (visibility_modifier)) (binding_pattern_kind) (variable_declaration (simple_identifier)) (object_literal (class_body))) (property_declaration (modifiers (visibility_modifier)) (binding_pattern_kind) (variable_declaration (simple_identifier)) (call_expression (simple_identifier) (call_suffix (annotated_lambda (lambda_literal))))) (property_declaration (modifiers (visibility_modifier)) (binding_pattern_kind) (variable_declaration (simple_identifier)) (object_literal (delegation_specifier (user_type (type_identifier))) (class_body (function_declaration (modifiers (member_modifier)) (simple_identifier) (function_value_parameters) (function_body)))))))) ``` -------------------------------- ### Kotlin JvmPackageName Annotation Example Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/topJvmPackageName.txt Demonstrates the use of the JvmPackageName file-level annotation in Kotlin. ```kotlin // LIBRARY_PLATFORMS: JVM @file:Suppress("UNCHECKED_CAST", "NOTHING_TO_INLINE", "INVISIBLE_MEMBER", "INVISIBLE_REFERENCE") @file:JvmName("OtherKt") @file:kotlin.jvm.JvmPackageName("some.other.jvm") package some.other @SinceKotlin("1.2") fun foo() {} ``` -------------------------------- ### Kotlin AST Structure Example Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/EOLsOnRollback.txt This example shows the Abstract Syntax Tree (AST) structure for a Kotlin source file, including comments, function declarations, class declarations, type aliases, and property declarations. This is useful for understanding how the parser represents code. ```tree-sitter-query (source_file (line_comment) (function_declaration (simple_identifier) (function_value_parameters) (function_body (statements (class_declaration (type_identifier)) (function_declaration (simple_identifier) (function_value_parameters)) (class_declaration (type_identifier)) (type_alias (type_identifier) (user_type (type_identifier))) (property_declaration (binding_pattern_kind) (variable_declaration (simple_identifier))) (property_declaration (modifiers (annotation (user_type (type_identifier)))) (binding_pattern_kind) (variable_declaration (simple_identifier)) (integer_literal)) (integer_literal) (property_declaration (modifiers (annotation (user_type (type_identifier)))) (binding_pattern_kind) (variable_declaration (simple_identifier)))))) ``` -------------------------------- ### Kotlin Line Comment Example Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/LineCommentForFirstDeclaration.txt Demonstrates a simple line comment in Kotlin. This syntax is recognized by the parser. ```kotlin // This is foo fun foo() {} ``` -------------------------------- ### Fetch JetBrains Fixtures Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/README.md Download the JetBrains PSI test fixtures. This is a one-time setup or can be run to update fixtures. ```bash npm run vendor-fixtures ``` -------------------------------- ### Kotlin Destructuring Lambda Examples Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/destructuringInLambdas.txt Examples of various destructuring patterns within lambda parameters in Kotlin. ```kotlin // COMPILATION_ERRORS fun foo() { a1.filter { (x, y) -> } a2.filter { (x) -> } a3.filter { z, (x, y) -> } a4.filter { (x, y), z -> } a5.filter { q, (x, y), z -> } a6.filter { (x, y), (z, w) -> } a7.filter { (x, y): Type, (z: Type), (w, u: T) : V -> foo7() } } ``` -------------------------------- ### Run Project Tests Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/README.md Execute this command to run all project tests. Ensure Node.js 18+ is installed. ```bash npm test ``` -------------------------------- ### Kotlin Class Delegation Example Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/delegation.txt Demonstrates the use of the 'by' keyword to delegate interface implementation to a class instance. ```kotlin interface T { fun f() val g: Int } class A() : T { override val g = 3 override fun f() { } } class Delegation(val c: Int = 3, a: A) : T by a { fun ff(): Int = 3 } ``` -------------------------------- ### Kotlin Repeatable Annotation Example Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/repeatableAnnotation.txt Demonstrates the usage of repeatable annotations on classes in Kotlin. ```kotlin class RepeatableAnnotation { @MyRepeatableAnnotation(1) class ClassWithOneRepeatableAnnotation @MyRepeatableAnnotation(1) @MyRepeatableAnnotation(2) class ClassWithTwoRepeatableAnnotations @MyRepeatableAnnotation(1) @MyRepeatableAnnotation(2) @MyRepeatableAnnotation(3) class ClassWithThreeRepeatableAnnotations } @Repeatable annotation class MyRepeatableAnnotation(val index: Int) ``` -------------------------------- ### Build WebAssembly Target Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/README.md Compile the grammar to WebAssembly using Emscripten. Ensure Emscripten is installed (e.g., via Homebrew). ```bash npm run build-wasm ``` -------------------------------- ### Kotlin Object Declaration Example Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/objects.txt A sample Kotlin file containing nested objects and class definitions. ```kotlin public object Objects { val c = 0 fun f() { } fun g() = 1 private object InnerObject : A { val c = 0 fun f() { } } public object OtherObject : NestedClass() { val c = 0 fun f() { } } public open class NestedClass } interface A { } ``` -------------------------------- ### Kotlin Import Syntax Examples Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/Imports.txt Demonstrates various ways to import classes, functions, and objects in Kotlin, including aliasing and wildcard imports. Ensure correct package and identifier structure for valid imports. ```kotlin // COMPILATION_ERRORS package foo.bar.goo import foo import foo.bar import foo as bar import foo.bar as bar import foo.* import foo. * ``` -------------------------------- ### Integer Literals Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/literals.txt Examples of various integer literals in Kotlin, including decimal representations. ```kotlin 0 ``` ```kotlin 8 ``` ```kotlin 23 ``` ```kotlin 9847 ``` -------------------------------- ### Kotlin Class Members Example Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/classMembers.txt A sample Kotlin class demonstrating various modifiers, properties, and function declarations. ```kotlin package test abstract class ClassMembers(private val p: Int, public open var p2: String, p3: Int, p4: Int = 10, final val p5: String = "aaa") { val foo = 3 fun bar(): Int { return 3 } open fun openFun() { } abstract fun abstractFun() open val openVal = 3 abstract var abstractVar: Int } ``` -------------------------------- ### Kotlin Underscored Type Arguments Examples Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/UnderscoredTypeArgumentsOfType.txt Illustrates various ways to use underscored type arguments in Kotlin function calls and type declarations. Note that some examples may lead to compilation errors. ```kotlin fun main() { val x = foo>() val x = foo>() val x = foo, Int>() val x = foo>() val x = foo, Float>, Float>() val y: Foo<_> = 1 val y: Foo<_, _> = 1 } interface A : Foo<_> typealias Foo = Foo<_, K> ``` -------------------------------- ### Kotlin AST Structure Example Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/HangOnLonelyModifier.txt Illustrates the Abstract Syntax Tree (AST) structure for a simple Kotlin source file. This representation is useful for understanding how the parser interprets code. ```tree-sitter (source_file (line_comment) (function_declaration (simple_identifier) (function_value_parameters) (function_body (statements (simple_identifier))))) ``` -------------------------------- ### Binary Literals Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/literals.txt Examples of binary literals in Kotlin, represented using the `0b` prefix. ```kotlin 0b0 ``` ```kotlin 0b1 ``` ```kotlin 0b11 ``` ```kotlin 0b111 ``` -------------------------------- ### Import tree-sitter-kotlin Go module Source: https://context7.com/fwcd/tree-sitter-kotlin/llms.txt Import the Go bindings module for tree-sitter-kotlin into your Go project using go get. ```bash go get github.com/fwcd/tree-sitter-kotlin ``` -------------------------------- ### Kotlin Class Object Structure Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/classObject.txt Example of nested companion objects and class declarations in Kotlin. ```kotlin package test.class_object class ClassObject { fun f() { } val c = 1 public companion object { val j = 0 fun z() = 0 class A { class B { val i: Int = 0 fun f() = 0 } } } class B { companion object { class C { companion object { class D { companion object { val i = 3 fun f() { } enum class En annotation class Anno } } } } } } } ``` -------------------------------- ### Tree-sitter Parse Tree for JVM Multifile Example Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/topJvmPackageNameMultifile.txt The resulting Tree-sitter S-expression representation for the provided Kotlin source code. ```scheme (source_file (line_comment) (file_annotation (constructor_invocation (user_type (type_identifier)) (value_arguments (value_argument (string_literal (string_content))) (value_argument (string_literal (string_content))) (value_argument (string_literal (string_content))) (value_argument (string_literal (string_content)))))) (file_annotation (constructor_invocation (user_type (type_identifier)) (value_arguments (value_argument (string_literal (string_content)))))) (file_annotation (user_type (type_identifier))) (file_annotation (constructor_invocation (user_type (type_identifier) (type_identifier) (type_identifier)) (value_arguments (value_argument (string_literal (string_content)))))) (package_header (identifier (simple_identifier) (simple_identifier))) (function_declaration (modifiers (annotation (constructor_invocation (user_type (type_identifier)) (value_arguments (value_argument (string_literal (string_content))))))) (simple_identifier) (function_value_parameters) (function_body))) ``` -------------------------------- ### Kotlin NotIs and NotIn Syntax Examples Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/NotIsAndNotIn.txt Demonstrates the syntax for !is and !in operators in Kotlin, noting that these are expected to produce compilation errors in this context. ```kotlin // COMPILATION_ERRORS fun test() { a !is B a !in B !isBoolean(a) !inRange(a) } ``` -------------------------------- ### Build WebAssembly Parser for Browser Source: https://context7.com/fwcd/tree-sitter-kotlin/llms.txt Compiles the Tree-sitter Kotlin grammar to WebAssembly for use in browser-based applications. Requires Emscripten to be installed. ```bash # Requires Emscripten installed # On macOS: brew install emscripten # Build the WASM version npm run build-wasm # Start the interactive playground npm run playground # The playground opens in your browser at http://localhost:8000 # You can paste Kotlin code and see the live syntax tree ``` -------------------------------- ### Kotlin Package Directive and Function Declaration Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/DocCommentOnPackageDirectiveLine.txt Illustrates a basic Kotlin file structure with a package directive and a simple function declaration. This serves as a fundamental example for parsing Kotlin source code. ```kotlin package p1.p2;/** some */ fun foo(){} ``` ```tree-sitter-kotlin (source_file (package_header (identifier (simple_identifier) (simple_identifier))) (multiline_comment) (function_declaration (simple_identifier) (function_value_parameters) (function_body))) ``` -------------------------------- ### Kotlin ModifierAsSelector Example Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/ModifierAsSelector.txt A simple Kotlin snippet demonstrating property declaration and function call. ```kotlin // LIBRARY_PLATFORMS: JVM // JET-1 val z = System.out fun foo() { throw Exception(); } ``` -------------------------------- ### Kotlin Anonymous Initializer Syntax Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/AnonymousInitializer.txt Example of an anonymous initializer block within a class declaration. ```kotlin // COMPILATION_ERRORS class Foo { init { foo() val c = f } } ``` -------------------------------- ### Use Highlighting Queries in Python Source: https://context7.com/fwcd/tree-sitter-kotlin/llms.txt Loads syntax highlighting queries and executes them against a parsed Kotlin code tree to identify specific code elements like function names, constants, and annotations. Ensure the tree-sitter-kotlin library and Tree-sitter are installed. ```python import tree_sitter_kotlin as ts_kotlin from tree_sitter import Language, Parser, Query KOTLIN_LANGUAGE = Language(ts_kotlin.language()) parser = Parser(KOTLIN_LANGUAGE) code = b""" @Deprecated("Use newMethod instead") fun oldMethod(): Int { val result = 42 return result } class MyClass { companion object { const val CONSTANT = "value" } } """ tree = parser.parse(code) # Load the highlights query highlights_query = ts_kotlin.HIGHLIGHTS_QUERY # Create a query for function names and constants query = KOTLIN_LANGUAGE.query(""" (function_declaration (simple_identifier) @function.name) (property_declaration (variable_declaration (simple_identifier) @constant.name)) (annotation (user_type (type_identifier) @annotation.name)) """) # Execute the query captures = query.captures(tree.root_node) for node, capture_name in captures: print(f"{capture_name}: {node.text.decode()} at line {node.start_point[0] + 1}") # Output: # annotation.name: Deprecated at line 1 # function.name: oldMethod at line 2 # constant.name: CONSTANT at line 9 ``` -------------------------------- ### Generate Tree-sitter Kotlin Parser Source: https://context7.com/fwcd/tree-sitter-kotlin/llms.txt Installs dependencies and generates the Tree-sitter parser implementation from the grammar.js file. This process creates essential parser files. ```bash # Install dependencies npm install # Generate the parser from grammar.js npm run generate # This creates: # - src/parser.c (the parser implementation) # - src/node-types.json (node type information) # - src/grammar.json (serialized grammar) ``` -------------------------------- ### Kotlin Source and S-expression Tree Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/LineCommentAfterFileAnnotations.txt Example of a Kotlin file with a line comment after a file annotation and its resulting tree-sitter parse tree. ```kotlin @file:[Volatile] // class C class C{} ``` ```scheme (source_file (line_comment) (file_annotation (user_type (type_identifier))) (line_comment) (class_declaration (type_identifier) (class_body))) ``` -------------------------------- ### Tree-sitter Parse Tree for Delegation Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/delegation.txt The concrete syntax tree generated by the Tree-sitter Kotlin grammar for the provided delegation example. ```scheme (source_file (class_declaration (type_identifier) (class_body (function_declaration (simple_identifier) (function_value_parameters)) (property_declaration (binding_pattern_kind) (variable_declaration (simple_identifier) (user_type (type_identifier)))))) (class_declaration (type_identifier) (primary_constructor) (delegation_specifier (user_type (type_identifier))) (class_body (property_declaration (modifiers (member_modifier)) (binding_pattern_kind) (variable_declaration (simple_identifier)) (integer_literal)) (function_declaration (modifiers (member_modifier)) (simple_identifier) (function_value_parameters) (function_body)))) (class_declaration (type_identifier) (primary_constructor (class_parameter (binding_pattern_kind) (simple_identifier) (user_type (type_identifier)) (integer_literal)) (class_parameter (simple_identifier) (user_type (type_identifier)))) (delegation_specifier (explicit_delegation (user_type (type_identifier)) (simple_identifier))) (class_body (function_declaration (simple_identifier) (function_value_parameters) (user_type (type_identifier)) (function_body (integer_literal)))))) ``` -------------------------------- ### Tree-sitter Parse Tree for TypeAlias Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/TypeAlias.txt The concrete syntax tree representation of the provided Kotlin typealias examples. ```lisp (source_file (line_comment) (package_header (identifier (simple_identifier) (simple_identifier) (simple_identifier))) (type_alias (type_identifier) (user_type (type_identifier))) (type_alias (type_identifier) (type_parameters (type_parameter (type_identifier))) (user_type (type_identifier))) (type_alias (type_identifier) (type_parameters (type_parameter (type_identifier) (user_type (type_identifier)))) (user_type (type_identifier))) (type_alias (type_identifier) (type_parameters (type_parameter (type_identifier)) (type_parameter (type_identifier))) (user_type (type_identifier))) (type_alias (type_identifier) (type_parameters (type_parameter (type_identifier)) (type_parameter (type_identifier) (user_type (type_identifier)))) (user_type (type_identifier))) (type_alias (type_identifier) (user_type (type_identifier))) (type_alias (type_identifier) (type_parameters (type_parameter (type_identifier))) (user_type (type_identifier))) (type_alias (type_identifier) (type_parameters (type_parameter (type_identifier) (user_type (type_identifier)))) (user_type (type_identifier))) (type_alias (type_identifier) (type_parameters (type_parameter (type_identifier)) (type_parameter (type_identifier))) (user_type (type_identifier))) (type_alias (type_identifier) (type_parameters (type_parameter (type_identifier)) (type_parameter (type_identifier) (user_type (type_identifier)))) (user_type (type_identifier)))) ``` -------------------------------- ### Kotlin Internal Constant Declaration Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/internalConst.txt Demonstrates the declaration of an internal constant in Kotlin. This is a basic example of a top-level constant. ```kotlin internal const val FOO = 3.14 + FOO2 ``` -------------------------------- ### Kotlin Dynamic Receiver Syntax Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/DynamicReceiver.txt Examples of function and property declarations using the dynamic receiver type in Kotlin. ```kotlin // COMPILATION_ERRORS fun dynamic.foo() fun dynamic?.foo() val dynamic.foo: Int val dynamic?.foo: Int val foo: dynamic.() -> Unit // testing look-ahead with comments and whitespace fun dynamic . foo() fun dynamic .foo() fun dynamic// line-comment .foo() fun dynamic/* */.foo() ``` -------------------------------- ### Kotlin Local Class and Object Expression Example Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/localClass.txt Demonstrates various ways to define local classes, anonymous objects, and SAM conversions within a Kotlin class. ```kotlin // LIBRARY_PLATFORMS: JVM package test class LocalClass { private fun foo() = run { class Local Local() } private val bar = object {} private val sam = Runnable {} private val sub = object : Runnable { override fun run() { } } } ``` -------------------------------- ### Kotlin Underscored Type Arguments Example Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/UnderscoredTypeArgumentsOfCall.txt Kotlin code snippet demonstrating the use of underscores in generic type arguments. ```kotlin // COMPILATION_ERRORS fun main() { val x = foo() val x = foo<_, _, _>() val x = foo<_, _, Int>() val x = foo<_>() } ``` -------------------------------- ### Kotlin Floating-Point Literal Examples Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/FloatingPointLiteral.txt A collection of various floating-point literal formats in Kotlin, including scientific notation and underscores. ```kotlin val array = array( 1, 1.0, 1e1, 1.0e1, 1e-1, 1.0e-1, 1F, 1.0F, 1e1F, 1.0e1F, 1e-1F, 1.0e-1F, 1f, 1.0f, 1e1f, 1.0e1f, 1e-1f, 1.0e-1f, .1_1, 3.141_592, 1e1__3_7, 1_0f, 1e1_2f, 2_2.0f, .3_3f, 3.14_16f, 6.022___137e+2_3f ) ``` -------------------------------- ### Kotlin Property Accessor Syntax Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/propertyAccessors.txt Examples of property declarations with private setters, explicit public getters, and inline properties. ```kotlin var privateSetter = 0 private set private var privateVarPrivateSetter = 1 private set val explicitPublicGetter = 2 public get inline val inlineProperty get() = 3 ``` -------------------------------- ### Kotlin Interface Constructor Syntax Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/TraitConstructor.txt Example of interface declarations with and without primary constructors, which are invalid in standard Kotlin. ```kotlin // COMPILATION_ERRORS interface TestTrait(val a: Int, var b: String, c: Double) interface TestTrait() ``` -------------------------------- ### Parse get after newline Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/newlines.txt Illustrates the getter structure within a property declaration when the get keyword is on a new line. ```kotlin class Foo { val maxMemory: Long get() = bar() / 1024 } ``` ```scheme (source_file (class_declaration (type_identifier) (class_body (property_declaration (binding_pattern_kind) (variable_declaration (simple_identifier) (user_type (type_identifier))) (getter (function_body (multiplicative_expression (call_expression (simple_identifier) (call_suffix (value_arguments))) (integer_literal))))))) ``` -------------------------------- ### Run Unit Tests Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/README.md This command executes the project's unit tests, including those generated from JetBrains fixtures. ```bash npm run test ``` -------------------------------- ### Kotlin Underscored Type Parameters Examples Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/UnderscoredTypeParameters.txt Examples of class, typealias, and function declarations using underscored type parameters that result in compilation errors. ```kotlin // COMPILATION_ERRORS class A<_> {} typealias Foo = Foo fun foo() {} fun foo() {} ``` ```scheme (source_file (line_comment) (class_declaration (type_identifier) (type_parameters (type_parameter (type_identifier))) (class_body)) (type_alias (type_identifier) (type_parameters (type_parameter (type_identifier)) (type_parameter (type_identifier))) (user_type (type_identifier) (type_arguments (type_projection (user_type (type_identifier)))))) (function_declaration (type_parameters (type_parameter (type_identifier) (user_type (type_identifier))) (type_parameter (type_identifier)) (type_parameter (type_identifier))) (simple_identifier) (function_value_parameters) (function_body)) (function_declaration (type_parameters (type_parameter (type_identifier)) (type_parameter (type_identifier) (user_type (type_identifier)))) (simple_identifier) (function_value_parameters) (function_body))) ``` -------------------------------- ### Traverse Kotlin Syntax Tree in Node.js Source: https://context7.com/fwcd/tree-sitter-kotlin/llms.txt Navigate the parsed syntax tree to find function and class declarations in Node.js. This example demonstrates how to extract names, line numbers, and data class status. ```javascript const Parser = require('tree-sitter'); const Kotlin = require('tree-sitter-kotlin'); const parser = new Parser(); parser.setLanguage(Kotlin); const sourceCode = ` data class User(val name: String, val age: Int) fun main() { val user = User("Alice", 30) println(user.name) } `; const tree = parser.parse(sourceCode); // Find all function declarations function findFunctions(node) { const functions = []; if (node.type === 'function_declaration') { const nameNode = node.childForFieldName('name') || node.children.find(c => c.type === 'simple_identifier'); if (nameNode) { functions.push({ name: nameNode.text, startLine: node.startPosition.row + 1, endLine: node.endPosition.row + 1 }); } } for (const child of node.children) { functions.push(...findFunctions(child)); } return functions; } // Find all class declarations function findClasses(node) { const classes = []; if (node.type === 'class_declaration') { const nameNode = node.children.find(c => c.type === 'type_identifier'); if (nameNode) { classes.push({ name: nameNode.text, startLine: node.startPosition.row + 1, isDataClass: node.children.some(c => c.type === 'modifiers' && c.text.includes('data')) }); } } for (const child of node.children) { classes.push(...findClasses(child)); } return classes; } console.log('Functions:', findFunctions(tree.rootNode)); // Output: Functions: [{ name: 'main', startLine: 4, endLine: 7 }] console.log('Classes:', findClasses(tree.rootNode)); // Output: Classes: [{ name: 'User', startLine: 2, isDataClass: true }] ``` -------------------------------- ### Kotlin Type Modifiers Examples Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/TypeModifiers.txt Demonstrates various type modifiers like 'suspend', annotations, and variance in Kotlin. These examples illustrate how these modifiers can be applied to different type constructs. ```kotlin val p1: suspend a ``` ```kotlin val p2: suspend (a) -> a ``` ```kotlin val p3: suspend (a) -> suspend a ``` ```kotlin val p4: suspend a.() -> a ``` ```kotlin val p4a: @a a.() -> a ``` ```kotlin val p5: (suspend a).() -> a ``` ```kotlin val p5a: (@a a).() -> a ``` ```kotlin val p6: a ``` ```kotlin val p7: a ``` ```kotlin val p8: a ``` ```kotlin val p9: a ``` ```kotlin val p10: suspend a ``` ```kotlin val p11: suspend @a a ``` ```kotlin val p12: @a suspend a ``` ```kotlin val p13: @a suspend @a a ``` ```kotlin val p14: @[a] suspend @[a] a ``` ```kotlin val p15: suspend (suspend (() -> Unit)) -> Unit ``` ```kotlin @a fun @a a.f1() {} ``` ```kotlin fun (@a a.(a) -> a).f2() {} ``` -------------------------------- ### Launch Interactive Playground Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/README.md Launch an interactive editing environment in the browser after compiling the grammar to WebAssembly. This allows you to see the parsed syntax tree on-the-fly. ```bash npm run playground ``` -------------------------------- ### Kotlin Generic Function Calls with Type Arguments Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/expressions.txt Provides examples of calling generic functions with type arguments, including different numbers of value arguments. ```kotlin foo(1,2) foo(1) ``` -------------------------------- ### Kotlin File with Annotation and Doc Comment Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/DocCommentAfterFileAnnotations.txt Demonstrates a Kotlin file with a file-level annotation and a documentation comment preceding a class declaration. Requires the Volatile annotation to be available. ```kotlin @file:[Volatile] /** * Doc comment */ class C{} ``` -------------------------------- ### Kotlin Interface Declaration Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/Interface.txt Example of an interface definition containing a function and a property. ```kotlin // COMPILATION_ERRORS interface Foo { fun f() val a } ``` -------------------------------- ### Class with Annotations Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/annotations.txt Demonstrates applying annotations to a class, its primary constructor, properties, and methods. Includes custom annotations like '@a' and '@b'. ```kotlin @a public class Annotations private @a constructor(private @property:a @param:a val c1: Int, @property:a @param:a val c2: Int) { @a() val hasValueArguments = 42 protected @a fun f() { } inline fun inlineFun() { } private fun annotationWithVararg(@a vararg i: Int) {} @b(E.E1) private val c: Int = 1 @a @b(E.E2) public fun g(@a p1: E) { } var withCustomAccessors: Int = 0 //TODO: accessor modifiers are lost @a get @a private set private @b(E.E2) companion object { @f val field = 42 } class Nested @a private @b(E.E1) @b(E.E2) constructor() enum class En { Entry1, @a @b(E.E2) Entry2, @a @c Entry3 } fun types(param: @a @b(E.E1) LongRange): @a @b(E.E2) Unit {} fun @receiver:a Int.foo() {} val @receiver:a Int.receiverField: String? get() = null @get: a val getterField : String? = null @set: a var setterField : String? = null @field: a val ownField : String? = null @setparam:a var setParam: String? = null @delegate:a val deleage by lazy { 12 } class ClassWithConstructor(@param: a val b: Int) } ``` -------------------------------- ### Kotlin When expression with mixed entries Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/expressions.txt Example of a when expression containing both guarded and unguarded entries. ```kotlin when (animal) { is Dog if animal.isHungry -> feedDog() is Cat -> petCat() else -> ignore() } ``` -------------------------------- ### Kotlin When expression with guard condition Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/expressions.txt Example of a when expression using a conjunction in a guard condition. ```kotlin when (animal) { is Animal.Cat if !animal.mouseHunter && animal.hungry -> feedCat() else -> doDefault() } ``` -------------------------------- ### Kotlin Compilation Error Example Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/HangOnLonelyModifier.txt Demonstrates a common compilation error in Kotlin due to incomplete syntax within a function body. This snippet highlights the need for proper statement completion. ```kotlin // COMPILATION_ERRORS fun test() { in } ``` -------------------------------- ### Parse file annotations Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/source-files.txt Demonstrates the syntax tree structure for a file-level annotation and a property declaration. ```kotlin @file:JvmName("HelloWorld") val x = 4 ``` ```tree-sitter (source_file (file_annotation (constructor_invocation (user_type (type_identifier)) (value_arguments (value_argument (string_literal (string_content)))))) (property_declaration (binding_pattern_kind) (variable_declaration (simple_identifier)) (integer_literal))) ``` -------------------------------- ### Type Constructor Usage Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/types.txt Shows how to use a type constructor with named arguments. ```Kotlin a as Foo(x = "hi", y = "bar") ``` -------------------------------- ### Kotlin Functional Interface Declaration Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/funInterfaceDeclaration.txt Example of defining functional interfaces with and without generics in Kotlin. ```kotlin package test class FunInterfaceDeclaration { @Suppress("UNSUPPORTED_FEATURE") fun interface KRunnable { fun invoke() } @Suppress("UNSUPPORTED_FEATURE") fun interface GenericKRunnable { fun invoke(t: T): R } } ``` -------------------------------- ### Parse import followed by comment and class Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/source-files.txt Demonstrates the inclusion of multiline comments and class declarations in the syntax tree. ```kotlin import foo.bar /** * Documentation */ class MyClass ``` ```tree-sitter (source_file (import_list (import_header (identifier (simple_identifier) (simple_identifier)))) (multiline_comment) (class_declaration (type_identifier))) ``` -------------------------------- ### Inheritance patterns Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/classes.txt Demonstrates various class inheritance and delegation specifier patterns. ```kotlin class A : B() {} class C(param: Int) : D(param) class D : SomeInterface ``` ```scheme (source_file (class_declaration (type_identifier) (delegation_specifier (constructor_invocation (user_type (type_identifier)) (value_arguments))) (class_body)) (class_declaration (type_identifier) (primary_constructor (class_parameter (simple_identifier) (user_type (type_identifier)))) (delegation_specifier (constructor_invocation (user_type (type_identifier)) (value_arguments (value_argument (simple_identifier)))))) (class_declaration (type_identifier) (delegation_specifier (user_type (type_identifier))))) ``` -------------------------------- ### Fetch JetBrains Kotlin PSI Test Fixtures Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/tools/README.md Fetches JetBrains Kotlin PSI test fixtures using a sparse checkout. It reads a pinned commit hash from `.fixtures-version`, clones the specified directory from the JetBrains/kotlin repository, and copies relevant files. The `.fixtures-version` file is tracked for reproducible builds. ```bash npm run vendor-fixtures ``` ```bash npm run vendor-fixtures -- ``` -------------------------------- ### Kotlin Nested Class Structure Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/nestedClasses.txt Example of nested and inner classes with generic type parameters in Kotlin. ```kotlin package test class NestedClasses { fun f() { } val c: Int = 0 private class Nested { fun f(p1: TN) { } val c = 1 public class NN { fun f(p1: TNN) { } val c = 1 } inner class NI { fun f(p1: TN, p2: TNI) { } } } public inner class Inner { fun f(p1: TI) { } private inner class II { fun f(p1: TII, p2: II>, p3: TOuter) { } } } } ``` -------------------------------- ### Define Empty Enum in Kotlin Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/emptyEnum.txt Example of an empty enum declaration in Kotlin, which can still contain methods. ```kotlin enum class EmptyEnum { ; fun foo() = 0 } ``` -------------------------------- ### Kotlin Class with Doc Comments Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/DocCommentsBinding.txt Demonstrates doc comments for a class, its primary constructor parameter, a function, and a property with getter and setter. ```kotlin /** * Doc comment for A */ // some comment class A( /** * Doc comment for val-parameter */ /*var*/val p: Int ) { /** * Doc comment for function */ fun foo() { /** * Doc comment for local function */ fun localFoo() { } /** * Doc comment for local class */ class LocalClass } /** * Doc comment for property */ var property: Int /** Doc comment for getter */ get() = 1 /** Doc comment for setter */ set(value) {} } /** * Doc comment for B */ class B { } ``` -------------------------------- ### Kotlin Const Property Declaration Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/const.txt Example of a private const property defined within a Kotlin object. ```kotlin package test object Const { const private val inObject = 1 } ``` -------------------------------- ### Tree-sitter parse tree for when expression Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/WhenWithSubjectVariable_SoftModifierName.txt The expected parse tree structure for the provided Kotlin when expression example. ```scheme (source_file (line_comment) (function_declaration (simple_identifier) (function_value_parameters) (function_body (statements (when_expression (when_subject (simple_identifier))) (when_expression (when_subject (simple_identifier))) (when_expression (when_subject (simple_identifier))) (when_expression (when_subject (simple_identifier))) (when_expression (when_subject (simple_identifier))) (when_expression (when_subject (simple_identifier))) (when_expression (when_subject (simple_identifier))) (when_expression (when_subject (simple_identifier))) (when_expression (when_subject (simple_identifier))) (when_expression (when_subject (simple_identifier))) (line_comment) (when_expression (when_subject (simple_identifier))) (when_expression (when_subject (simple_identifier))) (when_expression (when_subject (simple_identifier))) (when_expression (when_subject (simple_identifier))) (when_expression (when_subject (simple_identifier))) (when_expression (when_subject (simple_identifier))) (when_expression (when_subject (simple_identifier))) (when_expression (when_subject (simple_identifier))) (when_expression (when_subject (simple_identifier))) (when_expression (when_subject (simple_identifier))) (when_expression (when_subject (simple_identifier))) (when_expression (when_subject (simple_identifier))) (when_expression (when_subject (simple_identifier))) (when_expression (when_subject (simple_identifier))) (when_expression (when_subject (simple_identifier))) (when_expression (when_subject (simple_identifier))) (when_expression (when_subject (simple_identifier))))))) ``` -------------------------------- ### Parse Kotlin Files Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/README.md Use the tree-sitter CLI to parse Kotlin source files, with options for quiet output and statistics. ```shell ./node_modules/.bin/tree-sitter parse "/path/to/some/project/**/*.kt" --quiet --stat ``` -------------------------------- ### Tree-sitter S-expression Representation Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/DynamicReceiver.txt The corresponding Tree-sitter parse tree for the provided Kotlin dynamic receiver examples. ```scheme (source_file (line_comment) (function_declaration receiver: (receiver_type) (simple_identifier) (function_value_parameters)) (function_declaration receiver: (receiver_type (nullable_type (quest))) (simple_identifier) (function_value_parameters)) (property_declaration (binding_pattern_kind) receiver: (receiver_type) (variable_declaration (simple_identifier) (user_type (type_identifier)))) (property_declaration (binding_pattern_kind) receiver: (receiver_type (nullable_type (quest))) (variable_declaration (simple_identifier) (user_type (type_identifier)))) (property_declaration (binding_pattern_kind) (variable_declaration (simple_identifier) (function_type receiver: (receiver_type) (function_type_parameters) (user_type (type_identifier))))) (line_comment) (function_declaration receiver: (receiver_type) (simple_identifier) (function_value_parameters)) (function_declaration receiver: (receiver_type) (simple_identifier) (function_value_parameters)) (function_declaration receiver: (receiver_type) (line_comment) (simple_identifier) (function_value_parameters)) (function_declaration receiver: (receiver_type) (multiline_comment) (simple_identifier) (function_value_parameters))) ``` -------------------------------- ### Parse multiple file annotations Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/source-files.txt Shows how multiple file-level annotations are represented in the syntax tree. ```kotlin @file:JvmMultifileClass @file:JvmName("BuildersKt") @file:OptIn(ExperimentalContracts::class) ``` ```tree-sitter (source_file (file_annotation (user_type (type_identifier))) (file_annotation (constructor_invocation (user_type (type_identifier)) (value_arguments (value_argument (string_literal (string_content)))))) (file_annotation (constructor_invocation (user_type (type_identifier)) (value_arguments (value_argument (callable_reference (type_identifier))))))) ``` -------------------------------- ### Parse if-expression with newline Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/newlines.txt Shows the parse tree for an if-expression where the else branch starts on a new line. ```kotlin if (!foo) 3 else boo() ``` ```text (source_file (if_expression condition: (prefix_expression (simple_identifier)) consequence: (control_structure_body (integer_literal)) alternative: (control_structure_body (call_expression (simple_identifier) (call_suffix (value_arguments)))))) ``` -------------------------------- ### Kotlin Type Modifiers Example Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/typeModifiers2.txt Demonstrates various function type declarations including suspend and extension functions. ```kotlin public class TypeModifiers { val function: () -> Unit = null!! val suspendFunction: suspend () -> Unit = null!! val suspendExtFunction: suspend Any.() -> Unit = null!! val functionOnSuspendFunction: (suspend () -> Unit).() -> Unit = null!! } ``` -------------------------------- ### Kotlin Sealed Class Definition Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/jetbrains/sealed.txt A basic example of a sealed class containing a nested class and a top-level object. ```kotlin package test sealed class Sealed { class Nested: Sealed() object Top: Sealed() } ``` -------------------------------- ### Parse Constructor Delegation Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/classes.txt Shows the syntax tree for a class with a primary constructor and a secondary constructor using delegation. ```kotlin class Test(x: Int, y: Int) { constructor() : this(0, 0) } ``` ```lisp (source_file (class_declaration (type_identifier) (primary_constructor (class_parameter (simple_identifier) (user_type (type_identifier))) (class_parameter (simple_identifier) (user_type (type_identifier)))) (class_body (secondary_constructor (function_value_parameters) (constructor_delegation_call (value_arguments (value_argument (integer_literal)) (value_argument (integer_literal)))))))) ``` -------------------------------- ### Parse Kotlin Files with Tree-sitter CLI Source: https://context7.com/fwcd/tree-sitter-kotlin/llms.txt Utilizes the Tree-sitter CLI to parse Kotlin files, display syntax trees, and show parsing statistics. Supports glob patterns for multiple files and quiet mode. ```bash # Parse a single file and print the syntax tree npx tree-sitter parse examples/Logger.kt # Parse with quiet mode (only show errors) npx tree-sitter parse path/to/file.kt --quiet # Parse multiple files and get statistics npx tree-sitter parse "/path/to/project/**/*.kt" --quiet --stat # Example output: # Total: 150 files, 148 succeeded, 2 failed, 98.67% success rate # Highlight a file with syntax highlighting npx tree-sitter highlight examples/Logger.kt ``` -------------------------------- ### Parse lambda expressions with parameters Source: https://github.com/fwcd/tree-sitter-kotlin/blob/main/test/corpus/expressions.txt Illustrates the structure of a lambda expression with multi-variable declaration parameters. ```kotlin foo.forEach { (index, value) -> 2 } ``` ```text (source_file (call_expression (navigation_expression (simple_identifier) (navigation_suffix (simple_identifier))) (call_suffix (annotated_lambda (lambda_literal (lambda_parameters (multi_variable_declaration (variable_declaration (simple_identifier)) (variable_declaration (simple_identifier)))) (statements (integer_literal))))))) ```