Generate constructor without parameters if primary constructor has only parameters with default values

#KT-3085 Fixed
This commit is contained in:
Natalia.Ukhorskaya
2012-12-25 12:28:56 +04:00
parent d4a8ed5ae6
commit 808c5abc0f
24 changed files with 343 additions and 20 deletions
@@ -25,6 +25,7 @@ import org.jetbrains.asm4.MethodVisitor;
import org.jetbrains.asm4.Type;
import org.jetbrains.asm4.commons.InstructionAdapter;
import org.jetbrains.asm4.commons.Method;
import org.jetbrains.jet.codegen.binding.CodegenBinding;
import org.jetbrains.jet.codegen.context.CodegenContext;
import org.jetbrains.jet.codegen.context.MethodContext;
import org.jetbrains.jet.codegen.signature.JvmMethodParameterSignature;
@@ -528,6 +529,46 @@ public class FunctionCodegen extends GenerationStateAware {
}
}
static void generateConstructorWithoutParametersIfNeeded(
@NotNull GenerationState state,
@NotNull CallableMethod method,
@NotNull ConstructorDescriptor constructorDescriptor,
@NotNull ClassBuilder classBuilder
) {
if (!isDefaultConstructorNeeded(state.getBindingContext(), constructorDescriptor)) {
return;
}
int flags = getVisibilityAccessFlag(constructorDescriptor);
MethodVisitor mv = classBuilder.newMethod(null, flags, "<init>", "()V", null, null);
if (state.getClassBuilderMode() == ClassBuilderMode.SIGNATURES) {
return;
}
else if (state.getClassBuilderMode() == ClassBuilderMode.STUBS) {
genStubCode(mv);
}
else if (state.getClassBuilderMode() == ClassBuilderMode.FULL) {
InstructionAdapter v = new InstructionAdapter(mv);
mv.visitCode();
JvmClassName ownerInternalName = method.getOwner();
Method jvmSignature = method.getSignature().getAsmMethod();
v.load(0, ownerInternalName.getAsmType()); // Load this on stack
int mask = 0;
for (ValueParameterDescriptor parameterDescriptor : constructorDescriptor.getValueParameters()) {
Type paramType = state.getTypeMapper().mapType(parameterDescriptor.getType());
pushDefaultValueOnStack(paramType, v);
mask |= (1 << parameterDescriptor.getIndex());
}
v.iconst(mask);
String desc = jvmSignature.getDescriptor().replace(")", "I)");
v.invokespecial(ownerInternalName.getInternalName(), "<init>", desc);
v.areturn(Type.VOID_TYPE);
endVisit(mv, "default constructor for " + ownerInternalName.getInternalName(), null);
}
}
static void generateDefaultIfNeeded(
MethodContext owner,
GenerationState state,
@@ -551,9 +592,10 @@ public class FunctionCodegen extends GenerationStateAware {
ReceiverParameterDescriptor receiverParameter = functionDescriptor.getReceiverParameter();
boolean hasReceiver = receiverParameter != null;
// TODO change this condition when nested classes will be implemented
// Has outer in local variables (constructor for inner class)
boolean hasOuter = functionDescriptor instanceof ConstructorDescriptor && functionDescriptor.getExpectedThisObject() != null;
boolean hasOuter = functionDescriptor instanceof ConstructorDescriptor &&
CodegenBinding.canHaveOuter(state.getBindingContext(), ((ConstructorDescriptor) functionDescriptor).getContainingDeclaration());
boolean isStatic = isStatic(kind);
if (kind == OwnerKind.TRAIT_IMPL) {
@@ -734,6 +776,24 @@ public class FunctionCodegen extends GenerationStateAware {
return needed;
}
private static boolean isDefaultConstructorNeeded(@NotNull BindingContext context, @NotNull ConstructorDescriptor constructorDescriptor) {
ClassDescriptor classDescriptor = constructorDescriptor.getContainingDeclaration();
if (CodegenBinding.canHaveOuter(context, classDescriptor)) return false;
if (classDescriptor.getVisibility() == Visibilities.PRIVATE ||
constructorDescriptor.getVisibility() == Visibilities.PRIVATE) return false;
if (constructorDescriptor.getValueParameters().isEmpty()) return false;
for (ValueParameterDescriptor parameterDescriptor : constructorDescriptor.getValueParameters()) {
if (!parameterDescriptor.declaresDefaultValue()) {
return false;
}
}
return true;
}
private static boolean differentMethods(Method method, Method overridden) {
if (!method.getReturnType().equals(overridden.getReturnType())) {
return true;
@@ -939,27 +939,31 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
int flags = getVisibilityAccessFlag(constructorDescriptor);
final MethodVisitor mv = v.newMethod(myClass, flags, constructorMethod.getName(), constructorMethod.getAsmMethod().getDescriptor(),
constructorMethod.getGenericsSignature(), null);
if (state.getClassBuilderMode() == ClassBuilderMode.SIGNATURES) return;
if (state.getClassBuilderMode() != ClassBuilderMode.SIGNATURES) {
AnnotationVisitor jetConstructorVisitor = mv.visitAnnotation(JvmStdlibNames.JET_CONSTRUCTOR.getDescriptor(), true);
AnnotationVisitor jetConstructorVisitor = mv.visitAnnotation(JvmStdlibNames.JET_CONSTRUCTOR.getDescriptor(), true);
int flagsValue = getFlagsForVisibility(constructorDescriptor.getVisibility());
if (JvmStdlibNames.FLAGS_DEFAULT_VALUE != flagsValue) {
jetConstructorVisitor.visit(JvmStdlibNames.JET_FLAGS_FIELD, flagsValue);
int flagsValue = getFlagsForVisibility(constructorDescriptor.getVisibility());
if (JvmStdlibNames.FLAGS_DEFAULT_VALUE != flagsValue) {
jetConstructorVisitor.visit(JvmStdlibNames.JET_FLAGS_FIELD, flagsValue);
}
jetConstructorVisitor.visitEnd();
AnnotationCodegen.forMethod(mv, typeMapper).genAnnotations(constructorDescriptor);
writeParameterAnnotations(constructorDescriptor, constructorMethod, hasCapturedThis, mv);
if (state.getClassBuilderMode() == ClassBuilderMode.STUBS) {
genStubCode(mv);
return;
}
generatePrimaryConstructorImpl(constructorDescriptor, constructorContext, constructorMethod, callableMethod, hasCapturedThis,
closure, mv);
}
jetConstructorVisitor.visitEnd();
AnnotationCodegen.forMethod(mv, typeMapper).genAnnotations(constructorDescriptor);
writeParameterAnnotations(constructorDescriptor, constructorMethod, hasCapturedThis, mv);
if (state.getClassBuilderMode() == ClassBuilderMode.STUBS) {
genStubCode(mv);
return;
}
generatePrimaryConstructorImpl(constructorDescriptor, constructorContext, constructorMethod, callableMethod, hasCapturedThis, closure, mv);
FunctionCodegen.generateConstructorWithoutParametersIfNeeded(state, callableMethod, constructorDescriptor, v);
}
private void generatePrimaryConstructorImpl(
@@ -135,7 +135,7 @@ public class CodegenBinding {
bindingTrace.record(CLASS_FOR_FUNCTION, scriptDescriptor, classDescriptor);
}
private static boolean canHaveOuter(BindingContext bindingContext, @NotNull ClassDescriptor classDescriptor) {
public static boolean canHaveOuter(BindingContext bindingContext, @NotNull ClassDescriptor classDescriptor) {
final ClassKind kind = classDescriptor.getKind();
if (isSingleton(bindingContext, classDescriptor)) {
return false;
@@ -0,0 +1,8 @@
class A {
class object {
class Foo(val a: Int = 1) {}
}
}
// CLASS: A$object$Foo
// HAS_DEFAULT_CONSTRUCTOR: true
@@ -0,0 +1,6 @@
object o {
class Foo(val a: Int = 1) {}
}
// CLASS: o$Foo
// HAS_DEFAULT_CONSTRUCTOR: true
@@ -0,0 +1,4 @@
class Foo(val a: Int = 1, val b: String = "b") {}
// CLASS: Foo
// HAS_DEFAULT_CONSTRUCTOR: true
@@ -0,0 +1,4 @@
class Foo(vararg val a: String = Array<String>(1) {"default"})
// CLASS: Foo
// HAS_DEFAULT_CONSTRUCTOR: true
@@ -0,0 +1,4 @@
class Foo(val a: Int = 1) {}
// CLASS: Foo
// HAS_DEFAULT_CONSTRUCTOR: true
@@ -0,0 +1,4 @@
private class Foo(val a: Int = 1) {}
// CLASS: Foo
// HAS_DEFAULT_CONSTRUCTOR: false
@@ -0,0 +1,4 @@
class Foo private(val a: Int = 1) {}
// CLASS: Foo
// HAS_DEFAULT_CONSTRUCTOR: false
@@ -0,0 +1,4 @@
public class Foo(val a: Int = 1) {}
// CLASS: Foo
// HAS_DEFAULT_CONSTRUCTOR: true
@@ -0,0 +1,4 @@
public class Foo(val a: Int = 1, val b: Int) {}
// CLASS: Foo
// HAS_DEFAULT_CONSTRUCTOR: false
@@ -0,0 +1,10 @@
class A {
public class Foo(val a: Int = 1) {}
fun foo() {
Foo()
}
}
// CLASS: A$Foo
// HAS_DEFAULT_CONSTRUCTOR: false
@@ -0,0 +1,6 @@
private class A {
public class Foo(val a: Int = 1) {}
}
// CLASS: A$Foo
// HAS_DEFAULT_CONSTRUCTOR: false
@@ -0,0 +1,5 @@
class Simple {
void foo() {
new A();
}
}
@@ -0,0 +1 @@
class A(val a: Int = 1)
@@ -0,0 +1,5 @@
class Simple {
void foo() {
new A();
}
}
@@ -0,0 +1 @@
class A(val a: Int = 1, val b: String = "default")
@@ -0,0 +1 @@
class A(val a: Int = 1)
@@ -0,0 +1,5 @@
package bbb
fun main(args: Array<String>) {
A()
}
@@ -0,0 +1,74 @@
/*
* Copyright 2010-2012 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.jet.codegen.defaultConstructor;
import com.intellij.openapi.util.io.FileUtil;
import org.jetbrains.jet.ConfigurationKind;
import org.jetbrains.jet.codegen.ClassFileFactory;
import org.jetbrains.jet.codegen.CodegenTestCase;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.List;
import static org.jetbrains.jet.InTextDirectivesUtils.findListWithPrefix;
public abstract class AbstractDefaultConstructorCodegenTest extends CodegenTestCase {
@Override
public void setUp() throws Exception {
super.setUp();
createEnvironmentWithMockJdkAndIdeaAnnotations(ConfigurationKind.JDK_ONLY);
}
protected void doTest(String path) throws IOException {
loadFileByFullPath(path);
ClassFileFactory codegens = generateClassesInFile();
String fileText = FileUtil.loadFile(new File(path));
String className = loadInstructionValue(fileText, "CLASS");
boolean hasDefaultConstructor = loadInstructionValue(fileText, "HAS_DEFAULT_CONSTRUCTOR").equals("true");
Class aClass = loadClass(className, codegens);
assertNotNull("Cannot find class with name " + className, aClass);
try {
Constructor constructor = aClass.getDeclaredConstructor();
if (!hasDefaultConstructor) {
System.out.println(generateToText());
throw new AssertionError("Default constructor was found but it wasn't expected: " + constructor);
}
}
catch (NoSuchMethodException e) {
if (hasDefaultConstructor) {
System.out.println(generateToText());
throw new AssertionError("Cannot find default constructor");
}
}
catch (Throwable e) {
System.out.println(generateToText());
throw new RuntimeException(e);
}
}
private String loadInstructionValue(String fileContent, String instructionName) {
List<String> testedClass = findListWithPrefix("// " + instructionName + ": ", fileContent);
assertTrue("Cannot find " + instructionName + " instruction", !testedClass.isEmpty());
assertTrue(instructionName + " instruction must have only one element", testedClass.size() == 1);
return testedClass.get(0);
}
}
@@ -0,0 +1,91 @@
/*
* Copyright 2010-2012 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.jet.codegen.defaultConstructor;
import junit.framework.Assert;
import junit.framework.Test;
import junit.framework.TestSuite;
import java.io.File;
import org.jetbrains.jet.JetTestUtils;
import org.jetbrains.jet.test.InnerTestClasses;
import org.jetbrains.jet.test.TestMetadata;
import org.jetbrains.jet.codegen.defaultConstructor.AbstractDefaultConstructorCodegenTest;
/** This class is generated by {@link org.jetbrains.jet.generators.tests.GenerateTests}. DO NOT MODIFY MANUALLY */
@TestMetadata("compiler/testData/codegen/defaultArguments/reflection")
public class DefaultArgumentsReflectionTestGenerated extends AbstractDefaultConstructorCodegenTest {
public void testAllFilesPresentInReflection() throws Exception {
JetTestUtils.assertAllTestsPresentByMetadata(this.getClass(), "org.jetbrains.jet.generators.tests.GenerateTests", new File("compiler/testData/codegen/defaultArguments/reflection"), "kt", true);
}
@TestMetadata("classInClassObject.kt")
public void testClassInClassObject() throws Exception {
doTest("compiler/testData/codegen/defaultArguments/reflection/classInClassObject.kt");
}
@TestMetadata("classInObject.kt")
public void testClassInObject() throws Exception {
doTest("compiler/testData/codegen/defaultArguments/reflection/classInObject.kt");
}
@TestMetadata("classWithTwoDefaultArgs.kt")
public void testClassWithTwoDefaultArgs() throws Exception {
doTest("compiler/testData/codegen/defaultArguments/reflection/classWithTwoDefaultArgs.kt");
}
@TestMetadata("classWithVararg.kt")
public void testClassWithVararg() throws Exception {
doTest("compiler/testData/codegen/defaultArguments/reflection/classWithVararg.kt");
}
@TestMetadata("internalClass.kt")
public void testInternalClass() throws Exception {
doTest("compiler/testData/codegen/defaultArguments/reflection/internalClass.kt");
}
@TestMetadata("privateClass.kt")
public void testPrivateClass() throws Exception {
doTest("compiler/testData/codegen/defaultArguments/reflection/privateClass.kt");
}
@TestMetadata("privateConstructor.kt")
public void testPrivateConstructor() throws Exception {
doTest("compiler/testData/codegen/defaultArguments/reflection/privateConstructor.kt");
}
@TestMetadata("publicClass.kt")
public void testPublicClass() throws Exception {
doTest("compiler/testData/codegen/defaultArguments/reflection/publicClass.kt");
}
@TestMetadata("publicClassWoDefArgs.kt")
public void testPublicClassWoDefArgs() throws Exception {
doTest("compiler/testData/codegen/defaultArguments/reflection/publicClassWoDefArgs.kt");
}
@TestMetadata("publicInnerClass.kt")
public void testPublicInnerClass() throws Exception {
doTest("compiler/testData/codegen/defaultArguments/reflection/publicInnerClass.kt");
}
@TestMetadata("publicInnerClassInPrivateClass.kt")
public void testPublicInnerClassInPrivateClass() throws Exception {
doTest("compiler/testData/codegen/defaultArguments/reflection/publicInnerClassInPrivateClass.kt");
}
}
@@ -40,6 +40,16 @@ public class CompileJavaAgainstKotlinTestGenerated extends AbstractCompileJavaAg
JetTestUtils.assertAllTestsPresentByMetadata(this.getClass(), "org.jetbrains.jet.generators.tests.GenerateTests", new File("compiler/testData/compileJavaAgainstKotlin/class"), "kt", true);
}
@TestMetadata("DefaultConstructor.kt")
public void testDefaultConstructor() throws Exception {
doTest("compiler/testData/compileJavaAgainstKotlin/class/DefaultConstructor.kt");
}
@TestMetadata("DefaultConstructorWithTwoArgs.kt")
public void testDefaultConstructorWithTwoArgs() throws Exception {
doTest("compiler/testData/compileJavaAgainstKotlin/class/DefaultConstructorWithTwoArgs.kt");
}
@TestMetadata("ExtendsAbstractListT.kt")
public void testExtendsAbstractListT() throws Exception {
doTest("compiler/testData/compileJavaAgainstKotlin/class/ExtendsAbstractListT.kt");
@@ -24,6 +24,7 @@ import org.jetbrains.jet.codegen.AbstractCheckLocalVariablesTableTest;
import org.jetbrains.jet.codegen.AbstractDataClassCodegenTest;
import org.jetbrains.jet.codegen.AbstractIntrinsicsTestCase;
import org.jetbrains.jet.codegen.AbstractMultiDeclTestCase;
import org.jetbrains.jet.codegen.defaultConstructor.AbstractDefaultConstructorCodegenTest;
import org.jetbrains.jet.codegen.flags.AbstractWriteFlagsTest;
import org.jetbrains.jet.codegen.generated.AbstractCodegenTest;
import org.jetbrains.jet.jvm.compiler.AbstractCompileJavaAgainstKotlinTest;
@@ -108,6 +109,13 @@ public class GenerateTests {
testModel("compiler/testData/codegen/defaultArguments/blackBox")
);
generateTest(
"compiler/tests/",
"DefaultArgumentsReflectionTestGenerated",
AbstractDefaultConstructorCodegenTest.class,
testModel("compiler/testData/codegen/defaultArguments/reflection")
);
generateTest(
"compiler/tests/",
"DefaultArgumentsBlackBoxTestGenerated",