Skip to content

Commit b275e9f

Browse files
committed
feat(kotlin): add companion object support
1 parent 61a83d8 commit b275e9f

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

chapi-ast-kotlin/src/main/kotlin/chapi/ast/kotlinast/KotlinBasicIdentListener.kt

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,17 @@ open class KotlinBasicIdentListener(private val fileName: String) : KotlinAstLis
163163
isEnteredClass.decrementAndGet()
164164
}
165165

166+
override fun enterCompanionObject(ctx: KotlinParser.CompanionObjectContext?) {
167+
val classBody = ctx?.classBody() ?: return
168+
classBody.classMemberDeclarations().classMemberDeclaration().forEach {
169+
val propertyDeclaration = it.declaration()?.propertyDeclaration()
170+
val functionDeclaration = it.declaration()?.functionDeclaration()
171+
172+
if (propertyDeclaration != null) currentNode.Fields += buildField(propertyDeclaration)
173+
if (functionDeclaration != null) currentNode.Functions += buildFunction(functionDeclaration)
174+
}
175+
}
176+
166177
override fun enterPrimaryConstructor(ctx: KotlinParser.PrimaryConstructorContext) {
167178
val parameters = ctx.classParameters().classParameter().map(::buildProperty)
168179
val fields = ctx.classParameters().classParameter().mapNotNull(::buildField)

chapi-ast-kotlin/src/test/kotlin/chapi/ast/kotlinast/KotlinFunctionCallTest.kt

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,26 @@ class KotlinFunctionCallTest {
4141
assert(codeFunction.Name == "foo")
4242
}
4343

44+
@Test
45+
fun should_support_for_companion_object() {
46+
val code = """
47+
class A {
48+
companion object {
49+
fun foo() {
50+
println("Hello, world!")
51+
}
52+
}
53+
}
54+
""".trimIndent()
55+
56+
val codeContainer = KotlinAnalyser().analysis(code, "Test.kt", ParseMode.Full)
57+
val dataStructures = codeContainer.DataStructures.filter { it.NodeName == "A" }
58+
val codeFunction = dataStructures[0].Functions[0]
59+
60+
assert(codeFunction.Name == "foo")
61+
}
62+
63+
4464
@Test
4565
fun should_success_parse_test_usecase() {
4666
val code = """

0 commit comments

Comments
 (0)