NoArg: Initialize properties in noarg constructor (KT-16692)

This commit is contained in:
Yan Zhulanow
2017-05-04 17:55:35 +03:00
parent eba5baa7ff
commit 254e8156ac
13 changed files with 243 additions and 140 deletions
@@ -35,8 +35,13 @@ import java.util.List;
import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.enumEntryNeedSubclass;
public abstract class ClassBodyCodegen extends MemberCodegen<KtPureClassOrObject> {
@NotNull
public final KtPureClassOrObject myClass;
@NotNull
public final OwnerKind kind;
@NotNull
public final ClassDescriptor descriptor;
protected ClassBodyCodegen(
@@ -1047,7 +1047,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
}
private void generateInitializers(@NotNull ExpressionCodegen codegen) {
public void generateInitializers(@NotNull ExpressionCodegen codegen) {
generateInitializers(() -> codegen);
}
@@ -87,7 +87,7 @@ public class ClassConstructorDescriptorImpl extends FunctionDescriptorImpl imple
}
@Nullable
private ReceiverParameterDescriptor calculateDispatchReceiverParameter() {
public ReceiverParameterDescriptor calculateDispatchReceiverParameter() {
ClassDescriptor classDescriptor = getContainingDeclaration();
if (classDescriptor.isInner()) {
DeclarationDescriptor classContainer = classDescriptor.getContainingDeclaration();
@@ -151,6 +151,7 @@ import org.jetbrains.kotlin.lang.resolve.android.test.AbstractAndroidBytecodeSha
import org.jetbrains.kotlin.lang.resolve.android.test.AbstractAndroidSyntheticPropertyDescriptorTest
import org.jetbrains.kotlin.modules.xml.AbstractModuleXmlParserTest
import org.jetbrains.kotlin.multiplatform.AbstractMultiPlatformIntegrationTest
import org.jetbrains.kotlin.noarg.AbstractBlackBoxCodegenTestForNoArg
import org.jetbrains.kotlin.noarg.AbstractBytecodeListingTestForNoArg
import org.jetbrains.kotlin.parsing.AbstractParsingTest
import org.jetbrains.kotlin.psi.patternMatching.AbstractPsiUnifierTest
@@ -1210,15 +1211,19 @@ fun main(args: Array<String>) {
}
testGroup("plugins/plugins-tests/tests", "plugins/allopen/allopen-cli/testData") {
testClass<AbstractBytecodeListingTestForAllOpen>() {
testClass<AbstractBytecodeListingTestForAllOpen> {
model("bytecodeListing", extension = "kt")
}
}
testGroup("plugins/plugins-tests/tests", "plugins/noarg/noarg-cli/testData") {
testClass<AbstractBytecodeListingTestForNoArg>() {
testClass<AbstractBytecodeListingTestForNoArg> {
model("bytecodeListing", extension = "kt")
}
testClass<AbstractBlackBoxCodegenTestForNoArg> {
model("box", targetBackend = TargetBackend.JVM)
}
}
testGroup("plugins/plugins-tests/tests", "plugins/sam-with-receiver/sam-with-receiver-cli/testData") {
+1 -1
View File
@@ -2186,7 +2186,7 @@
<storageComponentContainerContributor implementation="org.jetbrains.kotlin.samWithReceiver.ide.IdeSamWithReceiverComponentContributor"/>
<classBuilderFactoryInterceptorExtension implementation="org.jetbrains.kotlin.noarg.NoArgClassBuilderInterceptorExtension"/>
<expressionCodegenExtension implementation="org.jetbrains.kotlin.noarg.NoArgExpressionCodegenExtension"/>
<storageComponentContainerContributor implementation="org.jetbrains.kotlin.noarg.ide.IdeNoArgComponentContainerContributor"/>
<defaultErrorMessages implementation="org.jetbrains.kotlin.noarg.diagnostic.DefaultErrorMessagesNoArg"/>
<versionInfoProvider implementation="org.jetbrains.kotlin.idea.facet.KotlinVersionInfoProviderByModuleDependencies"/>
@@ -1,130 +0,0 @@
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.noarg
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.codegen.ClassBuilder
import org.jetbrains.kotlin.codegen.ClassBuilderFactory
import org.jetbrains.kotlin.codegen.DelegatingClassBuilder
import org.jetbrains.kotlin.codegen.extensions.ClassBuilderInterceptorExtension
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.diagnostics.DiagnosticSink
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
import org.jetbrains.org.objectweb.asm.MethodVisitor
import org.jetbrains.org.objectweb.asm.Opcodes
class NoArgClassBuilderInterceptorExtension : ClassBuilderInterceptorExtension {
override fun interceptClassBuilderFactory(
interceptedFactory: ClassBuilderFactory,
bindingContext: BindingContext,
diagnostics: DiagnosticSink
): ClassBuilderFactory = NoArgClassBuilderFactory(interceptedFactory, bindingContext)
private inner class NoArgClassBuilderFactory(
private val delegateFactory: ClassBuilderFactory,
val bindingContext: BindingContext
) : ClassBuilderFactory {
override fun newClassBuilder(origin: JvmDeclarationOrigin): ClassBuilder {
return AllOpenClassBuilder(delegateFactory.newClassBuilder(origin), bindingContext)
}
override fun getClassBuilderMode() = delegateFactory.classBuilderMode
override fun asText(builder: ClassBuilder?): String? {
return delegateFactory.asText((builder as AllOpenClassBuilder).delegateClassBuilder)
}
override fun asBytes(builder: ClassBuilder?): ByteArray? {
return delegateFactory.asBytes((builder as AllOpenClassBuilder).delegateClassBuilder)
}
override fun close() {
delegateFactory.close()
}
}
private inner class AllOpenClassBuilder(
internal val delegateClassBuilder: ClassBuilder,
val bindingContext: BindingContext
) : DelegatingClassBuilder() {
override fun getDelegate() = delegateClassBuilder
private var superClassInternalName = ""
private var hasSpecialAnnotation = false
private var noArgConstructorGenerated = false
override fun defineClass(
origin: PsiElement?,
version: Int,
access: Int,
name: String,
signature: String?,
superName: String,
interfaces: Array<out String>
) {
super.defineClass(origin, version, access, name, signature, superName, interfaces)
hasSpecialAnnotation = false
noArgConstructorGenerated = false
superClassInternalName = superName
if (origin is KtClass) {
val descriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, origin] as? ClassDescriptor
if (descriptor != null && descriptor.kind == ClassKind.CLASS && origin.isNoArgClass()) {
hasSpecialAnnotation = true
}
}
}
private fun KtClass.isNoArgClass() = this.getUserData(NO_ARG_CLASS_KEY) ?: false
override fun newMethod(
origin: JvmDeclarationOrigin,
access: Int,
name: String,
desc: String,
signature: String?,
exceptions: Array<out String>?
): MethodVisitor {
if (name == "<init>" && desc == "()V") {
noArgConstructorGenerated = true
}
return super.newMethod(origin, access, name, desc, signature, exceptions)
}
override fun done() {
val superClassInternalName = this.superClassInternalName
if (hasSpecialAnnotation && !noArgConstructorGenerated && superClassInternalName.isNotEmpty()) {
super.newMethod(JvmDeclarationOrigin.NO_ORIGIN, Opcodes.ACC_PUBLIC, "<init>", "()V", null, null).apply {
visitCode()
visitVarInsn(Opcodes.ALOAD, 0)
visitMethodInsn(Opcodes.INVOKESPECIAL, superClassInternalName, "<init>", "()V", false)
visitInsn(Opcodes.RETURN)
visitMaxs(1, 1)
visitEnd()
}
}
super.done()
}
}
}
@@ -0,0 +1,83 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.noarg
import org.jetbrains.kotlin.codegen.*
import org.jetbrains.kotlin.codegen.context.ConstructorContext
import org.jetbrains.kotlin.codegen.extensions.ExpressionCodegenExtension
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.descriptors.impl.ClassConstructorDescriptorImpl
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassOrAny
import org.jetbrains.kotlin.resolve.descriptorUtil.hasDefaultValue
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.kotlin.resolve.jvm.annotations.findJvmOverloadsAnnotation
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature
import org.jetbrains.kotlin.codegen.FunctionGenerationStrategy.CodegenBased
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.Type
class NoArgExpressionCodegenExtension : ExpressionCodegenExtension {
override fun generateClassSyntheticParts(codegen: ImplementationBodyCodegen) = with(codegen) {
if (shouldGenerateNoArgConstructor()) {
generateNoArgConstructor()
}
}
private fun ImplementationBodyCodegen.generateNoArgConstructor() {
val superClassInternalName = typeMapper.mapClass(descriptor.getSuperClassOrAny()).internalName
val constructorDescriptor = createNoArgConstructorDescriptor(descriptor)
functionCodegen.generateMethod(JvmDeclarationOrigin.NO_ORIGIN, constructorDescriptor, object: CodegenBased(state) {
override fun doGenerateBody(codegen: ExpressionCodegen, signature: JvmMethodSignature) {
codegen.v.load(0, AsmTypes.OBJECT_TYPE)
codegen.v.visitMethodInsn(Opcodes.INVOKESPECIAL, superClassInternalName, "<init>", "()V", false)
generateInitializers(codegen)
codegen.v.visitInsn(Opcodes.RETURN)
}
})
}
private fun createNoArgConstructorDescriptor(containingClass: ClassDescriptor): ConstructorDescriptor {
return ClassConstructorDescriptorImpl.createSynthesized(containingClass, Annotations.EMPTY, false, SourceElement.NO_SOURCE).apply {
initialize(null, calculateDispatchReceiverParameter(), emptyList(), emptyList(),
containingClass.builtIns.unitType, Modality.OPEN, Visibilities.PUBLIC)
}
}
private fun KtClass.isNoArgClass() = this.getUserData(NO_ARG_CLASS_KEY) ?: false
private fun ImplementationBodyCodegen.shouldGenerateNoArgConstructor(): Boolean {
val origin = myClass as? KtClass ?: return false
if (descriptor.kind != ClassKind.CLASS || !origin.isNoArgClass()) {
return false
}
return descriptor.constructors.none { it.isZeroParameterConstructor() }
}
private fun ClassConstructorDescriptor.isZeroParameterConstructor(): Boolean {
val parameters = this.valueParameters
return parameters.isEmpty()
|| (parameters.all { it.hasDefaultValue() } && (isPrimary || findJvmOverloadsAnnotation() != null))
}
}
+2 -1
View File
@@ -20,6 +20,7 @@ import com.intellij.mock.MockProject
import com.intellij.openapi.extensions.Extensions
import org.jetbrains.kotlin.noarg.diagnostic.DefaultErrorMessagesNoArg
import org.jetbrains.kotlin.codegen.extensions.ClassBuilderInterceptorExtension
import org.jetbrains.kotlin.codegen.extensions.ExpressionCodegenExtension
import org.jetbrains.kotlin.compiler.plugin.CliOption
import org.jetbrains.kotlin.compiler.plugin.CliOptionProcessingException
import org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor
@@ -78,7 +79,7 @@ class NoArgComponentRegistrar : ComponentRegistrar {
Extensions.getRootArea().getExtensionPoint(DefaultErrorMessages.Extension.EP_NAME).registerExtension(DefaultErrorMessagesNoArg())
StorageComponentContainerContributor.registerExtension(project, CliNoArgComponentContainerContributor(annotations))
ClassBuilderInterceptorExtension.registerExtension(project, NoArgClassBuilderInterceptorExtension())
ExpressionCodegenExtension.registerExtension(project, NoArgExpressionCodegenExtension())
}
}
+35
View File
@@ -0,0 +1,35 @@
// WITH_RUNTIME
annotation class NoArg
class Simple(val a: String)
@NoArg
class Test(val a: String) {
val x = 5
val y = Simple("Hello, world!")
val z by lazy { "TEST" }
}
fun box(): String {
try {
val test = Test::class.java.newInstance()
if (test.x != 5) {
return "Bad 5"
}
if (test.y == null || test.y.a != "Hello, world!") {
return "Bad Hello, world!"
}
if (test.z != "TEST") {
return "Bad TEST"
}
return "OK"
} catch (e: Throwable) {
e.printStackTrace()
return "Fail"
}
}
+15
View File
@@ -0,0 +1,15 @@
// WITH_RUNTIME
annotation class NoArg
@NoArg
class Test(val a: String)
fun box(): String {
try {
Test::class.java.newInstance()
return "OK"
} catch (_: Throwable) {
return "Fail"
}
}
@@ -0,0 +1,37 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.noarg
import com.intellij.openapi.extensions.Extensions
import org.jetbrains.kotlin.codegen.AbstractBlackBoxCodegenTest
import org.jetbrains.kotlin.codegen.extensions.ExpressionCodegenExtension
import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages
import org.jetbrains.kotlin.extensions.StorageComponentContainerContributor.Companion.registerExtension
import org.jetbrains.kotlin.noarg.AbstractBytecodeListingTestForNoArg.Companion.NOARG_ANNOTATIONS
import org.jetbrains.kotlin.noarg.diagnostic.DefaultErrorMessagesNoArg
abstract class AbstractBlackBoxCodegenTestForNoArg : AbstractBlackBoxCodegenTest() {
override fun loadMultiFiles(files: MutableList<TestFile>) {
Extensions.getRootArea().getExtensionPoint(DefaultErrorMessages.Extension.EP_NAME).registerExtension(DefaultErrorMessagesNoArg())
val project = myEnvironment.project
registerExtension(project, CliNoArgComponentContainerContributor(NOARG_ANNOTATIONS))
ExpressionCodegenExtension.registerExtension(project, NoArgExpressionCodegenExtension())
super.loadMultiFiles(files)
}
}
@@ -19,19 +19,21 @@ package org.jetbrains.kotlin.noarg
import com.intellij.openapi.extensions.Extensions
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.jetbrains.kotlin.codegen.AbstractBytecodeListingTest
import org.jetbrains.kotlin.codegen.extensions.ClassBuilderInterceptorExtension
import org.jetbrains.kotlin.codegen.extensions.ExpressionCodegenExtension
import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages
import org.jetbrains.kotlin.extensions.StorageComponentContainerContributor
import org.jetbrains.kotlin.noarg.diagnostic.DefaultErrorMessagesNoArg
abstract class AbstractBytecodeListingTestForNoArg : AbstractBytecodeListingTest() {
private companion object {
internal companion object {
val NOARG_ANNOTATIONS = listOf("NoArg", "NoArg2", "test.NoArg")
}
override fun setupEnvironment(environment: KotlinCoreEnvironment) {
Extensions.getRootArea().getExtensionPoint(DefaultErrorMessages.Extension.EP_NAME).registerExtension(DefaultErrorMessagesNoArg())
StorageComponentContainerContributor.registerExtension(environment.project, CliNoArgComponentContainerContributor(NOARG_ANNOTATIONS))
ClassBuilderInterceptorExtension.registerExtension(environment.project, NoArgClassBuilderInterceptorExtension())
val project = environment.project
StorageComponentContainerContributor.registerExtension(project, CliNoArgComponentContainerContributor(NOARG_ANNOTATIONS))
ExpressionCodegenExtension.registerExtension(project, NoArgExpressionCodegenExtension())
}
}
@@ -0,0 +1,50 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.noarg;
import com.intellij.testFramework.TestDataPath;
import org.jetbrains.kotlin.test.JUnit3RunnerWithInners;
import org.jetbrains.kotlin.test.KotlinTestUtils;
import org.jetbrains.kotlin.test.TargetBackend;
import org.jetbrains.kotlin.test.TestMetadata;
import org.junit.runner.RunWith;
import java.io.File;
import java.util.regex.Pattern;
/** This class is generated by {@link org.jetbrains.kotlin.generators.tests.TestsPackage}. DO NOT MODIFY MANUALLY */
@SuppressWarnings("all")
@TestMetadata("plugins/noarg/noarg-cli/testData/box")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public class BlackBoxCodegenTestForNoArgGenerated extends AbstractBlackBoxCodegenTestForNoArg {
public void testAllFilesPresentInBox() throws Exception {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("plugins/noarg/noarg-cli/testData/box"), Pattern.compile("^(.+)\\.kt$"), TargetBackend.JVM, true);
}
@TestMetadata("initializers.kt")
public void testInitializers() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("plugins/noarg/noarg-cli/testData/box/initializers.kt");
doTest(fileName);
}
@TestMetadata("simple.kt")
public void testSimple() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("plugins/noarg/noarg-cli/testData/box/simple.kt");
doTest(fileName);
}
}