Extract a no-arg constuctor whenever a Kotlin class has default values for all parameters

This commit is contained in:
Chris Smowton
2022-12-01 12:11:41 +00:00
parent edfcc0cd6d
commit 1c0494ec53
4 changed files with 17 additions and 3 deletions

View File

@@ -1049,8 +1049,6 @@ open class KotlinFileExtractor(
private val jvmOverloadsFqName = FqName("kotlin.jvm.JvmOverloads")
private fun extractGeneratedOverloads(f: IrFunction, parentId: Label<out DbReftype>, maybeSourceParentId: Label<out DbReftype>?, extractBody: Boolean, extractMethodAndParameterTypeAccesses: Boolean, typeSubstitution: TypeSubstitution?, classTypeArgsIncludingOuterClasses: List<IrTypeArgument>?) {
if (!f.hasAnnotation(jvmOverloadsFqName))
return
fun extractGeneratedOverload(paramList: List<IrValueParameter?>) {
val overloadParameters = paramList.filterNotNull()
@@ -1096,6 +1094,15 @@ open class KotlinFileExtractor(
}
}
if (!f.hasAnnotation(jvmOverloadsFqName)) {
if (f is IrConstructor && f.valueParameters.isNotEmpty() && f.valueParameters.all { it.defaultValue != null }) {
// Per https://kotlinlang.org/docs/classes.html#creating-instances-of-classes, a single default overload gets created specifically
// when we have all default parameters, regardless of `@JvmOverloads`.
extractGeneratedOverload(f.valueParameters.map { _ -> null })
}
return
}
val paramList: MutableList<IrValueParameter?> = f.valueParameters.toMutableList()
for (n in (f.valueParameters.size - 1) downTo 0) {
if (f.valueParameters[n].defaultValue != null) {

View File

@@ -0,0 +1,5 @@
public class User {
public static void test() { new AllDefaultsConstructor(); }
}

View File

@@ -3,3 +3,5 @@ public class Test {
@JvmOverloads fun f(x: Int = 0, y: Int) { }
}
public class AllDefaultsConstructor(val x: Int = 1, val y: Int = 2) { }

View File

@@ -1,4 +1,4 @@
from create_database_utils import *
os.mkdir('bin')
run_codeql_database_create(["kotlinc test.kt -d bin", "kotlinc user.kt -cp bin"], lang="java")
run_codeql_database_create(["kotlinc test.kt -d bin", "kotlinc user.kt -cp bin", "javac User.java -cp bin"], lang="java")