Skip to content

Commit 1c0494e

Browse files
committed
Extract a no-arg constuctor whenever a Kotlin class has default values for all parameters
1 parent edfcc0c commit 1c0494e

File tree

4 files changed

+17
-3
lines changed

4 files changed

+17
-3
lines changed

java/kotlin-extractor/src/main/kotlin/KotlinFileExtractor.kt

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1049,8 +1049,6 @@ open class KotlinFileExtractor(
10491049
private val jvmOverloadsFqName = FqName("kotlin.jvm.JvmOverloads")
10501050

10511051
private fun extractGeneratedOverloads(f: IrFunction, parentId: Label<out DbReftype>, maybeSourceParentId: Label<out DbReftype>?, extractBody: Boolean, extractMethodAndParameterTypeAccesses: Boolean, typeSubstitution: TypeSubstitution?, classTypeArgsIncludingOuterClasses: List<IrTypeArgument>?) {
1052-
if (!f.hasAnnotation(jvmOverloadsFqName))
1053-
return
10541052

10551053
fun extractGeneratedOverload(paramList: List<IrValueParameter?>) {
10561054
val overloadParameters = paramList.filterNotNull()
@@ -1096,6 +1094,15 @@ open class KotlinFileExtractor(
10961094
}
10971095
}
10981096

1097+
if (!f.hasAnnotation(jvmOverloadsFqName)) {
1098+
if (f is IrConstructor && f.valueParameters.isNotEmpty() && f.valueParameters.all { it.defaultValue != null }) {
1099+
// Per https://kotlinlang.org/docs/classes.html#creating-instances-of-classes, a single default overload gets created specifically
1100+
// when we have all default parameters, regardless of `@JvmOverloads`.
1101+
extractGeneratedOverload(f.valueParameters.map { _ -> null })
1102+
}
1103+
return
1104+
}
1105+
10991106
val paramList: MutableList<IrValueParameter?> = f.valueParameters.toMutableList()
11001107
for (n in (f.valueParameters.size - 1) downTo 0) {
11011108
if (f.valueParameters[n].defaultValue != null) {
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
public class User {
2+
3+
public static void test() { new AllDefaultsConstructor(); }
4+
5+
}

java/ql/integration-tests/all-platforms/kotlin/jvmoverloads-external-class/test.kt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,5 @@ public class Test {
33
@JvmOverloads fun f(x: Int = 0, y: Int) { }
44

55
}
6+
7+
public class AllDefaultsConstructor(val x: Int = 1, val y: Int = 2) { }
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
from create_database_utils import *
22

33
os.mkdir('bin')
4-
run_codeql_database_create(["kotlinc test.kt -d bin", "kotlinc user.kt -cp bin"], lang="java")
4+
run_codeql_database_create(["kotlinc test.kt -d bin", "kotlinc user.kt -cp bin", "javac User.java -cp bin"], lang="java")

0 commit comments

Comments
 (0)