diff --git a/.idea/codeStyleSettings.xml b/.idea/codeStyleSettings.xml
index 0dd5af1923f..0279b53f8eb 100644
--- a/.idea/codeStyleSettings.xml
+++ b/.idea/codeStyleSettings.xml
@@ -176,6 +176,8 @@
+
+
@@ -227,38 +229,7 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/.idea/runConfigurations/All_Jvm_Backend_Tests.xml b/.idea/runConfigurations/All_Jvm_Backend_Tests.xml
new file mode 100644
index 00000000000..4270bdf9050
--- /dev/null
+++ b/.idea/runConfigurations/All_Jvm_Backend_Tests.xml
@@ -0,0 +1,30 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/compiler/android-tests/tests/org/jetbrains/jet/compiler/android/CodegenTestsOnAndroidGenerator.java b/compiler/android-tests/tests/org/jetbrains/jet/compiler/android/CodegenTestsOnAndroidGenerator.java
index ef313cbbebd..8184c54aac5 100644
--- a/compiler/android-tests/tests/org/jetbrains/jet/compiler/android/CodegenTestsOnAndroidGenerator.java
+++ b/compiler/android-tests/tests/org/jetbrains/jet/compiler/android/CodegenTestsOnAndroidGenerator.java
@@ -32,7 +32,7 @@ import org.jetbrains.jet.codegen.GenerationUtils;
import org.jetbrains.jet.compiler.PathManager;
import org.jetbrains.jet.lang.psi.JetFile;
import org.jetbrains.jet.lang.psi.JetPsiFactory;
-import org.jetbrains.jet.test.generator.Printer;
+import org.jetbrains.jet.utils.Printer;
import java.io.File;
import java.io.IOException;
diff --git a/compiler/android-tests/tests/org/jetbrains/jet/compiler/android/SpecialFiles.java b/compiler/android-tests/tests/org/jetbrains/jet/compiler/android/SpecialFiles.java
index 20f1c33372a..501a2584916 100644
--- a/compiler/android-tests/tests/org/jetbrains/jet/compiler/android/SpecialFiles.java
+++ b/compiler/android-tests/tests/org/jetbrains/jet/compiler/android/SpecialFiles.java
@@ -95,6 +95,7 @@ public class SpecialFiles {
excludedFiles.add("box.kt"); // MultiFileTest not supported yet
excludedFiles.add("kt2060_1.kt"); // MultiFileTest not supported yet
excludedFiles.add("kt2257_1.kt"); // MultiFileTest not supported yet
+ excludedFiles.add("kt1528_1.kt"); // MultiFileTest not supported yet
excludedFiles.add("kt684.jet"); // StackOverflow with StringBuilder (escape())
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/AccessorForFunctionDescriptor.java b/compiler/backend/src/org/jetbrains/jet/codegen/AccessorForFunctionDescriptor.java
new file mode 100644
index 00000000000..87735e64197
--- /dev/null
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/AccessorForFunctionDescriptor.java
@@ -0,0 +1,45 @@
+/*
+ * 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;
+
+import org.jetbrains.jet.lang.descriptors.*;
+import org.jetbrains.jet.lang.descriptors.annotations.AnnotationDescriptor;
+import org.jetbrains.jet.lang.resolve.name.Name;
+
+import java.util.Collections;
+
+/**
+ * @author alex.tkachman
+*/
+public class AccessorForFunctionDescriptor extends SimpleFunctionDescriptorImpl {
+ public AccessorForFunctionDescriptor(DeclarationDescriptor descriptor, DeclarationDescriptor containingDeclaration, int index) {
+ super(containingDeclaration, Collections.emptyList(),
+ Name.identifier(descriptor.getName() + "$b$" + index),
+ Kind.DECLARATION);
+
+ FunctionDescriptor fd = (SimpleFunctionDescriptor) descriptor;
+
+ initialize(fd.getReceiverParameter().exists() ? fd.getReceiverParameter().getType() : null,
+ fd.getExpectedThisObject(),
+ Collections.emptyList(),
+ fd.getValueParameters(),
+ fd.getReturnType(),
+ Modality.FINAL,
+ Visibilities.INTERNAL,
+ /*isInline = */ false);
+ }
+}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/AccessorForPropertyDescriptor.java b/compiler/backend/src/org/jetbrains/jet/codegen/AccessorForPropertyDescriptor.java
new file mode 100644
index 00000000000..fad288fc832
--- /dev/null
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/AccessorForPropertyDescriptor.java
@@ -0,0 +1,56 @@
+/*
+ * 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;
+
+import org.jetbrains.jet.lang.descriptors.*;
+import org.jetbrains.jet.lang.descriptors.annotations.AnnotationDescriptor;
+import org.jetbrains.jet.lang.resolve.name.Name;
+import org.jetbrains.jet.lang.types.JetType;
+
+import java.util.Collections;
+
+/**
+ * @author alex.tkachman
+*/
+public class AccessorForPropertyDescriptor extends PropertyDescriptor {
+ public AccessorForPropertyDescriptor(PropertyDescriptor pd, DeclarationDescriptor containingDeclaration, int index) {
+ super(containingDeclaration, Collections.emptyList(), Modality.FINAL, Visibilities.PUBLIC,
+ pd.isVar(), pd.isObjectDeclaration(), Name.identifier(pd.getName() + "$b$" + index),
+ Kind.DECLARATION);
+
+ JetType receiverType = pd.getReceiverParameter().exists() ? pd.getReceiverParameter().getType() : null;
+ setType(pd.getType(), Collections.emptyList(), pd.getExpectedThisObject(), receiverType);
+ initialize(new Getter(this), new Setter(this));
+ }
+
+ public static class Getter extends PropertyGetterDescriptor {
+ public Getter(AccessorForPropertyDescriptor property) {
+ super(property, Collections.emptyList(), Modality.FINAL, Visibilities.PUBLIC,
+ false,
+ false, Kind.DECLARATION);
+ initialize(property.getType());
+ }
+ }
+
+ public static class Setter extends PropertySetterDescriptor {
+ public Setter(AccessorForPropertyDescriptor property) {
+ super(property, Collections.emptyList(), Modality.FINAL, Visibilities.PUBLIC,
+ false,
+ false, Kind.DECLARATION);
+ }
+ }
+}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/AnnotationCodegen.java b/compiler/backend/src/org/jetbrains/jet/codegen/AnnotationCodegen.java
index fc649982437..ade7c42458c 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/AnnotationCodegen.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/AnnotationCodegen.java
@@ -233,4 +233,13 @@ public abstract class AnnotationCodegen {
}
};
}
+
+ public static AnnotationCodegen forParameter(final int parameter, final MethodVisitor mv, JetTypeMapper mapper) {
+ return new AnnotationCodegen(mapper) {
+ @Override
+ AnnotationVisitor visitAnnotation(String descr, boolean visible) {
+ return mv.visitParameterAnnotation(parameter, descr, visible);
+ }
+ };
+ }
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/CallableMethod.java b/compiler/backend/src/org/jetbrains/jet/codegen/CallableMethod.java
index f49e5489faa..4137ddfd573 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/CallableMethod.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/CallableMethod.java
@@ -67,7 +67,7 @@ public class CallableMethod implements Callable {
return owner;
}
- @NotNull
+ @Nullable
public JvmClassName getDefaultImplParam() {
return defaultImplParam;
}
@@ -96,6 +96,7 @@ public class CallableMethod implements Callable {
v.visitMethodInsn(getInvokeOpcode(), owner.getInternalName(), getSignature().getAsmMethod().getName(), getSignature().getAsmMethod().getDescriptor());
}
+ @Nullable
public Type getGenerateCalleeType() {
return generateCalleeType;
}
@@ -122,10 +123,6 @@ public class CallableMethod implements Callable {
return thisClass != null && generateCalleeType == null;
}
- public boolean isNeedsReceiver() {
- return receiverParameterType != null;
- }
-
public Type getReturnType() {
return signature.getAsmMethod().getReturnType();
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/ClassBodyCodegen.java b/compiler/backend/src/org/jetbrains/jet/codegen/ClassBodyCodegen.java
index 840c48b01fa..167a0fe6d11 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/ClassBodyCodegen.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/ClassBodyCodegen.java
@@ -24,14 +24,12 @@ import org.jetbrains.jet.lang.descriptors.ClassDescriptor;
import org.jetbrains.jet.lang.descriptors.PropertyDescriptor;
import org.jetbrains.jet.lang.psi.*;
import org.jetbrains.jet.lang.resolve.BindingContext;
-import org.jetbrains.jet.lang.types.lang.JetStandardLibrary;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.jetbrains.asm4.Opcodes.ACC_ABSTRACT;
-import static org.jetbrains.asm4.Opcodes.ACC_PRIVATE;
import static org.jetbrains.asm4.Opcodes.ACC_PUBLIC;
/**
@@ -99,25 +97,10 @@ public abstract class ClassBodyCodegen {
PropertyDescriptor propertyDescriptor = state.getBindingContext().get(BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, p);
if (propertyDescriptor != null) {
if (!isAnnotation) {
- int accessModifiers = JetTypeMapper.getAccessModifiers(propertyDescriptor, 0);
- if((accessModifiers & ACC_PRIVATE) == 0) {
- propertyCodegen.generateDefaultGetter(propertyDescriptor, accessModifiers, p);
- if (propertyDescriptor.isVar()) {
- propertyCodegen.generateDefaultSetter(propertyDescriptor, accessModifiers, origin);
- }
- }
-
- //noinspection ConstantConditions
- if (!(kind instanceof OwnerKind.DelegateKind) && state.getBindingContext().get(BindingContext.BACKING_FIELD_REQUIRED, propertyDescriptor)) {
- int modifiers = accessModifiers;
- if (!propertyDescriptor.isVar()) {
- modifiers |= Opcodes.ACC_FINAL;
- }
- if (JetStandardLibrary.isVolatile(propertyDescriptor)) {
- modifiers |= Opcodes.ACC_VOLATILE;
- }
- Type type = state.getInjector().getJetTypeMapper().mapType(propertyDescriptor.getType(), MapTypeMode.VALUE);
- v.newField(p, modifiers, p.getName(), type.getDescriptor(), null, null);
+ propertyCodegen.generateBackingField(p, propertyDescriptor);
+ propertyCodegen.generateDefaultGetter(propertyDescriptor, JetTypeMapper.getAccessModifiers(propertyDescriptor,0), p);
+ if (propertyDescriptor.isVar()) {
+ propertyCodegen.generateDefaultSetter(propertyDescriptor, JetTypeMapper.getAccessModifiers(propertyDescriptor,0), p);
}
}
else {
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/ClassBuilderFactories.java b/compiler/backend/src/org/jetbrains/jet/codegen/ClassBuilderFactories.java
index 679f1ecbcf4..9345f38177d 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/ClassBuilderFactories.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/ClassBuilderFactories.java
@@ -17,6 +17,7 @@
package org.jetbrains.jet.codegen;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.asm4.ClassVisitor;
import org.jetbrains.asm4.ClassWriter;
import org.jetbrains.asm4.util.TraceClassVisitor;
@@ -28,6 +29,34 @@ import java.io.StringWriter;
*/
public class ClassBuilderFactories {
+ public static ClassBuilderFactory TEST = new ClassBuilderFactory() {
+ @NotNull
+ @Override
+ public ClassBuilderMode getClassBuilderMode() {
+ return ClassBuilderMode.FULL;
+ }
+
+ @Override
+ public ClassBuilder newClassBuilder() {
+ return new TraceBuilder(new BinaryClassWriter());
+ }
+
+ @Override
+ public String asText(ClassBuilder builder) {
+ TraceClassVisitor visitor = (TraceClassVisitor) builder.getVisitor();
+
+ StringWriter writer = new StringWriter();
+ visitor.p.print(new PrintWriter(writer));
+
+ return writer.toString();
+ }
+
+ @Override
+ public byte[] asBytes(ClassBuilder builder) {
+ return ((TraceBuilder) builder).binary.toByteArray();
+ }
+ };
+
public static ClassBuilderFactory TEXT = new ClassBuilderFactory() {
@NotNull
@Override
@@ -56,6 +85,9 @@ public class ClassBuilderFactories {
}
};
+ private ClassBuilderFactories() {
+ }
+
public static ClassBuilderFactory binaries(final boolean stubs) {
return new ClassBuilderFactory() {
@NotNull
@@ -66,18 +98,7 @@ public class ClassBuilderFactories {
@Override
public ClassBuilder newClassBuilder() {
- return new ClassBuilder.Concrete(new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS){
- @Override
- protected String getCommonSuperClass(String type1, String type2) {
- try {
- return super.getCommonSuperClass(type1, type2);
- }
- catch (Throwable t) {
- // @todo we might need at some point do more sofisticated handling
- return "java/lang/Object";
- }
- }
- });
+ return new ClassBuilder.Concrete(new BinaryClassWriter());
}
@Override
@@ -92,4 +113,30 @@ public class ClassBuilderFactories {
}
};
}
+
+ private static class BinaryClassWriter extends ClassWriter {
+ public BinaryClassWriter() {
+ super(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
+ }
+
+ @Override
+ protected String getCommonSuperClass(String type1, String type2) {
+ try {
+ return super.getCommonSuperClass(type1, type2);
+ }
+ catch (Throwable t) {
+ // @todo we might need at some point do more sofisticated handling
+ return "java/lang/Object";
+ }
+ }
+ }
+
+ private static class TraceBuilder extends ClassBuilder.Concrete {
+ public final BinaryClassWriter binary;
+
+ public TraceBuilder(BinaryClassWriter binary) {
+ super(new TraceClassVisitor(binary, new PrintWriter(new StringWriter())));
+ this.binary = binary;
+ }
+ }
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/ClosureAnnotator.java b/compiler/backend/src/org/jetbrains/jet/codegen/ClosureAnnotator.java
index 83863901f75..5dfd501ff89 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/ClosureAnnotator.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/ClosureAnnotator.java
@@ -18,7 +18,6 @@ package org.jetbrains.jet.codegen;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
import org.jetbrains.jet.lang.descriptors.*;
import org.jetbrains.jet.lang.descriptors.annotations.AnnotationDescriptor;
import org.jetbrains.jet.lang.psi.*;
@@ -222,8 +221,8 @@ public class ClosureAnnotator {
}
private class MyJetVisitorVoid extends JetVisitorVoid {
- private LinkedList classStack = new LinkedList();
- private LinkedList nameStack = new LinkedList();
+ private final LinkedList classStack = new LinkedList();
+ private final LinkedList nameStack = new LinkedList();
private void recordEnclosing(ClassDescriptor classDescriptor) {
if (classStack.size() > 0) {
@@ -381,7 +380,9 @@ public class ClosureAnnotator {
else if (containingDeclaration instanceof NamespaceDescriptor) {
String peek = nameStack.peek();
if (peek.isEmpty()) { peek = "namespace"; }
- else { peek = peek + "/namespace"; }
+ else {
+ peek += "/namespace";
+ }
nameStack.push(peek + '$' + function.getName());
super.visitNamedFunction(function);
nameStack.pop();
@@ -410,9 +411,4 @@ public class ClosureAnnotator {
public JvmClassName classNameForClassDescriptor(@NotNull ClassDescriptor classDescriptor) {
return classNamesForClassDescriptor.get(classDescriptor);
}
-
- @Nullable
- public JvmClassName classNameForClassDescriptorIfDefined(@NotNull ClassDescriptor classDescriptor) {
- return classNamesForClassDescriptor.get(classDescriptor);
- }
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/CodegenContext.java b/compiler/backend/src/org/jetbrains/jet/codegen/CodegenContext.java
index 4f76c0d8c39..382fa0221fe 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/CodegenContext.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/CodegenContext.java
@@ -20,9 +20,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jet.lang.descriptors.*;
import org.jetbrains.jet.lang.descriptors.annotations.AnnotationDescriptor;
-import org.jetbrains.jet.lang.resolve.DescriptorUtils;
import org.jetbrains.jet.lang.resolve.java.JvmClassName;
-import org.jetbrains.jet.lang.resolve.name.Name;
import org.jetbrains.jet.lang.types.JetType;
import org.jetbrains.asm4.Type;
import org.jetbrains.asm4.commons.InstructionAdapter;
@@ -43,9 +41,6 @@ public abstract class CodegenContext {
private final CodegenContext parentContext;
public final ObjectOrClosureCodegen closure;
- HashMap typeInfoConstants;
- HashMap reverseTypeInfoConstants;
- int typeInfoConstantsCount;
HashMap accessors;
protected StackValue outerExpression;
@@ -183,50 +178,10 @@ public abstract class CodegenContext {
if (accessor != null) { return accessor; }
if (descriptor instanceof SimpleFunctionDescriptor) {
- SimpleFunctionDescriptorImpl myAccessor = new SimpleFunctionDescriptorImpl(contextDescriptor,
- Collections.emptyList(),
- Name.identifier(descriptor.getName() + "$b$" + getHierarchyCount() + "$" + accessors.size()),
- CallableMemberDescriptor.Kind.DECLARATION);
- FunctionDescriptor fd = (SimpleFunctionDescriptor) descriptor;
- myAccessor.initialize(fd.getReceiverParameter().exists() ? fd.getReceiverParameter().getType() : null,
- fd.getExpectedThisObject(),
- fd.getTypeParameters(),
- fd.getValueParameters(),
- fd.getReturnType(),
- Modality.FINAL,
- Visibilities.PUBLIC,
- /*isInline = */ false);
- accessor = myAccessor;
+ accessor = new AccessorForFunctionDescriptor(descriptor, contextDescriptor, accessors.size());
}
else if (descriptor instanceof PropertyDescriptor) {
- PropertyDescriptor pd = (PropertyDescriptor) descriptor;
- PropertyDescriptor myAccessor = new PropertyDescriptor(contextDescriptor,
- Collections.emptyList(),
- Modality.FINAL,
- Visibilities.PUBLIC,
- pd.isVar(),
- pd.isObjectDeclaration(),
- Name.identifier(pd.getName() + "$b$" + getHierarchyCount() + "$" + accessors.size()),
- CallableMemberDescriptor.Kind.DECLARATION
- );
- JetType receiverType = pd.getReceiverParameter().exists() ? pd.getReceiverParameter().getType() : null;
- myAccessor.setType(pd.getType(), Collections.emptyList(), pd.getExpectedThisObject(), receiverType);
-
- PropertyGetterDescriptor pgd = new PropertyGetterDescriptor(
- myAccessor, Collections.emptyList(),
- Modality.FINAL,
- Visibilities.PUBLIC,
- false, false, CallableMemberDescriptor.Kind.DECLARATION);
- pgd.initialize(myAccessor.getType());
-
- PropertySetterDescriptor psd = new PropertySetterDescriptor(
- myAccessor, Collections.emptyList(),
- Modality.FINAL,
- Visibilities.PUBLIC,
- false, false, CallableMemberDescriptor.Kind.DECLARATION);
-
- myAccessor.initialize(pgd, psd);
- accessor = myAccessor;
+ accessor = new AccessorForPropertyDescriptor((PropertyDescriptor) descriptor, contextDescriptor,accessors.size());
}
else {
throw new UnsupportedOperationException();
@@ -235,25 +190,6 @@ public abstract class CodegenContext {
return accessor;
}
- private int getHierarchyCount() {
- ClassDescriptor descriptor = getThisDescriptor();
- int c = 0;
- while(descriptor != null) {
- Collection extends JetType> supertypes = descriptor.getDefaultType().getConstructor().getSupertypes();
- if (supertypes.isEmpty()) {
- break;
- }
- c++;
- for (JetType supertype : supertypes) {
- descriptor = (ClassDescriptor) supertype.getConstructor().getDeclarationDescriptor();
- if (descriptor.getKind() == ClassKind.CLASS) {
- break;
- }
- }
- }
- return c;
- }
-
public StackValue getReceiverExpression(JetTypeMapper typeMapper) {
assert getReceiverDescriptor() != null;
Type asmType = typeMapper.mapType(getReceiverDescriptor().getReceiverParameter().getType(), MapTypeMode.VALUE);
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/CodegenContexts.java b/compiler/backend/src/org/jetbrains/jet/codegen/CodegenContexts.java
index bcb43beb1c9..ace432563b9 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/CodegenContexts.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/CodegenContexts.java
@@ -40,6 +40,9 @@ import java.util.List;
* @author Stepan Koltsov
*/
public class CodegenContexts {
+ private CodegenContexts() {
+ }
+
private static class FakeDescriptorForStaticContext implements DeclarationDescriptor {
@NotNull
@@ -214,7 +217,7 @@ public class CodegenContexts {
final Type type = enclosingClassType(typeMapper);
outerExpression = type != null
- ? StackValue.field(type, typeMapper.getClassFQName(contextDescriptor), "this$0", false)
+ ? StackValue.field(type, typeMapper.getJvmClassName(contextDescriptor), "this$0", false)
: null;
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/ConstructorFrameMap.java b/compiler/backend/src/org/jetbrains/jet/codegen/ConstructorFrameMap.java
index e2acc6b3063..cb3ffe37da7 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/ConstructorFrameMap.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/ConstructorFrameMap.java
@@ -17,6 +17,7 @@
package org.jetbrains.jet.codegen;
import org.jetbrains.annotations.Nullable;
+import org.jetbrains.jet.lang.descriptors.ClassKind;
import org.jetbrains.jet.lang.descriptors.ConstructorDescriptor;
import org.jetbrains.jet.lang.descriptors.ValueParameterDescriptor;
import org.jetbrains.asm4.Type;
@@ -42,6 +43,11 @@ public class ConstructorFrameMap extends FrameMap {
List explicitArgTypes = callableMethod.getValueParameterTypes();
+ if(descriptor != null && descriptor.getContainingDeclaration().getKind() == ClassKind.ENUM_CLASS) {
+ enterTemp(); // name
+ enterTemp(); // ordinal
+ }
+
List paramDescrs = descriptor != null
? descriptor.getValueParameters()
: Collections.emptyList();
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/ExpressionCodegen.java b/compiler/backend/src/org/jetbrains/jet/codegen/ExpressionCodegen.java
index 5f30fb424cc..9191951e0c9 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/ExpressionCodegen.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/ExpressionCodegen.java
@@ -687,14 +687,26 @@ public class ExpressionCodegen extends JetVisitor {
}
private StackValue generateSingleBranchIf(StackValue condition, JetExpression expression, boolean inverse) {
+ Type expressionType = expressionType(expression);
+ Type targetType = expressionType;
+ if (!expressionType.equals(TUPLE0_TYPE)) {
+ targetType = TYPE_OBJECT;
+ }
+
+ Label elseLabel = new Label();
+ condition.condJump(elseLabel, inverse, v);
+
+ gen(expression, expressionType);
+ StackValue.coerce(expressionType, targetType, v);
+
Label end = new Label();
+ v.goTo(end);
- condition.condJump(end, inverse, v);
-
- gen(expression, Type.VOID_TYPE);
+ v.mark(elseLabel);
+ StackValue.putTuple0Instance(v);
v.mark(end);
- return StackValue.none();
+ return StackValue.onStack(targetType);
}
@Override
@@ -1023,7 +1035,11 @@ public class ExpressionCodegen extends JetVisitor {
IntrinsicMethod intrinsic = null;
if (descriptor instanceof CallableMemberDescriptor) {
- intrinsic = state.getInjector().getIntrinsics().getIntrinsic((CallableMemberDescriptor) descriptor);
+ CallableMemberDescriptor memberDescriptor = (CallableMemberDescriptor) descriptor;
+ while(memberDescriptor.getKind() == CallableMemberDescriptor.Kind.FAKE_OVERRIDE) {
+ memberDescriptor = memberDescriptor.getOverriddenDescriptors().iterator().next();
+ }
+ intrinsic = state.getInjector().getIntrinsics().getIntrinsic(memberDescriptor);
}
if (intrinsic != null) {
final Type expectedType = expressionType(expression);
@@ -1099,11 +1115,7 @@ public class ExpressionCodegen extends JetVisitor {
if (descriptor instanceof ClassDescriptor) {
PsiElement declaration = BindingContextUtils.descriptorToDeclaration(bindingContext, descriptor);
if (declaration instanceof JetClass) {
- final JetClassObject classObject = ((JetClass) declaration).getClassObject();
- if (classObject == null) {
- throw new UnsupportedOperationException("trying to reference a class which doesn't have a class object");
- }
- final ClassDescriptor descriptor1 = bindingContext.get(BindingContext.CLASS, classObject.getObjectDeclaration());
+ final ClassDescriptor descriptor1 = ((ClassDescriptor)descriptor).getClassObjectDescriptor();
assert descriptor1 != null;
final Type type = typeMapper.mapType(descriptor1.getDefaultType(), MapTypeMode.VALUE);
return StackValue.field(type,
@@ -2717,25 +2729,38 @@ The "returned" value of try expression with no finally is either the last expres
(or blocks).
*/
JetFinallySection finallyBlock = expression.getFinallyBlock();
+ FinallyBlockStackElement finallyBlockStackElement = null;
if (finallyBlock != null) {
- blockStackElements.push(new FinallyBlockStackElement(expression));
+ finallyBlockStackElement = new FinallyBlockStackElement(expression);
+ blockStackElements.push(finallyBlockStackElement);
}
JetType jetType = bindingContext.get(BindingContext.EXPRESSION_TYPE, expression);
Type expectedAsmType = asmType(jetType);
-
+
Label tryStart = new Label();
v.mark(tryStart);
v.nop(); // prevent verify error on empty try
+
gen(expression.getTryBlock(), expectedAsmType);
+
+ int savedValue = myFrameMap.enterTemp(expectedAsmType.getSize());
+ v.store(savedValue, expectedAsmType);
+
Label tryEnd = new Label();
v.mark(tryEnd);
if (finallyBlock != null) {
+ blockStackElements.pop();
gen(finallyBlock.getFinalExpression(), Type.VOID_TYPE);
+ blockStackElements.push(finallyBlockStackElement);
}
Label end = new Label();
- v.goTo(end); // TODO don't generate goto if there's no code following try/catch
- for (JetCatchClause clause : expression.getCatchClauses()) {
+ v.goTo(end);
+
+ List clauses = expression.getCatchClauses();
+ for (int i = 0, size = clauses.size(); i < size; i++) {
+ JetCatchClause clause = clauses.get(i);
+
Label clauseStart = new Label();
v.mark(clauseStart);
@@ -2748,28 +2773,45 @@ The "returned" value of try expression with no finally is either the last expres
gen(clause.getCatchBody(), expectedAsmType);
+ v.store(savedValue, expectedAsmType);
+
myFrameMap.leave(descriptor);
if (finallyBlock != null) {
+ blockStackElements.pop();
gen(finallyBlock.getFinalExpression(), Type.VOID_TYPE);
+ blockStackElements.push(finallyBlockStackElement);
}
- v.goTo(end); // TODO don't generate goto if there's no code following try/catch
+ if (i != size - 1 || finallyBlock != null) {
+ v.goTo(end);
+ }
v.visitTryCatchBlock(tryStart, tryEnd, clauseStart, descriptorType.getInternalName());
}
+
if (finallyBlock != null) {
Label finallyStart = new Label();
v.mark(finallyStart);
+ int savedException = myFrameMap.enterTemp();
+ v.store(savedException, TYPE_THROWABLE);
+
+ blockStackElements.pop();
gen(finallyBlock.getFinalExpression(), Type.VOID_TYPE);
+ blockStackElements.push(finallyBlockStackElement);
+
+ v.load(savedException, TYPE_THROWABLE);
+ myFrameMap.leaveTemp();
v.athrow();
v.visitTryCatchBlock(tryStart, tryEnd, finallyStart, null);
}
v.mark(end);
- v.nop();
+
+ v.load(savedValue, expectedAsmType);
+ myFrameMap.leaveTemp(expectedAsmType.getSize());
if (finallyBlock != null) {
blockStackElements.pop();
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/FunctionCodegen.java b/compiler/backend/src/org/jetbrains/jet/codegen/FunctionCodegen.java
index cdfe31bb26a..a745a601f41 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/FunctionCodegen.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/FunctionCodegen.java
@@ -170,8 +170,9 @@ public class FunctionCodegen {
av.visitEnd();
}
for(int i = 0; i != paramDescrs.size(); ++i) {
- JetValueParameterAnnotationWriter av = JetValueParameterAnnotationWriter.visitParameterAnnotation(mv, i + start);
ValueParameterDescriptor parameterDescriptor = paramDescrs.get(i);
+ AnnotationCodegen.forParameter(i, mv, state.getInjector().getJetTypeMapper()).genAnnotations(parameterDescriptor);
+ JetValueParameterAnnotationWriter av = JetValueParameterAnnotationWriter.visitParameterAnnotation(mv, i + start);
av.writeName(parameterDescriptor.getName().getName());
av.writeHasDefaultValue(parameterDescriptor.declaresDefaultValue());
av.writeNullable(parameterDescriptor.getType().isNullable());
@@ -444,6 +445,10 @@ public class FunctionCodegen {
FrameMap frameMap = owner.prepareFrame(state.getInjector().getJetTypeMapper());
+ if (kind instanceof OwnerKind.StaticDelegateKind) {
+ frameMap.leaveTemp();
+ }
+
ExpressionCodegen codegen = new ExpressionCodegen(mv, frameMap, jvmSignature.getReturnType(), owner, state);
int var = 0;
@@ -452,15 +457,13 @@ public class FunctionCodegen {
}
Type receiverType;
- if (receiverParameter.exists()) {
+ if (hasReceiver) {
receiverType = state.getInjector().getJetTypeMapper().mapType(receiverParameter.getType(), MapTypeMode.VALUE);
+ var += receiverType.getSize();
}
else {
receiverType = Type.DOUBLE_TYPE;
}
- if (hasReceiver) {
- var += receiverType.getSize();
- }
Type[] argTypes = jvmSignature.getArgumentTypes();
List paramDescrs = functionDescriptor.getValueParameters();
@@ -484,12 +487,15 @@ public class FunctionCodegen {
int extra = hasReceiver ? 1 : 0;
- Type[] argumentTypes = jvmSignature.getArgumentTypes();
for (int index = 0; index < paramDescrs.size(); index++) {
ValueParameterDescriptor parameterDescriptor = paramDescrs.get(index);
- Type t = argumentTypes[extra + index];
- Label endArg = null;
+ Type t = argTypes[extra + index];
+
+ if (frameMap.getIndex(parameterDescriptor) < 0) {
+ frameMap.enter(parameterDescriptor, t.getSize());
+ }
+
if (parameterDescriptor.declaresDefaultValue()) {
iv.load(maskIndex, Type.INT_TYPE);
iv.iconst(1 << index);
@@ -501,18 +507,14 @@ public class FunctionCodegen {
assert jetParameter != null;
codegen.gen(jetParameter.getDefaultValue(), t);
- endArg = new Label();
- iv.goTo(endArg);
+ int ind = frameMap.getIndex(parameterDescriptor);
+ iv.store(ind, t);
iv.mark(loadArg);
}
iv.load(var, t);
var += t.getSize();
-
- if (parameterDescriptor.declaresDefaultValue()) {
- iv.mark(endArg);
- }
}
if (!isStatic) {
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/GenerationState.java b/compiler/backend/src/org/jetbrains/jet/codegen/GenerationState.java
index f970e41208a..72e89ad3ac1 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/GenerationState.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/GenerationState.java
@@ -19,10 +19,10 @@
*/
package org.jetbrains.jet.codegen;
-import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.asm4.commons.Method;
import org.jetbrains.jet.analyzer.AnalyzeExhaust;
import org.jetbrains.jet.di.InjectorForJvmCodegen;
import org.jetbrains.jet.lang.descriptors.ClassDescriptor;
@@ -30,11 +30,10 @@ import org.jetbrains.jet.lang.descriptors.ConstructorDescriptor;
import org.jetbrains.jet.lang.descriptors.ScriptDescriptor;
import org.jetbrains.jet.lang.psi.*;
import org.jetbrains.jet.lang.resolve.BindingContext;
-import org.jetbrains.jet.lang.resolve.java.JvmClassName;
import org.jetbrains.jet.lang.resolve.ScriptNameUtil;
+import org.jetbrains.jet.lang.resolve.java.JvmClassName;
import org.jetbrains.jet.lang.resolve.name.FqName;
import org.jetbrains.jet.utils.Progress;
-import org.jetbrains.asm4.commons.Method;
import java.util.Collection;
import java.util.Collections;
@@ -42,7 +41,6 @@ import java.util.List;
import java.util.Map;
public class GenerationState {
- private final Project project;
private final Progress progress;
@NotNull
private final AnalyzeExhaust analyzeExhaust;
@@ -60,20 +58,19 @@ public class GenerationState {
private Method scriptConstructorMethod;
- public GenerationState(Project project, ClassBuilderFactory builderFactory, AnalyzeExhaust analyzeExhaust, List files) {
- this(project, builderFactory, Progress.DEAF, analyzeExhaust, files, BuiltinToJavaTypesMapping.ENABLED);
+ public GenerationState(ClassBuilderFactory builderFactory, AnalyzeExhaust analyzeExhaust, List files) {
+ this(builderFactory, Progress.DEAF, analyzeExhaust, files, BuiltinToJavaTypesMapping.ENABLED);
}
- public GenerationState(Project project, ClassBuilderFactory builderFactory, Progress progress,
+ public GenerationState(ClassBuilderFactory builderFactory, Progress progress,
@NotNull AnalyzeExhaust exhaust, @NotNull List files, @NotNull BuiltinToJavaTypesMapping builtinToJavaTypesMapping) {
- this.project = project;
this.progress = progress;
this.analyzeExhaust = exhaust;
this.files = files;
this.classBuilderMode = builderFactory.getClassBuilderMode();
this.injector = new InjectorForJvmCodegen(
analyzeExhaust.getBindingContext(),
- this.files, project, builtinToJavaTypesMapping, builderFactory.getClassBuilderMode(), this, builderFactory);
+ this.files, builtinToJavaTypesMapping, builderFactory.getClassBuilderMode(), this, builderFactory);
}
private void markUsed() {
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/ImplementationBodyCodegen.java b/compiler/backend/src/org/jetbrains/jet/codegen/ImplementationBodyCodegen.java
index e259def68f1..3a4218d912d 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/ImplementationBodyCodegen.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/ImplementationBodyCodegen.java
@@ -35,6 +35,7 @@ import org.jetbrains.jet.lang.resolve.java.JvmAbi;
import org.jetbrains.jet.lang.resolve.java.JvmClassName;
import org.jetbrains.jet.lang.resolve.java.JvmStdlibNames;
import org.jetbrains.jet.lang.types.JetType;
+import org.jetbrains.jet.lang.types.lang.JetStandardLibrary;
import org.jetbrains.jet.lexer.JetTokens;
import org.jetbrains.jet.utils.BitSetUtils;
import org.jetbrains.asm4.AnnotationVisitor;
@@ -54,6 +55,7 @@ import static org.jetbrains.asm4.Opcodes.*;
* @author alex.tkachman
*/
public class ImplementationBodyCodegen extends ClassBodyCodegen {
+ public static final String VALUES = "$VALUES";
private JetDelegationSpecifier superCall;
private String superClass;
@Nullable // null means java/lang/Object
@@ -78,6 +80,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
boolean isFinal = false;
boolean isStatic = false;
boolean isAnnotation = false;
+ boolean isEnum = false;
if (myClass instanceof JetClass) {
JetClass jetClass = (JetClass) myClass;
@@ -87,12 +90,16 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
isAbstract = true;
isInterface = true;
}
- if (jetClass.isAnnotation()) {
+ else if (jetClass.isAnnotation()) {
isAbstract = true;
isInterface = true;
isAnnotation = true;
signature.getInterfaces().add(JdkNames.JLA_ANNOTATION.getInternalName());
}
+ else if (jetClass.hasModifier(JetTokens.ENUM_KEYWORD)) {
+ isEnum = true;
+ }
+
if (!jetClass.hasModifier(JetTokens.OPEN_KEYWORD) && !isAbstract) {
isFinal = true;
}
@@ -121,6 +128,9 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
if (isAnnotation) {
access |= ACC_ANNOTATION;
}
+ if (isEnum) {
+ access |= ACC_ENUM;
+ }
v.defineClass(myClass, V1_6,
access,
signature.getName(),
@@ -270,6 +280,13 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
}
}
+
+ if(superClassType == null) {
+ if (myClass instanceof JetClass && ((JetClass) myClass).hasModifier(JetTokens.ENUM_KEYWORD)) {
+ superClassType = JetStandardLibrary.getInstance().getEnumType(descriptor.getDefaultType());
+ superClass = typeMapper.mapType(superClassType,MapTypeMode.VALUE).getInternalName();
+ }
+ }
}
@Override
@@ -293,6 +310,38 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
generateTraitMethods();
generateAccessors();
+
+ generateEnumMethods();
+ }
+
+ private void generateEnumMethods() {
+ if(myEnumConstants.size() > 0) {
+ {
+ Type type = typeMapper.mapType(JetStandardLibrary.getInstance().getArrayType(descriptor.getDefaultType()), MapTypeMode.IMPL);
+
+ MethodVisitor mv =
+ v.newMethod(myClass, ACC_PUBLIC | ACC_STATIC, "values", "()" + type.getDescriptor(), null, null);
+ mv.visitCode();
+ mv.visitFieldInsn(GETSTATIC, typeMapper.mapType(descriptor.getDefaultType(),MapTypeMode.VALUE).getInternalName(), VALUES, type.getDescriptor());
+ mv.visitMethodInsn(INVOKEVIRTUAL, type.getInternalName(), "clone", "()Ljava/lang/Object;");
+ mv.visitTypeInsn(CHECKCAST, type.getInternalName());
+ mv.visitInsn(ARETURN);
+ FunctionCodegen.endVisit(mv,"values()",myClass);
+ }
+ {
+ Type type = typeMapper.mapType(descriptor.getDefaultType(), MapTypeMode.IMPL);
+
+ MethodVisitor mv =
+ v.newMethod(myClass, ACC_PUBLIC | ACC_STATIC, "valueOf", "(Ljava/lang/String;)" + type.getDescriptor(), null, null);
+ mv.visitCode();
+ mv.visitLdcInsn(type);
+ mv.visitVarInsn(ALOAD, 0);
+ mv.visitMethodInsn(INVOKESTATIC, "java/lang/Enum", "valueOf", "(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;");
+ mv.visitTypeInsn(CHECKCAST, type.getInternalName());
+ mv.visitInsn(ARETURN);
+ FunctionCodegen.endVisit(mv,"values()",myClass);
+ }
+ }
}
private void generateAccessors() {
@@ -312,7 +361,9 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
Method originalMethod = typeMapper.mapSignature(original.getName(), original).getAsmMethod();
Type[] argTypes = method.getArgumentTypes();
- MethodVisitor mv = v.newMethod(null, ACC_BRIDGE | ACC_FINAL, bridge.getName().getName(), method.getDescriptor(), null, null);
+ String owner = typeMapper.getOwner(original, OwnerKind.IMPLEMENTATION).getInternalName();
+ MethodVisitor mv = v.newMethod(null, ACC_BRIDGE | ACC_SYNTHETIC | ACC_STATIC, bridge.getName().getName(),
+ method.getDescriptor(), null, null);
if (state.getClassBuilderMode() == ClassBuilderMode.STUBS) {
StubCodegen.generateStubCode(mv);
}
@@ -322,13 +373,13 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
InstructionAdapter iv = new InstructionAdapter(mv);
iv.load(0, JetTypeMapper.TYPE_OBJECT);
- for (int i = 0, reg = 1; i < argTypes.length; i++) {
+ for (int i = 1, reg = 1; i < argTypes.length; i++) {
Type argType = argTypes[i];
iv.load(reg, argType);
//noinspection AssignmentToForLoopParameter
reg += argType.getSize();
}
- iv.invokespecial(typeMapper.getOwner(original, OwnerKind.IMPLEMENTATION).getInternalName(), originalMethod.getName(), originalMethod.getDescriptor());
+ iv.invokespecial(owner, originalMethod.getName(), originalMethod.getDescriptor());
iv.areturn(method.getReturnType());
FunctionCodegen.endVisit(iv, "accessor", null);
@@ -342,7 +393,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
Method method = typeMapper.mapGetterSignature(bridge, OwnerKind.IMPLEMENTATION).getJvmMethodSignature().getAsmMethod();
JvmPropertyAccessorSignature originalSignature = typeMapper.mapGetterSignature(original, OwnerKind.IMPLEMENTATION);
Method originalMethod = originalSignature.getJvmMethodSignature().getAsmMethod();
- MethodVisitor mv = v.newMethod(null, ACC_PUBLIC | ACC_BRIDGE | ACC_FINAL, method.getName(), method.getDescriptor(), null, null);
+ MethodVisitor mv = v.newMethod(null, ACC_BRIDGE | ACC_SYNTHETIC | ACC_STATIC, method.getName(), method.getDescriptor(), null, null);
PropertyCodegen.generateJetPropertyAnnotation(mv, originalSignature.getPropertyTypeKotlinSignature(),
originalSignature.getJvmMethodSignature().getKotlinTypeParameter(),
original, ((PropertyDescriptor) entry.getValue()).getGetter().getVisibility());
@@ -370,7 +421,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
Method method = typeMapper.mapSetterSignature(bridge, OwnerKind.IMPLEMENTATION).getJvmMethodSignature().getAsmMethod();
JvmPropertyAccessorSignature originalSignature2 = typeMapper.mapSetterSignature(original, OwnerKind.IMPLEMENTATION);
Method originalMethod = originalSignature2.getJvmMethodSignature().getAsmMethod();
- MethodVisitor mv = v.newMethod(null, ACC_PUBLIC | ACC_BRIDGE | ACC_FINAL, method.getName(), method.getDescriptor(), null, null);
+ MethodVisitor mv = v.newMethod(null, ACC_STATIC | ACC_BRIDGE | ACC_FINAL, method.getName(), method.getDescriptor(), null, null);
PropertyCodegen.generateJetPropertyAnnotation(mv, originalSignature2.getPropertyTypeKotlinSignature(),
originalSignature2.getJvmMethodSignature().getKotlinTypeParameter(),
original, ((PropertyDescriptor) entry.getValue()).getSetter().getVisibility());
@@ -384,7 +435,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
iv.load(0, JetTypeMapper.TYPE_OBJECT);
Type[] argTypes = method.getArgumentTypes();
- for (int i = 0, reg = 1; i < argTypes.length; i++) {
+ for (int i = 1, reg = 1; i < argTypes.length; i++) {
Type argType = argTypes[i];
iv.load(reg, argType);
//noinspection AssignmentToForLoopParameter
@@ -591,7 +642,12 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
i++;
}
+ if(myClass instanceof JetClass && ((JetClass)myClass).hasModifier(JetTokens.ENUM_KEYWORD)) {
+ i += 2;
+ }
+
for (ValueParameterDescriptor valueParameter : constructorDescriptor.getValueParameters()) {
+ AnnotationCodegen.forParameter(i, mv, state.getInjector().getJetTypeMapper()).genAnnotations(valueParameter);
JetValueParameterAnnotationWriter jetValueParameterAnnotation = JetValueParameterAnnotationWriter.visitParameterAnnotation(mv, i);
jetValueParameterAnnotation.writeName(valueParameter.getName().getName());
jetValueParameterAnnotation.writeHasDefaultValue(valueParameter.declaresDefaultValue());
@@ -638,7 +694,14 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
if (superCall == null) {
iv.load(0, Type.getType("L" + superClass + ";"));
- iv.invokespecial(superClass, "", "()V");
+ if(descriptor.getKind() == ClassKind.ENUM_CLASS) {
+ iv.load(1, JetTypeMapper.JL_STRING_TYPE);
+ iv.load(2, Type.INT_TYPE);
+ iv.invokespecial(superClass, "", "(Ljava/lang/String;I)V");
+ }
+ else {
+ iv.invokespecial(superClass, "", "()V");
+ }
}
else if (superCall instanceof JetDelegatorToSuperClass) {
iv.load(0, Type.getType("L" + superClass + ";"));
@@ -862,6 +925,10 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
ClassDescriptor classDecl = constructorDescriptor.getContainingDeclaration();
iv.load(0, TYPE_OBJECT);
+ if(classDecl.getKind() == ClassKind.ENUM_CLASS) {
+ iv.load(1, JetTypeMapper.TYPE_OBJECT);
+ iv.load(2, Type.INT_TYPE);
+ }
if (classDecl.getContainingDeclaration() instanceof ClassDescriptor) {
iv.load(frameMap.getOuterThisIndex(), typeMapper.mapType(((ClassDescriptor) descriptor.getContainingDeclaration()).getDefaultType(), MapTypeMode.IMPL));
@@ -892,7 +959,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
else if (declaration instanceof JetEnumEntry && !((JetEnumEntry) declaration).hasPrimaryConstructor()) {
String name = declaration.getName();
final String desc = "L" + typeMapper.mapType(descriptor.getDefaultType(), MapTypeMode.IMPL).getInternalName() + ";";
- v.newField(declaration, ACC_PUBLIC | ACC_STATIC | ACC_FINAL, name, desc, null, null);
+ v.newField(declaration, ACC_PUBLIC | ACC_ENUM | ACC_STATIC | ACC_FINAL, name, desc, null, null);
if (myEnumConstants.isEmpty()) {
staticInitializerChunks.add(new CodeChunk() {
@Override
@@ -910,19 +977,40 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
private final List myEnumConstants = new ArrayList();
- private void initializeEnumConstants(InstructionAdapter v) {
- ExpressionCodegen codegen = new ExpressionCodegen(v, new FrameMap(), Type.VOID_TYPE, context, state);
+ private void initializeEnumConstants(InstructionAdapter iv) {
+ ExpressionCodegen codegen = new ExpressionCodegen(iv, new FrameMap(), Type.VOID_TYPE, context, state);
+ int ordinal = -1;
+ JetType myType = descriptor.getDefaultType();
+ Type myAsmType = typeMapper.mapType(myType, MapTypeMode.IMPL);
+
+ assert myEnumConstants.size() > 0;
+ JetType arrayType = JetStandardLibrary.getInstance().getArrayType(myType);
+ Type arrayAsmType = typeMapper.mapType(arrayType, MapTypeMode.IMPL);
+ v.newField(myClass, ACC_PRIVATE | ACC_STATIC | ACC_FINAL | ACC_SYNTHETIC, "$VALUES", arrayAsmType.getDescriptor(), null, null);
+
+ iv.iconst(myEnumConstants.size());
+ iv.newarray(myAsmType);
+ iv.dup();
+
for (JetEnumEntry enumConstant : myEnumConstants) {
+ ordinal++;
+
+ iv.dup();
+ iv.iconst(ordinal);
+
// TODO type and constructor parameters
- String implClass = typeMapper.mapType(descriptor.getDefaultType(), MapTypeMode.IMPL).getInternalName();
+ String implClass = typeMapper.mapType(myType, MapTypeMode.IMPL).getInternalName();
final List delegationSpecifiers = enumConstant.getDelegationSpecifiers();
if (delegationSpecifiers.size() > 1) {
throw new UnsupportedOperationException("multiple delegation specifiers for enum constant not supported");
}
- v.anew(Type.getObjectType(implClass));
- v.dup();
+ iv.anew(Type.getObjectType(implClass));
+ iv.dup();
+
+ iv.aconst(enumConstant.getName());
+ iv.iconst(ordinal);
if (delegationSpecifiers.size() == 1) {
final JetDelegationSpecifier specifier = delegationSpecifiers.get(0);
@@ -937,10 +1025,13 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
}
else {
- v.invokespecial(implClass, "", "()V");
+ iv.invokespecial(implClass, "", "(Ljava/lang/String;I)V");
}
- v.putstatic(implClass, enumConstant.getName(), "L" + implClass + ";");
+ iv.dup();
+ iv.putstatic(implClass, enumConstant.getName(), "L" + implClass + ";");
+ iv.astore(TYPE_OBJECT);
}
+ iv.putstatic(myAsmType.getInternalName(), "$VALUES", arrayAsmType.getDescriptor());
}
public static void generateInitializers(@NotNull ExpressionCodegen codegen, @NotNull InstructionAdapter iv, @NotNull List declarations,
@@ -1024,18 +1115,6 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
}
}
-
- for (JetParameter p : toClass.getPrimaryConstructorParameters()) {
- if (p.getValOrVarNode() != null) {
- PropertyDescriptor propertyDescriptor = bindingContext.get(BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, p);
- if (propertyDescriptor != null) {
- propertyCodegen.generateDefaultGetter(propertyDescriptor, ACC_PUBLIC, p);
- if (propertyDescriptor.isVar()) {
- propertyCodegen.generateDefaultSetter(propertyDescriptor, ACC_PUBLIC, p);
- }
- }
- }
- }
}
@Nullable
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/JetTypeMapper.java b/compiler/backend/src/org/jetbrains/jet/codegen/JetTypeMapper.java
index 11e8445e0e9..aea38a49409 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/JetTypeMapper.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/JetTypeMapper.java
@@ -62,6 +62,7 @@ public class JetTypeMapper {
public static final Type JL_NUMBER_TYPE = Type.getObjectType("java/lang/Number");
public static final Type JL_STRING_BUILDER = Type.getObjectType("java/lang/StringBuilder");
public static final Type JL_STRING_TYPE = Type.getObjectType("java/lang/String");
+ public static final Type JL_ENUM_TYPE = Type.getObjectType("java/lang/Enum");
public static final Type JL_CHAR_SEQUENCE_TYPE = Type.getObjectType("java/lang/CharSequence");
private static final Type JL_COMPARABLE_TYPE = Type.getObjectType("java/lang/Comparable");
public static final Type JL_CLASS_TYPE = Type.getObjectType("java/lang/Class");
@@ -84,11 +85,79 @@ public class JetTypeMapper {
public static final Type TYPE_FUNCTION0 = Type.getObjectType("jet/Function0");
public static final Type TYPE_FUNCTION1 = Type.getObjectType("jet/Function1");
+ public static class SpecialTypes {
+ private static final class SpecialTypeKey {
+ @NotNull
+ private final FqNameUnsafe className;
+ private final boolean nullable;
+
+ private SpecialTypeKey(@NotNull FqNameUnsafe className, boolean nullable) {
+ this.className = className;
+ this.nullable = nullable;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ SpecialTypeKey that = (SpecialTypeKey) o;
+
+ if (nullable != that.nullable) return false;
+ if (!className.equals(that.className)) return false;
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = className.hashCode();
+ result = 31 * result + (nullable ? 1 : 0);
+ return result;
+ }
+ }
+
+ private final Map asmTypes = Maps.newHashMap();
+
+ @Nullable
+ public Type get(@NotNull JetType type) {
+ ClassifierDescriptor classifier = type.getConstructor().getDeclarationDescriptor();
+ return asmTypes.get(new SpecialTypeKey(DescriptorUtils.getFQName(classifier), type.isNullable()));
+ }
+
+ private void register(@NotNull ClassName className, @NotNull Type nonNullType, @NotNull Type nullableType) {
+ asmTypes.put(new SpecialTypeKey(className.getFqName().toUnsafe(), true), nullableType);
+ asmTypes.put(new SpecialTypeKey(className.getFqName().toUnsafe(), false), nonNullType);
+ }
+
+ public void init() {
+ register(JetStandardLibraryNames.NOTHING, TYPE_NOTHING, TYPE_NOTHING);
+
+ for (JvmPrimitiveType jvmPrimitiveType : JvmPrimitiveType.values()) {
+ PrimitiveType primitiveType = jvmPrimitiveType.getPrimitiveType();
+ register(primitiveType.getClassName(), jvmPrimitiveType.getAsmType(), jvmPrimitiveType.getWrapper().getAsmType());
+ }
+
+ register(JetStandardLibraryNames.NUMBER, JL_NUMBER_TYPE, JL_NUMBER_TYPE);
+ register(JetStandardLibraryNames.STRING, JL_STRING_TYPE, JL_STRING_TYPE);
+ register(JetStandardLibraryNames.CHAR_SEQUENCE, JL_CHAR_SEQUENCE_TYPE, JL_CHAR_SEQUENCE_TYPE);
+ register(JetStandardLibraryNames.THROWABLE, TYPE_THROWABLE, TYPE_THROWABLE);
+ register(JetStandardLibraryNames.COMPARABLE, JL_COMPARABLE_TYPE, JL_COMPARABLE_TYPE);
+ register(JetStandardLibraryNames.ENUM, JL_ENUM_TYPE, JL_ENUM_TYPE);
+
+ for (JvmPrimitiveType jvmPrimitiveType : JvmPrimitiveType.values()) {
+ PrimitiveType primitiveType = jvmPrimitiveType.getPrimitiveType();
+ register(primitiveType.getArrayClassName(), jvmPrimitiveType.getAsmArrayType(), jvmPrimitiveType.getAsmArrayType());
+ }
+ }
+ }
+
+
public BindingContext bindingContext;
private ClosureAnnotator closureAnnotator;
private boolean mapBuiltinsToJava;
private ClassBuilderMode classBuilderMode;
-
+ private final SpecialTypes specialTypes = new SpecialTypes();
@Inject
public void setBindingContext(BindingContext bindingContext) {
@@ -112,12 +181,9 @@ public class JetTypeMapper {
@PostConstruct
public void init() {
- initKnownTypes();
+ specialTypes.init();
}
-
-
-
public boolean hasThis0(ClassDescriptor classDescriptor) {
return closureAnnotator.hasThis0(classDescriptor);
}
@@ -126,40 +192,6 @@ public class JetTypeMapper {
return closureAnnotator;
}
- private static final class KnownTypeKey {
- @NotNull
- private final FqNameUnsafe className;
- private final boolean nullable;
-
- private KnownTypeKey(@NotNull FqNameUnsafe className, boolean nullable) {
- this.className = className;
- this.nullable = nullable;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
-
- KnownTypeKey that = (KnownTypeKey) o;
-
- if (nullable != that.nullable) return false;
- if (!className.equals(that.className)) return false;
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int result = className.hashCode();
- result = 31 * result + (nullable ? 1 : 0);
- return result;
- }
- }
-
- private final HashMap knowTypes = Maps.newHashMap();
-
-
public static boolean isIntPrimitive(Type type) {
return type == Type.INT_TYPE || type == Type.SHORT_TYPE || type == Type.BYTE_TYPE || type == Type.CHAR_TYPE;
}
@@ -309,17 +341,12 @@ public class JetTypeMapper {
return null;
}
- public JvmClassName getClassFQName(ClassDescriptor classDescriptor) {
- return JvmClassName.byInternalName(getFQName(classDescriptor));
+ public JvmClassName getJvmClassName(ClassDescriptor classDescriptor) {
+ return JvmClassName.byInternalName(getJvmInternalFQName(classDescriptor));
}
- /**
- * @return Internal name
- *
- * @see DescriptorUtils#getFQName(DeclarationDescriptor)
- */
@NotNull
- private String getFQName(@NotNull DeclarationDescriptor descriptor) {
+ private String getJvmInternalFQName(@NotNull DeclarationDescriptor descriptor) {
descriptor = descriptor.getOriginal();
if (descriptor instanceof FunctionDescriptor) {
@@ -340,12 +367,15 @@ public class JetTypeMapper {
if (klass.getContainingDeclaration() instanceof ClassDescriptor) {
ClassDescriptor containingKlass = (ClassDescriptor) klass.getContainingDeclaration();
if (containingKlass.getKind() == ClassKind.ENUM_CLASS) {
- return getFQName(containingKlass);
+ return getJvmInternalFQName(containingKlass);
+ }
+ else {
+ return getJvmInternalFQName(containingKlass) + JvmAbi.CLASS_OBJECT_SUFFIX;
}
}
}
else if (klass.getKind() == ClassKind.ENUM_ENTRY) {
- return getFQName(klass.getContainingDeclaration());
+ return getJvmInternalFQName(klass.getContainingDeclaration());
}
}
@@ -363,7 +393,7 @@ public class JetTypeMapper {
return className.getInternalName();
}
- String baseName = getFQName(container);
+ String baseName = getJvmInternalFQName(container);
if (!baseName.isEmpty()) {
return baseName + (container instanceof NamespaceDescriptor ? "/" : "$") + name.getIdentifier();
}
@@ -383,17 +413,16 @@ public class JetTypeMapper {
if (mapBuiltinsToJava) {
if (classifier instanceof ClassDescriptor) {
- KnownTypeKey key = new KnownTypeKey(DescriptorUtils.getFQName(classifier), jetType.isNullable());
- known = knowTypes.get(key);
+ known = specialTypes.get(jetType);
}
}
if (known != null) {
if (kind == MapTypeMode.VALUE) {
- return mapKnownAsmType(jetType, known, signatureVisitor, false);
+ return mapKnownAsmType(jetType, known, signatureVisitor);
}
else if (kind == MapTypeMode.TYPE_PARAMETER) {
- return mapKnownAsmType(jetType, known, signatureVisitor, true);
+ return mapKnownAsmType(jetType, boxType(known), signatureVisitor);
}
else if (kind == MapTypeMode.TRAIT_IMPL) {
throw new IllegalStateException("TRAIT_IMPL is not possible for " + jetType);
@@ -426,7 +455,7 @@ public class JetTypeMapper {
}
Type asmType = Type.getObjectType("error/NonExistentClass");
if (signatureVisitor != null) {
- visitAsmType(signatureVisitor, asmType, true);
+ writeSimpleType(signatureVisitor, asmType, true);
}
checkValidType(asmType);
return asmType;
@@ -459,7 +488,7 @@ public class JetTypeMapper {
if (JetStandardClasses.getAny().equals(descriptor)) {
if (signatureVisitor != null) {
- visitAsmType(signatureVisitor, TYPE_OBJECT, jetType.isNullable());
+ writeSimpleType(signatureVisitor, TYPE_OBJECT, jetType.isNullable());
}
checkValidType(TYPE_OBJECT);
return TYPE_OBJECT;
@@ -467,33 +496,12 @@ public class JetTypeMapper {
if (descriptor instanceof ClassDescriptor) {
- Type asmType;
- boolean forceReal;
- if (JetStandardLibraryNames.COMPARABLE.is((ClassDescriptor) descriptor) && mapBuiltinsToJava) {
- if (jetType.getArguments().size() != 1) {
- throw new UnsupportedOperationException("Comparable must have one type argument");
- }
+ JvmClassName name = getJvmClassName((ClassDescriptor) descriptor);
+ Type asmType = Type.getObjectType(name.getInternalName() + (kind == MapTypeMode.TRAIT_IMPL ? JvmAbi.TRAIT_IMPL_SUFFIX : ""));
+ boolean forceReal = isForceReal(name);
- asmType = JL_COMPARABLE_TYPE;
- forceReal = false;
- }
- else {
- JvmClassName name = getClassFQName((ClassDescriptor) descriptor);
- asmType = Type.getObjectType(name.getInternalName() + (kind == MapTypeMode.TRAIT_IMPL ? JvmAbi.TRAIT_IMPL_SUFFIX : ""));
- forceReal = isForceReal(name);
- }
-
- if (signatureVisitor != null) {
- signatureVisitor.writeClassBegin(asmType.getInternalName(), jetType.isNullable(), forceReal);
- for (TypeProjection proj : jetType.getArguments()) {
- // TODO: +-
- signatureVisitor.writeTypeArgument(proj.getProjectionKind());
- mapType(proj.getType(), signatureVisitor, MapTypeMode.TYPE_PARAMETER);
- signatureVisitor.writeTypeArgumentEnd();
- }
- signatureVisitor.writeClassEnd();
- }
+ writeGenericType(jetType, signatureVisitor, asmType, forceReal);
checkValidType(asmType);
return asmType;
@@ -513,26 +521,34 @@ public class JetTypeMapper {
throw new UnsupportedOperationException("Unknown type " + jetType);
}
-
- private Type mapKnownAsmType(JetType jetType, Type asmType, @Nullable BothSignatureWriter signatureVisitor, boolean boxPrimitive) {
- if (boxPrimitive) {
- Type boxed = boxType(asmType);
- if (signatureVisitor != null) {
- visitAsmType(signatureVisitor, boxed, jetType.isNullable());
+
+ private void writeGenericType(JetType jetType, BothSignatureWriter signatureVisitor, Type asmType, boolean forceReal) {
+ if (signatureVisitor != null) {
+ signatureVisitor.writeClassBegin(asmType.getInternalName(), jetType.isNullable(), forceReal);
+ for (TypeProjection proj : jetType.getArguments()) {
+ // TODO: +-
+ signatureVisitor.writeTypeArgument(proj.getProjectionKind());
+ mapType(proj.getType(), signatureVisitor, MapTypeMode.TYPE_PARAMETER);
+ signatureVisitor.writeTypeArgumentEnd();
}
- checkValidType(boxed);
- return boxed;
- }
- else {
- if (signatureVisitor != null) {
- visitAsmType(signatureVisitor, asmType, jetType.isNullable());
- }
- checkValidType(asmType);
- return asmType;
+ signatureVisitor.writeClassEnd();
}
}
- public static void visitAsmType(BothSignatureWriter visitor, Type asmType, boolean nullable) {
+ private Type mapKnownAsmType(JetType jetType, Type asmType, @Nullable BothSignatureWriter signatureVisitor) {
+ if (signatureVisitor != null) {
+ if (jetType.getArguments().isEmpty()) {
+ writeSimpleType(signatureVisitor, asmType, jetType.isNullable());
+ }
+ else {
+ writeGenericType(jetType, signatureVisitor, asmType, false);
+ }
+ }
+ checkValidType(asmType);
+ return asmType;
+ }
+
+ public static void writeSimpleType(BothSignatureWriter visitor, Type asmType, boolean nullable) {
visitor.writeAsmType(asmType, nullable);
}
@@ -611,6 +627,8 @@ public class JetTypeMapper {
boolean originalIsInterface = CodegenUtil.isInterface(declarationOwner);
boolean currentIsInterface = CodegenUtil.isInterface(currentOwner);
+ boolean isAccessor = isAccessor(functionDescriptor);
+
ClassDescriptor receiver;
if (currentIsInterface && !originalIsInterface) {
receiver = declarationOwner;
@@ -630,7 +648,7 @@ public class JetTypeMapper {
invokeOpcode = isInterface
? (superCall ? Opcodes.INVOKESTATIC : Opcodes.INVOKEINTERFACE)
- : (superCall ? Opcodes.INVOKESPECIAL : Opcodes.INVOKEVIRTUAL);
+ : (isAccessor ? Opcodes.INVOKESTATIC : (superCall ? Opcodes.INVOKESPECIAL : Opcodes.INVOKEVIRTUAL));
if (isInterface && superCall) {
descriptor = mapSignature(functionDescriptor, false, OwnerKind.TRAIT_IMPL);
owner = JvmClassName.byInternalName(owner.getInternalName() + JvmAbi.TRAIT_IMPL_SUFFIX);
@@ -653,7 +671,11 @@ public class JetTypeMapper {
owner, ownerForDefaultImpl, ownerForDefaultParam, descriptor, invokeOpcode,
thisClass, receiverParameterType, null);
}
-
+
+ private static boolean isAccessor(FunctionDescriptor functionDescriptor) {
+ return functionDescriptor instanceof AccessorForFunctionDescriptor || functionDescriptor instanceof AccessorForPropertyDescriptor.Getter || functionDescriptor instanceof AccessorForPropertyDescriptor.Setter;
+ }
+
@NotNull
private static FunctionDescriptor findAnyDeclaration(@NotNull FunctionDescriptor function) {
//if (function.getKind() == CallableMemberDescriptor.Kind.DECLARATION) {
@@ -682,6 +704,12 @@ public class JetTypeMapper {
signatureVisitor.writeParametersStart();
+ if(isAccessor(f)) {
+ signatureVisitor.writeParameterType(JvmMethodParameterKind.THIS);
+ mapType(((ClassifierDescriptor)f.getContainingDeclaration()).getDefaultType(), signatureVisitor, MapTypeMode.VALUE);
+ signatureVisitor.writeParameterTypeEnd();
+ }
+
if (kind == OwnerKind.TRAIT_IMPL) {
ClassDescriptor containingDeclaration = (ClassDescriptor) f.getContainingDeclaration();
JetType jetType = TraitImplBodyCodegen.getSuperClass(containingDeclaration);
@@ -784,7 +812,13 @@ public class JetTypeMapper {
writeFormalTypeParameters(f.getTypeParameters(), signatureWriter);
signatureWriter.writeParametersStart();
-
+
+ if(isAccessor(f)) {
+ signatureWriter.writeParameterType(JvmMethodParameterKind.THIS);
+ mapType(((ClassifierDescriptor)f.getContainingDeclaration()).getDefaultType(), signatureWriter, MapTypeMode.VALUE);
+ signatureWriter.writeParameterTypeEnd();
+ }
+
final List parameters = f.getValueParameters();
if (receiver.exists()) {
signatureWriter.writeParameterType(JvmMethodParameterKind.RECEIVER);
@@ -826,6 +860,13 @@ public class JetTypeMapper {
mapType(containingDeclaration.getDefaultType(), signatureWriter, MapTypeMode.IMPL);
signatureWriter.writeParameterTypeEnd();
}
+ else {
+ if(descriptor instanceof AccessorForPropertyDescriptor) {
+ signatureWriter.writeParameterType(JvmMethodParameterKind.THIS);
+ mapType(((ClassifierDescriptor)descriptor.getContainingDeclaration()).getDefaultType(), signatureWriter, MapTypeMode.VALUE);
+ signatureWriter.writeParameterTypeEnd();
+ }
+ }
if (descriptor.getReceiverParameter().exists()) {
signatureWriter.writeParameterType(JvmMethodParameterKind.RECEIVER);
@@ -866,6 +907,13 @@ public class JetTypeMapper {
mapType(containingDeclaration.getDefaultType(), signatureWriter, MapTypeMode.VALUE);
signatureWriter.writeParameterTypeEnd();
}
+ else {
+ if(descriptor instanceof AccessorForPropertyDescriptor) {
+ signatureWriter.writeParameterType(JvmMethodParameterKind.THIS);
+ mapType(((ClassifierDescriptor)descriptor.getContainingDeclaration()).getDefaultType(), signatureWriter, MapTypeMode.VALUE);
+ signatureWriter.writeParameterTypeEnd();
+ }
+ }
if (descriptor.getReceiverParameter().exists()) {
signatureWriter.writeParameterType(JvmMethodParameterKind.RECEIVER);
@@ -896,9 +944,19 @@ public class JetTypeMapper {
signatureWriter.writeParametersStart();
+ ClassDescriptor containingDeclaration = descriptor.getContainingDeclaration();
if (hasThis0) {
signatureWriter.writeParameterType(JvmMethodParameterKind.THIS0);
- mapType(closureAnnotator.getEclosingClassDescriptor(descriptor.getContainingDeclaration()).getDefaultType(), signatureWriter, MapTypeMode.VALUE);
+ mapType(closureAnnotator.getEclosingClassDescriptor(containingDeclaration).getDefaultType(), signatureWriter, MapTypeMode.VALUE);
+ signatureWriter.writeParameterTypeEnd();
+ }
+
+ if(containingDeclaration.getKind() == ClassKind.ENUM_CLASS) {
+ signatureWriter.writeParameterType(JvmMethodParameterKind.ENUM_NAME);
+ mapType(JetStandardLibrary.getInstance().getStringType(), signatureWriter, MapTypeMode.VALUE);
+ signatureWriter.writeParameterTypeEnd();
+ signatureWriter.writeParameterType(JvmMethodParameterKind.ENUM_ORDINAL);
+ mapType(JetStandardLibrary.getInstance().getIntType(), signatureWriter, MapTypeMode.VALUE);
signatureWriter.writeParameterTypeEnd();
}
@@ -971,7 +1029,7 @@ public class JetTypeMapper {
return defaultFlags;
}
if (p.getContainingDeclaration() instanceof NamespaceDescriptor) {
- return ACC_PROTECTED;
+ return 0;
}
return ACC_PRIVATE;
}
@@ -995,36 +1053,13 @@ public class JetTypeMapper {
return result;
}
- private void registerKnownType(@NotNull ClassName className, @NotNull Type nonNullType, @NotNull Type nullableType) {
- knowTypes.put(new KnownTypeKey(className.getFqName().toUnsafe(), true), nullableType);
- knowTypes.put(new KnownTypeKey(className.getFqName().toUnsafe(), false), nonNullType);
- }
-
- private void initKnownTypes() {
- registerKnownType(JetStandardLibraryNames.NOTHING, TYPE_NOTHING, TYPE_NOTHING);
-
- for (JvmPrimitiveType jvmPrimitiveType : JvmPrimitiveType.values()) {
- PrimitiveType primitiveType = jvmPrimitiveType.getPrimitiveType();
- registerKnownType(primitiveType.getClassName(), jvmPrimitiveType.getAsmType(), jvmPrimitiveType.getWrapper().getAsmType());
- }
-
- registerKnownType(JetStandardLibraryNames.NUMBER, JL_NUMBER_TYPE, JL_NUMBER_TYPE);
- registerKnownType(JetStandardLibraryNames.STRING, JL_STRING_TYPE, JL_STRING_TYPE);
- registerKnownType(JetStandardLibraryNames.CHAR_SEQUENCE, JL_CHAR_SEQUENCE_TYPE, JL_CHAR_SEQUENCE_TYPE);
- registerKnownType(JetStandardLibraryNames.THROWABLE, TYPE_THROWABLE, TYPE_THROWABLE);
-
- for (JvmPrimitiveType jvmPrimitiveType : JvmPrimitiveType.values()) {
- PrimitiveType primitiveType = jvmPrimitiveType.getPrimitiveType();
- registerKnownType(primitiveType.getArrayClassName(), jvmPrimitiveType.getAsmArrayType(), jvmPrimitiveType.getAsmArrayType());
- }
- }
-
private static boolean isForceReal(JvmClassName className) {
return JvmPrimitiveType.getByWrapperClass(className) != null
|| className.getFqName().getFqName().equals("java.lang.String")
|| className.getFqName().getFqName().equals("java.lang.CharSequence")
|| className.getFqName().getFqName().equals("java.lang.Object")
|| className.getFqName().getFqName().equals("java.lang.Number")
+ || className.getFqName().getFqName().equals("java.lang.Enum")
|| className.getFqName().getFqName().equals("java.lang.Comparable");
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/PropertyCodegen.java b/compiler/backend/src/org/jetbrains/jet/codegen/PropertyCodegen.java
index 84a2f4c6307..2b43bb9085f 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/PropertyCodegen.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/PropertyCodegen.java
@@ -41,6 +41,7 @@ import java.util.BitSet;
/**
* @author max
+ * @author alex.tkachman
*/
public class PropertyCodegen {
private final GenerationState state;
@@ -75,14 +76,14 @@ public class PropertyCodegen {
}
}
- private void generateBackingField(JetProperty p, PropertyDescriptor propertyDescriptor) {
+ public void generateBackingField(PsiElement p, PropertyDescriptor propertyDescriptor) {
if (state.getBindingContext().get(BindingContext.BACKING_FIELD_REQUIRED, propertyDescriptor)) {
DeclarationDescriptor containingDeclaration = propertyDescriptor.getContainingDeclaration();
if (CodegenUtil.isInterface(containingDeclaration))
return;
Object value = null;
- final JetExpression initializer = p.getInitializer();
+ final JetExpression initializer = p instanceof JetProperty ? ((JetProperty)p).getInitializer() : null;
if (initializer != null) {
if (initializer instanceof JetConstantExpression) {
CompileTimeConstant> compileTimeValue = state.getBindingContext().get(BindingContext.COMPILE_TIME_VALUE, initializer);
@@ -91,11 +92,10 @@ public class PropertyCodegen {
}
int modifiers;
if (kind == OwnerKind.NAMESPACE) {
- int access = JetTypeMapper.getAccessModifiers(propertyDescriptor, 0);
- modifiers = access | Opcodes.ACC_STATIC;
+ modifiers = Opcodes.ACC_STATIC;
}
else {
- modifiers = JetTypeMapper.getAccessModifiers(propertyDescriptor, 0);
+ modifiers = Opcodes.ACC_PRIVATE;
}
if (!propertyDescriptor.isVar()) {
modifiers |= Opcodes.ACC_FINAL;
@@ -104,7 +104,7 @@ public class PropertyCodegen {
modifiers |= Opcodes.ACC_VOLATILE;
}
Type type = state.getInjector().getJetTypeMapper().mapType(propertyDescriptor.getType(), MapTypeMode.VALUE);
- FieldVisitor fieldVisitor = v.newField(p, modifiers, p.getName(), type.getDescriptor(), null, value);
+ FieldVisitor fieldVisitor = v.newField(p, modifiers, propertyDescriptor.getName().getName(), type.getDescriptor(), null, value);
AnnotationCodegen.forField(fieldVisitor, state.getInjector().getJetTypeMapper()).genAnnotations(propertyDescriptor);
}
}
@@ -150,7 +150,8 @@ public class PropertyCodegen {
private void generateDefaultGetter(JetProperty p) {
final PropertyDescriptor propertyDescriptor = (PropertyDescriptor) state.getBindingContext().get(BindingContext.VARIABLE, p);
- int flags = JetTypeMapper.getAccessModifiers(propertyDescriptor, 0) | (propertyDescriptor.getModality() == Modality.ABSTRACT ? Opcodes.ACC_ABSTRACT : 0);
+ assert propertyDescriptor != null;
+ int flags = JetTypeMapper.getAccessModifiers(propertyDescriptor, 0) | (propertyDescriptor.getModality() == Modality.ABSTRACT ? Opcodes.ACC_ABSTRACT : (propertyDescriptor.getModality() == Modality.FINAL ? Opcodes.ACC_FINAL : 0));
generateDefaultGetter(propertyDescriptor, flags, p);
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/StackValue.java b/compiler/backend/src/org/jetbrains/jet/codegen/StackValue.java
index 726fbc6518a..88937bf29af 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/StackValue.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/StackValue.java
@@ -212,6 +212,13 @@ public abstract class StackValue {
}
}
+ protected static void pop(Type type, InstructionAdapter v) {
+ if (type.getSize() == 1)
+ v.pop();
+ else
+ v.pop2();
+ }
+
protected void coerce(Type toType, InstructionAdapter v) {
coerce(this.type, toType, v);
}
@@ -220,10 +227,7 @@ public abstract class StackValue {
if (toType.equals(fromType)) return;
if (toType.getSort() == Type.VOID && fromType.getSort() != Type.VOID) {
- if (fromType.getSize() == 1)
- v.pop();
- else
- v.pop2();
+ pop(fromType, v);
}
else if (toType.getSort() != Type.VOID && fromType.getSort() == Type.VOID) {
if (toType.getSort() == Type.OBJECT) {
@@ -238,6 +242,10 @@ public abstract class StackValue {
else
v.iconst(0);
}
+ else if (toType.equals(JetTypeMapper.TUPLE0_TYPE) && !fromType.equals(JetTypeMapper.TUPLE0_TYPE)) {
+ pop(fromType, v);
+ putTuple0Instance(v);
+ }
else if (toType.getSort() == Type.OBJECT && fromType.equals(JetTypeMapper.TYPE_OBJECT) || toType.getSort() == Type.ARRAY) {
v.checkcast(toType);
}
@@ -357,17 +365,7 @@ public abstract class StackValue {
@Override
public void put(Type type, InstructionAdapter v) {
- if (type == Type.VOID_TYPE && this.type != Type.VOID_TYPE) {
- if (this.type.getSize() == 2) {
- v.pop2();
- }
- else {
- v.pop();
- }
- }
- else {
- coerce(type, v);
- }
+ coerce(type, v);
}
@Override
@@ -627,10 +625,7 @@ public abstract class StackValue {
method.invoke(v);
Type returnType = asmMethod.getReturnType();
if (returnType != Type.VOID_TYPE) {
- if (returnType.getSize() == 2)
- v.pop2();
- else
- v.pop();
+ pop(returnType, v);
}
}
else
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/StubCodegen.java b/compiler/backend/src/org/jetbrains/jet/codegen/StubCodegen.java
index 734786acf63..1b6fd156bb2 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/StubCodegen.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/StubCodegen.java
@@ -24,6 +24,9 @@ import org.jetbrains.asm4.commons.InstructionAdapter;
* @author Stepan Koltsov
*/
public class StubCodegen {
+ private StubCodegen() {
+ }
+
public static void generateStubThrow(MethodVisitor mv) {
new InstructionAdapter(mv).anew(Type.getObjectType("java/lang/RuntimeException"));
new InstructionAdapter(mv).dup();
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EmptyRange.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EmptyRange.java
new file mode 100644
index 00000000000..67517bb264f
--- /dev/null
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EmptyRange.java
@@ -0,0 +1,56 @@
+/*
+ * 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.intrinsics;
+
+import com.intellij.psi.PsiElement;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.jetbrains.asm4.Type;
+import org.jetbrains.asm4.commons.InstructionAdapter;
+import org.jetbrains.jet.codegen.ExpressionCodegen;
+import org.jetbrains.jet.codegen.GenerationState;
+import org.jetbrains.jet.codegen.StackValue;
+import org.jetbrains.jet.lang.psi.JetExpression;
+import org.jetbrains.jet.lang.resolve.java.JvmClassName;
+import org.jetbrains.jet.lang.types.lang.PrimitiveType;
+
+import java.util.List;
+
+/**
+ * @author Evgeny Gerashchenko
+ * @since 08.08.12
+ */
+public class EmptyRange implements IntrinsicMethod {
+ private final PrimitiveType elementType;
+
+ public EmptyRange(PrimitiveType elementType) {
+ this.elementType = elementType;
+ }
+
+ @Override
+ public StackValue generate(ExpressionCodegen codegen,
+ InstructionAdapter v,
+ @NotNull Type expectedType,
+ @Nullable PsiElement element,
+ @Nullable List arguments,
+ StackValue receiver,
+ @NotNull GenerationState state) {
+ JvmClassName name = JvmClassName.byFqNameWithoutInnerClasses(elementType.getRangeClassName().getFqName());
+ v.getstatic(name.toString(), "EMPTY", "L" + name + ";");
+ return StackValue.onStack(expectedType);
+ }
+}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EnumName.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EnumName.java
new file mode 100644
index 00000000000..a5cdeec1e79
--- /dev/null
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EnumName.java
@@ -0,0 +1,48 @@
+/*
+ * 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.intrinsics;
+
+import com.intellij.psi.PsiElement;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.jetbrains.asm4.Type;
+import org.jetbrains.asm4.commons.InstructionAdapter;
+import org.jetbrains.jet.codegen.ExpressionCodegen;
+import org.jetbrains.jet.codegen.GenerationState;
+import org.jetbrains.jet.codegen.JetTypeMapper;
+import org.jetbrains.jet.codegen.StackValue;
+import org.jetbrains.jet.lang.psi.JetExpression;
+
+import java.util.List;
+
+public class EnumName implements IntrinsicMethod {
+ @Override
+ public StackValue generate(
+ ExpressionCodegen codegen,
+ InstructionAdapter v,
+ @NotNull Type expectedType,
+ @Nullable PsiElement element,
+ @Nullable List arguments,
+ StackValue receiver,
+ @NotNull GenerationState state
+ ) {
+ receiver.put(JetTypeMapper.TYPE_OBJECT, v);
+ v.invokevirtual("java/lang/Enum", "name", "()Ljava/lang/String;");
+ StackValue.onStack(JetTypeMapper.JL_STRING_TYPE).put(expectedType, v);
+ return StackValue.onStack(expectedType);
+ }
+}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EnumOrdinal.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EnumOrdinal.java
new file mode 100644
index 00000000000..48985a78d62
--- /dev/null
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EnumOrdinal.java
@@ -0,0 +1,48 @@
+/*
+ * 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.intrinsics;
+
+import com.intellij.psi.PsiElement;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.jetbrains.asm4.Type;
+import org.jetbrains.asm4.commons.InstructionAdapter;
+import org.jetbrains.jet.codegen.ExpressionCodegen;
+import org.jetbrains.jet.codegen.GenerationState;
+import org.jetbrains.jet.codegen.JetTypeMapper;
+import org.jetbrains.jet.codegen.StackValue;
+import org.jetbrains.jet.lang.psi.JetExpression;
+
+import java.util.List;
+
+public class EnumOrdinal implements IntrinsicMethod {
+ @Override
+ public StackValue generate(
+ ExpressionCodegen codegen,
+ InstructionAdapter v,
+ @NotNull Type expectedType,
+ @Nullable PsiElement element,
+ @Nullable List arguments,
+ StackValue receiver,
+ @NotNull GenerationState state
+ ) {
+ receiver.put(JetTypeMapper.TYPE_OBJECT, v);
+ v.invokevirtual("java/lang/Enum", "ordinal", "()I");
+ StackValue.onStack(Type.INT_TYPE).put(expectedType, v);
+ return StackValue.onStack(expectedType);
+ }
+}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EnumValueOf.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EnumValueOf.java
new file mode 100644
index 00000000000..bd6e321409f
--- /dev/null
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EnumValueOf.java
@@ -0,0 +1,51 @@
+/*
+ * 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.intrinsics;
+
+import com.intellij.psi.PsiElement;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.jetbrains.asm4.Type;
+import org.jetbrains.asm4.commons.InstructionAdapter;
+import org.jetbrains.jet.codegen.*;
+import org.jetbrains.jet.lang.descriptors.CallableDescriptor;
+import org.jetbrains.jet.lang.psi.JetCallExpression;
+import org.jetbrains.jet.lang.psi.JetExpression;
+import org.jetbrains.jet.lang.resolve.BindingContext;
+import org.jetbrains.jet.lang.resolve.calls.ResolvedCall;
+import org.jetbrains.jet.lang.resolve.java.JvmPrimitiveType;
+
+import java.util.List;
+
+/**
+ * @author alex.tkachman
+ */
+public class EnumValueOf implements IntrinsicMethod {
+ @Override
+ public StackValue generate(ExpressionCodegen codegen, InstructionAdapter v, @NotNull Type expectedType, @Nullable PsiElement element,
+ @Nullable List arguments, StackValue receiver, @NotNull GenerationState state) {
+ JetCallExpression call = (JetCallExpression) element;
+ ResolvedCall extends CallableDescriptor> resolvedCall = codegen.getBindingContext().get(BindingContext.RESOLVED_CALL, call.getCalleeExpression());
+ CallableDescriptor resultingDescriptor = resolvedCall.getResultingDescriptor();
+ Type type = state.getInjector().getJetTypeMapper().mapType(
+ resultingDescriptor.getReturnType(), MapTypeMode.VALUE);
+ codegen.gen(arguments.get(0),JetTypeMapper.JL_STRING_TYPE);
+ v.invokestatic(type.getInternalName(),"valueOf","(Ljava/lang/String;)" + type.getDescriptor());
+ StackValue.onStack(type).put(expectedType, v);
+ return StackValue.onStack(expectedType);
+ }
+}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EnumValues.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EnumValues.java
new file mode 100644
index 00000000000..45f805f873c
--- /dev/null
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EnumValues.java
@@ -0,0 +1,49 @@
+/*
+ * 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.intrinsics;
+
+import com.intellij.psi.PsiElement;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.jetbrains.asm4.Type;
+import org.jetbrains.asm4.commons.InstructionAdapter;
+import org.jetbrains.jet.codegen.*;
+import org.jetbrains.jet.lang.descriptors.CallableDescriptor;
+import org.jetbrains.jet.lang.psi.JetCallExpression;
+import org.jetbrains.jet.lang.psi.JetExpression;
+import org.jetbrains.jet.lang.resolve.BindingContext;
+import org.jetbrains.jet.lang.resolve.calls.ResolvedCall;
+
+import java.util.List;
+
+/**
+ * @author alex.tkachman
+ */
+public class EnumValues implements IntrinsicMethod {
+ @Override
+ public StackValue generate(ExpressionCodegen codegen, InstructionAdapter v, @NotNull Type expectedType, @Nullable PsiElement element,
+ @Nullable List arguments, StackValue receiver, @NotNull GenerationState state) {
+ JetCallExpression call = (JetCallExpression) element;
+ ResolvedCall extends CallableDescriptor> resolvedCall = codegen.getBindingContext().get(BindingContext.RESOLVED_CALL, call.getCalleeExpression());
+ CallableDescriptor resultingDescriptor = resolvedCall.getResultingDescriptor();
+ Type type = state.getInjector().getJetTypeMapper().mapType(
+ resultingDescriptor.getReturnType(), MapTypeMode.VALUE);
+ v.invokestatic(type.getElementType().getInternalName(), "values", "()" + type);
+ StackValue.onStack(type).put(expectedType, v);
+ return StackValue.onStack(expectedType);
+ }
+}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/IntrinsicMethods.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/IntrinsicMethods.java
index c3dad7f1755..982705e6267 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/IntrinsicMethods.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/IntrinsicMethods.java
@@ -17,23 +17,27 @@
package org.jetbrains.jet.codegen.intrinsics;
import com.google.common.collect.ImmutableList;
-import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
-import org.jetbrains.jet.lang.descriptors.*;
+import org.jetbrains.asm4.Opcodes;
+import org.jetbrains.jet.lang.descriptors.CallableMemberDescriptor;
+import org.jetbrains.jet.lang.descriptors.ClassDescriptor;
+import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor;
+import org.jetbrains.jet.lang.descriptors.SimpleFunctionDescriptor;
import org.jetbrains.jet.lang.descriptors.annotations.AnnotationDescriptor;
+import org.jetbrains.jet.lang.psi.JetPsiUtil;
import org.jetbrains.jet.lang.resolve.DescriptorUtils;
import org.jetbrains.jet.lang.resolve.java.JvmPrimitiveType;
import org.jetbrains.jet.lang.resolve.name.FqNameUnsafe;
import org.jetbrains.jet.lang.resolve.name.Name;
+import org.jetbrains.jet.lang.types.expressions.OperatorConventions;
import org.jetbrains.jet.lang.types.lang.JetStandardClasses;
import org.jetbrains.jet.lang.types.lang.PrimitiveType;
-import org.jetbrains.jet.lang.types.expressions.OperatorConventions;
-import org.jetbrains.asm4.Opcodes;
import javax.annotation.PostConstruct;
-import javax.inject.Inject;
-import java.util.*;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
/**
* @author yole
@@ -44,14 +48,11 @@ public class IntrinsicMethods {
private static final IntrinsicMethod UNARY_PLUS = new UnaryPlus();
private static final IntrinsicMethod NUMBER_CAST = new NumberCast();
private static final IntrinsicMethod INV = new Inv();
- private static final IntrinsicMethod UP_TO = new UpTo(true);
- private static final IntrinsicMethod DOWN_TO = new UpTo(false);
+ private static final IntrinsicMethod RANGE_TO = new RangeTo();
private static final IntrinsicMethod INC = new Increment(1);
private static final IntrinsicMethod DEC = new Increment(-1);
private static final IntrinsicMethod HASH_CODE = new HashCode();
- private static final List PRIMITIVE_TYPES = ImmutableList.of(Name.identifier("Boolean"), Name.identifier("Byte"), Name.identifier("Char"), Name.identifier("Short"), Name.identifier("Int"), Name.identifier("Float"), Name.identifier("Long"), Name.identifier("Double"));
- private static final List PRIMITIVE_NUMBER_TYPES = ImmutableList.of(Name.identifier("Byte"), Name.identifier("Char"), Name.identifier("Short"), Name.identifier("Int"), Name.identifier("Float"), Name.identifier("Long"), Name.identifier("Double"));
public static final IntrinsicMethod ARRAY_SIZE = new ArraySize();
public static final IntrinsicMethod ARRAY_INDICES = new ArrayIndices();
public static final Equals EQUALS = new Equals();
@@ -63,18 +64,14 @@ public class IntrinsicMethods {
public static final String KOTLIN_JAVA_CLASS_FUNCTION = "kotlin.javaClass.function";
public static final String KOTLIN_ARRAYS_ARRAY = "kotlin.arrays.array";
public static final String KOTLIN_JAVA_CLASS_PROPERTY = "kotlin.javaClass.property";
+ public static final EnumValues ENUM_VALUES = new EnumValues();
+ public static final EnumValueOf ENUM_VALUE_OF = new EnumValueOf();
- private Project myProject;
private final Map namedMethods = new HashMap();
private static final IntrinsicMethod ARRAY_ITERATOR = new ArrayIterator();
private final IntrinsicsMap intrinsicsMap = new IntrinsicsMap();
- @Inject
- public void setMyProject(Project myProject) {
- this.myProject = myProject;
- }
-
@PostConstruct
public void init() {
namedMethods.put(KOTLIN_JAVA_CLASS_FUNCTION, new JavaClassFunction());
@@ -84,22 +81,21 @@ public class IntrinsicMethods {
ImmutableList primitiveCastMethods = OperatorConventions.NUMBER_CONVERSIONS.asList();
for (Name method : primitiveCastMethods) {
declareIntrinsicFunction(Name.identifier("Number"), method, 0, NUMBER_CAST);
- for (Name type : PRIMITIVE_NUMBER_TYPES) {
- declareIntrinsicFunction(type, method, 0, NUMBER_CAST);
+ for (PrimitiveType type : PrimitiveType.NUMBER_TYPES) {
+ declareIntrinsicFunction(type.getTypeName(), method, 0, NUMBER_CAST);
}
}
- for (Name type : PRIMITIVE_NUMBER_TYPES) {
- declareIntrinsicFunction(type, Name.identifier("plus"), 0, UNARY_PLUS);
- declareIntrinsicFunction(type, Name.identifier("minus"), 0, UNARY_MINUS);
- declareIntrinsicFunction(type, Name.identifier("inv"), 0, INV);
- declareIntrinsicFunction(type, Name.identifier("rangeTo"), 1, UP_TO);
- declareIntrinsicFunction(type, Name.identifier("upto"), 1, UP_TO);
- declareIntrinsicFunction(type, Name.identifier("downto"), 1, DOWN_TO);
- declareIntrinsicFunction(type, Name.identifier("inc"), 0, INC);
- declareIntrinsicFunction(type, Name.identifier("dec"), 0, DEC);
- declareIntrinsicFunction(type, Name.identifier("hashCode"), 0, HASH_CODE);
- declareIntrinsicFunction(type, Name.identifier("equals"), 1, EQUALS);
+ for (PrimitiveType type : PrimitiveType.NUMBER_TYPES) {
+ Name typeName = type.getTypeName();
+ declareIntrinsicFunction(typeName, Name.identifier("plus"), 0, UNARY_PLUS);
+ declareIntrinsicFunction(typeName, Name.identifier("minus"), 0, UNARY_MINUS);
+ declareIntrinsicFunction(typeName, Name.identifier("inv"), 0, INV);
+ declareIntrinsicFunction(typeName, Name.identifier("rangeTo"), 1, RANGE_TO);
+ declareIntrinsicFunction(typeName, Name.identifier("inc"), 0, INC);
+ declareIntrinsicFunction(typeName, Name.identifier("dec"), 0, DEC);
+ declareIntrinsicFunction(typeName, Name.identifier("hashCode"), 0, HASH_CODE);
+ declareIntrinsicFunction(typeName, Name.identifier("equals"), 1, EQUALS);
}
declareBinaryOp(Name.identifier("plus"), Opcodes.IADD);
@@ -120,6 +116,9 @@ public class IntrinsicMethods {
declareIntrinsicFunction(Name.identifier("CharSequence"), Name.identifier("get"), 1, new StringGetChar());
declareIntrinsicFunction(Name.identifier("String"), Name.identifier("get"), 1, new StringGetChar());
+ intrinsicsMap.registerIntrinsic(JetStandardClasses.STANDARD_CLASSES_FQNAME, Name.identifier("name"), 0, new EnumName());
+ intrinsicsMap.registerIntrinsic(JetStandardClasses.STANDARD_CLASSES_FQNAME, Name.identifier("ordinal"), 0, new EnumOrdinal());
+
intrinsicsMap.registerIntrinsic(JetStandardClasses.STANDARD_CLASSES_FQNAME, Name.identifier("toString"), 0, new ToString());
intrinsicsMap.registerIntrinsic(JetStandardClasses.STANDARD_CLASSES_FQNAME, Name.identifier("equals"), 1, EQUALS);
intrinsicsMap.registerIntrinsic(JetStandardClasses.STANDARD_CLASSES_FQNAME, Name.identifier("identityEquals"), 1, IDENTITY_EQUALS);
@@ -139,14 +138,20 @@ public class IntrinsicMethods {
declareIntrinsicFunction(Name.identifier("FloatIterator"), Name.identifier("next"), 0, ITERATOR_NEXT);
declareIntrinsicFunction(Name.identifier("DoubleIterator"), Name.identifier("next"), 0, ITERATOR_NEXT);
- for (Name type : PRIMITIVE_TYPES) {
- declareIntrinsicFunction(type, Name.identifier("compareTo"), 1, new CompareTo());
+ for (PrimitiveType type : PrimitiveType.values()) {
+ declareIntrinsicFunction(type.getTypeName(), Name.identifier("compareTo"), 1, new CompareTo());
}
// declareIntrinsicFunction("Any", "equals", 1, new Equals());
//
declareIntrinsicProperty(Name.identifier("CharSequence"), Name.identifier("length"), new StringLength());
declareIntrinsicProperty(Name.identifier("String"), Name.identifier("length"), new StringLength());
+ for (PrimitiveType type : PrimitiveType.NUMBER_TYPES) {
+ intrinsicsMap.registerIntrinsic(
+ JetStandardClasses.STANDARD_CLASSES_FQNAME.child(type.getRangeTypeName()).toUnsafe().child(JetPsiUtil.NO_NAME_PROVIDED),
+ Name.identifier("EMPTY"), -1, new EmptyRange(type));
+ }
+
declareArrayMethods();
}
@@ -178,8 +183,8 @@ public class IntrinsicMethods {
private void declareBinaryOp(Name methodName, int opcode) {
BinaryOp op = new BinaryOp(opcode);
- for (Name type : PRIMITIVE_TYPES) {
- declareIntrinsicFunction(type, methodName, 1, op);
+ for (PrimitiveType type : PrimitiveType.values()) {
+ declareIntrinsicFunction(type.getTypeName(), methodName, 1, op);
}
}
@@ -220,6 +225,15 @@ public class IntrinsicMethods {
return new PsiMethodCall(functionDescriptor);
}
}
+
+ if(isEnumClassObject(functionDescriptor.getContainingDeclaration())) {
+ if("values".equals(functionDescriptor.getName().getName())) {
+ return ENUM_VALUES;
+ }
+ if("valueOf".equals(functionDescriptor.getName().getName())) {
+ return ENUM_VALUE_OF;
+ }
+ }
}
List annotations = descriptor.getAnnotations();
@@ -235,4 +249,17 @@ public class IntrinsicMethods {
return intrinsicMethod;
}
+ private static boolean isEnumClassObject(DeclarationDescriptor declaration) {
+ if(declaration instanceof ClassDescriptor) {
+ ClassDescriptor descriptor = (ClassDescriptor) declaration;
+ if(descriptor.getContainingDeclaration() instanceof ClassDescriptor) {
+ ClassDescriptor containingDeclaration = (ClassDescriptor) descriptor.getContainingDeclaration();
+ //noinspection ConstantConditions
+ if(containingDeclaration != null && containingDeclaration.getClassObjectDescriptor() != null && containingDeclaration.getClassObjectDescriptor().equals(descriptor)) {
+ return true;
+ }
+ }
+ }
+ return false; //To change body of created methods use File | Settings | File Templates.
+ }
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/IntrinsicsMap.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/IntrinsicsMap.java
index c069a0dcee6..631ce95ebf8 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/IntrinsicsMap.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/IntrinsicsMap.java
@@ -82,11 +82,18 @@ class IntrinsicsMap {
private Map intrinsicsMap = Maps.newHashMap();
+ /**
+ * @param valueParameterCount -1 for property
+ */
+ public void registerIntrinsic(@NotNull FqNameUnsafe owner, @NotNull Name name, int valueParameterCount, @NotNull IntrinsicMethod impl) {
+ intrinsicsMap.put(new Key(owner, name, valueParameterCount), impl);
+ }
+
/**
* @param valueParameterCount -1 for property
*/
public void registerIntrinsic(@NotNull FqName owner, @NotNull Name name, int valueParameterCount, @NotNull IntrinsicMethod impl) {
- intrinsicsMap.put(new Key(owner.toUnsafe(), name, valueParameterCount), impl);
+ registerIntrinsic(owner.toUnsafe(), name, valueParameterCount, impl);
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/JavaClassFunction.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/JavaClassFunction.java
index f6869377639..6c73cc6d6c2 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/JavaClassFunction.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/JavaClassFunction.java
@@ -27,6 +27,7 @@ import org.jetbrains.jet.lang.resolve.BindingContext;
import org.jetbrains.jet.lang.resolve.calls.ResolvedCall;
import org.jetbrains.asm4.Type;
import org.jetbrains.asm4.commons.InstructionAdapter;
+import org.jetbrains.jet.lang.resolve.java.JvmPrimitiveType;
import java.util.List;
@@ -42,7 +43,13 @@ public class JavaClassFunction implements IntrinsicMethod {
CallableDescriptor resultingDescriptor = resolvedCall.getResultingDescriptor();
Type type = state.getInjector().getJetTypeMapper().mapType(
resultingDescriptor.getReturnType().getArguments().get(0).getType(), MapTypeMode.VALUE);
- v.aconst(type);
+ JvmPrimitiveType primitiveType = JvmPrimitiveType.getByAsmType(type);
+ if (primitiveType != null) {
+ v.getstatic(primitiveType.getWrapper().getAsmType().getInternalName(), "TYPE", "Ljava/lang/Class;");
+ }
+ else {
+ v.aconst(type);
+ }
return StackValue.onStack(JetTypeMapper.JL_CLASS_TYPE);
}
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/JavaClassProperty.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/JavaClassProperty.java
index 7ef1c4a1b9c..177f557030f 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/JavaClassProperty.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/JavaClassProperty.java
@@ -26,6 +26,7 @@ import org.jetbrains.jet.codegen.StackValue;
import org.jetbrains.jet.lang.psi.JetExpression;
import org.jetbrains.asm4.Type;
import org.jetbrains.asm4.commons.InstructionAdapter;
+import org.jetbrains.jet.lang.resolve.java.JvmPrimitiveType;
import java.util.List;
@@ -36,33 +37,13 @@ public class JavaClassProperty implements IntrinsicMethod {
@Override
public StackValue generate(ExpressionCodegen codegen, InstructionAdapter v, @NotNull Type expectedType, @Nullable PsiElement element, @Nullable List arguments, StackValue receiver, @NotNull GenerationState state) {
receiver.put(receiver.type, v);
- switch (receiver.type.getSort()) {
- case Type.BOOLEAN:
- v.getstatic("java/lang/Boolean", "TYPE", "Ljava/lang/Class;");
- break;
- case Type.BYTE:
- v.getstatic("java/lang/Byte", "TYPE", "Ljava/lang/Class;");
- break;
- case Type.SHORT:
- v.getstatic("java/lang/Short", "TYPE", "Ljava/lang/Class;");
- break;
- case Type.CHAR:
- v.getstatic("java/lang/Character", "TYPE", "Ljava/lang/Class;");
- break;
- case Type.INT:
- v.getstatic("java/lang/Integer", "TYPE", "Ljava/lang/Class;");
- break;
- case Type.LONG:
- v.getstatic("java/lang/Long", "TYPE", "Ljava/lang/Class;");
- break;
- case Type.FLOAT:
- v.getstatic("java/lang/Float", "TYPE", "Ljava/lang/Class;");
- break;
- case Type.DOUBLE:
- v.getstatic("java/lang/Double", "TYPE", "Ljava/lang/Class;");
- break;
- default:
- v.invokevirtual("java/lang/Object", "getClass", "()Ljava/lang/Class;");
+ JvmPrimitiveType primitiveType = JvmPrimitiveType.getByAsmType(receiver.type);
+ if (primitiveType != null) {
+ v.pop();
+ v.getstatic(primitiveType.getWrapper().getAsmType().getInternalName(), "TYPE", "Ljava/lang/Class;");
+ }
+ else {
+ v.invokevirtual("java/lang/Object", "getClass", "()Ljava/lang/Class;");
}
return StackValue.onStack(JetTypeMapper.JL_CLASS_TYPE);
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/PsiMethodCall.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/PsiMethodCall.java
index c8866f2229b..08ef6dbb284 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/PsiMethodCall.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/PsiMethodCall.java
@@ -32,16 +32,16 @@ import java.util.List;
* @author alex.tkachman
*/
public class PsiMethodCall implements IntrinsicMethod {
- private final SimpleFunctionDescriptor myMethod;
+ private final SimpleFunctionDescriptor method;
public PsiMethodCall(SimpleFunctionDescriptor method) {
- myMethod = method;
+ this.method = method;
}
@Override
public StackValue generate(ExpressionCodegen codegen, InstructionAdapter v, @NotNull Type expectedType, PsiElement element,
List arguments, StackValue receiver, @NotNull GenerationState state) {
- final CallableMethod callableMethod = state.getInjector().getJetTypeMapper().mapToCallableMethod(myMethod, false, OwnerKind.IMPLEMENTATION);
+ final CallableMethod callableMethod = state.getInjector().getJetTypeMapper().mapToCallableMethod(method, false, OwnerKind.IMPLEMENTATION);
codegen.invokeMethodWithArguments(callableMethod, (JetCallExpression) element, receiver);
return StackValue.onStack(callableMethod.getSignature().getAsmMethod().getReturnType());
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/UpTo.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/RangeTo.java
similarity index 82%
rename from compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/UpTo.java
rename to compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/RangeTo.java
index c83e22b7c43..f145a0a976f 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/UpTo.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/RangeTo.java
@@ -32,11 +32,9 @@ import java.util.List;
* @author yole
* @author alex.tkachman
*/
-public class UpTo implements IntrinsicMethod {
- private boolean forward;
+public class RangeTo implements IntrinsicMethod {
- public UpTo(boolean forward) {
- this.forward = forward;
+ public RangeTo() {
}
@Override
@@ -46,7 +44,7 @@ public class UpTo implements IntrinsicMethod {
final Type rightType = codegen.expressionType(arguments.get(0));
receiver.put(Type.INT_TYPE, v);
codegen.gen(arguments.get(0), rightType);
- v.invokestatic("jet/runtime/Ranges", forward ? "upTo" : "downTo", "(" + receiver.type.getDescriptor() + leftType.getDescriptor() + ")" + expectedType.getDescriptor());
+ v.invokestatic("jet/runtime/Ranges", "rangeTo", "(" + receiver.type.getDescriptor() + leftType.getDescriptor() + ")" + expectedType.getDescriptor());
return StackValue.onStack(expectedType);
}
else {
@@ -56,7 +54,7 @@ public class UpTo implements IntrinsicMethod {
// if (JetTypeMapper.isIntPrimitive(leftType)) {
codegen.gen(expression.getLeft(), leftType);
codegen.gen(expression.getRight(), rightType);
- v.invokestatic("jet/runtime/Ranges", forward ? "upTo" : "downTo", "(" + leftType.getDescriptor() + rightType.getDescriptor() + ")" + expectedType.getDescriptor());
+ v.invokestatic("jet/runtime/Ranges", "rangeTo", "(" + leftType.getDescriptor() + rightType.getDescriptor() + ")" + expectedType.getDescriptor());
return StackValue.onStack(expectedType);
// }
// else {
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/signature/JvmMethodParameterKind.java b/compiler/backend/src/org/jetbrains/jet/codegen/signature/JvmMethodParameterKind.java
index e35f2fedcac..a1c6a82c467 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/signature/JvmMethodParameterKind.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/signature/JvmMethodParameterKind.java
@@ -27,4 +27,6 @@ public enum JvmMethodParameterKind {
THIS0,
RECEIVER,
SHARED_VAR,
+ ENUM_NAME,
+ ENUM_ORDINAL,
}
diff --git a/compiler/backend/src/org/jetbrains/jet/di/InjectorForJvmCodegen.java b/compiler/backend/src/org/jetbrains/jet/di/InjectorForJvmCodegen.java
index 2837110638b..1a4039db2b2 100644
--- a/compiler/backend/src/org/jetbrains/jet/di/InjectorForJvmCodegen.java
+++ b/compiler/backend/src/org/jetbrains/jet/di/InjectorForJvmCodegen.java
@@ -20,7 +20,6 @@ package org.jetbrains.jet.di;
import org.jetbrains.jet.lang.resolve.BindingContext;
import java.util.List;
import org.jetbrains.jet.lang.psi.JetFile;
-import com.intellij.openapi.project.Project;
import org.jetbrains.jet.codegen.BuiltinToJavaTypesMapping;
import org.jetbrains.jet.codegen.ClassBuilderMode;
import org.jetbrains.jet.codegen.GenerationState;
@@ -40,7 +39,6 @@ public class InjectorForJvmCodegen {
private final BindingContext bindingContext;
private final List listOfJetFile;
- private final Project project;
private final BuiltinToJavaTypesMapping builtinToJavaTypesMapping;
private final ClassBuilderMode classBuilderMode;
private final GenerationState generationState;
@@ -56,7 +54,6 @@ public class InjectorForJvmCodegen {
public InjectorForJvmCodegen(
@NotNull BindingContext bindingContext,
@NotNull List listOfJetFile,
- @NotNull Project project,
@NotNull BuiltinToJavaTypesMapping builtinToJavaTypesMapping,
@NotNull ClassBuilderMode classBuilderMode,
@NotNull GenerationState generationState,
@@ -64,7 +61,6 @@ public class InjectorForJvmCodegen {
) {
this.bindingContext = bindingContext;
this.listOfJetFile = listOfJetFile;
- this.project = project;
this.builtinToJavaTypesMapping = builtinToJavaTypesMapping;
this.classBuilderMode = classBuilderMode;
this.generationState = generationState;
@@ -92,8 +88,6 @@ public class InjectorForJvmCodegen {
this.scriptCodegen.setMemberCodegen(memberCodegen);
this.scriptCodegen.setState(generationState);
- this.intrinsics.setMyProject(project);
-
this.classFileFactory.setBuilderFactory(classBuilderFactory);
this.classFileFactory.setState(generationState);
diff --git a/compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/KotlinToJVMBytecodeCompiler.java b/compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/KotlinToJVMBytecodeCompiler.java
index fcd5fb1139b..cfd3dbf3969 100644
--- a/compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/KotlinToJVMBytecodeCompiler.java
+++ b/compiler/cli/src/org/jetbrains/jet/cli/jvm/compiler/KotlinToJVMBytecodeCompiler.java
@@ -339,7 +339,7 @@ public class KotlinToJVMBytecodeCompiler {
environment.getConfiguration().get(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY).report(CompilerMessageSeverity.LOGGING, message, CompilerMessageLocation.NO_LOCATION);
}
};
- GenerationState generationState = new GenerationState(project, ClassBuilderFactories.binaries(stubs), backendProgress,
+ GenerationState generationState = new GenerationState(ClassBuilderFactories.binaries(stubs), backendProgress,
exhaust, environment.getSourceFiles(),
environment.getConfiguration().get(
JVMConfigurationKeys.BUILTIN_TO_JAVA_TYPES_MAPPING_KEY,
diff --git a/compiler/cli/src/org/jetbrains/jet/cli/jvm/repl/ReplInterpreter.java b/compiler/cli/src/org/jetbrains/jet/cli/jvm/repl/ReplInterpreter.java
index 8c2da3446e4..04d00a1461d 100644
--- a/compiler/cli/src/org/jetbrains/jet/cli/jvm/repl/ReplInterpreter.java
+++ b/compiler/cli/src/org/jetbrains/jet/cli/jvm/repl/ReplInterpreter.java
@@ -236,7 +236,7 @@ public class ReplInterpreter {
earierScripts.add(Pair.create(earlierLine.getScriptDescriptor(), earlierLine.getClassName()));
}
- GenerationState generationState = new GenerationState(jetCoreEnvironment.getProject(), ClassBuilderFactories.binaries(false), backendProgress,
+ GenerationState generationState = new GenerationState(ClassBuilderFactories.binaries(false), backendProgress,
AnalyzeExhaust.success(trace.getBindingContext()), Collections.singletonList(psiFile),
BuiltinToJavaTypesMapping.ENABLED);
generationState.compileScript(psiFile.getScript(), scriptClassName, earierScripts, CompilationErrorHandler.THROW_EXCEPTION);
diff --git a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaDescriptorResolver.java b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaDescriptorResolver.java
index dcdea8b641c..9ea0ffdd520 100644
--- a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaDescriptorResolver.java
+++ b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaDescriptorResolver.java
@@ -321,7 +321,7 @@ public class JavaDescriptorResolver implements DependencyClassByQualifiedNameRes
checkPsiClassIsNotJet(psiClass);
Name name = Name.identifier(psiClass.getName());
- ClassKind kind = psiClass.isInterface() ? (psiClass.isAnnotationType() ? ClassKind.ANNOTATION_CLASS : ClassKind.TRAIT) : ClassKind.CLASS;
+ ClassKind kind = psiClass.isInterface() ? (psiClass.isAnnotationType() ? ClassKind.ANNOTATION_CLASS : ClassKind.TRAIT) : (psiClass.isEnum() ? ClassKind.ENUM_CLASS : ClassKind.CLASS);
ClassOrNamespaceDescriptor containingDeclaration = resolveParentDescriptor(psiClass);
// class may be resolved during resolution of parent
diff --git a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaTypeTransformer.java b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaTypeTransformer.java
index 601ba5d926e..10d99e88bfd 100644
--- a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaTypeTransformer.java
+++ b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaTypeTransformer.java
@@ -266,6 +266,7 @@ public class JavaTypeTransformer {
classDescriptorMap.put(new FqName("java.lang.Throwable"), JetStandardLibrary.getInstance().getThrowable());
classDescriptorMap.put(new FqName("java.lang.Number"), JetStandardLibrary.getInstance().getNumber());
classDescriptorMap.put(new FqName("java.lang.Comparable"), JetStandardLibrary.getInstance().getComparable());
+ classDescriptorMap.put(new FqName("java.lang.Enum"), JetStandardLibrary.getInstance().getEnum());
}
return classDescriptorMap;
}
diff --git a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JdkNames.java b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JdkNames.java
index 352658c8d37..3aaeaacbafd 100644
--- a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JdkNames.java
+++ b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JdkNames.java
@@ -24,5 +24,8 @@ public class JdkNames {
public static final JvmClassName JL_OBJECT = JvmClassName.byInternalName("java/lang/Object");
public static final JvmClassName JL_STRING = JvmClassName.byInternalName("java/lang/String");
public static final JvmClassName JLA_ANNOTATION = JvmClassName.byInternalName("java/lang/annotation/Annotation");
+ public static final JvmClassName JLA_ENUM = JvmClassName.byInternalName("java/lang/Enum");
+ private JdkNames() {
+ }
}
diff --git a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JvmAbi.java b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JvmAbi.java
index 0c155960369..d130927080e 100644
--- a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JvmAbi.java
+++ b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JvmAbi.java
@@ -30,4 +30,7 @@ public class JvmAbi {
public static final JvmClassName JETBRAINS_NOT_NULL_ANNOTATION =
JvmClassName.byFqNameWithoutInnerClasses("org.jetbrains.annotations.NotNull");
+
+ private JvmAbi() {
+ }
}
diff --git a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JvmClassName.java b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JvmClassName.java
index 4b288bf2ea1..8d4ca797420 100644
--- a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JvmClassName.java
+++ b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JvmClassName.java
@@ -25,13 +25,6 @@ import org.jetbrains.asm4.Type;
*/
public class JvmClassName {
- @NotNull
- private final String internalName;
-
- private JvmClassName(@NotNull String internalName) {
- this.internalName = internalName;
- }
-
@NotNull
public static JvmClassName byInternalName(@NotNull String internalName) {
return new JvmClassName(internalName);
@@ -47,7 +40,7 @@ public class JvmClassName {
}
/**
- * WARNING: fq name is cannot be uniquely mapped to JVM class name.
+ * WARNING: fq name cannot be uniquely mapped to JVM class name.
*/
@NotNull
public static JvmClassName byFqNameWithoutInnerClasses(@NotNull FqName fqName) {
@@ -62,8 +55,16 @@ public class JvmClassName {
}
+ @NotNull
+ private final String internalName;
- private transient FqName fqName;
+ private FqName fqName;
+ private String descriptor;
+ private Type asmType;
+
+ private JvmClassName(@NotNull String internalName) {
+ this.internalName = internalName;
+ }
@NotNull
public FqName getFqName() {
@@ -73,15 +74,11 @@ public class JvmClassName {
return fqName;
}
-
-
@NotNull
public String getInternalName() {
return internalName;
}
- private transient String descriptor;
-
@NotNull
public String getDescriptor() {
if (descriptor == null) {
@@ -94,8 +91,6 @@ public class JvmClassName {
return descriptor;
}
- private transient Type asmType;
-
@NotNull
public Type getAsmType() {
if (asmType == null) {
diff --git a/compiler/frontend/src/jet/Enum.jet b/compiler/frontend/src/jet/Enum.jet
new file mode 100644
index 00000000000..1ded3978aee
--- /dev/null
+++ b/compiler/frontend/src/jet/Enum.jet
@@ -0,0 +1,6 @@
+package jet
+
+public abstract class Enum>(name: String, ordinal: Int) {
+ public final fun name() : String
+ public final fun ordinal() : Int
+}
diff --git a/compiler/frontend/src/jet/Numbers.jet b/compiler/frontend/src/jet/Numbers.jet
index 793b09f7ebd..190d036c0ff 100644
--- a/compiler/frontend/src/jet/Numbers.jet
+++ b/compiler/frontend/src/jet/Numbers.jet
@@ -73,22 +73,6 @@ public class Double : Number, Comparable {
public fun rangeTo(other : Byte) : DoubleRange
public fun rangeTo(other : Char) : DoubleRange
- public fun upto(other : Double) : DoubleRange
- public fun upto(other : Float) : DoubleRange
- public fun upto(other : Long) : DoubleRange
- public fun upto(other : Int) : DoubleRange
- public fun upto(other : Short) : DoubleRange
- public fun upto(other : Byte) : DoubleRange
- public fun upto(other : Char) : DoubleRange
-
- public fun downto(other : Double) : DoubleRange
- public fun downto(other : Float) : DoubleRange
- public fun downto(other : Long) : DoubleRange
- public fun downto(other : Int) : DoubleRange
- public fun downto(other : Short) : DoubleRange
- public fun downto(other : Byte) : DoubleRange
- public fun downto(other : Char) : DoubleRange
-
public fun inc() : Double
public fun dec() : Double
public fun plus() : Double
@@ -163,22 +147,6 @@ public class Float : Number, Comparable {
public fun rangeTo(other : Byte) : FloatRange
public fun rangeTo(other : Char) : FloatRange
- public fun upto(other : Double) : DoubleRange
- public fun upto(other : Float) : FloatRange
- public fun upto(other : Long) : DoubleRange
- public fun upto(other : Int) : FloatRange
- public fun upto(other : Short) : FloatRange
- public fun upto(other : Byte) : FloatRange
- public fun upto(other : Char) : FloatRange
-
- public fun downto(other : Double) : DoubleRange
- public fun downto(other : Float) : FloatRange
- public fun downto(other : Long) : DoubleRange
- public fun downto(other : Int) : FloatRange
- public fun downto(other : Short) : FloatRange
- public fun downto(other : Byte) : FloatRange
- public fun downto(other : Char) : FloatRange
-
public fun inc() : Float
public fun dec() : Float
public fun plus() : Float
@@ -253,22 +221,6 @@ public class Long : Number, Comparable {
public fun rangeTo(other : Byte) : LongRange
public fun rangeTo(other : Char) : LongRange
- public fun upto(other : Double) : DoubleRange
- public fun upto(other : Float) : FloatRange
- public fun upto(other : Long) : LongRange
- public fun upto(other : Int) : LongRange
- public fun upto(other : Short) : LongRange
- public fun upto(other : Byte) : LongRange
- public fun upto(other : Char) : LongRange
-
- public fun downto(other : Double) : DoubleRange
- public fun downto(other : Float) : FloatRange
- public fun downto(other : Long) : LongRange
- public fun downto(other : Int) : LongRange
- public fun downto(other : Short) : LongRange
- public fun downto(other : Byte) : LongRange
- public fun downto(other : Char) : LongRange
-
public fun inc() : Long
public fun dec() : Long
public fun plus() : Long
@@ -351,22 +303,6 @@ public class Int : Number, Comparable {
public fun rangeTo(other : Byte) : IntRange
public fun rangeTo(other : Char) : IntRange
- public fun upto(other : Double) : DoubleRange
- public fun upto(other : Float) : FloatRange
- public fun upto(other : Long) : LongRange
- public fun upto(other : Int) : IntRange
- public fun upto(other : Short) : IntRange
- public fun upto(other : Byte) : IntRange
- public fun upto(other : Char) : IntRange
-
- public fun downto(other : Double) : DoubleRange
- public fun downto(other : Float) : FloatRange
- public fun downto(other : Long) : LongRange
- public fun downto(other : Int) : IntRange
- public fun downto(other : Short) : IntRange
- public fun downto(other : Byte) : IntRange
- public fun downto(other : Char) : IntRange
-
public fun inc() : Int
public fun dec() : Int
public fun plus() : Int
@@ -449,22 +385,6 @@ public class Char : Number, Comparable {
public fun rangeTo(other : Byte) : CharRange
public fun rangeTo(other : Char) : CharRange
- public fun upto(other : Double) : DoubleRange
- public fun upto(other : Float) : FloatRange
- public fun upto(other : Long) : LongRange
- public fun upto(other : Int) : IntRange
- public fun upto(other : Short) : ShortRange
- public fun upto(other : Byte) : CharRange
- public fun upto(other : Char) : CharRange
-
- public fun downto(other : Double) : DoubleRange
- public fun downto(other : Float) : FloatRange
- public fun downto(other : Long) : LongRange
- public fun downto(other : Int) : IntRange
- public fun downto(other : Short) : ShortRange
- public fun downto(other : Byte) : CharRange
- public fun downto(other : Char) : CharRange
-
public fun inc() : Char
public fun dec() : Char
public fun plus() : Int
@@ -539,22 +459,6 @@ public class Short : Number, Comparable {
public fun rangeTo(other : Byte) : ShortRange
public fun rangeTo(other : Char) : ShortRange
- public fun upto(other : Double) : DoubleRange
- public fun upto(other : Float) : FloatRange
- public fun upto(other : Long) : LongRange
- public fun upto(other : Int) : IntRange
- public fun upto(other : Short) : ShortRange
- public fun upto(other : Byte) : ShortRange
- public fun upto(other : Char) : ShortRange
-
- public fun downto(other : Double) : DoubleRange
- public fun downto(other : Float) : FloatRange
- public fun downto(other : Long) : LongRange
- public fun downto(other : Int) : IntRange
- public fun downto(other : Short) : ShortRange
- public fun downto(other : Byte) : ShortRange
- public fun downto(other : Char) : ShortRange
-
public fun inc() : Short
public fun dec() : Short
public fun plus() : Short
@@ -629,22 +533,6 @@ public class Byte : Number, Comparable {
public fun rangeTo(other : Byte) : ByteRange
public fun rangeTo(other : Char) : CharRange
- public fun upto(other : Double) : DoubleRange
- public fun upto(other : Float) : FloatRange
- public fun upto(other : Long) : LongRange
- public fun upto(other : Int) : IntRange
- public fun upto(other : Short) : ShortRange
- public fun upto(other : Byte) : ByteRange
- public fun upto(other : Char) : CharRange
-
- public fun downto(other : Double) : DoubleRange
- public fun downto(other : Float) : FloatRange
- public fun downto(other : Long) : LongRange
- public fun downto(other : Int) : IntRange
- public fun downto(other : Short) : ShortRange
- public fun downto(other : Byte) : ByteRange
- public fun downto(other : Char) : CharRange
-
public fun inc() : Byte
public fun dec() : Byte
public fun plus() : Byte
diff --git a/compiler/frontend/src/jet/Ranges.jet b/compiler/frontend/src/jet/Ranges.jet
index ff24d077f30..e4e3a01c092 100644
--- a/compiler/frontend/src/jet/Ranges.jet
+++ b/compiler/frontend/src/jet/Ranges.jet
@@ -13,11 +13,13 @@ public class IntRange(public val start : Int, public val size : Int) : Range, LongIterable {
@@ -29,11 +31,13 @@ public class LongRange(public val start : Long, public val size : Long) : Range<
public val end : Long
- public fun minus() : LongRange
-
public fun step(step: Long) : LongIterator
public val isReversed : Boolean
+
+ public class object {
+ public val EMPTY: LongRange
+ }
}
public class ByteRange(public val start : Byte, public val size : Int) : Range, ByteIterable {
@@ -45,11 +49,13 @@ public class ByteRange(public val start : Byte, public val size : Int) : Range, ShortIterable {
@@ -61,11 +67,13 @@ public class ShortRange(public val start : Short, public val size : Int) : Range
public val end : Short
- public fun minus() : ShortRange
-
public fun step(step: Int) : ShortIterator
public val isReversed : Boolean
+
+ public class object {
+ public val EMPTY: ShortRange
+ }
}
public class CharRange(public val start : Char, public val size : Int) : Range, CharIterable {
@@ -77,11 +85,13 @@ public class CharRange(public val start : Char, public val size : Int) : Range {
@@ -89,11 +99,13 @@ public class FloatRange(public val start : Float, public val size : Float) : Ran
public val end : Float
- public fun minus() : FloatRange
-
public fun step(step: Float) : FloatIterator
public val isReversed : Boolean
+
+ public class object {
+ public val EMPTY: FloatRange
+ }
}
public class DoubleRange(public val start : Double, public val size : Double) : Range {
@@ -101,9 +113,11 @@ public class DoubleRange(public val start : Double, public val size : Double) :
public val end : Double
- public fun minus() : DoubleRange
-
public fun step(step: Double) : DoubleIterator
public val isReversed : Boolean
+
+ public class object {
+ public val EMPTY: DoubleRange
+ }
}
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/MutableClassDescriptorLite.java b/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/MutableClassDescriptorLite.java
index 29146968b7f..b45513ba267 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/MutableClassDescriptorLite.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/MutableClassDescriptorLite.java
@@ -17,11 +17,9 @@
package org.jetbrains.jet.lang.descriptors;
import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jet.lang.descriptors.annotations.AnnotationDescriptor;
-import org.jetbrains.jet.lang.resolve.BindingTrace;
import org.jetbrains.jet.lang.resolve.name.Name;
import org.jetbrains.jet.lang.resolve.scopes.InnerClassesScopeWrapper;
import org.jetbrains.jet.lang.resolve.scopes.JetScope;
@@ -31,7 +29,10 @@ import org.jetbrains.jet.lang.resolve.scopes.receivers.ReceiverDescriptor;
import org.jetbrains.jet.lang.types.*;
import org.jetbrains.jet.resolve.DescriptorRenderer;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
/**
* @author Stepan Koltsov
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/ScriptDescriptor.java b/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/ScriptDescriptor.java
index c65634add26..9bcc56b5514 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/ScriptDescriptor.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/ScriptDescriptor.java
@@ -21,7 +21,6 @@ import org.jetbrains.annotations.Nullable;
import org.jetbrains.jet.lang.descriptors.annotations.AnnotationDescriptor;
import org.jetbrains.jet.lang.psi.*;
import org.jetbrains.jet.lang.resolve.BindingContext;
-import org.jetbrains.jet.lang.resolve.BindingTrace;
import org.jetbrains.jet.lang.resolve.DescriptorResolver;
import org.jetbrains.jet.lang.resolve.ScriptNameUtil;
import org.jetbrains.jet.lang.resolve.name.FqName;
@@ -34,11 +33,9 @@ import org.jetbrains.jet.lang.resolve.scopes.receivers.ClassReceiver;
import org.jetbrains.jet.lang.resolve.scopes.receivers.ReceiverDescriptor;
import org.jetbrains.jet.lang.resolve.scopes.receivers.ScriptReceiver;
import org.jetbrains.jet.lang.types.JetType;
-import org.jetbrains.jet.lang.types.TypeProjection;
import org.jetbrains.jet.lang.types.TypeSubstitutor;
import org.jetbrains.jet.lang.types.lang.JetStandardClasses;
-import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
@@ -106,17 +103,8 @@ public class ScriptDescriptor extends DeclarationDescriptorNonRootImpl {
if(jetDeclaration instanceof JetProperty) {
VariableDescriptor descriptor = bindingContext.get(BindingContext.VARIABLE, jetDeclaration);
assert descriptor != null;
- propertyDescriptor = new PropertyDescriptor(classDescriptor,
- Collections.emptyList(),
- Modality.FINAL,
- propertyDescriptor.getVisibility(),
- false,
- false,
- descriptor.getName(),
- CallableMemberDescriptor.Kind.DECLARATION);
- propertyDescriptor.setType(returnType, Collections.emptyList(), classReceiver, ReceiverDescriptor.NO_RECEIVER);
- propertyDescriptor.initialize(null, null);
- classScope.addPropertyDescriptor(propertyDescriptor);
+ initializeWithDefaultGetterSetter((PropertyDescriptor) descriptor);
+ classScope.addPropertyDescriptor(descriptor);
}
else if(jetDeclaration instanceof JetNamedFunction) {
SimpleFunctionDescriptor descriptor = bindingContext.get(BindingContext.FUNCTION, jetDeclaration);
@@ -128,6 +116,21 @@ public class ScriptDescriptor extends DeclarationDescriptorNonRootImpl {
}
}
+ public static void initializeWithDefaultGetterSetter(PropertyDescriptor propertyDescriptor) {
+ PropertyGetterDescriptor getter = propertyDescriptor.getGetter();
+ if(getter == null) {
+ getter = propertyDescriptor.getVisibility() != Visibilities.PRIVATE ? DescriptorResolver.createDefaultGetter(propertyDescriptor) : null;
+ if(getter != null)
+ getter.initialize(propertyDescriptor.getType());
+ }
+
+ PropertySetterDescriptor setter = propertyDescriptor.getSetter();
+ if(setter == null) {
+ setter = propertyDescriptor.isVar() ? DescriptorResolver.createDefaultSetter(propertyDescriptor) : null;
+ }
+ propertyDescriptor.initialize(getter, setter);
+ }
+
public int getPriority() {
return priority;
}
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/TabledDescriptorRenderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/TabledDescriptorRenderer.java
index 65f82c9d199..44a0c395d78 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/TabledDescriptorRenderer.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/TabledDescriptorRenderer.java
@@ -141,43 +141,6 @@ public class TabledDescriptorRenderer {
return new TableRenderer();
}
-
- //protected final List previousTables = Lists.newArrayList();
- //private TextRow currentFirstText;
- //private List currentRows;
- //
- //public TabledDescriptorRenderer newElement() {
- // previousTables.add(new TableRenderer(currentFirstText, currentRows));
- // currentFirstText = null;
- // currentRows = Lists.newArrayList();
- // return this;
- //}
- //
- //public TabledDescriptorRenderer text(String text) {
- // if (currentRows.isEmpty()) {
- // currentFirstText = new TextRow(text);
- // return this;
- // }
- // currentRows.add(new TextRow(text));
- // return this;
- //}
- //
- //public TabledDescriptorRenderer text(String text, Object... args) {
- // return text(String.format(text, args));
- //}
-
-
-
-
- //private TabledDescriptorRenderer(@Nullable TextRow firstText, @NotNull List rows) {
- // this.currentFirstText = firstText;
- // this.currentRows = rows;
- //}
- //
- //protected TabledDescriptorRenderer() {
- // this(null, Lists.newArrayList());
- //}
-
@Override
public String toString() {
StringBuilder result = new StringBuilder();
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/parsing/JetParsing.java b/compiler/frontend/src/org/jetbrains/jet/lang/parsing/JetParsing.java
index c4c1f75402f..82bf5429fed 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/parsing/JetParsing.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/parsing/JetParsing.java
@@ -97,7 +97,7 @@ public class JetParsing extends AbstractJetParsing {
void parseFile() {
PsiBuilder.Marker fileMarker = mark();
- parsePreamble();
+ parsePreamble(true);
parseToplevelDeclarations(false);
@@ -107,22 +107,7 @@ public class JetParsing extends AbstractJetParsing {
void parseScript() {
PsiBuilder.Marker fileMarker = mark();
- PsiBuilder.Marker namespaceHeader = mark();
- PsiBuilder.Marker firstEntry = mark();
- parseModifierList(MODIFIER_LIST, true);
-
- if (at(PACKAGE_KEYWORD)) {
- advance(); // PACKAGE_KEYWORD
-
- parseNamespaceName();
-
- firstEntry.drop();
- consumeIf(SEMICOLON);
- }
- else {
- firstEntry.rollbackTo();
- }
- namespaceHeader.done(NAMESPACE_HEADER);
+ parsePreamble(false);
PsiBuilder.Marker scriptMarker = mark();
parseImportDirectives();
@@ -155,7 +140,7 @@ public class JetParsing extends AbstractJetParsing {
* : namespaceHeader? import*
* ;
*/
- private void parsePreamble() {
+ private void parsePreamble(boolean imports) {
/*
* namespaceHeader
* : modifiers "namespace" SimpleName{"."} SEMI?
@@ -187,7 +172,8 @@ public class JetParsing extends AbstractJetParsing {
}
namespaceHeader.done(NAMESPACE_HEADER);
- parseImportDirectives();
+ if(imports)
+ parseImportDirectives();
}
/* SimpleName{"."} */
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/parsing/JetScriptDefinition.java b/compiler/frontend/src/org/jetbrains/jet/lang/parsing/JetScriptDefinition.java
index cfd97e990af..df784f85136 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/parsing/JetScriptDefinition.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/parsing/JetScriptDefinition.java
@@ -28,12 +28,10 @@ import java.util.List;
public class JetScriptDefinition {
private final String extension;
private final List parameters;
- private final List imports;
- public JetScriptDefinition(String extension, List scriptParameters, @Nullable List imports) {
+ public JetScriptDefinition(String extension, List scriptParameters) {
this.extension = extension;
parameters = scriptParameters == null ? Collections.emptyList() : scriptParameters;
- this.imports = imports == null || imports.isEmpty() ? Collections.emptyList() : importPaths(imports);
}
private static List importPaths(List imports) {
@@ -44,10 +42,6 @@ public class JetScriptDefinition {
return paths;
}
- public JetScriptDefinition(String extension, List scriptParameters) {
- this(extension, scriptParameters, null);
- }
-
public JetScriptDefinition(String extension, AnalyzerScriptParameter... scriptParameters) {
this(extension, Arrays.asList(scriptParameters));
}
@@ -59,8 +53,4 @@ public class JetScriptDefinition {
public String getExtension() {
return extension;
}
-
- public List getImports() {
- return imports;
- }
}
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DescriptorResolver.java b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DescriptorResolver.java
index 4f3e312880c..90dac89c0e8 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DescriptorResolver.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DescriptorResolver.java
@@ -32,6 +32,7 @@ import org.jetbrains.jet.lang.resolve.name.Name;
import org.jetbrains.jet.lang.resolve.scopes.JetScope;
import org.jetbrains.jet.lang.resolve.scopes.WritableScope;
import org.jetbrains.jet.lang.resolve.scopes.WritableScopeImpl;
+import org.jetbrains.jet.lang.resolve.scopes.receivers.ClassReceiver;
import org.jetbrains.jet.lang.resolve.scopes.receivers.ExtensionReceiver;
import org.jetbrains.jet.lang.resolve.scopes.receivers.ReceiverDescriptor;
import org.jetbrains.jet.lang.types.*;
@@ -47,6 +48,7 @@ import javax.inject.Inject;
import java.util.*;
import static org.jetbrains.jet.lang.diagnostics.Errors.*;
+import static org.jetbrains.jet.lang.resolve.BindingContext.CLASS;
import static org.jetbrains.jet.lang.resolve.BindingContext.CONSTRUCTOR;
/**
@@ -76,7 +78,11 @@ public class DescriptorResolver {
}
- public void resolveMutableClassDescriptor(@NotNull JetClass classElement, @NotNull MutableClassDescriptor descriptor, BindingTrace trace) {
+ public void resolveMutableClassDescriptor(
+ @NotNull JetClass classElement,
+ @NotNull MutableClassDescriptor descriptor,
+ BindingTrace trace
+ ) {
// TODO : Where-clause
List typeParameters = Lists.newArrayList();
int index = 0;
@@ -114,8 +120,11 @@ public class DescriptorResolver {
public List resolveSupertypes(@NotNull JetScope scope, @NotNull JetClassOrObject jetClass, BindingTrace trace) {
List result = Lists.newArrayList();
List delegationSpecifiers = jetClass.getDelegationSpecifiers();
+ boolean isEnum = jetClass instanceof JetClass && ((JetClass) jetClass).hasModifier(JetTokens.ENUM_KEYWORD);
if (delegationSpecifiers.isEmpty()) {
- result.add(getDefaultSupertype(jetClass, trace));
+ if (!isEnum) {
+ result.add(getDefaultSupertype(jetClass, trace));
+ }
}
else {
Collection supertypes = resolveDelegationSpecifiers(
@@ -126,6 +135,19 @@ public class DescriptorResolver {
result.add(supertype);
}
}
+ if (isEnum) {
+ boolean hasSuper = false;
+ for (JetType type : result) {
+ ClassifierDescriptor descriptor = type.getConstructor().getDeclarationDescriptor();
+ if (descriptor instanceof ClassDescriptor && ((ClassDescriptor) descriptor).getKind() != ClassKind.TRAIT) {
+ hasSuper = true;
+ }
+ }
+ if (!hasSuper) {
+ ClassDescriptor classDescriptor = trace.getBindingContext().get(CLASS, jetClass);
+ result.add(0, JetStandardLibrary.getInstance().getEnumType(classDescriptor.getDefaultType()));
+ }
+ }
return result;
}
@@ -138,14 +160,20 @@ public class DescriptorResolver {
return parentDescriptor.getDefaultType();
}
else {
- trace.report(NO_GENERICS_IN_SUPERTYPE_SPECIFIER.on(((JetEnumEntry) jetClass).getNameIdentifier()));
+ trace.report(NO_GENERICS_IN_SUPERTYPE_SPECIFIER.on(jetClass.getNameIdentifier()));
return ErrorUtils.createErrorType("Supertype not specified");
}
}
return JetStandardClasses.getAnyType();
}
- public Collection resolveDelegationSpecifiers(JetScope extensibleScope, List delegationSpecifiers, @NotNull TypeResolver resolver, BindingTrace trace, boolean checkBounds) {
+ public Collection resolveDelegationSpecifiers(
+ JetScope extensibleScope,
+ List delegationSpecifiers,
+ @NotNull TypeResolver resolver,
+ BindingTrace trace,
+ boolean checkBounds
+ ) {
if (delegationSpecifiers.isEmpty()) {
return Collections.emptyList();
}
@@ -178,17 +206,24 @@ public class DescriptorResolver {
}
@NotNull
- public SimpleFunctionDescriptor resolveFunctionDescriptor(DeclarationDescriptor containingDescriptor, final JetScope scope, final JetNamedFunction function, final BindingTrace trace) {
+ public SimpleFunctionDescriptor resolveFunctionDescriptor(
+ DeclarationDescriptor containingDescriptor,
+ final JetScope scope,
+ final JetNamedFunction function,
+ final BindingTrace trace
+ ) {
final SimpleFunctionDescriptorImpl functionDescriptor = new SimpleFunctionDescriptorImpl(
containingDescriptor,
annotationResolver.resolveAnnotations(scope, function.getModifierList(), trace),
JetPsiUtil.safeName(function.getName()),
CallableMemberDescriptor.Kind.DECLARATION
);
- WritableScope innerScope = new WritableScopeImpl(scope, functionDescriptor, new TraceBasedRedeclarationHandler(trace), "Function descriptor header scope");
+ WritableScope innerScope = new WritableScopeImpl(scope, functionDescriptor, new TraceBasedRedeclarationHandler(trace),
+ "Function descriptor header scope");
innerScope.addLabeledDeclaration(functionDescriptor);
- List typeParameterDescriptors = resolveTypeParameters(functionDescriptor, innerScope, function.getTypeParameters(), trace);
+ List typeParameterDescriptors =
+ resolveTypeParameters(functionDescriptor, innerScope, function.getTypeParameters(), trace);
innerScope.changeLockLevel(WritableScope.LockLevel.BOTH);
resolveGenericBounds(function, innerScope, typeParameterDescriptors, trace);
@@ -197,12 +232,13 @@ public class DescriptorResolver {
if (receiverTypeRef != null) {
JetScope scopeForReceiver =
function.hasTypeParameterListBeforeFunctionName()
- ? innerScope
- : scope;
+ ? innerScope
+ : scope;
receiverType = typeResolver.resolveType(scopeForReceiver, receiverTypeRef, trace, true);
}
- List valueParameterDescriptors = resolveValueParameters(functionDescriptor, innerScope, function.getValueParameters(), trace);
+ List valueParameterDescriptors =
+ resolveValueParameters(functionDescriptor, innerScope, function.getValueParameters(), trace);
innerScope.changeLockLevel(WritableScope.LockLevel.READING);
@@ -217,13 +253,14 @@ public class DescriptorResolver {
else {
final JetExpression bodyExpression = function.getBodyExpression();
if (bodyExpression != null) {
- returnType = DeferredType.create(trace, new LazyValueWithDefault(ErrorUtils.createErrorType("Recursive dependency")) {
- @Override
- protected JetType compute() {
- //JetFlowInformationProvider flowInformationProvider = computeFlowData(function, bodyExpression);
- return expressionTypingServices.inferFunctionReturnType(scope, function, functionDescriptor, trace);
- }
- });
+ returnType =
+ DeferredType.create(trace, new LazyValueWithDefault(ErrorUtils.createErrorType("Recursive dependency")) {
+ @Override
+ protected JetType compute() {
+ //JetFlowInformationProvider flowInformationProvider = computeFlowData(function, bodyExpression);
+ return expressionTypingServices.inferFunctionReturnType(scope, function, functionDescriptor, trace);
+ }
+ });
}
else {
returnType = ErrorUtils.createErrorType("No type, no body");
@@ -263,7 +300,12 @@ public class DescriptorResolver {
}
@NotNull
- private List resolveValueParameters(FunctionDescriptor functionDescriptor, WritableScope parameterScope, List valueParameters, BindingTrace trace) {
+ private List resolveValueParameters(
+ FunctionDescriptor functionDescriptor,
+ WritableScope parameterScope,
+ List valueParameters,
+ BindingTrace trace
+ ) {
List result = new ArrayList();
for (int i = 0, valueParametersSize = valueParameters.size(); i < valueParametersSize; i++) {
JetParameter valueParameter = valueParameters.get(i);
@@ -278,7 +320,8 @@ public class DescriptorResolver {
type = typeResolver.resolveType(parameterScope, typeReference, trace, true);
}
- ValueParameterDescriptor valueParameterDescriptor = resolveValueParameterDescriptor(parameterScope, functionDescriptor, valueParameter, i, type, trace);
+ ValueParameterDescriptor valueParameterDescriptor =
+ resolveValueParameterDescriptor(parameterScope, functionDescriptor, valueParameter, i, type, trace);
parameterScope.addVariableDescriptor(valueParameterDescriptor);
result.add(valueParameterDescriptor);
}
@@ -288,7 +331,8 @@ public class DescriptorResolver {
@NotNull
public MutableValueParameterDescriptor resolveValueParameterDescriptor(
JetScope scope, DeclarationDescriptor declarationDescriptor,
- JetParameter valueParameter, int index, JetType type, BindingTrace trace) {
+ JetParameter valueParameter, int index, JetType type, BindingTrace trace
+ ) {
JetType varargElementType = null;
JetType variableType = type;
if (valueParameter.hasModifier(JetTokens.VARARG_KEYWORD)) {
@@ -320,7 +364,12 @@ public class DescriptorResolver {
}
}
- public List resolveTypeParameters(DeclarationDescriptor containingDescriptor, WritableScope extensibleScope, List typeParameters, BindingTrace trace) {
+ public List resolveTypeParameters(
+ DeclarationDescriptor containingDescriptor,
+ WritableScope extensibleScope,
+ List typeParameters,
+ BindingTrace trace
+ ) {
List result = new ArrayList();
for (int i = 0, typeParametersSize = typeParameters.size(); i < typeParametersSize; i++) {
JetTypeParameter typeParameter = typeParameters.get(i);
@@ -329,11 +378,17 @@ public class DescriptorResolver {
return result;
}
- private TypeParameterDescriptorImpl resolveTypeParameter(DeclarationDescriptor containingDescriptor, WritableScope extensibleScope, JetTypeParameter typeParameter, int index, BindingTrace trace) {
-// JetTypeReference extendsBound = typeParameter.getExtendsBound();
-// JetType bound = extendsBound == null
-// ? JetStandardClasses.getDefaultBound()
-// : typeResolver.resolveType(extensibleScope, extendsBound);
+ private TypeParameterDescriptorImpl resolveTypeParameter(
+ DeclarationDescriptor containingDescriptor,
+ WritableScope extensibleScope,
+ JetTypeParameter typeParameter,
+ int index,
+ BindingTrace trace
+ ) {
+ // JetTypeReference extendsBound = typeParameter.getExtendsBound();
+ // JetType bound = extendsBound == null
+ // ? JetStandardClasses.getDefaultBound()
+ // : typeResolver.resolveType(extensibleScope, extendsBound);
TypeParameterDescriptorImpl typeParameterDescriptor = TypeParameterDescriptorImpl.createForFurtherModification(
containingDescriptor,
annotationResolver.createAnnotationStubs(typeParameter.getModifierList(), trace),
@@ -342,7 +397,7 @@ public class DescriptorResolver {
JetPsiUtil.safeName(typeParameter.getName()),
index
);
-// typeParameterDescriptor.addUpperBound(bound);
+ // typeParameterDescriptor.addUpperBound(bound);
extensibleScope.addTypeParameterDescriptor(typeParameterDescriptor);
trace.record(BindingContext.TYPE_PARAMETER, typeParameter, typeParameterDescriptor);
return typeParameterDescriptor;
@@ -372,7 +427,7 @@ public class DescriptorResolver {
return constructorDescriptor;
}
- final class UpperBoundCheckerTask {
+ static final class UpperBoundCheckerTask {
JetTypeReference upperBound;
JetType upperBoundType;
boolean isClassObjectConstraint;
@@ -384,7 +439,12 @@ public class DescriptorResolver {
}
}
- public void resolveGenericBounds(@NotNull JetTypeParameterListOwner declaration, JetScope scope, List parameters, BindingTrace trace) {
+ public void resolveGenericBounds(
+ @NotNull JetTypeParameterListOwner declaration,
+ JetScope scope,
+ List parameters,
+ BindingTrace trace
+ ) {
List deferredUpperBoundCheckerTasks = Lists.newArrayList();
List typeParameters = declaration.getTypeParameters();
@@ -416,7 +476,8 @@ public class DescriptorResolver {
JetType bound = null;
if (boundTypeReference != null) {
bound = typeResolver.resolveType(scope, boundTypeReference, trace, false);
- deferredUpperBoundCheckerTasks.add(new UpperBoundCheckerTask(boundTypeReference, bound, constraint.isClassObjectContraint()));
+ deferredUpperBoundCheckerTasks
+ .add(new UpperBoundCheckerTask(boundTypeReference, bound, constraint.isClassObjectContraint()));
}
if (typeParameterDescriptor == null) {
@@ -469,7 +530,12 @@ public class DescriptorResolver {
}
}
- private static void checkUpperBoundType(JetTypeReference upperBound, JetType upperBoundType, boolean isClassObjectConstraint, BindingTrace trace) {
+ private static void checkUpperBoundType(
+ JetTypeReference upperBound,
+ JetType upperBoundType,
+ boolean isClassObjectConstraint,
+ BindingTrace trace
+ ) {
if (!TypeUtils.canHaveSubtypes(JetTypeChecker.INSTANCE, upperBoundType)) {
if (isClassObjectConstraint) {
trace.report(FINAL_CLASS_OBJECT_UPPER_BOUND.on(upperBound, upperBoundType));
@@ -481,7 +547,12 @@ public class DescriptorResolver {
}
@NotNull
- public VariableDescriptor resolveLocalVariableDescriptor(@NotNull DeclarationDescriptor containingDeclaration, @NotNull JetScope scope, @NotNull JetParameter parameter, BindingTrace trace) {
+ public VariableDescriptor resolveLocalVariableDescriptor(
+ @NotNull DeclarationDescriptor containingDeclaration,
+ @NotNull JetScope scope,
+ @NotNull JetParameter parameter,
+ BindingTrace trace
+ ) {
JetType type = resolveParameterType(scope, parameter, trace);
return resolveLocalVariableDescriptor(containingDeclaration, parameter, type, trace);
}
@@ -502,7 +573,12 @@ public class DescriptorResolver {
return type;
}
- public VariableDescriptor resolveLocalVariableDescriptor(@NotNull DeclarationDescriptor containingDeclaration, @NotNull JetParameter parameter, @NotNull JetType type, BindingTrace trace) {
+ public VariableDescriptor resolveLocalVariableDescriptor(
+ @NotNull DeclarationDescriptor containingDeclaration,
+ @NotNull JetParameter parameter,
+ @NotNull JetType type,
+ BindingTrace trace
+ ) {
VariableDescriptor variableDescriptor = new LocalVariableDescriptor(
containingDeclaration,
annotationResolver.createAnnotationStubs(parameter.getModifierList(), trace),
@@ -514,7 +590,13 @@ public class DescriptorResolver {
}
@NotNull
- public VariableDescriptor resolveLocalVariableDescriptor(DeclarationDescriptor containingDeclaration, JetScope scope, JetProperty property, DataFlowInfo dataFlowInfo, BindingTrace trace) {
+ public VariableDescriptor resolveLocalVariableDescriptor(
+ DeclarationDescriptor containingDeclaration,
+ JetScope scope,
+ JetProperty property,
+ DataFlowInfo dataFlowInfo,
+ BindingTrace trace
+ ) {
if (property.isScriptDeclaration()) {
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(
containingDeclaration,
@@ -527,24 +609,31 @@ public class DescriptorResolver {
CallableMemberDescriptor.Kind.DECLARATION
);
- JetType type = getVariableType(scope, property, dataFlowInfo, false, trace); // For a local variable the type must not be deferred
+ JetType type =
+ getVariableType(scope, property, dataFlowInfo, false, trace); // For a local variable the type must not be deferred
propertyDescriptor.setType(type, Collections.emptyList(), scope.getImplicitReceiver(), (JetType) null);
trace.record(BindingContext.VARIABLE, property, propertyDescriptor);
return propertyDescriptor;
-
}
else {
- VariableDescriptorImpl variableDescriptor = resolveLocalVariableDescriptorWithType(containingDeclaration, property, null, trace);
+ VariableDescriptorImpl variableDescriptor =
+ resolveLocalVariableDescriptorWithType(containingDeclaration, property, null, trace);
- JetType type = getVariableType(scope, property, dataFlowInfo, false, trace); // For a local variable the type must not be deferred
+ JetType type =
+ getVariableType(scope, property, dataFlowInfo, false, trace); // For a local variable the type must not be deferred
variableDescriptor.setOutType(type);
return variableDescriptor;
}
}
@NotNull
- public VariableDescriptorImpl resolveLocalVariableDescriptorWithType(DeclarationDescriptor containingDeclaration, JetProperty property, JetType type, BindingTrace trace) {
+ public VariableDescriptorImpl resolveLocalVariableDescriptorWithType(
+ DeclarationDescriptor containingDeclaration,
+ JetProperty property,
+ JetType type,
+ BindingTrace trace
+ ) {
VariableDescriptorImpl variableDescriptor = new LocalVariableDescriptor(
containingDeclaration,
annotationResolver.createAnnotationStubs(property.getModifierList(), trace),
@@ -556,11 +645,13 @@ public class DescriptorResolver {
}
@NotNull
- public VariableDescriptor resolveObjectDeclaration(@NotNull DeclarationDescriptor containingDeclaration,
+ public VariableDescriptor resolveObjectDeclaration(
+ @NotNull DeclarationDescriptor containingDeclaration,
@NotNull JetClassOrObject objectDeclaration,
- @NotNull ClassDescriptor classDescriptor, BindingTrace trace) {
+ @NotNull ClassDescriptor classDescriptor, BindingTrace trace
+ ) {
boolean isProperty = (containingDeclaration instanceof NamespaceDescriptor)
- || (containingDeclaration instanceof ClassDescriptor);
+ || (containingDeclaration instanceof ClassDescriptor);
if (isProperty) {
return resolveObjectDeclarationAsPropertyDescriptor(containingDeclaration, objectDeclaration, classDescriptor, trace);
}
@@ -570,9 +661,11 @@ public class DescriptorResolver {
}
@NotNull
- public PropertyDescriptor resolveObjectDeclarationAsPropertyDescriptor(@NotNull DeclarationDescriptor containingDeclaration,
+ public PropertyDescriptor resolveObjectDeclarationAsPropertyDescriptor(
+ @NotNull DeclarationDescriptor containingDeclaration,
@NotNull JetClassOrObject objectDeclaration,
- @NotNull ClassDescriptor classDescriptor, BindingTrace trace) {
+ @NotNull ClassDescriptor classDescriptor, BindingTrace trace
+ ) {
JetModifierList modifierList = objectDeclaration.getModifierList();
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(
containingDeclaration,
@@ -584,7 +677,8 @@ public class DescriptorResolver {
JetPsiUtil.safeName(objectDeclaration.getName()),
CallableMemberDescriptor.Kind.DECLARATION
);
- propertyDescriptor.setType(classDescriptor.getDefaultType(), Collections.emptyList(), DescriptorUtils.getExpectedThisObjectIfNeeded(containingDeclaration), ReceiverDescriptor.NO_RECEIVER);
+ propertyDescriptor.setType(classDescriptor.getDefaultType(), Collections.emptyList(),
+ DescriptorUtils.getExpectedThisObjectIfNeeded(containingDeclaration), ReceiverDescriptor.NO_RECEIVER);
propertyDescriptor.initialize(createDefaultGetter(propertyDescriptor), null);
JetObjectDeclarationName nameAsDeclaration = objectDeclaration.getNameAsDeclaration();
if (nameAsDeclaration != null) {
@@ -594,15 +688,17 @@ public class DescriptorResolver {
}
@NotNull
- private VariableDescriptor resolveObjectDeclarationAsLocalVariable(@NotNull DeclarationDescriptor containingDeclaration,
+ private VariableDescriptor resolveObjectDeclarationAsLocalVariable(
+ @NotNull DeclarationDescriptor containingDeclaration,
@NotNull JetClassOrObject objectDeclaration,
- @NotNull ClassDescriptor classDescriptor, BindingTrace trace) {
+ @NotNull ClassDescriptor classDescriptor, BindingTrace trace
+ ) {
VariableDescriptorImpl variableDescriptor = new LocalVariableDescriptor(
- containingDeclaration,
- annotationResolver.createAnnotationStubs(objectDeclaration.getModifierList(), trace),
- JetPsiUtil.safeName(objectDeclaration.getName()),
- classDescriptor.getDefaultType(),
- /*isVar =*/ false);
+ containingDeclaration,
+ annotationResolver.createAnnotationStubs(objectDeclaration.getModifierList(), trace),
+ JetPsiUtil.safeName(objectDeclaration.getName()),
+ classDescriptor.getDefaultType(),
+ /*isVar =*/ false);
JetObjectDeclarationName nameAsDeclaration = objectDeclaration.getNameAsDeclaration();
if (nameAsDeclaration != null) {
trace.record(BindingContext.VARIABLE, nameAsDeclaration, variableDescriptor);
@@ -610,10 +706,13 @@ public class DescriptorResolver {
return variableDescriptor;
}
- public JetScope getPropertyDeclarationInnerScope(@NotNull JetScope outerScope, @NotNull List extends TypeParameterDescriptor> typeParameters,
- @NotNull ReceiverDescriptor receiver, BindingTrace trace) {
+ public JetScope getPropertyDeclarationInnerScope(
+ @NotNull JetScope outerScope, @NotNull List extends TypeParameterDescriptor> typeParameters,
+ @NotNull ReceiverDescriptor receiver, BindingTrace trace
+ ) {
WritableScopeImpl result = new WritableScopeImpl(
- outerScope, outerScope.getContainingDeclaration(), new TraceBasedRedeclarationHandler(trace), "Property declaration inner scope");
+ outerScope, outerScope.getContainingDeclaration(), new TraceBasedRedeclarationHandler(trace),
+ "Property declaration inner scope");
for (TypeParameterDescriptor typeParameterDescriptor : typeParameters) {
result.addTypeParameterDescriptor(typeParameterDescriptor);
}
@@ -625,7 +724,12 @@ public class DescriptorResolver {
}
@NotNull
- public PropertyDescriptor resolvePropertyDescriptor(@NotNull DeclarationDescriptor containingDeclaration, @NotNull JetScope scope, JetProperty property, BindingTrace trace) {
+ public PropertyDescriptor resolvePropertyDescriptor(
+ @NotNull DeclarationDescriptor containingDeclaration,
+ @NotNull JetScope scope,
+ JetProperty property,
+ BindingTrace trace
+ ) {
JetModifierList modifierList = property.getModifierList();
boolean isVar = property.isVar();
@@ -655,7 +759,8 @@ public class DescriptorResolver {
}
else {
WritableScope writableScope = new WritableScopeImpl(
- scope, containingDeclaration, new TraceBasedRedeclarationHandler(trace), "Scope with type parameters of a property");
+ scope, containingDeclaration, new TraceBasedRedeclarationHandler(trace),
+ "Scope with type parameters of a property");
typeParameterDescriptors = resolveTypeParameters(containingDeclaration, writableScope, typeParameters, trace);
writableScope.changeLockLevel(WritableScope.LockLevel.READING);
resolveGenericBounds(property, writableScope, typeParameterDescriptors, trace);
@@ -669,14 +774,15 @@ public class DescriptorResolver {
}
ReceiverDescriptor receiverDescriptor = receiverType == null
- ? ReceiverDescriptor.NO_RECEIVER
- : new ExtensionReceiver(propertyDescriptor, receiverType);
+ ? ReceiverDescriptor.NO_RECEIVER
+ : new ExtensionReceiver(propertyDescriptor, receiverType);
JetScope propertyScope = getPropertyDeclarationInnerScope(scope, typeParameterDescriptors, ReceiverDescriptor.NO_RECEIVER, trace);
JetType type = getVariableType(propertyScope, property, DataFlowInfo.EMPTY, true, trace);
- propertyDescriptor.setType(type, typeParameterDescriptors, DescriptorUtils.getExpectedThisObjectIfNeeded(containingDeclaration), receiverDescriptor);
+ propertyDescriptor.setType(type, typeParameterDescriptors, DescriptorUtils.getExpectedThisObjectIfNeeded(containingDeclaration),
+ receiverDescriptor);
PropertyGetterDescriptor getter = resolvePropertyGetterDescriptor(scopeWithTypeParameters, property, propertyDescriptor, trace);
PropertySetterDescriptor setter = resolvePropertySetterDescriptor(scopeWithTypeParameters, property, propertyDescriptor, trace);
@@ -687,7 +793,8 @@ public class DescriptorResolver {
return propertyDescriptor;
}
- /*package*/ static boolean hasBody(JetProperty property) {
+ /*package*/
+ static boolean hasBody(JetProperty property) {
boolean hasBody = property.getInitializer() != null;
if (!hasBody) {
JetPropertyAccessor getter = property.getGetter();
@@ -703,7 +810,13 @@ public class DescriptorResolver {
}
@NotNull
- private JetType getVariableType(@NotNull final JetScope scope, @NotNull final JetProperty property, @NotNull final DataFlowInfo dataFlowInfo, boolean allowDeferred, final BindingTrace trace) {
+ private JetType getVariableType(
+ @NotNull final JetScope scope,
+ @NotNull final JetProperty property,
+ @NotNull final DataFlowInfo dataFlowInfo,
+ boolean allowDeferred,
+ final BindingTrace trace
+ ) {
// TODO : receiver?
JetTypeReference propertyTypeRef = property.getPropertyTypeRef();
@@ -760,7 +873,9 @@ public class DescriptorResolver {
@NotNull
/*package*/ static Visibility resolveVisibilityFromModifiers(@Nullable JetModifierList modifierList) {
- Visibility defaultVisibility = modifierList != null && modifierList.hasModifier(JetTokens.OVERRIDE_KEYWORD) ? Visibilities.INHERITED : Visibilities.INTERNAL;
+ Visibility defaultVisibility = modifierList != null && modifierList.hasModifier(JetTokens.OVERRIDE_KEYWORD)
+ ? Visibilities.INHERITED
+ : Visibilities.INTERNAL;
return resolveVisibilityFromModifiers(modifierList, defaultVisibility);
}
@@ -775,7 +890,12 @@ public class DescriptorResolver {
}
@Nullable
- private PropertySetterDescriptor resolvePropertySetterDescriptor(@NotNull JetScope scope, @NotNull JetProperty property, @NotNull PropertyDescriptor propertyDescriptor, BindingTrace trace) {
+ private PropertySetterDescriptor resolvePropertySetterDescriptor(
+ @NotNull JetScope scope,
+ @NotNull JetProperty property,
+ @NotNull PropertyDescriptor propertyDescriptor,
+ BindingTrace trace
+ ) {
JetPropertyAccessor setter = property.getSetter();
PropertySetterDescriptor setterDescriptor = null;
if (setter != null) {
@@ -783,7 +903,8 @@ public class DescriptorResolver {
JetParameter parameter = setter.getParameter();
setterDescriptor = new PropertySetterDescriptor(
- propertyDescriptor, annotations, resolveModalityFromModifiers(setter.getModifierList(), propertyDescriptor.getModality()),
+ propertyDescriptor, annotations,
+ resolveModalityFromModifiers(setter.getModifierList(), propertyDescriptor.getModality()),
resolveVisibilityFromModifiers(setter.getModifierList(), propertyDescriptor.getVisibility()),
setter.getBodyExpression() != null, false, CallableMemberDescriptor.Kind.DECLARATION);
if (parameter != null) {
@@ -812,7 +933,8 @@ public class DescriptorResolver {
}
}
- MutableValueParameterDescriptor valueParameterDescriptor = resolveValueParameterDescriptor(scope, setterDescriptor, parameter, 0, type, trace);
+ MutableValueParameterDescriptor valueParameterDescriptor =
+ resolveValueParameterDescriptor(scope, setterDescriptor, parameter, 0, type, trace);
setterDescriptor.initialize(valueParameterDescriptor);
}
else {
@@ -825,16 +947,16 @@ public class DescriptorResolver {
setterDescriptor = createDefaultSetter(propertyDescriptor);
}
- if (! property.isVar()) {
+ if (!property.isVar()) {
if (setter != null) {
-// trace.getErrorHandler().genericError(setter.asElement().getNode(), "A 'val'-property cannot have a setter");
+ // trace.getErrorHandler().genericError(setter.asElement().getNode(), "A 'val'-property cannot have a setter");
trace.report(VAL_WITH_SETTER.on(setter));
}
}
return setterDescriptor;
}
- private PropertySetterDescriptor createDefaultSetter(PropertyDescriptor propertyDescriptor) {
+ public static PropertySetterDescriptor createDefaultSetter(PropertyDescriptor propertyDescriptor) {
PropertySetterDescriptor setterDescriptor;
setterDescriptor = new PropertySetterDescriptor(
propertyDescriptor, Collections.emptyList(), propertyDescriptor.getModality(),
@@ -845,7 +967,12 @@ public class DescriptorResolver {
}
@Nullable
- private PropertyGetterDescriptor resolvePropertyGetterDescriptor(@NotNull JetScope scope, @NotNull JetProperty property, @NotNull PropertyDescriptor propertyDescriptor, BindingTrace trace) {
+ private PropertyGetterDescriptor resolvePropertyGetterDescriptor(
+ @NotNull JetScope scope,
+ @NotNull JetProperty property,
+ @NotNull PropertyDescriptor propertyDescriptor,
+ BindingTrace trace
+ ) {
PropertyGetterDescriptor getterDescriptor;
JetPropertyAccessor getter = property.getGetter();
if (getter != null) {
@@ -862,7 +989,8 @@ public class DescriptorResolver {
}
getterDescriptor = new PropertyGetterDescriptor(
- propertyDescriptor, annotations, resolveModalityFromModifiers(getter.getModifierList(), propertyDescriptor.getModality()),
+ propertyDescriptor, annotations,
+ resolveModalityFromModifiers(getter.getModifierList(), propertyDescriptor.getModality()),
resolveVisibilityFromModifiers(getter.getModifierList(), propertyDescriptor.getVisibility()),
getter.getBodyExpression() != null, false, CallableMemberDescriptor.Kind.DECLARATION);
getterDescriptor.initialize(returnType);
@@ -891,7 +1019,8 @@ public class DescriptorResolver {
boolean isPrimary,
@Nullable JetModifierList modifierList,
@NotNull JetDeclaration declarationToTrace,
- List typeParameters, @NotNull List valueParameters, BindingTrace trace) {
+ List typeParameters, @NotNull List valueParameters, BindingTrace trace
+ ) {
ConstructorDescriptorImpl constructorDescriptor = new ConstructorDescriptorImpl(
classDescriptor,
annotationResolver.resolveAnnotations(scope, modifierList, trace),
@@ -911,7 +1040,12 @@ public class DescriptorResolver {
}
@Nullable
- public ConstructorDescriptorImpl resolvePrimaryConstructorDescriptor(@NotNull JetScope scope, @NotNull ClassDescriptor classDescriptor, @NotNull JetClass classElement, BindingTrace trace) {
+ public ConstructorDescriptorImpl resolvePrimaryConstructorDescriptor(
+ @NotNull JetScope scope,
+ @NotNull ClassDescriptor classDescriptor,
+ @NotNull JetClass classElement,
+ BindingTrace trace
+ ) {
if (classDescriptor.getKind() == ClassKind.ENUM_ENTRY && !classElement.hasPrimaryConstructor()) return null;
return createConstructorDescriptor(
scope,
@@ -927,7 +1061,8 @@ public class DescriptorResolver {
@NotNull ClassDescriptor classDescriptor,
@NotNull ValueParameterDescriptor valueParameter,
@NotNull JetScope scope,
- @NotNull JetParameter parameter, BindingTrace trace) {
+ @NotNull JetParameter parameter, BindingTrace trace
+ ) {
JetType type = resolveParameterType(scope, parameter, trace);
Name name = parameter.getNameAsName();
boolean isMutable = parameter.isMutable();
@@ -950,7 +1085,8 @@ public class DescriptorResolver {
name == null ? Name.special("") : name,
CallableMemberDescriptor.Kind.DECLARATION
);
- propertyDescriptor.setType(type, Collections.emptyList(), DescriptorUtils.getExpectedThisObjectIfNeeded(classDescriptor), ReceiverDescriptor.NO_RECEIVER);
+ propertyDescriptor.setType(type, Collections.emptyList(),
+ DescriptorUtils.getExpectedThisObjectIfNeeded(classDescriptor), ReceiverDescriptor.NO_RECEIVER);
PropertyGetterDescriptor getter = createDefaultGetter(propertyDescriptor);
PropertySetterDescriptor setter = propertyDescriptor.isVar() ? createDefaultSetter(propertyDescriptor) : null;
@@ -993,7 +1129,8 @@ public class DescriptorResolver {
@NotNull JetTypeReference jetTypeArgument,
@NotNull JetType typeArgument,
@NotNull TypeParameterDescriptor typeParameterDescriptor,
- @NotNull TypeSubstitutor substitutor, BindingTrace trace) {
+ @NotNull TypeSubstitutor substitutor, BindingTrace trace
+ ) {
for (JetType bound : typeParameterDescriptor.getUpperBounds()) {
JetType substitutedBound = substitutor.safeSubstitute(bound, Variance.INVARIANT);
if (!JetTypeChecker.INSTANCE.isSubtypeOf(typeArgument, substitutedBound)) {
@@ -1001,4 +1138,51 @@ public class DescriptorResolver {
}
}
}
+
+ public static SimpleFunctionDescriptor createEnumClassObjectValuesMethod(
+ final ClassDescriptor mutableClassDescriptor,
+ ClassDescriptor classObjectDescriptor,
+ BindingTrace trace
+ ) {
+ List annotations = Collections.emptyList();
+ SimpleFunctionDescriptorImpl values =
+ new SimpleFunctionDescriptorImpl(classObjectDescriptor, annotations,
+ Name.identifier("values"),
+ CallableMemberDescriptor.Kind.DECLARATION);
+ ClassReceiver classReceiver = new ClassReceiver(classObjectDescriptor);
+ JetType type = DeferredType.create(trace, new LazyValue() {
+ @Override
+ protected JetType compute() {
+ return JetStandardLibrary.getInstance().getArrayType(mutableClassDescriptor.getDefaultType());
+ }
+ });
+ values.initialize(null, classReceiver, Collections.emptyList(),Collections.emptyList(),
+ type, Modality.FINAL,
+ Visibilities.PUBLIC, false);
+ return values;
+ }
+
+ public static SimpleFunctionDescriptor createEnumClassObjectValueOfMethod(
+ final ClassDescriptor mutableClassDescriptor,
+ ClassDescriptor classObjectDescriptor,
+ BindingTrace trace
+ ) {
+ List annotations = Collections.emptyList();
+ SimpleFunctionDescriptorImpl values =
+ new SimpleFunctionDescriptorImpl(classObjectDescriptor, annotations,
+ Name.identifier("valueOf"),
+ CallableMemberDescriptor.Kind.DECLARATION);
+ ClassReceiver classReceiver = new ClassReceiver(classObjectDescriptor);
+ JetType type = DeferredType.create(trace, new LazyValue() {
+ @Override
+ protected JetType compute() {
+ return mutableClassDescriptor.getDefaultType();
+ }
+ });
+ ValueParameterDescriptorImpl parameterDescriptor = new ValueParameterDescriptorImpl(values,0,Collections.emptyList(),Name.identifier("value"),false,JetStandardLibrary.getInstance().getStringType(),false,null);
+ values.initialize(null, classReceiver, Collections.emptyList(),Arrays.asList(parameterDescriptor),
+ type, Modality.FINAL,
+ Visibilities.PUBLIC, false);
+ return values;
+ }
}
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/ImportsResolver.java b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/ImportsResolver.java
index 9784d7bf31f..aaa45193dd7 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/ImportsResolver.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/ImportsResolver.java
@@ -22,7 +22,6 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.jet.lang.ModuleConfiguration;
import org.jetbrains.jet.lang.descriptors.*;
import org.jetbrains.jet.lang.psi.*;
-import org.jetbrains.jet.lang.resolve.lazy.ScopeProvider;
import org.jetbrains.jet.lang.resolve.name.Name;
import org.jetbrains.jet.lang.resolve.scopes.JetScope;
import org.jetbrains.jet.lang.resolve.scopes.WritableScope;
@@ -80,7 +79,7 @@ public class ImportsResolver {
private void processImports(boolean onlyClasses, @NotNull JetScope rootScope) {
for (JetFile file : context.getNamespaceDescriptors().keySet()) {
WritableScope namespaceScope = context.getNamespaceScopes().get(file);
- processImportsInFile(onlyClasses, namespaceScope, ScopeProvider.getFileImports(file), rootScope);
+ processImportsInFile(onlyClasses, namespaceScope, Lists.newArrayList(file.getImportDirectives()), rootScope);
}
for (JetScript script : context.getScripts().keySet()) {
WritableScope scriptScope = context.getScriptScopes().get(script);
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/OverrideResolver.java b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/OverrideResolver.java
index e689fef3fd1..3f446cbed43 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/OverrideResolver.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/OverrideResolver.java
@@ -189,7 +189,7 @@ public class OverrideResolver {
extractAndBindOverridesForMember(fromCurrent, notOverridden, current, sink);
}
- bindFakeOverrides(current, notOverridden, sink);
+ createAndBindFakeOverrides(current, notOverridden, sink);
}
private static void extractAndBindOverridesForMember(
@@ -222,7 +222,7 @@ public class OverrideResolver {
}
}
- private static void bindFakeOverrides(
+ private static void createAndBindFakeOverrides(
@NotNull ClassDescriptor current,
@NotNull List notOverridden,
@NotNull DescriptorSink sink
@@ -231,11 +231,11 @@ public class OverrideResolver {
while (!fromSuperQueue.isEmpty()) {
CallableMemberDescriptor notOverriddenFromSuper = fromSuperQueue.remove();
Collection overridables = extractMembersOverridableBy(notOverriddenFromSuper, fromSuperQueue, sink);
- bindFakeOverride(notOverriddenFromSuper, overridables, current, sink);
+ createAndBindFakeOverride(notOverriddenFromSuper, overridables, current, sink);
}
}
- private static void bindFakeOverride(
+ private static void createAndBindFakeOverride(
@NotNull CallableMemberDescriptor notOverriddenFromSuper,
@NotNull Collection overridables,
@NotNull ClassDescriptor current,
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TypeHierarchyResolver.java b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TypeHierarchyResolver.java
index 566fb301940..126c06e878e 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TypeHierarchyResolver.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TypeHierarchyResolver.java
@@ -24,24 +24,26 @@ import com.intellij.psi.PsiNameIdentifierOwner;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jet.lang.descriptors.*;
+import org.jetbrains.jet.lang.descriptors.annotations.AnnotationDescriptor;
import org.jetbrains.jet.lang.psi.*;
import org.jetbrains.jet.lang.resolve.name.Name;
import org.jetbrains.jet.lang.resolve.scopes.JetScope;
import org.jetbrains.jet.lang.resolve.scopes.RedeclarationHandler;
import org.jetbrains.jet.lang.resolve.scopes.WritableScope;
import org.jetbrains.jet.lang.resolve.scopes.WriteThroughScope;
-import org.jetbrains.jet.lang.types.JetType;
-import org.jetbrains.jet.lang.types.SubstitutionUtils;
-import org.jetbrains.jet.lang.types.TypeConstructor;
-import org.jetbrains.jet.lang.types.TypeProjection;
+import org.jetbrains.jet.lang.resolve.scopes.receivers.ClassReceiver;
+import org.jetbrains.jet.lang.types.*;
import org.jetbrains.jet.lang.types.checker.JetTypeChecker;
+import org.jetbrains.jet.lang.types.lang.JetStandardLibrary;
import org.jetbrains.jet.lexer.JetTokens;
+import org.jetbrains.jet.util.lazy.LazyValue;
import javax.inject.Inject;
import java.util.*;
import static org.jetbrains.jet.lang.diagnostics.Errors.*;
-import static org.jetbrains.jet.lang.resolve.BindingContext.*;
+import static org.jetbrains.jet.lang.resolve.BindingContext.FQNAME_TO_CLASS_DESCRIPTOR;
+import static org.jetbrains.jet.lang.resolve.BindingContext.TYPE;
/**
* @author abreslav
@@ -93,8 +95,10 @@ public class TypeHierarchyResolver {
this.trace = trace;
}
- public void process(@NotNull JetScope outerScope, @NotNull NamespaceLikeBuilder owner,
- @NotNull Collection extends PsiElement> declarations) {
+ public void process(
+ @NotNull JetScope outerScope, @NotNull NamespaceLikeBuilder owner,
+ @NotNull Collection extends PsiElement> declarations
+ ) {
{
// TODO: Very temp code - main goal is to remove recursion from collectNamespacesAndClassifiers
@@ -142,7 +146,7 @@ public class TypeHierarchyResolver {
// At this point, there are no loops in the type hierarchy
checkSupertypesForConsistency();
-// computeSuperclasses();
+ // computeSuperclasses();
checkTypesInClassHeaders(); // Check bounds in the types used in generic bounds and supertype lists
}
@@ -170,11 +174,11 @@ public class TypeHierarchyResolver {
DeclarationDescriptor declaration = classDescriptor.getContainingDeclaration();
if (declaration instanceof NamespaceDescriptorImpl) {
- return getStaticScope(declarationElement, ((NamespaceDescriptorImpl)declaration).getBuilder());
+ return getStaticScope(declarationElement, ((NamespaceDescriptorImpl) declaration).getBuilder());
}
if (declaration instanceof MutableClassDescriptorLite) {
- return getStaticScope(declarationElement, ((MutableClassDescriptorLite)declaration).getBuilder());
+ return getStaticScope(declarationElement, ((MutableClassDescriptorLite) declaration).getBuilder());
}
}
@@ -202,7 +206,7 @@ public class TypeHierarchyResolver {
namespaceScope.changeLockLevel(WritableScope.LockLevel.BOTH);
context.getNamespaceScopes().put(file, namespaceScope);
- if(file.isScript()) {
+ if (file.isScript()) {
scriptHeaderResolver.processScriptHierarchy(file.getScript(), namespaceScope);
}
@@ -228,6 +232,7 @@ public class TypeHierarchyResolver {
@Override
public void visitObjectDeclaration(JetObjectDeclaration declaration) {
final MutableClassDescriptor objectDescriptor = createClassDescriptorForObject(declaration, owner, outerScope);
+ owner.addObjectDescriptor(objectDescriptor);
trace.record(FQNAME_TO_CLASS_DESCRIPTOR, JetPsiUtil.getFQName(declaration), objectDescriptor);
}
@@ -266,7 +271,8 @@ public class TypeHierarchyResolver {
public void visitClassObject(JetClassObject classObject) {
JetObjectDeclaration objectDeclaration = classObject.getObjectDeclaration();
if (objectDeclaration != null) {
- MutableClassDescriptor classObjectDescriptor = createClassDescriptorForObject(objectDeclaration, owner, getStaticScope(classObject, owner));
+ MutableClassDescriptor classObjectDescriptor =
+ createClassDescriptorForObject(objectDeclaration, owner, getStaticScope(classObject, owner));
NamespaceLikeBuilder.ClassObjectStatus status = owner.setClassObjectDescriptor(classObjectDescriptor);
switch (status) {
case DUPLICATE:
@@ -282,22 +288,27 @@ public class TypeHierarchyResolver {
}
}
- private void createClassObjectForEnumClass(JetClass klass, MutableClassDescriptor mutableClassDescriptor) {
+ private void createClassObjectForEnumClass(JetClass klass, final MutableClassDescriptor mutableClassDescriptor) {
if (klass.hasModifier(JetTokens.ENUM_KEYWORD)) {
MutableClassDescriptor classObjectDescriptor = new MutableClassDescriptor(
- mutableClassDescriptor, outerScope, ClassKind.OBJECT, Name.special(""));
+ mutableClassDescriptor, outerScope, ClassKind.OBJECT,
+ Name.special(""));
classObjectDescriptor.setModality(Modality.FINAL);
classObjectDescriptor.setVisibility(DescriptorResolver.resolveVisibilityFromModifiers(klass.getModifierList()));
classObjectDescriptor.setTypeParameterDescriptors(new ArrayList(0));
classObjectDescriptor.createTypeConstructor();
- ConstructorDescriptorImpl primaryConstructorForObject = createPrimaryConstructorForObject(null, classObjectDescriptor);
+ ConstructorDescriptorImpl primaryConstructorForObject =
+ createPrimaryConstructorForObject(null, classObjectDescriptor);
primaryConstructorForObject.setReturnType(classObjectDescriptor.getDefaultType());
+ classObjectDescriptor.getBuilder().addFunctionDescriptor(DescriptorResolver.createEnumClassObjectValuesMethod(mutableClassDescriptor, classObjectDescriptor, trace));
+ classObjectDescriptor.getBuilder().addFunctionDescriptor(DescriptorResolver.createEnumClassObjectValueOfMethod(mutableClassDescriptor, classObjectDescriptor,trace));
mutableClassDescriptor.getBuilder().setClassObjectDescriptor(classObjectDescriptor);
}
}
private MutableClassDescriptor createClassDescriptorForObject(
- @NotNull JetObjectDeclaration declaration, @NotNull NamespaceLikeBuilder owner, JetScope scope) {
+ @NotNull JetObjectDeclaration declaration, @NotNull NamespaceLikeBuilder owner, JetScope scope
+ ) {
MutableClassDescriptor mutableClassDescriptor = new MutableClassDescriptor(
owner.getOwnerForChildren(), scope, ClassKind.OBJECT, JetPsiUtil.safeName(declaration.getName()));
context.getObjects().put(declaration, mutableClassDescriptor);
@@ -307,14 +318,17 @@ public class TypeHierarchyResolver {
prepareForDeferredCall(classScope, mutableClassDescriptor, declaration);
createPrimaryConstructorForObject(declaration, mutableClassDescriptor);
- owner.addObjectDescriptor(mutableClassDescriptor);
trace.record(BindingContext.CLASS, declaration, mutableClassDescriptor);
return mutableClassDescriptor;
}
- private MutableClassDescriptor createClassDescriptorForEnumEntry(@NotNull JetEnumEntry declaration, @NotNull NamespaceLikeBuilder owner) {
+ private MutableClassDescriptor createClassDescriptorForEnumEntry(
+ @NotNull JetEnumEntry declaration,
+ @NotNull NamespaceLikeBuilder owner
+ ) {
MutableClassDescriptor mutableClassDescriptor = new MutableClassDescriptor(
- owner.getOwnerForChildren(), getStaticScope(declaration, owner), ClassKind.ENUM_ENTRY, JetPsiUtil.safeName(declaration.getName()));
+ owner.getOwnerForChildren(), getStaticScope(declaration, owner), ClassKind.ENUM_ENTRY,
+ JetPsiUtil.safeName(declaration.getName()));
context.getClasses().put(declaration, mutableClassDescriptor);
prepareForDeferredCall(mutableClassDescriptor.getScopeForMemberResolution(), mutableClassDescriptor, declaration);
@@ -326,17 +340,21 @@ public class TypeHierarchyResolver {
return mutableClassDescriptor;
}
- private ConstructorDescriptorImpl createPrimaryConstructorForObject(@Nullable PsiElement object,
- MutableClassDescriptor mutableClassDescriptor) {
+ private ConstructorDescriptorImpl createPrimaryConstructorForObject(
+ @Nullable PsiElement object,
+ MutableClassDescriptor mutableClassDescriptor
+ ) {
ConstructorDescriptorImpl constructorDescriptor = DescriptorResolver
.createPrimaryConstructorForObject(object, mutableClassDescriptor, trace);
mutableClassDescriptor.setPrimaryConstructor(constructorDescriptor, trace);
return constructorDescriptor;
}
- private void prepareForDeferredCall(@NotNull JetScope outerScope,
- @NotNull WithDeferredResolve withDeferredResolve,
- @NotNull JetDeclarationContainer container) {
+ private void prepareForDeferredCall(
+ @NotNull JetScope outerScope,
+ @NotNull WithDeferredResolve withDeferredResolve,
+ @NotNull JetDeclarationContainer container
+ ) {
forDeferredResolve.add(container);
context.normalScope.put(container, outerScope);
context.forDeferredResolver.put(container, withDeferredResolve);
@@ -412,9 +430,11 @@ public class TypeHierarchyResolver {
}
}
- private static void topologicallySort(MutableClassDescriptor mutableClassDescriptor,
- Set visited,
- LinkedList topologicalOrder) {
+ private static void topologicallySort(
+ MutableClassDescriptor mutableClassDescriptor,
+ Set visited,
+ LinkedList topologicalOrder
+ ) {
if (!visited.add(mutableClassDescriptor)) {
return;
}
@@ -428,10 +448,12 @@ public class TypeHierarchyResolver {
topologicalOrder.addFirst(mutableClassDescriptor);
}
- private void traverseTypeHierarchy(MutableClassDescriptor currentClass,
- Set visited,
- Set beingProcessed,
- List currentPath) {
+ private void traverseTypeHierarchy(
+ MutableClassDescriptor currentClass,
+ Set visited,
+ Set beingProcessed,
+ List currentPath
+ ) {
if (!visited.add(currentClass)) {
if (beingProcessed.contains(currentClass)) {
markCycleErrors(currentPath, currentClass);
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/calls/CallResolver.java b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/calls/CallResolver.java
index fa6e828d16f..9afda1d11fd 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/calls/CallResolver.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/calls/CallResolver.java
@@ -305,13 +305,13 @@ public class CallResolver {
private OverloadResolutionResults completeTypeInferenceDependentOnExpectedType(
@NotNull BasicResolutionContext context,
- @NotNull OverloadResolutionResults results,
+ @NotNull OverloadResolutionResults resultsWithIncompleteTypeInference,
@NotNull TracingStrategy tracing
) {
- if (results.getResultCode() != OverloadResolutionResults.Code.INCOMPLETE_TYPE_INFERENCE) return results;
+ if (resultsWithIncompleteTypeInference.getResultCode() != OverloadResolutionResults.Code.INCOMPLETE_TYPE_INFERENCE) return resultsWithIncompleteTypeInference;
Set> successful = Sets.newLinkedHashSet();
Set> failed = Sets.newLinkedHashSet();
- for (ResolvedCall extends D> call : results.getResultingCalls()) {
+ for (ResolvedCall extends D> call : resultsWithIncompleteTypeInference.getResultingCalls()) {
if (!(call instanceof ResolvedCallImpl)) continue;
ResolvedCallImpl resolvedCall = (ResolvedCallImpl) call;
if (!resolvedCall.hasUnknownTypeParameters()) {
@@ -325,16 +325,11 @@ public class CallResolver {
}
completeTypeInferenceDependentOnExpectedTypeForCall(resolvedCall, context, tracing, successful, failed);
}
- if (results.getResultingCalls().size() > 1) {
- for (ResolvedCallWithTrace call : successful) {
- if (call instanceof ResolvedCallImpl) {
- ((ResolvedCallImpl)call).addStatus(ResolutionStatus.OTHER_ERROR);
- failed.add(call);
- }
- }
- successful.clear();
+ OverloadResolutionResultsImpl results = computeResultAndReportErrors(context.trace, tracing, successful, failed);
+ if (!results.isSingleResult()) {
+ checkTypesWithNoCallee(context);
}
- return computeResultAndReportErrors(context.trace, tracing, successful, failed);
+ return results;
}
private void completeTypeInferenceDependentOnExpectedTypeForCall(ResolvedCallImpl resolvedCall,
@@ -381,9 +376,9 @@ public class CallResolver {
if (constraintSystemWithoutExpectedTypeConstraint.isSuccessful()) {
resolvedCall.setResultingSubstitutor(constraintSystemWithoutExpectedTypeConstraint.getResultingSubstitutor());
}
- List argumentTypes = checkValueArgumentTypes(context, resolvedCall, context.trace).argumentTypes;
+ List argumentTypes = checkValueArgumentTypes(context, resolvedCall, resolvedCall.getTrace()).argumentTypes;
JetType receiverType = resolvedCall.getReceiverArgument().exists() ? resolvedCall.getReceiverArgument().getType() : null;
- tracing.typeInferenceFailed(context.trace,
+ tracing.typeInferenceFailed(resolvedCall.getTrace(),
InferenceErrorData
.create(descriptor, constraintSystem, argumentTypes, receiverType, context.expectedType),
constraintSystemWithoutExpectedTypeConstraint);
@@ -394,9 +389,9 @@ public class CallResolver {
resolvedCall.setResultingSubstitutor(constraintSystem.getResultingSubstitutor());
// Here we type check the arguments with inferred types expected
- checkValueArgumentTypes(context, resolvedCall, context.trace);
+ checkValueArgumentTypes(context, resolvedCall, resolvedCall.getTrace());
- checkBounds(resolvedCall, constraintSystem, context.trace, tracing);
+ checkBounds(resolvedCall, constraintSystem, resolvedCall.getTrace(), tracing);
resolvedCall.setHasUnknownTypeParameters(false);
if (resolvedCall.getStatus().isSuccess() || resolvedCall.getStatus() == ResolutionStatus.UNKNOWN_STATUS) {
resolvedCall.addStatus(ResolutionStatus.SUCCESS);
@@ -596,7 +591,7 @@ public class CallResolver {
OverloadResolutionResultsImpl results = computeResultAndReportErrors(task.trace, task.tracing, successfulCandidates,
failedCandidates);
- if (!results.isSingleResult() && results.getResultCode() != OverloadResolutionResults.Code.INCOMPLETE_TYPE_INFERENCE) {
+ if (!results.isSingleResult() && !results.isIncomplete()) {
checkTypesWithNoCallee(task.toBasic());
}
return results;
@@ -768,20 +763,25 @@ public class CallResolver {
// Solution
- if (!constraintsSystem.hasContradiction()) {
+ boolean hasContradiction = constraintsSystem.hasContradiction();
+ boolean boundsAreSatisfied = ConstraintsUtil.checkBoundsAreSatisfied(constraintsSystem);
+ if (!hasContradiction && boundsAreSatisfied) {
candidateCall.setHasUnknownTypeParameters(true);
return SUCCESS;
}
- else {
- ValueArgumentsCheckingResult checkingResult = checkAllValueArguments(context);
- ResolutionStatus argumentsStatus = checkingResult.status;
- List argumentTypes = checkingResult.argumentTypes;
- JetType receiverType = candidateCall.getReceiverArgument().exists() ? candidateCall.getReceiverArgument().getType() : null;
- context.tracing.typeInferenceFailed(context.trace,
- InferenceErrorData.create(candidate, constraintSystemWithRightTypeParameters, argumentTypes, receiverType, context.expectedType),
- constraintSystemWithRightTypeParameters);
- return TYPE_INFERENCE_ERROR.combine(argumentsStatus);
+ ValueArgumentsCheckingResult checkingResult = checkAllValueArguments(context);
+ ResolutionStatus argumentsStatus = checkingResult.status;
+ List argumentTypes = checkingResult.argumentTypes;
+ JetType receiverType = candidateCall.getReceiverArgument().exists() ? candidateCall.getReceiverArgument().getType() : null;
+ InferenceErrorData inferenceErrorData = InferenceErrorData
+ .create(candidate, constraintSystemWithRightTypeParameters, argumentTypes, receiverType, context.expectedType);
+ if (hasContradiction) {
+ context.tracing.typeInferenceFailed(candidateCall.getTrace(), inferenceErrorData, constraintSystemWithRightTypeParameters);
}
+ else {
+ context.tracing.upperBoundViolated(candidateCall.getTrace(), inferenceErrorData);
+ }
+ return TYPE_INFERENCE_ERROR.combine(argumentsStatus);
}
private boolean addConstraintForValueArgument(ValueArgument valueArgument,
@@ -1033,7 +1033,7 @@ public class CallResolver {
}
if (!thisLevel.isEmpty()) {
OverloadResolutionResultsImpl results = chooseAndReportMaximallySpecific(thisLevel, false);
- if (results.isSuccess()) {
+ if (results.isSingleResult()) {
results.getResultingCall().getTrace().commit();
return OverloadResolutionResultsImpl.singleFailedCandidate(results.getResultingCall());
}
@@ -1058,9 +1058,6 @@ public class CallResolver {
ResolvedCallWithTrace failed = failedCandidates.iterator().next();
failed.getTrace().commit();
- if (failed.getStatus() != ResolutionStatus.STRONG_ERROR && failed.hasUnknownTypeParameters()) {
- return OverloadResolutionResultsImpl.incompleteTypeInference(failed);
- }
return OverloadResolutionResultsImpl.singleFailedCandidate(failed);
}
else {
@@ -1078,13 +1075,9 @@ public class CallResolver {
private OverloadResolutionResultsImpl chooseAndReportMaximallySpecific(Set> candidates, boolean discriminateGenerics) {
if (candidates.size() != 1) {
- boolean dirty = false;
Set> cleanCandidates = Sets.newLinkedHashSet(candidates);
for (Iterator> iterator = cleanCandidates.iterator(); iterator.hasNext(); ) {
ResolvedCallWithTrace candidate = iterator.next();
- if (candidate.hasUnknownTypeParameters()) {
- dirty = true;
- }
if (candidate.isDirty()) {
iterator.remove();
}
@@ -1107,10 +1100,6 @@ public class CallResolver {
Set> noOverrides = OverridingUtil.filterOverrides(candidates, MAP_TO_RESULT);
- if (dirty) {
- return OverloadResolutionResultsImpl.incompleteTypeInference(candidates);
- }
-
return OverloadResolutionResultsImpl.ambiguity(noOverrides);
}
else {
@@ -1118,9 +1107,6 @@ public class CallResolver {
TemporaryBindingTrace temporaryTrace = result.getTrace();
temporaryTrace.commit();
- if (result.hasUnknownTypeParameters()) {
- return OverloadResolutionResultsImpl.incompleteTypeInference(result);
- }
return OverloadResolutionResultsImpl.success(result);
}
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/calls/OverloadResolutionResults.java b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/calls/OverloadResolutionResults.java
index d1c148858d8..07de185bf28 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/calls/OverloadResolutionResults.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/calls/OverloadResolutionResults.java
@@ -63,4 +63,6 @@ public interface OverloadResolutionResults {
boolean isNothing();
boolean isAmbiguity();
+
+ boolean isIncomplete();
}
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/calls/OverloadResolutionResultsImpl.java b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/calls/OverloadResolutionResultsImpl.java
index db3fd1aa4e3..34dfc0c87d7 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/calls/OverloadResolutionResultsImpl.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/calls/OverloadResolutionResultsImpl.java
@@ -28,8 +28,11 @@ import java.util.Collections;
*/
/*package*/ class OverloadResolutionResultsImpl implements OverloadResolutionResults {
- public static OverloadResolutionResultsImpl success(@NotNull ResolvedCallWithTrace descriptor) {
- return new OverloadResolutionResultsImpl(Code.SUCCESS, Collections.singleton(descriptor));
+ public static OverloadResolutionResultsImpl success(@NotNull ResolvedCallWithTrace candidate) {
+ if (candidate.hasUnknownTypeParameters()) {
+ return incompleteTypeInference(candidate);
+ }
+ return new OverloadResolutionResultsImpl(Code.SUCCESS, Collections.singleton(candidate));
}
public static OverloadResolutionResultsImpl nameNotFound() {
@@ -37,22 +40,30 @@ import java.util.Collections;
}
public static OverloadResolutionResultsImpl singleFailedCandidate(ResolvedCallWithTrace candidate) {
+ if (candidate.getStatus() != ResolutionStatus.STRONG_ERROR && candidate.hasUnknownTypeParameters()) {
+ return incompleteTypeInference(candidate);
+ }
return new OverloadResolutionResultsImpl(Code.SINGLE_CANDIDATE_ARGUMENT_MISMATCH, Collections.singleton(candidate));
}
public static OverloadResolutionResultsImpl manyFailedCandidates(Collection> failedCandidates) {
return new OverloadResolutionResultsImpl(Code.MANY_FAILED_CANDIDATES, failedCandidates);
}
- public static OverloadResolutionResultsImpl ambiguity(Collection> descriptors) {
- return new OverloadResolutionResultsImpl(Code.AMBIGUITY, descriptors);
+ public static OverloadResolutionResultsImpl ambiguity(Collection> candidates) {
+ for (ResolvedCallWithTrace candidate : candidates) {
+ if (candidate.hasUnknownTypeParameters()) {
+ return incompleteTypeInference(candidates);
+ }
+ }
+ return new OverloadResolutionResultsImpl(Code.AMBIGUITY, candidates);
}
- public static OverloadResolutionResultsImpl incompleteTypeInference(Collection> descriptors) {
- return new OverloadResolutionResultsImpl(Code.INCOMPLETE_TYPE_INFERENCE, descriptors);
+ private static OverloadResolutionResultsImpl incompleteTypeInference(Collection> candidates) {
+ return new OverloadResolutionResultsImpl(Code.INCOMPLETE_TYPE_INFERENCE, candidates);
}
- public static OverloadResolutionResultsImpl incompleteTypeInference(ResolvedCallWithTrace descriptor) {
- return new OverloadResolutionResultsImpl(Code.INCOMPLETE_TYPE_INFERENCE, Collections.singleton(descriptor));
+ private static OverloadResolutionResultsImpl incompleteTypeInference(ResolvedCallWithTrace candidate) {
+ return incompleteTypeInference(Collections.singleton(candidate));
}
private final Collection> results;
@@ -96,7 +107,7 @@ import java.util.Collections;
@Override
public boolean isSingleResult() {
- return isSuccess() || resultCode == Code.SINGLE_CANDIDATE_ARGUMENT_MISMATCH;
+ return results.size() == 1;
}
@Override
@@ -108,7 +119,13 @@ import java.util.Collections;
public boolean isAmbiguity() {
return resultCode == Code.AMBIGUITY;
}
-//
+
+ @Override
+ public boolean isIncomplete() {
+ return resultCode == Code.INCOMPLETE_TYPE_INFERENCE;
+ }
+
+ //
// public OverloadResolutionResultsImpl newContents(@NotNull Collection functionDescriptors) {
// return new OverloadResolutionResultsImpl(resultCode, functionDescriptors);
// }
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/calls/ResolutionStatus.java b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/calls/ResolutionStatus.java
index 060299446ea..7def2ca8beb 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/calls/ResolutionStatus.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/calls/ResolutionStatus.java
@@ -32,8 +32,8 @@ public enum ResolutionStatus {
@SuppressWarnings("unchecked")
public static final EnumSet[] SEVERITY_LEVELS = new EnumSet[] {
EnumSet.of(UNSAFE_CALL_ERROR), // weakest
- EnumSet.of(OTHER_ERROR),
EnumSet.of(TYPE_INFERENCE_ERROR),
+ EnumSet.of(OTHER_ERROR),
EnumSet.of(STRONG_ERROR), // most severe
};
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/calls/inference/ConstraintSystemImpl.java b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/calls/inference/ConstraintSystemImpl.java
index 5df320ed699..4a55b396da9 100644
--- a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/calls/inference/ConstraintSystemImpl.java
+++ b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/calls/inference/ConstraintSystemImpl.java
@@ -30,6 +30,9 @@ import org.jetbrains.jet.lang.resolve.calls.inference.TypeConstraintsImpl.Constr
import java.util.*;
+import static org.jetbrains.jet.lang.resolve.calls.inference.TypeConstraintsImpl.ConstraintKind.*;
+import static org.jetbrains.jet.lang.types.Variance.*;
+
/**
* @author svtk
*/
@@ -137,12 +140,12 @@ public class ConstraintSystemImpl implements ConstraintSystem {
@Override
public void addSubtypingConstraint(@NotNull JetType subjectType, @Nullable JetType constrainingType, @NotNull ConstraintPosition constraintPosition) {
- addConstraint(ConstraintKind.SUB_TYPE, subjectType, constrainingType, constraintPosition);
+ addConstraint(SUB_TYPE, subjectType, constrainingType, constraintPosition);
}
@Override
public void addSupertypeConstraint(@NotNull JetType subjectType, @Nullable JetType constrainingType, @NotNull ConstraintPosition constraintPosition) {
- addConstraint(ConstraintKind.SUPER_TYPE, subjectType, constrainingType, constraintPosition);
+ addConstraint(SUPER_TYPE, subjectType, constrainingType, constraintPosition);
}
private void addConstraint(@NotNull ConstraintKind constraintKind,
@@ -210,12 +213,100 @@ public class ConstraintSystemImpl implements ConstraintSystem {
List constrainingArguments = constrainingType.getArguments();
List parameters = typeConstructor.getParameters();
for (int i = 0; i < subjectArguments.size(); i++) {
- //todo constrainingArguments.get(i).getType() -> type projections
- addConstraint(ConstraintKind.fromVariance(parameters.get(i).getVariance()), subjectArguments.get(i).getType(),
- constrainingArguments.get(i).getType(), constraintPosition);
+ Variance typeParameterVariance = parameters.get(i).getVariance();
+ TypeProjection subjectArgument = subjectArguments.get(i);
+ TypeProjection constrainingArgument = constrainingArguments.get(i);
+
+ ConstraintKind typeParameterConstraintKind = getTypeParameterConstraintKind(typeParameterVariance,
+ subjectArgument, constrainingArgument, constraintKind);
+
+ addConstraint(typeParameterConstraintKind, subjectArgument.getType(), constrainingArgument.getType(), constraintPosition);
}
}
+ /**
+ * Determines what constraint (supertype, subtype or equal) should be generated for type parameter {@code T} in a constraint like (in this example subtype one):
+ * {@code MyClass <: MyClass}, where {@code MyClass} is declared.
+ *
+ * The parameters description is given according to the example above.
+ * @param typeParameterVariance declared variance of T
+ * @param subjectTypeProjection {@code in/out/- A}
+ * @param constrainingTypeProjection {@code in/out/- B}
+ * @param upperConstraintKind kind of the constraint {@code MyClass<...A> <: MyClass<...B>} (subtype in this example).
+ * @return kind of constraint to be generated: {@code A <: B} (subtype), {@code A >: B} (supertype) or {@code A = B} (equal).
+ */
+ @NotNull
+ private static ConstraintKind getTypeParameterConstraintKind(
+ @NotNull Variance typeParameterVariance,
+ @NotNull TypeProjection subjectTypeProjection,
+ @NotNull TypeProjection constrainingTypeProjection,
+ @NotNull ConstraintKind upperConstraintKind
+ ) {
+ // If variance of type parameter is non-trivial, it should be taken into consideration to infer result constraint type.
+ // Otherwise when type parameter declared as INVARIANT, there might be non-trivial use-site variance of a supertype.
+ //
+ // Example: Let class MyClass is declared.
+ //
+ // If super type has 'out' projection:
+ // MyClass <: MyClass,
+ // then constraint A <: B can be generated.
+ //
+ // If super type has 'in' projection:
+ // MyClass <: MyClass,
+ // then constraint A >: B can be generated.
+ //
+ // Otherwise constraint A = B should be generated.
+
+ Variance varianceForTypeParameter;
+ if (typeParameterVariance != INVARIANT) {
+ varianceForTypeParameter = typeParameterVariance;
+ }
+ else if (upperConstraintKind == SUB_TYPE) {
+ varianceForTypeParameter = constrainingTypeProjection.getProjectionKind();
+ }
+ else if (upperConstraintKind == SUPER_TYPE) {
+ varianceForTypeParameter = subjectTypeProjection.getProjectionKind();
+ }
+ else {
+ varianceForTypeParameter = INVARIANT;
+ }
+
+ return getTypeParameterConstraintKind(varianceForTypeParameter, upperConstraintKind);
+ }
+
+ /**
+ * Let class {@code MyClass} is declared.
+ *
+ * If upperConstraintKind is SUB_TYPE:
+ * {@code MyClass <: MyClass},
+ * then constraints {@code A = D, B <: E, C >: F} are generated.
+ *
+ * If upperConstraintKind is SUPER_TYPE:
+ * {@code MyClass >: MyClass},
+ * then constraints {@code A = D, B >: E, C <: F} are generated.
+ *
+ * If upperConstraintKind is EQUAL:
+ * {@code MyClass = MyClass},