Refactor: process mentions of class object

Rename usages that refer to "default object" concept now
Test data file names are left as is
This commit is contained in:
Pavel V. Talanov
2015-03-03 17:28:24 +03:00
parent 27f5d71e4f
commit 48fbce9582
137 changed files with 471 additions and 479 deletions
@@ -195,8 +195,8 @@ public class AsmUtil {
} }
} }
if (AnnotationsPackage.isPlatformStaticInClassObject(functionDescriptor)) { if (AnnotationsPackage.isPlatformStaticInDefaultObject(functionDescriptor)) {
// Native method will be a member of the class, the class object method will be delegated to it // Native method will be a member of the class, the default object method will be delegated to it
flags &= ~Opcodes.ACC_NATIVE; flags &= ~Opcodes.ACC_NATIVE;
} }
@@ -733,7 +733,7 @@ public class AsmUtil {
public static boolean isPropertyWithBackingFieldInOuterClass(@NotNull PropertyDescriptor propertyDescriptor) { public static boolean isPropertyWithBackingFieldInOuterClass(@NotNull PropertyDescriptor propertyDescriptor) {
return propertyDescriptor.getKind() != CallableMemberDescriptor.Kind.FAKE_OVERRIDE && return propertyDescriptor.getKind() != CallableMemberDescriptor.Kind.FAKE_OVERRIDE &&
isClassObjectWithBackingFieldsInOuter(propertyDescriptor.getContainingDeclaration()); isDefaultObjectWithBackingFieldsInOuter(propertyDescriptor.getContainingDeclaration());
} }
public static int getVisibilityForSpecialPropertyBackingField(@NotNull PropertyDescriptor propertyDescriptor, boolean isDelegate) { public static int getVisibilityForSpecialPropertyBackingField(@NotNull PropertyDescriptor propertyDescriptor, boolean isDelegate) {
@@ -762,14 +762,14 @@ public class AsmUtil {
DeclarationDescriptor propertyContainer = propertyDescriptor.getContainingDeclaration(); DeclarationDescriptor propertyContainer = propertyDescriptor.getContainingDeclaration();
return !propertyDescriptor.isVar() return !propertyDescriptor.isVar()
&& !isExtensionProperty && !isExtensionProperty
&& isClassObject(propertyContainer) && isTrait(propertyContainer.getContainingDeclaration()) && isDefaultObject(propertyContainer) && isTrait(propertyContainer.getContainingDeclaration())
&& areBothAccessorDefault(propertyDescriptor) && areBothAccessorDefault(propertyDescriptor)
&& getVisibilityForSpecialPropertyBackingField(propertyDescriptor, false) == ACC_PUBLIC; && getVisibilityForSpecialPropertyBackingField(propertyDescriptor, false) == ACC_PUBLIC;
} }
public static boolean isClassObjectWithBackingFieldsInOuter(@NotNull DeclarationDescriptor classObject) { public static boolean isDefaultObjectWithBackingFieldsInOuter(@NotNull DeclarationDescriptor defaultObject) {
DeclarationDescriptor containingClass = classObject.getContainingDeclaration(); DeclarationDescriptor containingClass = defaultObject.getContainingDeclaration();
return isClassObject(classObject) && (isClass(containingClass) || isEnumClass(containingClass)); return isDefaultObject(defaultObject) && (isClass(containingClass) || isEnumClass(containingClass));
} }
private static boolean areBothAccessorDefault(@NotNull PropertyDescriptor propertyDescriptor) { private static boolean areBothAccessorDefault(@NotNull PropertyDescriptor propertyDescriptor) {
@@ -1922,9 +1922,9 @@ public class ExpressionCodegen extends JetVisitor<StackValue, StackValue> implem
Type type = typeMapper.mapType((ClassDescriptor) enumClass); Type type = typeMapper.mapType((ClassDescriptor) enumClass);
return StackValue.field(type, type, descriptor.getName().asString(), true, StackValue.none()); return StackValue.field(type, type, descriptor.getName().asString(), true, StackValue.none());
} }
ClassDescriptor classObjectDescriptor = classDescriptor.getDefaultObjectDescriptor(); ClassDescriptor defaultObjectDescriptor = classDescriptor.getDefaultObjectDescriptor();
if (classObjectDescriptor != null) { if (defaultObjectDescriptor != null) {
return StackValue.singleton(classObjectDescriptor, typeMapper); return StackValue.singleton(defaultObjectDescriptor, typeMapper);
} }
return StackValue.none(); return StackValue.none();
} }
@@ -2382,7 +2382,7 @@ public class ExpressionCodegen extends JetVisitor<StackValue, StackValue> implem
public StackValue generateReceiverValue(@NotNull ReceiverValue receiverValue) { public StackValue generateReceiverValue(@NotNull ReceiverValue receiverValue) {
if (receiverValue instanceof ClassReceiver) { if (receiverValue instanceof ClassReceiver) {
ClassDescriptor receiverDescriptor = ((ClassReceiver) receiverValue).getDeclarationDescriptor(); ClassDescriptor receiverDescriptor = ((ClassReceiver) receiverValue).getDeclarationDescriptor();
if (DescriptorUtils.isClassObject(receiverDescriptor)) { if (DescriptorUtils.isDefaultObject(receiverDescriptor)) {
CallableMemberDescriptor contextDescriptor = context.getContextDescriptor(); CallableMemberDescriptor contextDescriptor = context.getContextDescriptor();
if (contextDescriptor instanceof FunctionDescriptor && receiverDescriptor == contextDescriptor.getContainingDeclaration()) { if (contextDescriptor instanceof FunctionDescriptor && receiverDescriptor == contextDescriptor.getContainingDeclaration()) {
return StackValue.LOCAL_0; return StackValue.LOCAL_0;
@@ -47,12 +47,12 @@ public class FieldInfo {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@NotNull @NotNull
public static FieldInfo deprecatedFieldForClassObject(@NotNull ClassDescriptor classObject, @NotNull JetTypeMapper typeMapper) { public static FieldInfo deprecatedFieldForDefaultObject(@NotNull ClassDescriptor defaultObject, @NotNull JetTypeMapper typeMapper) {
assert DescriptorUtils.isClassObject(classObject) : "Not a class object: " + classObject; assert DescriptorUtils.isDefaultObject(defaultObject) : "Not a default object: " + defaultObject;
return new FieldInfo( return new FieldInfo(
typeMapper.mapType((ClassifierDescriptor) classObject.getContainingDeclaration()), typeMapper.mapType((ClassifierDescriptor) defaultObject.getContainingDeclaration()),
typeMapper.mapType(classObject), typeMapper.mapType(defaultObject),
JvmAbi.DEPRECATED_CLASS_OBJECT_FIELD, JvmAbi.DEPRECATED_DEFAULT_OBJECT_FIELD,
true true
); );
} }
@@ -168,8 +168,8 @@ public class FunctionCodegen {
generateBridges(functionDescriptor); generateBridges(functionDescriptor);
boolean staticInClassObject = AnnotationsPackage.isPlatformStaticInClassObject(functionDescriptor); boolean staticInDefaultObject = AnnotationsPackage.isPlatformStaticInDefaultObject(functionDescriptor);
if (staticInClassObject) { if (staticInDefaultObject) {
ImplementationBodyCodegen parentBodyCodegen = (ImplementationBodyCodegen) memberCodegen.getParentCodegen(); ImplementationBodyCodegen parentBodyCodegen = (ImplementationBodyCodegen) memberCodegen.getParentCodegen();
parentBodyCodegen.addAdditionalTask(new PlatformStaticGenerator(functionDescriptor, origin, state)); parentBodyCodegen.addAdditionalTask(new PlatformStaticGenerator(functionDescriptor, origin, state));
} }
@@ -192,8 +192,8 @@ public class FunctionCodegen {
if (!isNative) { if (!isNative) {
generateMethodBody(mv, functionDescriptor, methodContext, jvmSignature, strategy, memberCodegen); generateMethodBody(mv, functionDescriptor, methodContext, jvmSignature, strategy, memberCodegen);
} }
else if (staticInClassObject) { else if (staticInDefaultObject) {
// native platformStatic foo() in class object should delegate to the static native function moved to the outer class // native platformStatic foo() in default object should delegate to the static native function moved to the outer class
mv.visitCode(); mv.visitCode();
FunctionDescriptor staticFunctionDescriptor = PlatformStaticGenerator.createStaticFunctionDescriptor(functionDescriptor); FunctionDescriptor staticFunctionDescriptor = PlatformStaticGenerator.createStaticFunctionDescriptor(functionDescriptor);
JvmMethodSignature jvmMethodSignature = JvmMethodSignature jvmMethodSignature =
@@ -43,7 +43,6 @@ import org.jetbrains.kotlin.name.FqName;
import org.jetbrains.kotlin.name.Name; import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.psi.*; import org.jetbrains.kotlin.psi.*;
import org.jetbrains.kotlin.resolve.BindingContext; import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.DeclarationResolver;
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils; import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils;
import org.jetbrains.kotlin.resolve.DescriptorUtils; import org.jetbrains.kotlin.resolve.DescriptorUtils;
import org.jetbrains.kotlin.resolve.annotations.AnnotationsPackage; import org.jetbrains.kotlin.resolve.annotations.AnnotationsPackage;
@@ -92,7 +91,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
private JetType superClassType; private JetType superClassType;
private final Type classAsmType; private final Type classAsmType;
private List<PropertyAndDefaultValue> classObjectPropertiesToCopy; private List<PropertyAndDefaultValue> defaultObjectPropertiesToCopy;
private final List<Function2<ImplementationBodyCodegen, ClassBuilder, Unit>> additionalTasks = private final List<Function2<ImplementationBodyCodegen, ClassBuilder, Unit>> additionalTasks =
new ArrayList<Function2<ImplementationBodyCodegen, ClassBuilder, Unit>>(); new ArrayList<Function2<ImplementationBodyCodegen, ClassBuilder, Unit>>();
@@ -152,7 +151,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
isStatic = !jetClass.isInner(); isStatic = !jetClass.isInner();
} }
else { else {
isStatic = myClass instanceof JetObjectDeclaration && ((JetObjectDeclaration) myClass).isClassObject() ; isStatic = myClass instanceof JetObjectDeclaration && ((JetObjectDeclaration) myClass).isDefault() ;
isFinal = true; isFinal = true;
} }
@@ -370,7 +369,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
generateFieldForSingleton(); generateFieldForSingleton();
generateClassObjectBackingFieldCopies(); generateDefaultObjectBackingFieldCopies();
DelegationFieldsInfo delegationFieldsInfo = getDelegationFieldsInfo(myClass.getDelegationSpecifiers()); DelegationFieldsInfo delegationFieldsInfo = getDelegationFieldsInfo(myClass.getDelegationSpecifiers());
try { try {
@@ -885,7 +884,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
@Override @Override
public void doGenerateBody(@NotNull ExpressionCodegen codegen, @NotNull JvmMethodSignature signature) { public void doGenerateBody(@NotNull ExpressionCodegen codegen, @NotNull JvmMethodSignature signature) {
boolean forceField = AsmUtil.isPropertyWithBackingFieldInOuterClass(original) && boolean forceField = AsmUtil.isPropertyWithBackingFieldInOuterClass(original) &&
!isClassObject(bridge.getContainingDeclaration()); !isDefaultObject(bridge.getContainingDeclaration());
StackValue property = StackValue property =
codegen.intermediateValueForProperty(original, forceField, null, MethodKind.SYNTHETIC_ACCESSOR, codegen.intermediateValueForProperty(original, forceField, null, MethodKind.SYNTHETIC_ACCESSOR,
StackValue.none()); StackValue.none());
@@ -975,7 +974,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
} }
private void generateFieldForSingleton() { private void generateFieldForSingleton() {
if (isEnumEntry(descriptor) || isClassObject(descriptor)) return; if (isEnumEntry(descriptor) || isDefaultObject(descriptor)) return;
if (isObject(descriptor)) { if (isObject(descriptor)) {
StackValue.Field field = StackValue.singleton(descriptor, typeMapper); StackValue.Field field = StackValue.singleton(descriptor, typeMapper);
@@ -990,34 +989,34 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
return; return;
} }
ClassDescriptor classObjectDescriptor = descriptor.getDefaultObjectDescriptor(); ClassDescriptor defaultObjectDescriptor = descriptor.getDefaultObjectDescriptor();
if (classObjectDescriptor == null) { if (defaultObjectDescriptor == null) {
return; return;
} }
JetObjectDeclaration classObject = ((JetClass) myClass).getClassObject(); JetObjectDeclaration defaultObject = ((JetClass) myClass).getDefaultObject();
assert classObject != null : "Class object not found: " + myClass.getText(); assert defaultObject != null : "Default object not found: " + myClass.getText();
StackValue.Field field = StackValue.singleton(classObjectDescriptor, typeMapper); StackValue.Field field = StackValue.singleton(defaultObjectDescriptor, typeMapper);
v.newField(OtherOrigin(classObject), ACC_PUBLIC | ACC_STATIC | ACC_FINAL, field.name, field.type.getDescriptor(), null, null); v.newField(OtherOrigin(defaultObject), ACC_PUBLIC | ACC_STATIC | ACC_FINAL, field.name, field.type.getDescriptor(), null, null);
StackValue.Field deprecatedField = StackValue.deprecatedClassObjectAccessor(classObjectDescriptor, typeMapper); StackValue.Field deprecatedField = StackValue.deprecatedDefaultObjectAccessor(defaultObjectDescriptor, typeMapper);
FieldVisitor fv = v.newField(OtherOrigin(classObject), ACC_PUBLIC | ACC_STATIC | ACC_FINAL | ACC_DEPRECATED, FieldVisitor fv = v.newField(OtherOrigin(defaultObject), ACC_PUBLIC | ACC_STATIC | ACC_FINAL | ACC_DEPRECATED,
deprecatedField.name, deprecatedField.type.getDescriptor(), null, null); deprecatedField.name, deprecatedField.type.getDescriptor(), null, null);
fv.visitAnnotation(asmDescByFqNameWithoutInnerClasses(new FqName("java.lang.Deprecated")), true).visitEnd(); fv.visitAnnotation(asmDescByFqNameWithoutInnerClasses(new FqName("java.lang.Deprecated")), true).visitEnd();
if (state.getClassBuilderMode() != ClassBuilderMode.FULL) return; if (state.getClassBuilderMode() != ClassBuilderMode.FULL) return;
if (!isClassObjectWithBackingFieldsInOuter(classObjectDescriptor)) { if (!isDefaultObjectWithBackingFieldsInOuter(defaultObjectDescriptor)) {
generateClassObjectInitializer(classObjectDescriptor); generateDefaultObjectInitializer(defaultObjectDescriptor);
} }
} }
private void generateClassObjectBackingFieldCopies() { private void generateDefaultObjectBackingFieldCopies() {
if (classObjectPropertiesToCopy == null) return; if (defaultObjectPropertiesToCopy == null) return;
for (PropertyAndDefaultValue info : classObjectPropertiesToCopy) { for (PropertyAndDefaultValue info : defaultObjectPropertiesToCopy) {
PropertyDescriptor property = info.descriptor; PropertyDescriptor property = info.descriptor;
Type type = typeMapper.mapType(property); Type type = typeMapper.mapType(property);
@@ -1033,40 +1032,40 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
// TODO: test this code // TODO: test this code
if (state.getClassBuilderMode() == ClassBuilderMode.FULL && info.defaultValue == null) { if (state.getClassBuilderMode() == ClassBuilderMode.FULL && info.defaultValue == null) {
ExpressionCodegen codegen = createOrGetClInitCodegen(); ExpressionCodegen codegen = createOrGetClInitCodegen();
int classObjectIndex = putClassObjectInLocalVar(codegen); int defaultObjectIndex = putDefaultObjectInLocalVar(codegen);
StackValue.local(classObjectIndex, OBJECT_TYPE).put(OBJECT_TYPE, codegen.v); StackValue.local(defaultObjectIndex, OBJECT_TYPE).put(OBJECT_TYPE, codegen.v);
copyFieldFromClassObject(property); copyFieldFromDefaultObject(property);
} }
} }
} }
private int putClassObjectInLocalVar(ExpressionCodegen codegen) { private int putDefaultObjectInLocalVar(ExpressionCodegen codegen) {
FrameMap frameMap = codegen.myFrameMap; FrameMap frameMap = codegen.myFrameMap;
ClassDescriptor classObjectDescriptor = descriptor.getDefaultObjectDescriptor(); ClassDescriptor defaultObjectDescriptor = descriptor.getDefaultObjectDescriptor();
int classObjectIndex = frameMap.getIndex(classObjectDescriptor); int defaultObjectIndex = frameMap.getIndex(defaultObjectDescriptor);
if (classObjectIndex == -1) { if (defaultObjectIndex == -1) {
classObjectIndex = frameMap.enter(classObjectDescriptor, OBJECT_TYPE); defaultObjectIndex = frameMap.enter(defaultObjectDescriptor, OBJECT_TYPE);
StackValue classObject = StackValue.singleton(classObjectDescriptor, typeMapper); StackValue defaultObject = StackValue.singleton(defaultObjectDescriptor, typeMapper);
StackValue.local(classObjectIndex, classObject.type).store(classObject, codegen.v); StackValue.local(defaultObjectIndex, defaultObject.type).store(defaultObject, codegen.v);
} }
return classObjectIndex; return defaultObjectIndex;
} }
private void copyFieldFromClassObject(PropertyDescriptor propertyDescriptor) { private void copyFieldFromDefaultObject(PropertyDescriptor propertyDescriptor) {
ExpressionCodegen codegen = createOrGetClInitCodegen(); ExpressionCodegen codegen = createOrGetClInitCodegen();
StackValue property = codegen.intermediateValueForProperty(propertyDescriptor, false, null, StackValue.none()); StackValue property = codegen.intermediateValueForProperty(propertyDescriptor, false, null, StackValue.none());
StackValue.Field field = StackValue.field(property.type, classAsmType, propertyDescriptor.getName().asString(), true, StackValue.none()); StackValue.Field field = StackValue.field(property.type, classAsmType, propertyDescriptor.getName().asString(), true, StackValue.none());
field.store(property, codegen.v); field.store(property, codegen.v);
} }
private void generateClassObjectInitializer(@NotNull ClassDescriptor classObject) { private void generateDefaultObjectInitializer(@NotNull ClassDescriptor defaultObject) {
ExpressionCodegen codegen = createOrGetClInitCodegen(); ExpressionCodegen codegen = createOrGetClInitCodegen();
FunctionDescriptor constructor = codegen.accessibleFunctionDescriptor(KotlinPackage.single(classObject.getConstructors())); FunctionDescriptor constructor = codegen.accessibleFunctionDescriptor(KotlinPackage.single(defaultObject.getConstructors()));
generateMethodCallTo(constructor, codegen.v); generateMethodCallTo(constructor, codegen.v);
codegen.v.dup(); codegen.v.dup();
StackValue instance = StackValue.onStack(typeMapper.mapClass(classObject)); StackValue instance = StackValue.onStack(typeMapper.mapClass(defaultObject));
StackValue.singleton(classObject, typeMapper).store(instance, codegen.v, true); StackValue.singleton(defaultObject, typeMapper).store(instance, codegen.v, true);
StackValue.deprecatedClassObjectAccessor(classObject, typeMapper).store(instance, codegen.v, true); StackValue.deprecatedDefaultObjectAccessor(defaultObject, typeMapper).store(instance, codegen.v, true);
} }
private void generatePrimaryConstructor(final DelegationFieldsInfo delegationFieldsInfo) { private void generatePrimaryConstructor(final DelegationFieldsInfo delegationFieldsInfo) {
@@ -1098,7 +1097,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
CallableMethod callableMethod = typeMapper.mapToCallableMethod(constructorDescriptor); CallableMethod callableMethod = typeMapper.mapToCallableMethod(constructorDescriptor);
FunctionCodegen.generateConstructorWithoutParametersIfNeeded(state, callableMethod, constructorDescriptor, v, myClass); FunctionCodegen.generateConstructorWithoutParametersIfNeeded(state, callableMethod, constructorDescriptor, v, myClass);
if (isClassObject(descriptor)) { if (isDefaultObject(descriptor)) {
context.recordSyntheticAccessorIfNeeded(constructorDescriptor, bindingContext); context.recordSyntheticAccessorIfNeeded(constructorDescriptor, bindingContext);
} }
} }
@@ -1151,9 +1150,9 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
curParam++; curParam++;
} }
if (isClassObjectWithBackingFieldsInOuter(descriptor)) { if (isDefaultObjectWithBackingFieldsInOuter(descriptor)) {
final ImplementationBodyCodegen parentCodegen = (ImplementationBodyCodegen) getParentCodegen(); final ImplementationBodyCodegen parentCodegen = (ImplementationBodyCodegen) getParentCodegen();
parentCodegen.generateClassObjectInitializer(descriptor); parentCodegen.generateDefaultObjectInitializer(descriptor);
generateInitializers(new Function0<ExpressionCodegen>() { generateInitializers(new Function0<ExpressionCodegen>() {
@Override @Override
public ExpressionCodegen invoke() { public ExpressionCodegen invoke() {
@@ -1638,11 +1637,11 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
} }
} }
public void addClassObjectPropertyToCopy(@NotNull PropertyDescriptor descriptor, Object defaultValue) { public void addDefaultObjectPropertyToCopy(@NotNull PropertyDescriptor descriptor, Object defaultValue) {
if (classObjectPropertiesToCopy == null) { if (defaultObjectPropertiesToCopy == null) {
classObjectPropertiesToCopy = new ArrayList<PropertyAndDefaultValue>(); defaultObjectPropertiesToCopy = new ArrayList<PropertyAndDefaultValue>();
} }
classObjectPropertiesToCopy.add(new PropertyAndDefaultValue(descriptor, defaultValue)); defaultObjectPropertiesToCopy.add(new PropertyAndDefaultValue(descriptor, defaultValue));
} }
@Override @Override
@@ -179,8 +179,8 @@ public class JvmCodegenUtil {
// Delegated and extension properties have no backing fields // Delegated and extension properties have no backing fields
if (isDelegated || property.getExtensionReceiverParameter() != null) return false; if (isDelegated || property.getExtensionReceiverParameter() != null) return false;
// Class object properties cannot be accessed directly because their backing fields are stored in the containing class // Default object properties cannot be accessed directly because their backing fields are stored in the containing class
if (DescriptorUtils.isClassObject(property.getContainingDeclaration())) return false; if (DescriptorUtils.isDefaultObject(property.getContainingDeclaration())) return false;
PropertyAccessorDescriptor accessor = forGetter ? property.getGetter() : property.getSetter(); PropertyAccessorDescriptor accessor = forGetter ? property.getGetter() : property.getSetter();
@@ -48,7 +48,7 @@ import java.util.List;
import static org.jetbrains.kotlin.codegen.AsmUtil.*; import static org.jetbrains.kotlin.codegen.AsmUtil.*;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isInterface; import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isInterface;
import static org.jetbrains.kotlin.codegen.JvmSerializationBindings.*; import static org.jetbrains.kotlin.codegen.JvmSerializationBindings.*;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.isClassObject; import static org.jetbrains.kotlin.resolve.DescriptorUtils.isDefaultObject;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.isTrait; import static org.jetbrains.kotlin.resolve.DescriptorUtils.isTrait;
import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.PROPERTY_METADATA_TYPE; import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.PROPERTY_METADATA_TYPE;
import static org.jetbrains.kotlin.resolve.jvm.diagnostics.DiagnosticsPackage.OtherOrigin; import static org.jetbrains.kotlin.resolve.jvm.diagnostics.DiagnosticsPackage.OtherOrigin;
@@ -144,8 +144,8 @@ public class PropertyCodegen {
// Delegated or extension properties can only be referenced via accessors // Delegated or extension properties can only be referenced via accessors
if (declaration.hasDelegate() || declaration.getReceiverTypeReference() != null) return true; if (declaration.hasDelegate() || declaration.getReceiverTypeReference() != null) return true;
// Class object properties always should have accessors, because their backing fields are moved/copied to the outer class // Default object properties always should have accessors, because their backing fields are moved/copied to the outer class
if (isClassObject(descriptor.getContainingDeclaration())) return true; if (isDefaultObject(descriptor.getContainingDeclaration())) return true;
// Private class properties have accessors only in cases when those accessors are non-trivial // Private class properties have accessors only in cases when those accessors are non-trivial
if (kind == OwnerKind.IMPLEMENTATION && Visibilities.isPrivate(descriptor.getVisibility())) { if (kind == OwnerKind.IMPLEMENTATION && Visibilities.isPrivate(descriptor.getVisibility())) {
@@ -265,7 +265,7 @@ public class PropertyCodegen {
if (AsmUtil.isPropertyWithBackingFieldCopyInOuterClass(propertyDescriptor)) { if (AsmUtil.isPropertyWithBackingFieldCopyInOuterClass(propertyDescriptor)) {
ImplementationBodyCodegen parentBodyCodegen = (ImplementationBodyCodegen) memberCodegen.getParentCodegen(); ImplementationBodyCodegen parentBodyCodegen = (ImplementationBodyCodegen) memberCodegen.getParentCodegen();
parentBodyCodegen.addClassObjectPropertyToCopy(propertyDescriptor, defaultValue); parentBodyCodegen.addDefaultObjectPropertyToCopy(propertyDescriptor, defaultValue);
} }
String name = backingFieldContext.getFieldName(propertyDescriptor, isDelegate); String name = backingFieldContext.getFieldName(propertyDescriptor, isDelegate);
@@ -513,8 +513,8 @@ public abstract class StackValue {
return field(FieldInfo.createForSingleton(classDescriptor, typeMapper)); return field(FieldInfo.createForSingleton(classDescriptor, typeMapper));
} }
public static Field deprecatedClassObjectAccessor(ClassDescriptor classDescriptor, JetTypeMapper typeMapper) { public static Field deprecatedDefaultObjectAccessor(ClassDescriptor classDescriptor, JetTypeMapper typeMapper) {
return field(FieldInfo.deprecatedFieldForClassObject(classDescriptor, typeMapper)); return field(FieldInfo.deprecatedFieldForDefaultObject(classDescriptor, typeMapper));
} }
public static StackValue operation(Type type, Function1<InstructionAdapter, Unit> lambda) { public static StackValue operation(Type type, Function1<InstructionAdapter, Unit> lambda) {
@@ -51,7 +51,7 @@ public final class PsiCodegenPredictor {
*/ */
@Nullable @Nullable
public static String getPredefinedJvmInternalName(@NotNull JetDeclaration declaration) { public static String getPredefinedJvmInternalName(@NotNull JetDeclaration declaration) {
// TODO: Method won't work for declarations inside class objects // TODO: Method won't work for declarations inside default objects
// TODO: Method won't give correct class name for traits implementations // TODO: Method won't give correct class name for traits implementations
JetDeclaration parentDeclaration = JetStubbedPsiUtil.getContainingDeclaration(declaration); JetDeclaration parentDeclaration = JetStubbedPsiUtil.getContainingDeclaration(declaration);
@@ -61,7 +61,7 @@ public class ClassContext extends FieldOwnerContext<ClassDescriptor> {
} }
@Nullable @Nullable
public CodegenContext getClassObjectContext() { public CodegenContext getDefaultObjectContext() {
if (getContextDescriptor().getDefaultObjectDescriptor() != null) { if (getContextDescriptor().getDefaultObjectDescriptor() != null) {
return findChildContext(getContextDescriptor().getDefaultObjectDescriptor()); return findChildContext(getContextDescriptor().getDefaultObjectDescriptor());
} }
@@ -361,7 +361,7 @@ public abstract class CodegenContext<T extends DeclarationDescriptor> {
CodegenContext descriptorContext = null; CodegenContext descriptorContext = null;
if (!fromOutsideContext || getClassOrPackageParentContext().getContextDescriptor() != descriptor.getContainingDeclaration()) { if (!fromOutsideContext || getClassOrPackageParentContext().getContextDescriptor() != descriptor.getContainingDeclaration()) {
DeclarationDescriptor enclosed = descriptor.getContainingDeclaration(); DeclarationDescriptor enclosed = descriptor.getContainingDeclaration();
boolean isClassObjectMember = DescriptorUtils.isClassObject(enclosed); boolean isDefaultObjectMember = DescriptorUtils.isDefaultObject(enclosed);
//go upper //go upper
if (hasThisDescriptor() && (enclosed != getThisDescriptor() || !fromOutsideContext)) { if (hasThisDescriptor() && (enclosed != getThisDescriptor() || !fromOutsideContext)) {
CodegenContext currentContext = this; CodegenContext currentContext = this;
@@ -371,12 +371,12 @@ public abstract class CodegenContext<T extends DeclarationDescriptor> {
break; break;
} }
//accessors for private members in class object for call from class //accessors for private members in default object for call from class
if (isClassObjectMember && currentContext instanceof ClassContext) { if (isDefaultObjectMember && currentContext instanceof ClassContext) {
ClassContext classContext = (ClassContext) currentContext; ClassContext classContext = (ClassContext) currentContext;
CodegenContext classObject = classContext.getClassObjectContext(); CodegenContext defaultObjectContext = classContext.getDefaultObjectContext();
if (classObject != null && classObject.getContextDescriptor() == enclosed) { if (defaultObjectContext != null && defaultObjectContext.getContextDescriptor() == enclosed) {
descriptorContext = classObject; descriptorContext = defaultObjectContext;
break; break;
} }
} }
@@ -417,7 +417,7 @@ public abstract class CodegenContext<T extends DeclarationDescriptor> {
} }
protected boolean shouldAddChild(@NotNull CodegenContext child) { protected boolean shouldAddChild(@NotNull CodegenContext child) {
return DescriptorUtils.isClassObject(child.contextDescriptor); return DescriptorUtils.isDefaultObject(child.contextDescriptor);
} }
@Nullable @Nullable
@@ -81,7 +81,7 @@ public abstract class FileBasedKotlinClass implements KotlinJvmBinaryClass {
@NotNull @NotNull
protected abstract byte[] getFileContents(); protected abstract byte[] getFileContents();
// TODO public to be accessible in class object of subclass, workaround for KT-3974 // TODO public to be accessible in default object of subclass, workaround for KT-3974
@Nullable @Nullable
public static <T extends FileBasedKotlinClass> T create( public static <T extends FileBasedKotlinClass> T create(
@NotNull byte[] fileContents, @NotNull byte[] fileContents,
@@ -102,9 +102,9 @@ public class PlatformStaticAnnotationChecker : AnnotationChecker {
diagnosticHolder: DiagnosticSink diagnosticHolder: DiagnosticSink
) { ) {
val insideObject = containerKindIs(descriptor, ClassKind.OBJECT) val insideObject = containerKindIs(descriptor, ClassKind.OBJECT)
val insideClassObject = containerKindIs(descriptor, ClassKind.CLASS_OBJECT) val insideDefaultObject = containerKindIs(descriptor, ClassKind.CLASS_OBJECT)
if (!insideObject && !(insideClassObject && containerKindIs(descriptor.getContainingDeclaration()!!, ClassKind.CLASS))) { if (!insideObject && !(insideDefaultObject && containerKindIs(descriptor.getContainingDeclaration()!!, ClassKind.CLASS))) {
diagnosticHolder.report(ErrorsJvm.PLATFORM_STATIC_NOT_IN_OBJECT.on(declaration)); diagnosticHolder.report(ErrorsJvm.PLATFORM_STATIC_NOT_IN_OBJECT.on(declaration));
} }
@@ -42,7 +42,7 @@ public class NeedSyntheticChecker implements CallChecker {
//Necessary synthetic accessors in outer classes generated via old logic: CodegenContext.getAccessor //Necessary synthetic accessors in outer classes generated via old logic: CodegenContext.getAccessor
//Generation of accessors in nested classes (to invoke from outer, //Generation of accessors in nested classes (to invoke from outer,
// e.g.: from class to classobject) controlled via NEED_SYNTHETIC_ACCESSOR slice // e.g.: from class to default object) controlled via NEED_SYNTHETIC_ACCESSOR slice
private boolean needSyntheticAccessor(JetScope invokationScope, CallableDescriptor targetDescriptor) { private boolean needSyntheticAccessor(JetScope invokationScope, CallableDescriptor targetDescriptor) {
return targetDescriptor instanceof CallableMemberDescriptor && return targetDescriptor instanceof CallableMemberDescriptor &&
Visibilities.isPrivate(targetDescriptor.getVisibility()) && Visibilities.isPrivate(targetDescriptor.getVisibility()) &&
@@ -45,7 +45,7 @@ public class DefaultErrorMessagesJvm implements DefaultErrorMessages.Extension {
static { static {
MAP.put(ErrorsJvm.CONFLICTING_JVM_DECLARATIONS, "Platform declaration clash: {0}", CONFLICTING_JVM_DECLARATIONS_DATA); MAP.put(ErrorsJvm.CONFLICTING_JVM_DECLARATIONS, "Platform declaration clash: {0}", CONFLICTING_JVM_DECLARATIONS_DATA);
MAP.put(ErrorsJvm.ACCIDENTAL_OVERRIDE, "Accidental override: {0}", CONFLICTING_JVM_DECLARATIONS_DATA); MAP.put(ErrorsJvm.ACCIDENTAL_OVERRIDE, "Accidental override: {0}", CONFLICTING_JVM_DECLARATIONS_DATA);
MAP.put(ErrorsJvm.PLATFORM_STATIC_NOT_IN_OBJECT, "Only functions in named objects and class objects of classes can be annotated with 'platformStatic'"); MAP.put(ErrorsJvm.PLATFORM_STATIC_NOT_IN_OBJECT, "Only functions in named objects and default objects of classes can be annotated with 'platformStatic'");
MAP.put(ErrorsJvm.OVERRIDE_CANNOT_BE_STATIC, "Override cannot be 'platformStatic' in object"); MAP.put(ErrorsJvm.OVERRIDE_CANNOT_BE_STATIC, "Override cannot be 'platformStatic' in object");
MAP.put(ErrorsJvm.PLATFORM_STATIC_ILLEGAL_USAGE, "This declaration does not support ''platformStatic''", DescriptorRenderer.SHORT_NAMES_IN_TYPES); MAP.put(ErrorsJvm.PLATFORM_STATIC_ILLEGAL_USAGE, "This declaration does not support ''platformStatic''", DescriptorRenderer.SHORT_NAMES_IN_TYPES);
MAP.put(ErrorsJvm.NATIVE_DECLARATION_CANNOT_BE_ABSTRACT, "Native declaration can not be abstract"); MAP.put(ErrorsJvm.NATIVE_DECLARATION_CANNOT_BE_ABSTRACT, "Native declaration can not be abstract");
@@ -1379,7 +1379,7 @@ public class JetControlFlowProcessor {
@Override @Override
public void visitTypeProjection(@NotNull JetTypeProjection typeProjection) { public void visitTypeProjection(@NotNull JetTypeProjection typeProjection) {
// TODO : Support Type Arguments. Class object may be initialized at this point"); // TODO : Support Type Arguments. Default object may be initialized at this point");
} }
@Override @Override
@@ -44,7 +44,7 @@ public class MutableClassDescriptor extends ClassDescriptorBase implements Class
private List<TypeParameterDescriptor> typeParameters; private List<TypeParameterDescriptor> typeParameters;
private Collection<JetType> supertypes = new ArrayList<JetType>(); private Collection<JetType> supertypes = new ArrayList<JetType>();
private MutableClassDescriptor classObjectDescriptor; private MutableClassDescriptor defaultObjectDescriptor;
private final Set<ConstructorDescriptor> constructors = Sets.newLinkedHashSet(); private final Set<ConstructorDescriptor> constructors = Sets.newLinkedHashSet();
private ConstructorDescriptor primaryConstructor; private ConstructorDescriptor primaryConstructor;
@@ -93,7 +93,7 @@ public class MutableClassDescriptor extends ClassDescriptorBase implements Class
@Nullable @Nullable
@Override @Override
public MutableClassDescriptor getDefaultObjectDescriptor() { public MutableClassDescriptor getDefaultObjectDescriptor() {
return classObjectDescriptor; return defaultObjectDescriptor;
} }
@NotNull @NotNull
@@ -306,8 +306,8 @@ public class MutableClassDescriptor extends ClassDescriptorBase implements Class
public void lockScopes() { public void lockScopes() {
getScopeForMemberLookupAsWritableScope().changeLockLevel(WritableScope.LockLevel.READING); getScopeForMemberLookupAsWritableScope().changeLockLevel(WritableScope.LockLevel.READING);
if (classObjectDescriptor != null) { if (defaultObjectDescriptor != null) {
classObjectDescriptor.lockScopes(); defaultObjectDescriptor.lockScopes();
} }
scopeForSupertypeResolution.changeLockLevel(WritableScope.LockLevel.READING); scopeForSupertypeResolution.changeLockLevel(WritableScope.LockLevel.READING);
scopeForMemberResolution.changeLockLevel(WritableScope.LockLevel.READING); scopeForMemberResolution.changeLockLevel(WritableScope.LockLevel.READING);
@@ -186,10 +186,10 @@ public interface Errors {
DiagnosticFactory1<JetTypeReference, ClassDescriptor> ENUM_ENTRY_ILLEGAL_TYPE = DiagnosticFactory1.create(ERROR); DiagnosticFactory1<JetTypeReference, ClassDescriptor> ENUM_ENTRY_ILLEGAL_TYPE = DiagnosticFactory1.create(ERROR);
DiagnosticFactory1<JetClass, ClassDescriptor> LOCAL_ENUM_NOT_ALLOWED = DiagnosticFactory1.create(ERROR, DECLARATION_NAME); DiagnosticFactory1<JetClass, ClassDescriptor> LOCAL_ENUM_NOT_ALLOWED = DiagnosticFactory1.create(ERROR, DECLARATION_NAME);
// Class objects // Default objects
DiagnosticFactory0<JetObjectDeclaration> MANY_CLASS_OBJECTS = DiagnosticFactory0.create(ERROR); DiagnosticFactory0<JetObjectDeclaration> MANY_DEFAULT_OBJECTS = DiagnosticFactory0.create(ERROR);
DiagnosticFactory0<JetObjectDeclaration> CLASS_OBJECT_NOT_ALLOWED = DiagnosticFactory0.create(ERROR); DiagnosticFactory0<JetObjectDeclaration> DEFAULT_OBJECT_NOT_ALLOWED = DiagnosticFactory0.create(ERROR);
// Objects // Objects
@@ -198,12 +198,12 @@ public interface Errors {
// Type parameter declarations // Type parameter declarations
DiagnosticFactory1<JetTypeReference, JetType> FINAL_UPPER_BOUND = DiagnosticFactory1.create(WARNING); DiagnosticFactory1<JetTypeReference, JetType> FINAL_UPPER_BOUND = DiagnosticFactory1.create(WARNING);
DiagnosticFactory1<JetTypeReference, JetType> FINAL_CLASS_OBJECT_UPPER_BOUND = DiagnosticFactory1.create(ERROR); DiagnosticFactory1<JetTypeReference, JetType> FINAL_DEFAULT_OBJECT_UPPER_BOUND = DiagnosticFactory1.create(ERROR);
DiagnosticFactory0<JetTypeReference> DYNAMIC_UPPER_BOUND = DiagnosticFactory0.create(ERROR); DiagnosticFactory0<JetTypeReference> DYNAMIC_UPPER_BOUND = DiagnosticFactory0.create(ERROR);
DiagnosticFactory1<JetNamedDeclaration, TypeParameterDescriptor> CONFLICTING_UPPER_BOUNDS = DiagnosticFactory1<JetNamedDeclaration, TypeParameterDescriptor> CONFLICTING_UPPER_BOUNDS =
DiagnosticFactory1.create(ERROR, DECLARATION_NAME); DiagnosticFactory1.create(ERROR, DECLARATION_NAME);
DiagnosticFactory1<JetNamedDeclaration, TypeParameterDescriptor> CONFLICTING_CLASS_OBJECT_UPPER_BOUNDS DiagnosticFactory1<JetNamedDeclaration, TypeParameterDescriptor> CONFLICTING_DEFAULT_OBJECT_UPPER_BOUNDS
= DiagnosticFactory1.create(ERROR, DECLARATION_NAME); = DiagnosticFactory1.create(ERROR, DECLARATION_NAME);
DiagnosticFactory2<JetSimpleNameExpression, JetTypeConstraint, JetTypeParameterListOwner> NAME_IN_CONSTRAINT_IS_NOT_A_TYPE_PARAMETER = DiagnosticFactory2<JetSimpleNameExpression, JetTypeConstraint, JetTypeParameterListOwner> NAME_IN_CONSTRAINT_IS_NOT_A_TYPE_PARAMETER =
@@ -605,7 +605,7 @@ public interface Errors {
DiagnosticFactory0<JetThisExpression> NO_THIS = DiagnosticFactory0.create(ERROR); DiagnosticFactory0<JetThisExpression> NO_THIS = DiagnosticFactory0.create(ERROR);
DiagnosticFactory0<JetRootPackageExpression> PACKAGE_IS_NOT_AN_EXPRESSION = DiagnosticFactory0.create(ERROR); DiagnosticFactory0<JetRootPackageExpression> PACKAGE_IS_NOT_AN_EXPRESSION = DiagnosticFactory0.create(ERROR);
DiagnosticFactory1<JetSimpleNameExpression, ClassifierDescriptor> NO_CLASS_OBJECT = DiagnosticFactory1.create(ERROR); DiagnosticFactory1<JetSimpleNameExpression, ClassifierDescriptor> NO_DEFAULT_OBJECT = DiagnosticFactory1.create(ERROR);
DiagnosticFactory1<JetSimpleNameExpression, TypeParameterDescriptor> TYPE_PARAMETER_IS_NOT_AN_EXPRESSION = DiagnosticFactory1.create(ERROR); DiagnosticFactory1<JetSimpleNameExpression, TypeParameterDescriptor> TYPE_PARAMETER_IS_NOT_AN_EXPRESSION = DiagnosticFactory1.create(ERROR);
DiagnosticFactory1<JetSimpleNameExpression, TypeParameterDescriptor> TYPE_PARAMETER_ON_LHS_OF_DOT = DiagnosticFactory1.create(ERROR); DiagnosticFactory1<JetSimpleNameExpression, TypeParameterDescriptor> TYPE_PARAMETER_ON_LHS_OF_DOT = DiagnosticFactory1.create(ERROR);
DiagnosticFactory1<JetExpression, ClassDescriptor> NESTED_CLASS_ACCESSED_VIA_INSTANCE_REFERENCE = DiagnosticFactory1.create(ERROR); DiagnosticFactory1<JetExpression, ClassDescriptor> NESTED_CLASS_ACCESSED_VIA_INSTANCE_REFERENCE = DiagnosticFactory1.create(ERROR);
@@ -270,8 +270,8 @@ public class DefaultErrorMessages {
MAP.put(UNREACHABLE_CODE, "Unreachable code", TO_STRING); MAP.put(UNREACHABLE_CODE, "Unreachable code", TO_STRING);
MAP.put(MANY_CLASS_OBJECTS, "Only one class object is allowed per class"); MAP.put(MANY_DEFAULT_OBJECTS, "Only one default object is allowed per class");
MAP.put(CLASS_OBJECT_NOT_ALLOWED, "A class object is not allowed here"); MAP.put(DEFAULT_OBJECT_NOT_ALLOWED, "A default object is not allowed here");
MAP.put(LOCAL_OBJECT_NOT_ALLOWED, "Named object ''{0}'' is a singleton and cannot be local. Try to use anonymous object instead", NAME); MAP.put(LOCAL_OBJECT_NOT_ALLOWED, "Named object ''{0}'' is a singleton and cannot be local. Try to use anonymous object instead", NAME);
MAP.put(LOCAL_ENUM_NOT_ALLOWED, "Enum class ''{0}'' cannot be local", NAME); MAP.put(LOCAL_ENUM_NOT_ALLOWED, "Enum class ''{0}'' cannot be local", NAME);
MAP.put(DELEGATION_IN_TRAIT, "Traits cannot use delegation"); MAP.put(DELEGATION_IN_TRAIT, "Traits cannot use delegation");
@@ -315,9 +315,9 @@ public class DefaultErrorMessages {
MAP.put(USELESS_NULLABLE_CHECK, "Non-null type is checked for instance of nullable type"); MAP.put(USELESS_NULLABLE_CHECK, "Non-null type is checked for instance of nullable type");
MAP.put(WRONG_SETTER_PARAMETER_TYPE, "Setter parameter type must be equal to the type of the property, i.e. ''{0}''", RENDER_TYPE, RENDER_TYPE); MAP.put(WRONG_SETTER_PARAMETER_TYPE, "Setter parameter type must be equal to the type of the property, i.e. ''{0}''", RENDER_TYPE, RENDER_TYPE);
MAP.put(WRONG_GETTER_RETURN_TYPE, "Getter return type must be equal to the type of the property, i.e. ''{0}''", RENDER_TYPE, RENDER_TYPE); MAP.put(WRONG_GETTER_RETURN_TYPE, "Getter return type must be equal to the type of the property, i.e. ''{0}''", RENDER_TYPE, RENDER_TYPE);
MAP.put(NO_CLASS_OBJECT, "Please specify constructor invocation; classifier ''{0}'' does not have a class object", NAME); MAP.put(NO_DEFAULT_OBJECT, "Please specify constructor invocation; classifier ''{0}'' does not have a default object", NAME);
MAP.put(TYPE_PARAMETER_IS_NOT_AN_EXPRESSION, "Type parameter ''{0}'' is not an expression", NAME); MAP.put(TYPE_PARAMETER_IS_NOT_AN_EXPRESSION, "Type parameter ''{0}'' is not an expression", NAME);
MAP.put(TYPE_PARAMETER_ON_LHS_OF_DOT, "Type parameter ''{0}'' cannot have or inherit a class object, so it cannot be on the left hand side of dot", NAME); MAP.put(TYPE_PARAMETER_ON_LHS_OF_DOT, "Type parameter ''{0}'' cannot have or inherit a default object, so it cannot be on the left hand side of dot", NAME);
MAP.put(NO_GENERICS_IN_SUPERTYPE_SPECIFIER, "Generic arguments of the base type must be specified"); MAP.put(NO_GENERICS_IN_SUPERTYPE_SPECIFIER, "Generic arguments of the base type must be specified");
MAP.put(NESTED_CLASS_ACCESSED_VIA_INSTANCE_REFERENCE, "Nested {0} accessed via instance reference", RENDER_CLASS_OR_OBJECT_NAME); MAP.put(NESTED_CLASS_ACCESSED_VIA_INSTANCE_REFERENCE, "Nested {0} accessed via instance reference", RENDER_CLASS_OR_OBJECT_NAME);
MAP.put(NESTED_CLASS_SHOULD_BE_QUALIFIED, "Nested {0} should be qualified as ''{1}''", RENDER_CLASS_OR_OBJECT_NAME, TO_STRING); MAP.put(NESTED_CLASS_SHOULD_BE_QUALIFIED, "Nested {0} should be qualified as ''{1}''", RENDER_CLASS_OR_OBJECT_NAME, TO_STRING);
@@ -375,12 +375,12 @@ public class DefaultErrorMessages {
}); });
MAP.put(UPPER_BOUND_VIOLATED, "Type argument is not within its bounds: should be subtype of ''{0}''", RENDER_TYPE, RENDER_TYPE); MAP.put(UPPER_BOUND_VIOLATED, "Type argument is not within its bounds: should be subtype of ''{0}''", RENDER_TYPE, RENDER_TYPE);
MAP.put(FINAL_CLASS_OBJECT_UPPER_BOUND, "''{0}'' is a final type, and thus a class object cannot extend it", RENDER_TYPE); MAP.put(FINAL_DEFAULT_OBJECT_UPPER_BOUND, "''{0}'' is a final type, and thus a default object cannot extend it", RENDER_TYPE);
MAP.put(FINAL_UPPER_BOUND, "''{0}'' is a final type, and thus a value of the type parameter is predetermined", RENDER_TYPE); MAP.put(FINAL_UPPER_BOUND, "''{0}'' is a final type, and thus a value of the type parameter is predetermined", RENDER_TYPE);
MAP.put(DYNAMIC_UPPER_BOUND, "Dynamic type can not be used as an upper bound"); MAP.put(DYNAMIC_UPPER_BOUND, "Dynamic type can not be used as an upper bound");
MAP.put(USELESS_ELVIS, "Elvis operator (?:) always returns the left operand of non-nullable type {0}", RENDER_TYPE); MAP.put(USELESS_ELVIS, "Elvis operator (?:) always returns the left operand of non-nullable type {0}", RENDER_TYPE);
MAP.put(CONFLICTING_UPPER_BOUNDS, "Upper bounds of {0} have empty intersection", NAME); MAP.put(CONFLICTING_UPPER_BOUNDS, "Upper bounds of {0} have empty intersection", NAME);
MAP.put(CONFLICTING_CLASS_OBJECT_UPPER_BOUNDS, "Class object upper bounds of {0} have empty intersection", NAME); MAP.put(CONFLICTING_DEFAULT_OBJECT_UPPER_BOUNDS, "Default object upper bounds of {0} have empty intersection", NAME);
MAP.put(TOO_MANY_ARGUMENTS, "Too many arguments for {0}", FQ_NAMES_IN_TYPES); MAP.put(TOO_MANY_ARGUMENTS, "Too many arguments for {0}", FQ_NAMES_IN_TYPES);
@@ -765,7 +765,7 @@ public class JetParsing extends AbstractJetParsing {
* ; * ;
* *
* memberDeclaration' * memberDeclaration'
* : classObject * : defaultObject
* : constructor * : constructor
* : function * : function
* : property * : property
@@ -798,7 +798,7 @@ public class JetParsing extends AbstractJetParsing {
IElementType declType = null; IElementType declType = null;
if (keywordToken == CLASS_KEYWORD) { if (keywordToken == CLASS_KEYWORD) {
if (lookahead(1) == OBJECT_KEYWORD) { if (lookahead(1) == OBJECT_KEYWORD) {
declType = parseClassObject(); declType = parseDefaultObject();
} }
else { else {
declType = parseClass(isEnum); declType = parseClass(isEnum);
@@ -876,11 +876,11 @@ public class JetParsing extends AbstractJetParsing {
} }
/* /*
* classObject * defaultObject
* : modifiers "class" object * : modifiers "class" object
* ; * ;
*/ */
private IElementType parseClassObject() { private IElementType parseDefaultObject() {
assert _at(CLASS_KEYWORD) && lookahead(1) == OBJECT_KEYWORD; assert _at(CLASS_KEYWORD) && lookahead(1) == OBJECT_KEYWORD;
advance(); // CLASS_KEYWORD advance(); // CLASS_KEYWORD
parseObject(NameParsingMode.ALLOWED, true); parseObject(NameParsingMode.ALLOWED, true);
@@ -237,7 +237,7 @@ private object DebugTextBuildingVisitor : JetVisitor<String, Unit>() {
return buildText { return buildText {
append("STUB: ") append("STUB: ")
appendInn(declaration.getModifierList(), suffix = " ") appendInn(declaration.getModifierList(), suffix = " ")
if (declaration.isClassObject()) { if (declaration.isDefault()) {
append("class ") append("class ")
} }
append("object ") append("object ")
@@ -273,7 +273,7 @@ private object DebugTextBuildingVisitor : JetVisitor<String, Unit>() {
override fun visitTypeConstraint(constraint: JetTypeConstraint, data: Unit?): String? { override fun visitTypeConstraint(constraint: JetTypeConstraint, data: Unit?): String? {
return buildText { return buildText {
if (constraint.isClassObjectConstraint()) { if (constraint.isDefaultObjectConstraint()) {
append("class object ") append("class object ")
} }
appendInn(constraint.getSubjectTypeParameterName()) appendInn(constraint.getSubjectTypeParameterName())
@@ -142,10 +142,10 @@ public class JetClass extends JetTypeParameterListOwnerStub<KotlinClassStub> imp
} }
@Nullable @Nullable
public JetObjectDeclaration getClassObject() { public JetObjectDeclaration getDefaultObject() {
JetClassBody body = getBody(); JetClassBody body = getBody();
if (body == null) return null; if (body == null) return null;
return body.getClassObject(); return body.getDefaultObject();
} }
public List<JetProperty> getProperties() { public List<JetProperty> getProperties() {
@@ -67,15 +67,15 @@ public class JetClassBody extends JetElementImplStub<KotlinPlaceHolderStub<JetCl
} }
@Nullable @Nullable
public JetObjectDeclaration getClassObject() { public JetObjectDeclaration getDefaultObject() {
return firstOrNull(getAllClassObjects()); return firstOrNull(getAllDefaultObjects());
} }
@NotNull @NotNull
public List<JetObjectDeclaration> getAllClassObjects() { public List<JetObjectDeclaration> getAllDefaultObjects() {
List<JetObjectDeclaration> result = Lists.newArrayList(); List<JetObjectDeclaration> result = Lists.newArrayList();
for (JetObjectDeclaration declaration : getStubOrPsiChildrenAsList(JetStubElementTypes.OBJECT_DECLARATION)) { for (JetObjectDeclaration declaration : getStubOrPsiChildrenAsList(JetStubElementTypes.OBJECT_DECLARATION)) {
if (declaration.isClassObject()) { if (declaration.isDefault()) {
result.add(declaration); result.add(declaration);
} }
} }
@@ -95,10 +95,10 @@ abstract class JetNamedDeclarationStub<T extends KotlinStubWithFqName> extends J
if (hasModifier(JetTokens.PRIVATE_KEYWORD)) { if (hasModifier(JetTokens.PRIVATE_KEYWORD)) {
JetElement containingClass = PsiTreeUtil.getParentOfType(this, JetClassOrObject.class); JetElement containingClass = PsiTreeUtil.getParentOfType(this, JetClassOrObject.class);
if (containingClass instanceof JetObjectDeclaration && ((JetObjectDeclaration) containingClass).isClassObject()) { if (containingClass instanceof JetObjectDeclaration && ((JetObjectDeclaration) containingClass).isDefault()) {
JetElement classObjectClass = PsiTreeUtil.getParentOfType(containingClass, JetClassOrObject.class); JetElement defaultObjectClass = PsiTreeUtil.getParentOfType(containingClass, JetClassOrObject.class);
if (classObjectClass != null) { if (defaultObjectClass != null) {
containingClass = classObjectClass; containingClass = defaultObjectClass;
} }
} }
if (containingClass != null) { if (containingClass != null) {
@@ -51,7 +51,7 @@ public class JetObjectDeclaration extends JetNamedDeclarationStub<KotlinObjectSt
} }
JetObjectDeclarationName nameAsDeclaration = getNameAsDeclaration(); JetObjectDeclarationName nameAsDeclaration = getNameAsDeclaration();
if (nameAsDeclaration == null && isClassObject()) { if (nameAsDeclaration == null && isDefault()) {
//NOTE: a hack in PSI that simplifies writing frontend code //NOTE: a hack in PSI that simplifies writing frontend code
return SpecialNames.DEFAULT_NAME_FOR_DEFAULT_OBJECT.toString(); return SpecialNames.DEFAULT_NAME_FOR_DEFAULT_OBJECT.toString();
} }
@@ -86,10 +86,10 @@ public class JetObjectDeclaration extends JetNamedDeclarationStub<KotlinObjectSt
return (JetObjectDeclarationName) findChildByType(JetNodeTypes.OBJECT_DECLARATION_NAME); return (JetObjectDeclarationName) findChildByType(JetNodeTypes.OBJECT_DECLARATION_NAME);
} }
public boolean isClassObject() { public boolean isDefault() {
KotlinObjectStub stub = getStub(); KotlinObjectStub stub = getStub();
if (stub != null) { if (stub != null) {
return stub.isClassObject(); return stub.isDefault();
} }
return getClassKeyword() != null; return getClassKeyword() != null;
} }
@@ -37,10 +37,10 @@ public class JetTypeConstraint extends JetElementImplStub<KotlinTypeConstraintSt
return visitor.visitTypeConstraint(this, data); return visitor.visitTypeConstraint(this, data);
} }
public boolean isClassObjectConstraint() { public boolean isDefaultObjectConstraint() {
KotlinTypeConstraintStub stub = getStub(); KotlinTypeConstraintStub stub = getStub();
if (stub != null) { if (stub != null) {
return stub.isClassObjectConstraint(); return stub.isDefaultObjectConstraint();
} }
return findChildByType(JetTokens.CLASS_KEYWORD) != null && return findChildByType(JetTokens.CLASS_KEYWORD) != null &&
findChildByType(JetTokens.OBJECT_KEYWORD) != null; findChildByType(JetTokens.OBJECT_KEYWORD) != null;
@@ -47,7 +47,7 @@ public trait KotlinClassStub : KotlinClassOrObjectStub<JetClass> {
} }
public trait KotlinObjectStub : KotlinClassOrObjectStub<JetObjectDeclaration> { public trait KotlinObjectStub : KotlinClassOrObjectStub<JetObjectDeclaration> {
public fun isClassObject(): Boolean public fun isDefault(): Boolean
public fun isObjectLiteral(): Boolean public fun isObjectLiteral(): Boolean
} }
@@ -104,7 +104,7 @@ public trait KotlinPropertyStub : KotlinStubWithFqName<JetProperty> {
} }
public trait KotlinTypeConstraintStub : StubElement<JetTypeConstraint> { public trait KotlinTypeConstraintStub : StubElement<JetTypeConstraint> {
public fun isClassObjectConstraint(): Boolean public fun isDefaultObjectConstraint(): Boolean
} }
public trait KotlinTypeParameterStub : KotlinStubWithFqName<JetTypeParameter> { public trait KotlinTypeParameterStub : KotlinStubWithFqName<JetTypeParameter> {
@@ -45,7 +45,7 @@ public class JetObjectElementType extends JetStubElementType<KotlinObjectStub, J
FqName fqName = ResolveSessionUtils.safeFqNameForLazyResolve(psi); FqName fqName = ResolveSessionUtils.safeFqNameForLazyResolve(psi);
List<String> superNames = PsiUtilPackage.getSuperNames(psi); List<String> superNames = PsiUtilPackage.getSuperNames(psi);
return new KotlinObjectStubImpl(parentStub, StringRef.fromString(name), fqName, Utils.INSTANCE$.wrapStrings(superNames), return new KotlinObjectStubImpl(parentStub, StringRef.fromString(name), fqName, Utils.INSTANCE$.wrapStrings(superNames),
psi.isTopLevel(), psi.isClassObject(), psi.isLocal(), psi.isObjectLiteral()); psi.isTopLevel(), psi.isDefault(), psi.isLocal(), psi.isObjectLiteral());
} }
@Override @Override
@@ -56,7 +56,7 @@ public class JetObjectElementType extends JetStubElementType<KotlinObjectStub, J
dataStream.writeName(fqName != null ? fqName.toString() : null); dataStream.writeName(fqName != null ? fqName.toString() : null);
dataStream.writeBoolean(stub.isTopLevel()); dataStream.writeBoolean(stub.isTopLevel());
dataStream.writeBoolean(stub.isClassObject()); dataStream.writeBoolean(stub.isDefault());
dataStream.writeBoolean(stub.isLocal()); dataStream.writeBoolean(stub.isLocal());
dataStream.writeBoolean(stub.isObjectLiteral()); dataStream.writeBoolean(stub.isObjectLiteral());
@@ -75,7 +75,7 @@ public class JetObjectElementType extends JetStubElementType<KotlinObjectStub, J
FqName fqName = fqNameStr != null ? new FqName(fqNameStr.toString()) : null; FqName fqName = fqNameStr != null ? new FqName(fqNameStr.toString()) : null;
boolean isTopLevel = dataStream.readBoolean(); boolean isTopLevel = dataStream.readBoolean();
boolean isClassObject = dataStream.readBoolean(); boolean isDefault = dataStream.readBoolean();
boolean isLocal = dataStream.readBoolean(); boolean isLocal = dataStream.readBoolean();
boolean isObjectLiteral = dataStream.readBoolean(); boolean isObjectLiteral = dataStream.readBoolean();
@@ -85,7 +85,7 @@ public class JetObjectElementType extends JetStubElementType<KotlinObjectStub, J
superNames[i] = dataStream.readName(); superNames[i] = dataStream.readName();
} }
return new KotlinObjectStubImpl(parentStub, name, fqName, superNames, isTopLevel, isClassObject, isLocal, isObjectLiteral); return new KotlinObjectStubImpl(parentStub, name, fqName, superNames, isTopLevel, isDefault, isLocal, isObjectLiteral);
} }
@Override @Override
@@ -34,18 +34,18 @@ public class JetTypeConstraintElementType extends JetStubElementType<KotlinTypeC
@Override @Override
public KotlinTypeConstraintStub createStub(@NotNull JetTypeConstraint psi, StubElement parentStub) { public KotlinTypeConstraintStub createStub(@NotNull JetTypeConstraint psi, StubElement parentStub) {
return new KotlinTypeConstraintStubImpl(parentStub, psi.isClassObjectConstraint()); return new KotlinTypeConstraintStubImpl(parentStub, psi.isDefaultObjectConstraint());
} }
@Override @Override
public void serialize(@NotNull KotlinTypeConstraintStub stub, @NotNull StubOutputStream dataStream) throws IOException { public void serialize(@NotNull KotlinTypeConstraintStub stub, @NotNull StubOutputStream dataStream) throws IOException {
dataStream.writeBoolean(stub.isClassObjectConstraint()); dataStream.writeBoolean(stub.isDefaultObjectConstraint());
} }
@NotNull @NotNull
@Override @Override
public KotlinTypeConstraintStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException { public KotlinTypeConstraintStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException {
boolean isClassObjectConstraint = dataStream.readBoolean(); boolean isDefaultObjectConstraint = dataStream.readBoolean();
return new KotlinTypeConstraintStubImpl(parentStub, isClassObjectConstraint); return new KotlinTypeConstraintStubImpl(parentStub, isDefaultObjectConstraint);
} }
} }
@@ -31,7 +31,7 @@ public class KotlinObjectStubImpl(
private val fqName: FqName?, private val fqName: FqName?,
private val superNames: Array<StringRef>, private val superNames: Array<StringRef>,
private val isTopLevel: Boolean, private val isTopLevel: Boolean,
private val isClassObject: Boolean, private val isDefault: Boolean,
private val isLocal: Boolean, private val isLocal: Boolean,
private val isObjectLiteral: Boolean private val isObjectLiteral: Boolean
) : KotlinStubBaseImpl<JetObjectDeclaration>(parent, JetStubElementTypes.OBJECT_DECLARATION), KotlinObjectStub { ) : KotlinStubBaseImpl<JetObjectDeclaration>(parent, JetStubElementTypes.OBJECT_DECLARATION), KotlinObjectStub {
@@ -39,7 +39,7 @@ public class KotlinObjectStubImpl(
override fun getName() = StringRef.toString(name) override fun getName() = StringRef.toString(name)
override fun getSuperNames() = superNames map { it.toString() } override fun getSuperNames() = superNames map { it.toString() }
override fun isTopLevel() = isTopLevel override fun isTopLevel() = isTopLevel
override fun isClassObject() = isClassObject override fun isDefault() = isDefault
override fun isObjectLiteral() = isObjectLiteral override fun isObjectLiteral() = isObjectLiteral
override fun isLocal() = isLocal override fun isLocal() = isLocal
} }
@@ -24,8 +24,8 @@ import com.intellij.psi.PsiElement
public class KotlinTypeConstraintStubImpl( public class KotlinTypeConstraintStubImpl(
parent: StubElement<out PsiElement>?, parent: StubElement<out PsiElement>?,
private val isClassObjectConstraint: Boolean private val isDefaultObjectConstraint: Boolean
) : KotlinStubBaseImpl<JetTypeConstraint>(parent, JetStubElementTypes.TYPE_CONSTRAINT), KotlinTypeConstraintStub { ) : KotlinStubBaseImpl<JetTypeConstraint>(parent, JetStubElementTypes.TYPE_CONSTRAINT), KotlinTypeConstraintStub {
override fun isClassObjectConstraint() = isClassObjectConstraint override fun isDefaultObjectConstraint() = isDefaultObjectConstraint
} }
@@ -38,7 +38,7 @@ public fun DeclarationDescriptor.hasIntrinsicAnnotation(): Boolean {
public fun CallableDescriptor.isPlatformStaticInObjectOrClass(): Boolean = public fun CallableDescriptor.isPlatformStaticInObjectOrClass(): Boolean =
isPlatformStaticIn(ClassKind.OBJECT, ClassKind.CLASS) isPlatformStaticIn(ClassKind.OBJECT, ClassKind.CLASS)
public fun CallableDescriptor.isPlatformStaticInClassObject(): Boolean = public fun CallableDescriptor.isPlatformStaticInDefaultObject(): Boolean =
isPlatformStaticIn(ClassKind.CLASS_OBJECT) isPlatformStaticIn(ClassKind.CLASS_OBJECT)
private fun CallableDescriptor.isPlatformStaticIn(vararg kinds: ClassKind): Boolean = private fun CallableDescriptor.isPlatformStaticIn(vararg kinds: ClassKind): Boolean =
@@ -61,16 +61,16 @@ public class DeclarationResolver {
public fun checkRedeclarationsInInnerClassNames(c: TopDownAnalysisContext) { public fun checkRedeclarationsInInnerClassNames(c: TopDownAnalysisContext) {
for (classDescriptor in c.getDeclaredClasses().values()) { for (classDescriptor in c.getDeclaredClasses().values()) {
if (classDescriptor.getKind() == ClassKind.CLASS_OBJECT) { if (classDescriptor.getKind() == ClassKind.CLASS_OBJECT) {
// Class objects should be considered during analysing redeclarations in classes // Default objects should be considered during analysing redeclarations in classes
continue continue
} }
var allDescriptors = classDescriptor.getScopeForMemberLookup().getOwnDeclaredDescriptors() var allDescriptors = classDescriptor.getScopeForMemberLookup().getOwnDeclaredDescriptors()
val classObj = classDescriptor.getDefaultObjectDescriptor() val defaultObject = classDescriptor.getDefaultObjectDescriptor()
if (classObj != null) { if (defaultObject != null) {
val classObjDescriptors = classObj.getScopeForMemberLookup().getOwnDeclaredDescriptors() val descriptorsFromDefaultObject = defaultObject.getScopeForMemberLookup().getOwnDeclaredDescriptors()
if (classObjDescriptors.isNotEmpty()) { if (descriptorsFromDefaultObject.isNotEmpty()) {
allDescriptors = allDescriptors + classObjDescriptors allDescriptors = allDescriptors + descriptorsFromDefaultObject
} }
} }
@@ -154,7 +154,7 @@ public class DeclarationsChecker {
for (JetTypeConstraint constraint : jetClass.getTypeConstraints()) { for (JetTypeConstraint constraint : jetClass.getTypeConstraints()) {
checkBoundsForTypeInClassHeader(constraint.getBoundTypeReference()); checkBoundsForTypeInClassHeader(constraint.getBoundTypeReference());
checkFinalUpperBounds(constraint.getBoundTypeReference(), constraint.isClassObjectConstraint()); checkFinalUpperBounds(constraint.getBoundTypeReference(), constraint.isDefaultObjectConstraint());
} }
} }
@@ -167,11 +167,11 @@ public class DeclarationsChecker {
} }
} }
private void checkFinalUpperBounds(@Nullable JetTypeReference typeReference, boolean isClassObjectConstraint) { private void checkFinalUpperBounds(@Nullable JetTypeReference typeReference, boolean isDefaultObjectConstraint) {
if (typeReference != null) { if (typeReference != null) {
JetType type = trace.getBindingContext().get(TYPE, typeReference); JetType type = trace.getBindingContext().get(TYPE, typeReference);
if (type != null) { if (type != null) {
DescriptorResolver.checkUpperBoundType(typeReference, type, isClassObjectConstraint, trace); DescriptorResolver.checkUpperBoundType(typeReference, type, isDefaultObjectConstraint, trace);
} }
} }
} }
@@ -260,7 +260,7 @@ public class DeclarationsChecker {
private void checkObject(JetObjectDeclaration declaration, ClassDescriptor classDescriptor) { private void checkObject(JetObjectDeclaration declaration, ClassDescriptor classDescriptor) {
reportErrorIfHasIllegalModifier(declaration); reportErrorIfHasIllegalModifier(declaration);
if (declaration.isLocal() && !declaration.isClassObject() && !declaration.isObjectLiteral()) { if (declaration.isLocal() && !declaration.isDefault() && !declaration.isObjectLiteral()) {
trace.report(LOCAL_OBJECT_NOT_ALLOWED.on(declaration, classDescriptor)); trace.report(LOCAL_OBJECT_NOT_ALLOWED.on(declaration, classDescriptor));
} }
} }
@@ -651,12 +651,12 @@ public class DescriptorResolver {
static final class UpperBoundCheckerTask { static final class UpperBoundCheckerTask {
JetTypeReference upperBound; JetTypeReference upperBound;
JetType upperBoundType; JetType upperBoundType;
boolean isClassObjectConstraint; boolean isDefaultObjectConstraint;
private UpperBoundCheckerTask(JetTypeReference upperBound, JetType upperBoundType, boolean classObjectConstraint) { private UpperBoundCheckerTask(JetTypeReference upperBound, JetType upperBoundType, boolean defaultObjectConstraint) {
this.upperBound = upperBound; this.upperBound = upperBound;
this.upperBoundType = upperBoundType; this.upperBoundType = upperBoundType;
isClassObjectConstraint = classObjectConstraint; isDefaultObjectConstraint = defaultObjectConstraint;
} }
} }
@@ -685,7 +685,7 @@ public class DescriptorResolver {
} }
} }
for (JetTypeConstraint constraint : declaration.getTypeConstraints()) { for (JetTypeConstraint constraint : declaration.getTypeConstraints()) {
reportUnsupportedClassObjectConstraint(trace, constraint); reportUnsupportedDefaultObjectConstraint(trace, constraint);
JetSimpleNameExpression subjectTypeParameterName = constraint.getSubjectTypeParameterName(); JetSimpleNameExpression subjectTypeParameterName = constraint.getSubjectTypeParameterName();
if (subjectTypeParameterName == null) { if (subjectTypeParameterName == null) {
@@ -698,15 +698,14 @@ public class DescriptorResolver {
if (boundTypeReference != null) { if (boundTypeReference != null) {
bound = typeResolver.resolveType(scope, boundTypeReference, trace, false); bound = typeResolver.resolveType(scope, boundTypeReference, trace, false);
deferredUpperBoundCheckerTasks deferredUpperBoundCheckerTasks
.add(new UpperBoundCheckerTask(boundTypeReference, bound, constraint.isClassObjectConstraint())); .add(new UpperBoundCheckerTask(boundTypeReference, bound, constraint.isDefaultObjectConstraint()));
} }
if (typeParameterDescriptor != null) { if (typeParameterDescriptor != null) {
trace.record(BindingContext.REFERENCE_TARGET, subjectTypeParameterName, typeParameterDescriptor); trace.record(BindingContext.REFERENCE_TARGET, subjectTypeParameterName, typeParameterDescriptor);
if (bound != null) { if (bound != null) {
if (constraint.isClassObjectConstraint()) { if (constraint.isDefaultObjectConstraint()) {
// Class object bounds are not supported // Default object bounds are not supported
//typeParameterDescriptor.addClassObjectBound(bound);
} }
else { else {
typeParameterDescriptor.addUpperBound(bound); typeParameterDescriptor.addUpperBound(bound);
@@ -725,7 +724,7 @@ public class DescriptorResolver {
if (!(declaration instanceof JetClass)) { if (!(declaration instanceof JetClass)) {
for (UpperBoundCheckerTask checkerTask : deferredUpperBoundCheckerTasks) { for (UpperBoundCheckerTask checkerTask : deferredUpperBoundCheckerTasks) {
checkUpperBoundType(checkerTask.upperBound, checkerTask.upperBoundType, checkerTask.isClassObjectConstraint, trace); checkUpperBoundType(checkerTask.upperBound, checkerTask.upperBoundType, checkerTask.isDefaultObjectConstraint, trace);
} }
checkNamesInConstraints(declaration, descriptor, scope, trace); checkNamesInConstraints(declaration, descriptor, scope, trace);
@@ -743,7 +742,7 @@ public class DescriptorResolver {
JetType classObjectType = parameter.getClassObjectType(); JetType classObjectType = parameter.getClassObjectType();
if (classObjectType != null && KotlinBuiltIns.isNothing(classObjectType)) { if (classObjectType != null && KotlinBuiltIns.isNothing(classObjectType)) {
trace.report(CONFLICTING_CLASS_OBJECT_UPPER_BOUNDS.on(typeParameter, parameter)); trace.report(CONFLICTING_DEFAULT_OBJECT_UPPER_BOUNDS.on(typeParameter, parameter));
} }
} }
@@ -778,21 +777,21 @@ public class DescriptorResolver {
} }
} }
public static void reportUnsupportedClassObjectConstraint(BindingTrace trace, JetTypeConstraint constraint) { public static void reportUnsupportedDefaultObjectConstraint(BindingTrace trace, JetTypeConstraint constraint) {
if (constraint.isClassObjectConstraint()) { if (constraint.isDefaultObjectConstraint()) {
trace.report(UNSUPPORTED.on(constraint, "Class objects constraints are not supported yet")); trace.report(UNSUPPORTED.on(constraint, "Default objects constraints are not supported yet"));
} }
} }
public static void checkUpperBoundType( public static void checkUpperBoundType(
JetTypeReference upperBound, JetTypeReference upperBound,
@NotNull JetType upperBoundType, @NotNull JetType upperBoundType,
boolean isClassObjectConstraint, boolean isDefaultObjectConstraint,
BindingTrace trace BindingTrace trace
) { ) {
if (!TypeUtils.canHaveSubtypes(JetTypeChecker.DEFAULT, upperBoundType)) { if (!TypeUtils.canHaveSubtypes(JetTypeChecker.DEFAULT, upperBoundType)) {
if (isClassObjectConstraint) { if (isDefaultObjectConstraint) {
trace.report(FINAL_CLASS_OBJECT_UPPER_BOUND.on(upperBound, upperBoundType)); trace.report(FINAL_DEFAULT_OBJECT_UPPER_BOUND.on(upperBound, upperBoundType));
} }
else { else {
trace.report(FINAL_UPPER_BOUND.on(upperBound, upperBoundType)); trace.report(FINAL_UPPER_BOUND.on(upperBound, upperBoundType));
@@ -36,7 +36,7 @@ import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import static org.jetbrains.kotlin.diagnostics.Errors.MANY_CLASS_OBJECTS; import static org.jetbrains.kotlin.diagnostics.Errors.MANY_DEFAULT_OBJECTS;
import static org.jetbrains.kotlin.diagnostics.Errors.UNSUPPORTED; import static org.jetbrains.kotlin.diagnostics.Errors.UNSUPPORTED;
public class LazyTopDownAnalyzer { public class LazyTopDownAnalyzer {
@@ -191,19 +191,19 @@ public class LazyTopDownAnalyzer {
registerDeclarations(classOrObject.getDeclarations()); registerDeclarations(classOrObject.getDeclarations());
registerTopLevelFqName(topLevelFqNames, classOrObject, descriptor); registerTopLevelFqName(topLevelFqNames, classOrObject, descriptor);
checkManyClassObjects(classOrObject); checkManyDefaultObjects(classOrObject);
} }
private void checkManyClassObjects(JetClassOrObject classOrObject) { private void checkManyDefaultObjects(JetClassOrObject classOrObject) {
boolean classObjectAlreadyFound = false; boolean defaultObjectAlreadyFound = false;
for (JetDeclaration jetDeclaration : classOrObject.getDeclarations()) { for (JetDeclaration jetDeclaration : classOrObject.getDeclarations()) {
jetDeclaration.accept(this); jetDeclaration.accept(this);
if (jetDeclaration instanceof JetObjectDeclaration && ((JetObjectDeclaration) jetDeclaration).isClassObject()) { if (jetDeclaration instanceof JetObjectDeclaration && ((JetObjectDeclaration) jetDeclaration).isDefault()) {
if (classObjectAlreadyFound) { if (defaultObjectAlreadyFound) {
trace.report(MANY_CLASS_OBJECTS.on((JetObjectDeclaration) jetDeclaration)); trace.report(MANY_DEFAULT_OBJECTS.on((JetObjectDeclaration) jetDeclaration));
} }
classObjectAlreadyFound = true; defaultObjectAlreadyFound = true;
} }
} }
} }
@@ -243,7 +243,7 @@ public class ModifiersChecker {
if (DescriptorUtils.isTrait(containingDeclaration)) { if (DescriptorUtils.isTrait(containingDeclaration)) {
return InnerModifierCheckResult.IN_TRAIT; return InnerModifierCheckResult.IN_TRAIT;
} }
else if (DescriptorUtils.isClassObject(containingDeclaration) || DescriptorUtils.isObject(containingDeclaration)) { else if (DescriptorUtils.isDefaultObject(containingDeclaration) || DescriptorUtils.isObject(containingDeclaration)) {
return InnerModifierCheckResult.IN_OBJECT; return InnerModifierCheckResult.IN_OBJECT;
} }
else { else {
@@ -121,7 +121,7 @@ public class OverloadResolver {
return name; return name;
} }
if (jetClass instanceof JetObjectDeclaration) { if (jetClass instanceof JetObjectDeclaration) {
// must be class object // must be default object
name = classDescriptor.getContainingDeclaration().getName().asString(); name = classDescriptor.getContainingDeclaration().getName().asString();
return "class object " + name; return "class object " + name;
} }
@@ -35,7 +35,7 @@ public class FakeCallableDescriptorForObject(
{ {
assert(classDescriptor.getClassObjectType() != null) { assert(classDescriptor.getClassObjectType() != null) {
"FakeCallableDescriptorForObject can be created only for objects, classes with class object or enum entries: $classDescriptor" "FakeCallableDescriptorForObject can be created only for objects, classes with default object or enum entries: $classDescriptor"
} }
} }
@@ -49,7 +49,7 @@ public class ConstantExpressionEvaluator private (val trace: BindingTrace) : Jet
return false return false
} }
if (DescriptorUtils.isObject(descriptor.getContainingDeclaration()) || if (DescriptorUtils.isObject(descriptor.getContainingDeclaration()) ||
DescriptorUtils.isClassObject(descriptor.getContainingDeclaration()) || DescriptorUtils.isDefaultObject(descriptor.getContainingDeclaration()) ||
DescriptorUtils.isStaticDeclaration(descriptor)) { DescriptorUtils.isStaticDeclaration(descriptor)) {
val returnType = descriptor.getType() val returnType = descriptor.getType()
return KotlinBuiltIns.isPrimitiveType(returnType) || KotlinBuiltIns.isString(returnType) return KotlinBuiltIns.isPrimitiveType(returnType) || KotlinBuiltIns.isString(returnType)
@@ -46,8 +46,8 @@ public class JetClassInfo extends JetClassOrObjectInfo<JetClass> {
} }
@Override @Override
public JetObjectDeclaration getClassObject() { public JetObjectDeclaration getDefaultObject() {
return element.getClassObject(); return element.getDefaultObject();
} }
@Nullable @Nullable
@@ -34,11 +34,11 @@ public interface JetClassLikeInfo extends JetDeclarationContainer {
JetModifierList getModifierList(); JetModifierList getModifierList();
@Nullable @Nullable
JetObjectDeclaration getClassObject(); JetObjectDeclaration getDefaultObject();
@NotNull @NotNull
@ReadOnly @ReadOnly
List<JetObjectDeclaration> getClassObjects(); List<JetObjectDeclaration> getDefaultObjects();
// This element is used to identify resolution scope for the class // This element is used to identify resolution scope for the class
@NotNull @NotNull
@@ -58,12 +58,12 @@ public abstract class JetClassOrObjectInfo<E extends JetClassOrObject> implement
@NotNull @NotNull
@Override @Override
public List<JetObjectDeclaration> getClassObjects() { public List<JetObjectDeclaration> getDefaultObjects() {
JetClassBody body = element.getBody(); JetClassBody body = element.getBody();
if (body == null) { if (body == null) {
return Collections.emptyList(); return Collections.emptyList();
} }
return body.getAllClassObjects(); return body.getAllDefaultObjects();
} }
@NotNull @NotNull
@@ -34,11 +34,11 @@ public class JetObjectInfo extends JetClassOrObjectInfo<JetObjectDeclaration> {
super(element); super(element);
this.kind = element.isObjectLiteral() this.kind = element.isObjectLiteral()
? ClassKind.CLASS ? ClassKind.CLASS
: (element.isClassObject() ? ClassKind.CLASS_OBJECT : ClassKind.OBJECT); : (element.isDefault() ? ClassKind.CLASS_OBJECT : ClassKind.OBJECT);
} }
@Override @Override
public JetObjectDeclaration getClassObject() { public JetObjectDeclaration getDefaultObject() {
return null; return null;
} }
@@ -27,8 +27,8 @@ public class JetScriptInfo(
public val fqName: FqName = ScriptNameUtil.classNameForScript(script) public val fqName: FqName = ScriptNameUtil.classNameForScript(script)
override fun getContainingPackageFqName() = fqName.parent() override fun getContainingPackageFqName() = fqName.parent()
override fun getModifierList() = null override fun getModifierList() = null
override fun getClassObject() = null override fun getDefaultObject() = null
override fun getClassObjects() = listOf<JetObjectDeclaration>() override fun getDefaultObjects() = listOf<JetObjectDeclaration>()
override fun getScopeAnchor() = script override fun getScopeAnchor() = script
override fun getCorrespondingClassOrObject() = null override fun getCorrespondingClassOrObject() = null
override fun getTypeParameterList() = null override fun getTypeParameterList() = null
@@ -81,8 +81,8 @@ public class LazyClassDescriptor extends ClassDescriptorBase implements ClassDes
private final Annotations annotations; private final Annotations annotations;
private final Annotations danglingAnnotations; private final Annotations danglingAnnotations;
private final NullableLazyValue<LazyClassDescriptor> classObjectDescriptor; private final NullableLazyValue<LazyClassDescriptor> defaultObjectDescriptor;
private final MemoizedFunctionToNotNull<JetObjectDeclaration, ClassDescriptor> extraClassObjectDescriptors; private final MemoizedFunctionToNotNull<JetObjectDeclaration, ClassDescriptor> extraDefaultObjectDescriptors;
private final LazyClassMemberScope unsubstitutedMemberScope; private final LazyClassMemberScope unsubstitutedMemberScope;
private final JetScope staticScope = new StaticScopeForKotlinClass(this); private final JetScope staticScope = new StaticScopeForKotlinClass(this);
@@ -177,16 +177,16 @@ public class LazyClassDescriptor extends ClassDescriptorBase implements ClassDes
); );
} }
this.classObjectDescriptor = storageManager.createNullableLazyValue(new Function0<LazyClassDescriptor>() { this.defaultObjectDescriptor = storageManager.createNullableLazyValue(new Function0<LazyClassDescriptor>() {
@Override @Override
public LazyClassDescriptor invoke() { public LazyClassDescriptor invoke() {
return computeClassObjectDescriptor(getClassObjectIfAllowed()); return computeDefaultObjectDescriptor(getDefaultObjectIfAllowed());
} }
}); });
this.extraClassObjectDescriptors = storageManager.createMemoizedFunction(new Function1<JetObjectDeclaration, ClassDescriptor>() { this.extraDefaultObjectDescriptors = storageManager.createMemoizedFunction(new Function1<JetObjectDeclaration, ClassDescriptor>() {
@Override @Override
public ClassDescriptor invoke(JetObjectDeclaration classObject) { public ClassDescriptor invoke(JetObjectDeclaration defaultObject) {
return computeClassObjectDescriptor(classObject); return computeDefaultObjectDescriptor(defaultObject);
} }
}); });
this.scopeForClassHeaderResolution = storageManager.createLazyValue(new Function0<JetScope>() { this.scopeForClassHeaderResolution = storageManager.createLazyValue(new Function0<JetScope>() {
@@ -266,8 +266,8 @@ public class LazyClassDescriptor extends ClassDescriptorBase implements ClassDes
thisScope.setImplicitReceiver(this.getThisAsReceiverParameter()); thisScope.setImplicitReceiver(this.getThisAsReceiverParameter());
thisScope.changeLockLevel(WritableScope.LockLevel.READING); thisScope.changeLockLevel(WritableScope.LockLevel.READING);
ClassDescriptor classObject = getDefaultObjectDescriptor(); ClassDescriptor defaultObjectDescriptor = getDefaultObjectDescriptor();
JetScope classObjectAdapterScope = (classObject != null) ? new ClassObjectMixinScope(classObject) : JetScope.Empty.INSTANCE$; JetScope defaultObjectAdapterScope = (defaultObjectDescriptor != null) ? new DefaultObjectMixinScope(defaultObjectDescriptor) : JetScope.Empty.INSTANCE$;
return new ChainedScope( return new ChainedScope(
this, this,
@@ -275,7 +275,7 @@ public class LazyClassDescriptor extends ClassDescriptorBase implements ClassDes
thisScope, thisScope,
getScopeForMemberLookup(), getScopeForMemberLookup(),
getScopeForClassHeaderResolution(), getScopeForClassHeaderResolution(),
classObjectAdapterScope, defaultObjectAdapterScope,
getStaticScope() getStaticScope()
); );
} }
@@ -347,46 +347,46 @@ public class LazyClassDescriptor extends ClassDescriptorBase implements ClassDes
@Override @Override
public LazyClassDescriptor getDefaultObjectDescriptor() { public LazyClassDescriptor getDefaultObjectDescriptor() {
return classObjectDescriptor.invoke(); return defaultObjectDescriptor.invoke();
} }
@NotNull @NotNull
@ReadOnly @ReadOnly
public List<ClassDescriptor> getDescriptorsForExtraClassObjects() { public List<ClassDescriptor> getDescriptorsForExtraDefaultObjects() {
final JetObjectDeclaration allowedClassObject = getClassObjectIfAllowed(); final JetObjectDeclaration allowedDefaultObject = getDefaultObjectIfAllowed();
return KotlinPackage.map( return KotlinPackage.map(
KotlinPackage.filter( KotlinPackage.filter(
declarationProvider.getOwnerInfo().getClassObjects(), declarationProvider.getOwnerInfo().getDefaultObjects(),
new Function1<JetObjectDeclaration, Boolean>() { new Function1<JetObjectDeclaration, Boolean>() {
@Override @Override
public Boolean invoke(JetObjectDeclaration classObject) { public Boolean invoke(JetObjectDeclaration defaultObject) {
return classObject != allowedClassObject; return defaultObject != allowedDefaultObject;
} }
} }
), ),
new Function1<JetObjectDeclaration, ClassDescriptor>() { new Function1<JetObjectDeclaration, ClassDescriptor>() {
@Override @Override
public ClassDescriptor invoke(JetObjectDeclaration classObject) { public ClassDescriptor invoke(JetObjectDeclaration defaultObject) {
return extraClassObjectDescriptors.invoke(classObject); return extraDefaultObjectDescriptors.invoke(defaultObject);
} }
} }
); );
} }
@Nullable @Nullable
private LazyClassDescriptor computeClassObjectDescriptor(@Nullable JetObjectDeclaration classObject) { private LazyClassDescriptor computeDefaultObjectDescriptor(@Nullable JetObjectDeclaration defaultObject) {
JetClassLikeInfo classObjectInfo = getClassObjectInfo(classObject); JetClassLikeInfo defaultObjectInfo = getDefaultObjectInfo(defaultObject);
if (!(classObjectInfo instanceof JetClassOrObjectInfo)) { if (!(defaultObjectInfo instanceof JetClassOrObjectInfo)) {
return null; return null;
} }
Name name = ((JetClassOrObjectInfo) classObjectInfo).getName(); Name name = ((JetClassOrObjectInfo) defaultObjectInfo).getName();
assert name != null; assert name != null;
getScopeForMemberLookup().getClassifier(name); getScopeForMemberLookup().getClassifier(name);
ClassDescriptor classObjectDescriptor = c.getTrace().get(BindingContext.CLASS, classObject); ClassDescriptor defaultObjectDescriptor = c.getTrace().get(BindingContext.CLASS, defaultObject);
if (classObjectDescriptor instanceof LazyClassDescriptor) { if (defaultObjectDescriptor instanceof LazyClassDescriptor) {
assert DescriptorUtils.isClassObject(classObjectDescriptor) : "Not a class object: " + classObjectDescriptor; assert DescriptorUtils.isDefaultObject(defaultObjectDescriptor) : "Not a default object: " + defaultObjectDescriptor;
return (LazyClassDescriptor) classObjectDescriptor; return (LazyClassDescriptor) defaultObjectDescriptor;
} }
else { else {
return null; return null;
@@ -394,25 +394,25 @@ public class LazyClassDescriptor extends ClassDescriptorBase implements ClassDes
} }
@Nullable @Nullable
private JetClassLikeInfo getClassObjectInfo(@Nullable JetObjectDeclaration classObject) { private JetClassLikeInfo getDefaultObjectInfo(@Nullable JetObjectDeclaration defaultObject) {
if (classObject != null) { if (defaultObject != null) {
if (!isClassObjectAllowed()) { if (!isDefaultObjectAllowed()) {
c.getTrace().report(CLASS_OBJECT_NOT_ALLOWED.on(classObject)); c.getTrace().report(DEFAULT_OBJECT_NOT_ALLOWED.on(defaultObject));
} }
return JetClassInfoUtil.createClassLikeInfo(classObject); return JetClassInfoUtil.createClassLikeInfo(defaultObject);
} }
return null; return null;
} }
@Nullable @Nullable
private JetObjectDeclaration getClassObjectIfAllowed() { private JetObjectDeclaration getDefaultObjectIfAllowed() {
JetObjectDeclaration classObject = declarationProvider.getOwnerInfo().getClassObject(); JetObjectDeclaration defaultObject = declarationProvider.getOwnerInfo().getDefaultObject();
return (classObject != null && isClassObjectAllowed()) ? classObject : null; return (defaultObject != null && isDefaultObjectAllowed()) ? defaultObject : null;
} }
private boolean isClassObjectAllowed() { private boolean isDefaultObjectAllowed() {
return !(getKind().isSingleton() || isInner() || DescriptorUtils.isLocal(this)); return !(getKind().isSingleton() || isInner() || DescriptorUtils.isLocal(this));
} }
@@ -463,13 +463,13 @@ public class LazyClassDescriptor extends ClassDescriptorBase implements ClassDes
private void doForceResolveAllContents() { private void doForceResolveAllContents() {
resolveMemberHeaders(); resolveMemberHeaders();
ClassDescriptor classObjectDescriptor = getDefaultObjectDescriptor(); ClassDescriptor defaultObjectDescriptor = getDefaultObjectDescriptor();
if (classObjectDescriptor != null) { if (defaultObjectDescriptor != null) {
ForceResolveUtil.forceResolveAllContents(classObjectDescriptor); ForceResolveUtil.forceResolveAllContents(defaultObjectDescriptor);
} }
ForceResolveUtil.forceResolveAllContents(getConstructors()); ForceResolveUtil.forceResolveAllContents(getConstructors());
ForceResolveUtil.forceResolveAllContents(getDescriptorsForExtraClassObjects()); ForceResolveUtil.forceResolveAllContents(getDescriptorsForExtraDefaultObjects());
ForceResolveUtil.forceResolveAllContents(getScopeForMemberLookup()); ForceResolveUtil.forceResolveAllContents(getScopeForMemberLookup());
ForceResolveUtil.forceResolveAllContents(getTypeConstructor()); ForceResolveUtil.forceResolveAllContents(getTypeConstructor());
} }
@@ -481,7 +481,7 @@ public class LazyClassDescriptor extends ClassDescriptorBase implements ClassDes
getDefaultObjectDescriptor(); getDefaultObjectDescriptor();
getDescriptorsForExtraClassObjects(); getDescriptorsForExtraDefaultObjects();
getClassObjectType(); getClassObjectType();
getConstructors(); getConstructors();
@@ -230,7 +230,7 @@ public open class LazyClassMemberScope(
private fun <T : CallableMemberDescriptor> generateDelegatingDescriptors(name: Name, extractor: MemberExtractor<T>, existingDescriptors: Collection<CallableDescriptor>): Collection<T> { private fun <T : CallableMemberDescriptor> generateDelegatingDescriptors(name: Name, extractor: MemberExtractor<T>, existingDescriptors: Collection<CallableDescriptor>): Collection<T> {
val classOrObject = declarationProvider.getOwnerInfo().getCorrespondingClassOrObject() val classOrObject = declarationProvider.getOwnerInfo().getCorrespondingClassOrObject()
?: return setOf() // Enum class objects do not have delegated members ?: return setOf() // Enum default objects do not have delegated members
val lazyTypeResolver = DelegationResolver.TypeResolver { reference -> val lazyTypeResolver = DelegationResolver.TypeResolver { reference ->
c.typeResolver.resolveType(thisDescriptor.getScopeForClassHeaderResolution(), reference, trace, false) c.typeResolver.resolveType(thisDescriptor.getScopeForClassHeaderResolution(), reference, trace, false)
@@ -83,7 +83,7 @@ public class LazyTypeParameterDescriptor extends AbstractLazyTypeParameterDescri
if (classOrObject instanceof JetClass) { if (classOrObject instanceof JetClass) {
JetClass jetClass = (JetClass) classOrObject; JetClass jetClass = (JetClass) classOrObject;
for (JetTypeConstraint jetTypeConstraint : jetClass.getTypeConstraints()) { for (JetTypeConstraint jetTypeConstraint : jetClass.getTypeConstraints()) {
DescriptorResolver.reportUnsupportedClassObjectConstraint(c.getTrace(), jetTypeConstraint); DescriptorResolver.reportUnsupportedDefaultObjectConstraint(c.getTrace(), jetTypeConstraint);
JetSimpleNameExpression constrainedParameterName = jetTypeConstraint.getSubjectTypeParameterName(); JetSimpleNameExpression constrainedParameterName = jetTypeConstraint.getSubjectTypeParameterName();
if (constrainedParameterName != null) { if (constrainedParameterName != null) {
@@ -93,7 +93,7 @@ public class LazyTypeParameterDescriptor extends AbstractLazyTypeParameterDescri
JetTypeReference boundTypeReference = jetTypeConstraint.getBoundTypeReference(); JetTypeReference boundTypeReference = jetTypeConstraint.getBoundTypeReference();
if (boundTypeReference != null) { if (boundTypeReference != null) {
JetType boundType = resolveBoundType(boundTypeReference); JetType boundType = resolveBoundType(boundTypeReference);
if (!jetTypeConstraint.isClassObjectConstraint()) { if (!jetTypeConstraint.isDefaultObjectConstraint()) {
upperBounds.add(boundType); upperBounds.add(boundType);
} }
} }
@@ -19,12 +19,12 @@ package org.jetbrains.kotlin.resolve.scopes
import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor
/** /**
* Members of the class object are accessible from the class. * Members of the default object are accessible from the class.
* Scope lazily delegates requests to class object scope. * Scope lazily delegates requests to default object scope.
*/ */
public class ClassObjectMixinScope(private val classObjectDescriptor: ClassDescriptor) : AbstractScopeAdapter() { public class DefaultObjectMixinScope(private val defaultObjectDescriptor: ClassDescriptor) : AbstractScopeAdapter() {
override val workerScope: JetScope override val workerScope: JetScope
get() = classObjectDescriptor.getDefaultType().getMemberScope() get() = defaultObjectDescriptor.getDefaultType().getMemberScope()
override fun getImplicitReceiversHierarchy() = listOf(classObjectDescriptor.getThisAsReceiverParameter()) override fun getImplicitReceiversHierarchy() = listOf(defaultObjectDescriptor.getThisAsReceiverParameter())
} }
@@ -91,8 +91,8 @@ public abstract class WritableScopeWithImports(override val workerScope: JetScop
protected open fun computeImplicitReceiversHierarchy(): List<ReceiverParameterDescriptor> { protected open fun computeImplicitReceiversHierarchy(): List<ReceiverParameterDescriptor> {
val implicitReceiverHierarchy = Lists.newArrayList<ReceiverParameterDescriptor>() val implicitReceiverHierarchy = Lists.newArrayList<ReceiverParameterDescriptor>()
// Imported scopes come with their receivers // Imported scopes come with their receivers
// Example: class member resolution scope imports a scope of it's class object // Example: class member resolution scope imports a scope of it's default object
// members of the class object must be able to find it as an implicit receiver // members of the default object must be able to find it as an implicit receiver
for (scope in getImports()) { for (scope in getImports()) {
implicitReceiverHierarchy.addAll(scope.getImplicitReceiversHierarchy()) implicitReceiverHierarchy.addAll(scope.getImplicitReceiversHierarchy())
} }
@@ -129,7 +129,7 @@ private fun QualifierReceiver.resolveAsStandaloneExpression(context: ExpressionT
context.trace.report(TYPE_PARAMETER_IS_NOT_AN_EXPRESSION.on(referenceExpression, classifier)) context.trace.report(TYPE_PARAMETER_IS_NOT_AN_EXPRESSION.on(referenceExpression, classifier))
} }
else if (classifier is ClassDescriptor && classifier.getClassObjectType() == null) { else if (classifier is ClassDescriptor && classifier.getClassObjectType() == null) {
context.trace.report(NO_CLASS_OBJECT.on(referenceExpression, classifier)) context.trace.report(NO_DEFAULT_OBJECT.on(referenceExpression, classifier))
} }
else if (packageView != null) { else if (packageView != null) {
context.trace.report(EXPRESSION_EXPECTED_PACKAGE_FOUND.on(referenceExpression)) context.trace.report(EXPRESSION_EXPECTED_PACKAGE_FOUND.on(referenceExpression))
@@ -185,7 +185,7 @@ class DeclarationScopeProviderForLocalClassifierAnalyzer(
} }
override fun getOuterDataFlowInfoForDeclaration(elementOfDeclaration: PsiElement): DataFlowInfo { override fun getOuterDataFlowInfoForDeclaration(elementOfDeclaration: PsiElement): DataFlowInfo {
// nested (non-inner) classes and class objects are forbidden in local classes, so it's enough to be simply inside the class // nested (non-inner) classes and default objects are forbidden in local classes, so it's enough to be simply inside the class
if (localClassDescriptorManager.insideMyClass(elementOfDeclaration)) { if (localClassDescriptorManager.insideMyClass(elementOfDeclaration)) {
return localClassDescriptorManager.expressionTypingContext.dataFlowInfo return localClassDescriptorManager.expressionTypingContext.dataFlowInfo
} }
@@ -72,7 +72,7 @@ val t3 = test2<C>(C())
class Test<T> class Test<T>
where where
<!UNSUPPORTED!>class object T : <!FINAL_CLASS_OBJECT_UPPER_BOUND!>Foo<!><!>, <!UNSUPPORTED!>class object T : <!FINAL_DEFAULT_OBJECT_UPPER_BOUND!>Foo<!><!>,
<!UNSUPPORTED!>class object T : A<!> {} <!UNSUPPORTED!>class object T : A<!> {}
val <T, B : T> x : Int = 0 val <T, B : T> x : Int = 0
@@ -3,24 +3,24 @@ package foo
class X {} class X {}
val s = <!EXPRESSION_EXPECTED_PACKAGE_FOUND!>java<!> val s = <!EXPRESSION_EXPECTED_PACKAGE_FOUND!>java<!>
val ss = <!NO_CLASS_OBJECT!>System<!> val ss = <!NO_DEFAULT_OBJECT!>System<!>
val sss = <!NO_CLASS_OBJECT!>X<!> val sss = <!NO_DEFAULT_OBJECT!>X<!>
val x = "${<!NO_CLASS_OBJECT!>System<!>}" val x = "${<!NO_DEFAULT_OBJECT!>System<!>}"
val xs = java.<!EXPRESSION_EXPECTED_PACKAGE_FOUND!>lang<!> val xs = java.<!EXPRESSION_EXPECTED_PACKAGE_FOUND!>lang<!>
val xss = java.lang.<!NO_CLASS_OBJECT!>System<!> val xss = java.lang.<!NO_DEFAULT_OBJECT!>System<!>
val xsss = foo.<!NO_CLASS_OBJECT!>X<!> val xsss = foo.<!NO_DEFAULT_OBJECT!>X<!>
val xssss = <!EXPRESSION_EXPECTED_PACKAGE_FOUND!>foo<!> val xssss = <!EXPRESSION_EXPECTED_PACKAGE_FOUND!>foo<!>
val f = { <!NO_CLASS_OBJECT!>System<!> } val f = { <!NO_DEFAULT_OBJECT!>System<!> }
fun main(args : Array<String>) { fun main(args : Array<String>) {
<!EXPRESSION_EXPECTED_PACKAGE_FOUND!>java<!> = null <!EXPRESSION_EXPECTED_PACKAGE_FOUND!>java<!> = null
<!NO_CLASS_OBJECT!>System<!> = null <!NO_DEFAULT_OBJECT!>System<!> = null
<!NO_CLASS_OBJECT!>System<!>!! <!NO_DEFAULT_OBJECT!>System<!>!!
java.lang.<!NO_CLASS_OBJECT!>System<!> = null java.lang.<!NO_DEFAULT_OBJECT!>System<!> = null
java.lang.<!NO_CLASS_OBJECT!>System<!>!! java.lang.<!NO_DEFAULT_OBJECT!>System<!>!!
<!NO_CLASS_OBJECT!>System<!> is Int <!NO_DEFAULT_OBJECT!>System<!> is Int
<!INVISIBLE_MEMBER!>System<!>() <!INVISIBLE_MEMBER!>System<!>()
(<!NO_CLASS_OBJECT!>System<!>) (<!NO_DEFAULT_OBJECT!>System<!>)
@foo <!NO_CLASS_OBJECT!>System<!> @foo <!NO_DEFAULT_OBJECT!>System<!>
null in <!NO_CLASS_OBJECT!>System<!> null in <!NO_DEFAULT_OBJECT!>System<!>
} }
@@ -4,7 +4,7 @@ class A {
<!REDECLARATION!>class object<!> { <!REDECLARATION!>class object<!> {
val x = 1 val x = 1
} }
<!MANY_CLASS_OBJECTS, REDECLARATION!>class object<!> { <!MANY_DEFAULT_OBJECTS, REDECLARATION!>class object<!> {
val x = 1 val x = 1
} }
} }
@@ -13,10 +13,10 @@ class AA {
class object { class object {
val x = 1 val x = 1
} }
<!MANY_CLASS_OBJECTS!>class object A<!> { <!MANY_DEFAULT_OBJECTS!>class object A<!> {
val x = 1 val x = 1
} }
<!MANY_CLASS_OBJECTS!>class object AA<!> { <!MANY_DEFAULT_OBJECTS!>class object AA<!> {
val x = 1 val x = 1
} }
} }
@@ -26,7 +26,7 @@ class B() {
} }
object b { object b {
<!CLASS_OBJECT_NOT_ALLOWED!>class object<!> { <!DEFAULT_OBJECT_NOT_ALLOWED!>class object<!> {
val x = 1 val x = 1
} // error } // error
} }
@@ -35,7 +35,7 @@ val a = A.x
val c = B.<!UNRESOLVED_REFERENCE!>x<!> val c = B.<!UNRESOLVED_REFERENCE!>x<!>
val d = b.<!UNRESOLVED_REFERENCE!>x<!> val d = b.<!UNRESOLVED_REFERENCE!>x<!>
val s = <!NO_CLASS_OBJECT!>System<!> // error val s = <!NO_DEFAULT_OBJECT!>System<!> // error
fun test() { fun test() {
System.out.println() System.out.println()
java.lang.System.out.println() java.lang.System.out.println()
@@ -28,7 +28,7 @@ object O {
fun f() { fun f() {
A.c A.c
A.hashCode() A.hashCode()
A().<!NO_CLASS_OBJECT, NESTED_CLASS_ACCESSED_VIA_INSTANCE_REFERENCE!>Nested<!> A().<!NO_DEFAULT_OBJECT, NESTED_CLASS_ACCESSED_VIA_INSTANCE_REFERENCE!>Nested<!>
A.Nested() A.Nested()
A().Inner() A().Inner()
A.Default.<!UNRESOLVED_REFERENCE!>Nested<!> A.Default.<!UNRESOLVED_REFERENCE!>Nested<!>
@@ -2,7 +2,7 @@
class A { class A {
inner class B { inner class B {
<!CLASS_OBJECT_NOT_ALLOWED!>class object<!> { } <!DEFAULT_OBJECT_NOT_ALLOWED!>class object<!> { }
} }
} }
@@ -22,4 +22,4 @@ class C {
class D { class D {
class object { } class object { }
} }
} }
@@ -1,9 +1,9 @@
fun test() { fun test() {
class A { class A {
<!CLASS_OBJECT_NOT_ALLOWED!>class object<!> {} <!DEFAULT_OBJECT_NOT_ALLOWED!>class object<!> {}
} }
object { object {
<!CLASS_OBJECT_NOT_ALLOWED!>class object<!> {} <!DEFAULT_OBJECT_NOT_ALLOWED!>class object<!> {}
} }
} }
@@ -1,4 +1,4 @@
// !DIAGNOSTICS: -MANY_CLASS_OBJECTS -REDECLARATION // !DIAGNOSTICS: -MANY_DEFAULT_OBJECTS -REDECLARATION
// KT-3464 Front-end shouldn't allow override modifier in class declaration // KT-3464 Front-end shouldn't allow override modifier in class declaration
@@ -2,7 +2,7 @@ enum class E {
FIRST FIRST
SECOND { SECOND {
<!CLASS_OBJECT_NOT_ALLOWED!>class object<!> { <!DEFAULT_OBJECT_NOT_ALLOWED!>class object<!> {
fun foo() = 42 fun foo() = 42
} }
} }
@@ -1,5 +1,5 @@
package bar package bar
fun main(args : Array<String>) { fun main(args : Array<String>) {
<!DEBUG_INFO_ELEMENT_WITH_ERROR_TYPE!><!NO_CLASS_OBJECT!>String<!>[<!SYNTAX!><!>]<!> <!DEBUG_INFO_ELEMENT_WITH_ERROR_TYPE!>names<!> <!DEBUG_INFO_MISSING_UNRESOLVED!><!SYNTAX!>=<!> ["ads"]<!> <!DEBUG_INFO_ELEMENT_WITH_ERROR_TYPE!><!NO_DEFAULT_OBJECT!>String<!>[<!SYNTAX!><!>]<!> <!DEBUG_INFO_ELEMENT_WITH_ERROR_TYPE!>names<!> <!DEBUG_INFO_MISSING_UNRESOLVED!><!SYNTAX!>=<!> ["ads"]<!>
} }
@@ -4,11 +4,11 @@ class A<T> {
class B { class B {
fun test() { fun test() {
class C<W>() : P<W, <!INACCESSIBLE_OUTER_CLASS_EXPRESSION!>T<!>> { class C<W>() : P<W, <!INACCESSIBLE_OUTER_CLASS_EXPRESSION!>T<!>> {
<!CLASS_OBJECT_NOT_ALLOWED!>class object<!> : P<<!INACCESSIBLE_OUTER_CLASS_EXPRESSION!>W<!>, <!INACCESSIBLE_OUTER_CLASS_EXPRESSION!>T<!>> { <!DEFAULT_OBJECT_NOT_ALLOWED!>class object<!> : P<<!INACCESSIBLE_OUTER_CLASS_EXPRESSION!>W<!>, <!INACCESSIBLE_OUTER_CLASS_EXPRESSION!>T<!>> {
} }
inner class D : P<W, <!INACCESSIBLE_OUTER_CLASS_EXPRESSION!>T<!>> inner class D : P<W, <!INACCESSIBLE_OUTER_CLASS_EXPRESSION!>T<!>>
} }
} }
} }
} }
@@ -1 +1 @@
val a: String = <!NO_CLASS_OBJECT!>Nothing<!> val a: String = <!NO_DEFAULT_OBJECT!>Nothing<!>
@@ -11,6 +11,6 @@ class C {
} }
fun f() { fun f() {
<!NO_CLASS_OBJECT, FUNCTION_EXPECTED!>TestInterface<!>() <!NO_DEFAULT_OBJECT, FUNCTION_EXPECTED!>TestInterface<!>()
C.<!UNRESOLVED_REFERENCE!>I<!>() C.<!UNRESOLVED_REFERENCE!>I<!>()
} }
@@ -144,8 +144,8 @@ public class ClassGenTest extends CodegenTestCase {
loadFile("classes/classObjectIsInnerClass.kt"); loadFile("classes/classObjectIsInnerClass.kt");
GeneratedClassLoader loader = generateAndCreateClassLoader(); GeneratedClassLoader loader = generateAndCreateClassLoader();
Class<?> a = loader.loadClass("A"); Class<?> a = loader.loadClass("A");
Class<?> aClassObject = loader.loadClass("A$" + SpecialNames.DEFAULT_NAME_FOR_DEFAULT_OBJECT.asString()); Class<?> defaultObject = loader.loadClass("A$" + SpecialNames.DEFAULT_NAME_FOR_DEFAULT_OBJECT.asString());
assertSameElements(a.getDeclaredClasses(), aClassObject); assertSameElements(a.getDeclaredClasses(), defaultObject);
assertEquals(a, aClassObject.getDeclaringClass()); assertEquals(a, defaultObject.getDeclaringClass());
} }
} }
@@ -44,14 +44,14 @@ public class InnerClassInfoGenTest extends CodegenTestCase {
public void testInnerClassInfo() { public void testInnerClassInfo() {
InnerClassAttribute innerB = new InnerClassAttribute("A$B", "A", "B", ACC_PUBLIC | ACC_STATIC | ACC_FINAL); InnerClassAttribute innerB = new InnerClassAttribute("A$B", "A", "B", ACC_PUBLIC | ACC_STATIC | ACC_FINAL);
InnerClassAttribute innerC = new InnerClassAttribute("A$B$C", "A$B", "C", ACC_PUBLIC | ACC_FINAL); InnerClassAttribute innerC = new InnerClassAttribute("A$B$C", "A$B", "C", ACC_PUBLIC | ACC_FINAL);
String classObjectDefaultName = SpecialNames.DEFAULT_NAME_FOR_DEFAULT_OBJECT.asString(); String defaultObjectDefaultName = SpecialNames.DEFAULT_NAME_FOR_DEFAULT_OBJECT.asString();
InnerClassAttribute innerAClassObject = new InnerClassAttribute( InnerClassAttribute innerADefaultObject = new InnerClassAttribute(
"A$" + classObjectDefaultName, "A", classObjectDefaultName, ACC_PUBLIC | ACC_STATIC | ACC_FINAL); "A$" + defaultObjectDefaultName, "A", defaultObjectDefaultName, ACC_PUBLIC | ACC_STATIC | ACC_FINAL);
extractAndCompareInnerClasses("A", innerB, innerAClassObject); extractAndCompareInnerClasses("A", innerB, innerADefaultObject);
extractAndCompareInnerClasses("A$B", innerB, innerC); extractAndCompareInnerClasses("A$B", innerB, innerC);
extractAndCompareInnerClasses("A$B$C", innerB, innerC); extractAndCompareInnerClasses("A$B$C", innerB, innerC);
extractAndCompareInnerClasses("A$" + classObjectDefaultName, innerAClassObject); extractAndCompareInnerClasses("A$" + defaultObjectDefaultName, innerADefaultObject);
} }
public void testLocalClass() { public void testLocalClass() {
@@ -75,7 +75,9 @@ public abstract class AbstractAnnotationDescriptorResolveTest extends JetLiteFix
ClassDescriptor myClass = getClassDescriptor(testPackage, "MyClass"); ClassDescriptor myClass = getClassDescriptor(testPackage, "MyClass");
checkDescriptor(expectedAnnotation, myClass); checkDescriptor(expectedAnnotation, myClass);
checkDescriptor(expectedAnnotation, getClassObjectDescriptor(myClass)); ClassDescriptor defaultObjectDescriptor = myClass.getDefaultObjectDescriptor();
assert defaultObjectDescriptor != null : "Cannot find default object for class " + myClass.getName();
checkDescriptor(expectedAnnotation, defaultObjectDescriptor);
checkDescriptor(expectedAnnotation, getInnerClassDescriptor(myClass, "InnerClass")); checkDescriptor(expectedAnnotation, getInnerClassDescriptor(myClass, "InnerClass"));
FunctionDescriptor foo = getFunctionDescriptor(myClass, "foo"); FunctionDescriptor foo = getFunctionDescriptor(myClass, "foo");
@@ -199,13 +201,6 @@ public abstract class AbstractAnnotationDescriptorResolveTest extends JetLiteFix
return (ClassDescriptor) aClass; return (ClassDescriptor) aClass;
} }
@NotNull
private static ClassDescriptor getClassObjectDescriptor(@NotNull ClassDescriptor classDescriptor) {
ClassDescriptor objectDescriptor = classDescriptor.getDefaultObjectDescriptor();
assert objectDescriptor != null : "Cannot find class object for class " + classDescriptor.getName();
return objectDescriptor;
}
@NotNull @NotNull
private static ClassDescriptor getInnerClassDescriptor(@NotNull ClassDescriptor classDescriptor, @NotNull String name) { private static ClassDescriptor getInnerClassDescriptor(@NotNull ClassDescriptor classDescriptor, @NotNull String name) {
Name propertyName = Name.identifier(name); Name propertyName = Name.identifier(name);
@@ -46,7 +46,7 @@ public final class JvmAbi {
//TODO: To be removed after kotlin M11 //TODO: To be removed after kotlin M11
@Deprecated @Deprecated
public static final String DEPRECATED_CLASS_OBJECT_FIELD = "OBJECT$"; public static final String DEPRECATED_DEFAULT_OBJECT_FIELD = "OBJECT$";
@NotNull @NotNull
public static String getSyntheticMethodNameForAnnotatedProperty(@NotNull Name propertyName) { public static String getSyntheticMethodNameForAnnotatedProperty(@NotNull Name propertyName) {
@@ -159,7 +159,7 @@ public abstract class AbstractBinaryClassAnnotationAndConstantLoader<A : Any, C
val classKind = Flags.CLASS_KIND[classProto.getFlags()] val classKind = Flags.CLASS_KIND[classProto.getFlags()]
val classId = nameResolver.getClassId(classProto.getFqName()) val classId = nameResolver.getClassId(classProto.getFqName())
if (classKind == ProtoBuf.Class.Kind.CLASS_OBJECT && isStaticFieldInOuter(proto)) { if (classKind == ProtoBuf.Class.Kind.CLASS_OBJECT && isStaticFieldInOuter(proto)) {
// Backing fields of properties of a class object are generated in the outer class // Backing fields of properties of a default object are generated in the outer class
return kotlinClassFinder.findKotlinClass(classId.getOuterClassId()) return kotlinClassFinder.findKotlinClass(classId.getOuterClassId())
} }
else if (classKind == ProtoBuf.Class.Kind.TRAIT && annotatedCallableKind == AnnotatedCallableKind.PROPERTY) { else if (classKind == ProtoBuf.Class.Kind.TRAIT && annotatedCallableKind == AnnotatedCallableKind.PROPERTY) {
@@ -40,7 +40,7 @@ public class Visibilities {
DeclarationDescriptor parent = what; DeclarationDescriptor parent = what;
while (parent != null) { while (parent != null) {
parent = parent.getContainingDeclaration(); parent = parent.getContainingDeclaration();
if ((parent instanceof ClassDescriptor && !DescriptorUtils.isClassObject(parent)) || if ((parent instanceof ClassDescriptor && !DescriptorUtils.isDefaultObject(parent)) ||
parent instanceof PackageFragmentDescriptor) { parent instanceof PackageFragmentDescriptor) {
break; break;
} }
@@ -97,7 +97,7 @@ public class Visibilities {
@Override @Override
protected boolean isVisible(@NotNull ReceiverValue receiver, @NotNull DeclarationDescriptorWithVisibility what, @NotNull DeclarationDescriptor from) { protected boolean isVisible(@NotNull ReceiverValue receiver, @NotNull DeclarationDescriptorWithVisibility what, @NotNull DeclarationDescriptor from) {
ClassDescriptor classDescriptor = DescriptorUtils.getParentOfType(what, ClassDescriptor.class); ClassDescriptor classDescriptor = DescriptorUtils.getParentOfType(what, ClassDescriptor.class);
if (DescriptorUtils.isClassObject(classDescriptor)) { if (DescriptorUtils.isDefaultObject(classDescriptor)) {
classDescriptor = DescriptorUtils.getParentOfType(classDescriptor, ClassDescriptor.class); classDescriptor = DescriptorUtils.getParentOfType(classDescriptor, ClassDescriptor.class);
} }
if (classDescriptor == null) return false; if (classDescriptor == null) return false;
@@ -152,7 +152,7 @@ public abstract class AbstractTypeParameterDescriptor extends DeclarationDescrip
@Override @Override
public JetType getClassObjectType() { public JetType getClassObjectType() {
// TODO: class object bounds // TODO: default object bounds
return null; return null;
} }
@@ -50,7 +50,7 @@ public class EnumEntrySyntheticClassDescriptor extends ClassDescriptorBase {
private final NotNullLazyValue<Collection<Name>> enumMemberNames; private final NotNullLazyValue<Collection<Name>> enumMemberNames;
/** /**
* Creates and initializes descriptors for enum entry with the given name and its class object * Creates and initializes descriptors for enum entry with the given name and its default object
* @param enumMemberNames needed for fake overrides resolution * @param enumMemberNames needed for fake overrides resolution
*/ */
@NotNull @NotNull
@@ -214,7 +214,7 @@ public class EnumEntrySyntheticClassDescriptor extends ClassDescriptorBase {
@NotNull @NotNull
private JetScope getSupertypeScope() { private JetScope getSupertypeScope() {
Collection<JetType> supertype = getTypeConstructor().getSupertypes(); Collection<JetType> supertype = getTypeConstructor().getSupertypes();
assert supertype.size() == 1 : "Enum entry and its class object both should have exactly one supertype: " + supertype; assert supertype.size() == 1 : "Enum entry and its default object both should have exactly one supertype: " + supertype;
return supertype.iterator().next().getMemberScope(); return supertype.iterator().next().getMemberScope();
} }
@@ -53,13 +53,14 @@ public interface DescriptorRenderer extends Renderer<DeclarationDescriptor> {
.setWithoutTypeParameters(true) .setWithoutTypeParameters(true)
.setWithoutFunctionParameterNames(true) .setWithoutFunctionParameterNames(true)
.setReceiverAfterName(true) .setReceiverAfterName(true)
.setRenderClassObjectName(true) .setRenderDefaultObjectName(true)
.setWithoutSuperTypes(true) .setWithoutSuperTypes(true)
.setStartFromName(true).build(); .setStartFromName(true).build();
DescriptorRenderer FQ_NAMES_IN_TYPES = new DescriptorRendererBuilder().build(); DescriptorRenderer FQ_NAMES_IN_TYPES = new DescriptorRendererBuilder().build();
DescriptorRenderer SHORT_NAMES_IN_TYPES = new DescriptorRendererBuilder().setNameShortness(NameShortness.SHORT).setIncludeSynthesizedParameterNames(false).build(); DescriptorRenderer SHORT_NAMES_IN_TYPES = new DescriptorRendererBuilder().setNameShortness(
NameShortness.SHORT).setIncludeSynthesizedParameterNames(false).build();
DescriptorRenderer DEBUG_TEXT = new DescriptorRendererBuilder() DescriptorRenderer DEBUG_TEXT = new DescriptorRendererBuilder()
.setDebugMode(true) .setDebugMode(true)
@@ -77,7 +78,7 @@ public interface DescriptorRenderer extends Renderer<DeclarationDescriptor> {
DescriptorRenderer HTML_NAMES_WITH_SHORT_TYPES = new DescriptorRendererBuilder() DescriptorRenderer HTML_NAMES_WITH_SHORT_TYPES = new DescriptorRendererBuilder()
.setWithDefinedIn(false) .setWithDefinedIn(false)
.setNameShortness(NameShortness.SHORT) .setNameShortness(NameShortness.SHORT)
.setRenderClassObjectName(true) .setRenderDefaultObjectName(true)
.setTextFormat(TextFormat.HTML).build(); .setTextFormat(TextFormat.HTML).build();
DescriptorRenderer HTML = new DescriptorRendererBuilder().setTextFormat(TextFormat.HTML).build(); DescriptorRenderer HTML = new DescriptorRendererBuilder().setTextFormat(TextFormat.HTML).build();
@@ -63,7 +63,7 @@ public class DescriptorRendererBuilder {
@NotNull @NotNull
private Collection<FqName> excludedAnnotationClasses = Collections.emptyList(); private Collection<FqName> excludedAnnotationClasses = Collections.emptyList();
private boolean receiverAfterName = false; private boolean receiverAfterName = false;
private boolean renderClassObjectName = false; private boolean renderDefaultObjectName = false;
public DescriptorRendererBuilder() { public DescriptorRendererBuilder() {
} }
@@ -200,8 +200,8 @@ public class DescriptorRendererBuilder {
} }
@NotNull @NotNull
public DescriptorRendererBuilder setRenderClassObjectName(boolean renderClassObjectName) { public DescriptorRendererBuilder setRenderDefaultObjectName(boolean renderDefaultObjectName) {
this.renderClassObjectName = renderClassObjectName; this.renderDefaultObjectName = renderDefaultObjectName;
return this; return this;
} }
@@ -234,7 +234,7 @@ public class DescriptorRendererBuilder {
normalizedVisibilities, showInternalKeyword, prettyFunctionTypes, uninferredTypeParameterAsName, normalizedVisibilities, showInternalKeyword, prettyFunctionTypes, uninferredTypeParameterAsName,
overrideRenderingPolicy, valueParametersHandler, textFormat, excludedAnnotationClasses, includePropertyConstant, overrideRenderingPolicy, valueParametersHandler, textFormat, excludedAnnotationClasses, includePropertyConstant,
includeSynthesizedParameterNames, withoutFunctionParameterNames, withoutTypeParameters, receiverAfterName, includeSynthesizedParameterNames, withoutFunctionParameterNames, withoutTypeParameters, receiverAfterName,
renderClassObjectName, withoutSuperTypes, typeNormalizer, renderDefaultValues, flexibleTypesForCode); renderDefaultObjectName, withoutSuperTypes, typeNormalizer, renderDefaultValues, flexibleTypesForCode);
} }
} }
@@ -62,7 +62,7 @@ public class DescriptorRendererImpl implements DescriptorRenderer {
private final boolean includeSynthesizedParameterNames; private final boolean includeSynthesizedParameterNames;
private final boolean withoutFunctionParameterNames; private final boolean withoutFunctionParameterNames;
private final boolean withoutTypeParameters; private final boolean withoutTypeParameters;
private final boolean renderClassObjectName; private final boolean renderDefaultObjectName;
private final boolean withoutSuperTypes; private final boolean withoutSuperTypes;
private final boolean receiverAfterName; private final boolean receiverAfterName;
private final boolean renderDefaultValues; private final boolean renderDefaultValues;
@@ -100,7 +100,7 @@ public class DescriptorRendererImpl implements DescriptorRenderer {
boolean withoutFunctionParameterNames, boolean withoutFunctionParameterNames,
boolean withoutTypeParameters, boolean withoutTypeParameters,
boolean receiverAfterName, boolean receiverAfterName,
boolean renderClassObjectName, boolean renderDefaultObjectName,
boolean withoutSuperTypes, boolean withoutSuperTypes,
@NotNull Function1<JetType, JetType> typeNormalizer, @NotNull Function1<JetType, JetType> typeNormalizer,
boolean renderDefaultValues, boolean renderDefaultValues,
@@ -127,7 +127,7 @@ public class DescriptorRendererImpl implements DescriptorRenderer {
this.withoutFunctionParameterNames = withoutFunctionParameterNames; this.withoutFunctionParameterNames = withoutFunctionParameterNames;
this.withoutTypeParameters = withoutTypeParameters; this.withoutTypeParameters = withoutTypeParameters;
this.receiverAfterName = receiverAfterName; this.receiverAfterName = receiverAfterName;
this.renderClassObjectName = renderClassObjectName; this.renderDefaultObjectName = renderDefaultObjectName;
this.withoutSuperTypes = withoutSuperTypes; this.withoutSuperTypes = withoutSuperTypes;
this.typeNormalizer = typeNormalizer; this.typeNormalizer = typeNormalizer;
this.renderDefaultValues = renderDefaultValues; this.renderDefaultValues = renderDefaultValues;
@@ -234,8 +234,8 @@ public class DescriptorRendererImpl implements DescriptorRenderer {
builder.append(renderName(descriptor.getName())); builder.append(renderName(descriptor.getName()));
} }
private void renderClassObjectName(@NotNull DeclarationDescriptor descriptor, @NotNull StringBuilder builder) { private void renderDefaultObjectName(@NotNull DeclarationDescriptor descriptor, @NotNull StringBuilder builder) {
if (renderClassObjectName) { if (renderDefaultObjectName) {
if (startFromName) { if (startFromName) {
builder.append("class object"); builder.append("class object");
} }
@@ -956,7 +956,7 @@ public class DescriptorRendererImpl implements DescriptorRenderer {
renderName(klass, builder); renderName(klass, builder);
} }
else { else {
renderClassObjectName(klass, builder); renderDefaultObjectName(klass, builder);
} }
List<TypeParameterDescriptor> typeParameters = klass.getTypeConstructor().getParameters(); List<TypeParameterDescriptor> typeParameters = klass.getTypeConstructor().getParameters();
@@ -191,7 +191,7 @@ public class DescriptorUtils {
public static ClassDescriptor getContainingClass(@NotNull DeclarationDescriptor descriptor) { public static ClassDescriptor getContainingClass(@NotNull DeclarationDescriptor descriptor) {
DeclarationDescriptor containing = descriptor.getContainingDeclaration(); DeclarationDescriptor containing = descriptor.getContainingDeclaration();
while (containing != null) { while (containing != null) {
if (containing instanceof ClassDescriptor && !isClassObject(containing)) { if (containing instanceof ClassDescriptor && !isDefaultObject(containing)) {
return (ClassDescriptor) containing; return (ClassDescriptor) containing;
} }
containing = containing.getContainingDeclaration(); containing = containing.getContainingDeclaration();
@@ -240,7 +240,7 @@ public class DescriptorUtils {
return descriptor instanceof AnonymousFunctionDescriptor; return descriptor instanceof AnonymousFunctionDescriptor;
} }
public static boolean isClassObject(@Nullable DeclarationDescriptor descriptor) { public static boolean isDefaultObject(@Nullable DeclarationDescriptor descriptor) {
return isKindOf(descriptor, ClassKind.CLASS_OBJECT); return isKindOf(descriptor, ClassKind.CLASS_OBJECT);
} }
@@ -32,7 +32,7 @@ public class EnumValue extends CompileTimeConstant<ClassDescriptor> {
@Override @Override
public JetType getType(@NotNull KotlinBuiltIns kotlinBuiltIns) { public JetType getType(@NotNull KotlinBuiltIns kotlinBuiltIns) {
JetType type = value.getClassObjectType(); JetType type = value.getClassObjectType();
assert type != null : "Enum entry should have a class object: " + value; assert type != null : "Enum entry should have a default object: " + value;
return type; return type;
} }
@@ -24,9 +24,6 @@ import java.lang.reflect.Modifier
public trait JetScope { public trait JetScope {
/**
* Should not return object (class object or enum entry) class descriptors.
*/
public fun getClassifier(name: Name): ClassifierDescriptor? public fun getClassifier(name: Name): ClassifierDescriptor?
public fun getPackage(name: Name): PackageViewDescriptor? public fun getPackage(name: Name): PackageViewDescriptor?
@@ -52,7 +52,7 @@ message JvmFieldSignature {
required int32 name = 1; required int32 name = 1;
required JvmType type = 2; required JvmType type = 2;
// True iff this field is a backing field for a class object and is really present as a static // True iff this field is a backing field for a default object and is really present as a static
// field in the outer class, not as an instance field here // field in the outer class, not as an instance field here
optional bool is_static_in_outer = 3 [default = false]; optional bool is_static_in_outer = 3 [default = false];
} }
@@ -131,9 +131,9 @@ public class DescriptorSerializer {
} }
} }
ClassDescriptor classObject = classDescriptor.getDefaultObjectDescriptor(); ClassDescriptor defaultObjectDescriptor = classDescriptor.getDefaultObjectDescriptor();
if (classObject != null) { if (defaultObjectDescriptor != null) {
builder.setClassObjectName(stringTable.getSimpleNameIndex(classObject.getName())); builder.setClassObjectName(stringTable.getSimpleNameIndex(defaultObjectDescriptor.getName()));
} }
extension.serializeClass(classDescriptor, builder, stringTable); extension.serializeClass(classDescriptor, builder, stringTable);
@@ -60,7 +60,7 @@ public class DeserializedClassDescriptor(
private val containingDeclaration = outerContext.containingDeclaration private val containingDeclaration = outerContext.containingDeclaration
private val primaryConstructor = c.storageManager.createNullableLazyValue { computePrimaryConstructor() } private val primaryConstructor = c.storageManager.createNullableLazyValue { computePrimaryConstructor() }
private val classObjectDescriptor = c.storageManager.createNullableLazyValue { computeClassObjectDescriptor() } private val defaultObjectDescriptor = c.storageManager.createNullableLazyValue { computeDefaultObjectDescriptor() }
private val annotations = private val annotations =
if (!Flags.HAS_ANNOTATIONS.get(classProto.getFlags())) { if (!Flags.HAS_ANNOTATIONS.get(classProto.getFlags())) {
@@ -109,14 +109,14 @@ public class DeserializedClassDescriptor(
return listOf(constructor) return listOf(constructor)
} }
private fun computeClassObjectDescriptor(): ClassDescriptor? { private fun computeDefaultObjectDescriptor(): ClassDescriptor? {
if (!classProto.hasClassObjectName()) return null if (!classProto.hasClassObjectName()) return null
val classObjectName = c.nameResolver.getName(classProto.getClassObjectName()) val defaultObjectName = c.nameResolver.getName(classProto.getClassObjectName())
return memberScope.getClassifier(classObjectName) as? ClassDescriptor return memberScope.getClassifier(defaultObjectName) as? ClassDescriptor
} }
override fun getDefaultObjectDescriptor(): ClassDescriptor? = classObjectDescriptor() override fun getDefaultObjectDescriptor(): ClassDescriptor? = defaultObjectDescriptor()
private fun computeSuperTypes(): Collection<JetType> { private fun computeSuperTypes(): Collection<JetType> {
val supertypes = ArrayList<JetType>(classProto.getSupertypeCount()) val supertypes = ArrayList<JetType>(classProto.getSupertypeCount())
+2 -5
View File
@@ -27,7 +27,7 @@ class Example(a : Foo, i : Int) : Bar(i), Some {
*/ */
memberDeclaration memberDeclaration
: classObject : defaultObject
: object : object
: function : function
: property : property
@@ -40,12 +40,9 @@ anonymousInitializer
: block : block
; ;
classObject defaultObject
: modifiers "class" object : modifiers "class" object
; ;
/**
See [Class objects](classes.html#class-objects)
*/
valueParameters valueParameters
: "(" functionParameter{","}? ")" // default values : "(" functionParameter{","}? ")" // default values
@@ -88,7 +88,7 @@ public class ReferenceVariantsHelper(
val qualifier = context[BindingContext.QUALIFIER, receiverExpression] val qualifier = context[BindingContext.QUALIFIER, receiverExpression]
if (qualifier != null) { if (qualifier != null) {
// It's impossible to add extension function for package or class (if it's class object, expression type is not null) // It's impossible to add extension function for package or class (if it's default object, expression type is not null)
qualifier.scope.getDescriptorsFiltered(kindFilter exclude DescriptorKindExclude.Extensions, nameFilter).filterTo(descriptors) { callType.canCall(it) } qualifier.scope.getDescriptorsFiltered(kindFilter exclude DescriptorKindExclude.Extensions, nameFilter).filterTo(descriptors) { callType.canCall(it) }
} }
@@ -24,7 +24,7 @@ import org.jetbrains.kotlin.descriptors.ClassDescriptor
import java.util.HashSet import java.util.HashSet
public fun JetScope.getImplicitReceiversWithInstance(): List<ReceiverParameterDescriptor> { public fun JetScope.getImplicitReceiversWithInstance(): List<ReceiverParameterDescriptor> {
// we use a set to workaround a bug with receiver for class object present twice in the result of getImplicitReceiversHierarchy() // we use a set to workaround a bug with receiver for default object present twice in the result of getImplicitReceiversHierarchy()
val receivers = LinkedHashSet(getImplicitReceiversHierarchy()) val receivers = LinkedHashSet(getImplicitReceiversHierarchy())
val withInstance = HashSet<DeclarationDescriptor>() val withInstance = HashSet<DeclarationDescriptor>()
@@ -66,7 +66,7 @@ private class ClassClsStubBuilder(
supertypeIds supertypeIds
} }
} }
private val classObjectName = if (classProto.hasClassObjectName()) c.nameResolver.getName(classProto.getClassObjectName()) else null private val defaultObjectName = if (classProto.hasClassObjectName()) c.nameResolver.getName(classProto.getClassObjectName()) else null
private val classOrObjectStub = createClassOrObjectStubAndModifierListStub() private val classOrObjectStub = createClassOrObjectStubAndModifierListStub()
@@ -100,7 +100,7 @@ private class ClassClsStubBuilder(
} }
private fun doCreateClassOrObjectStub(): StubElement<out PsiElement> { private fun doCreateClassOrObjectStub(): StubElement<out PsiElement> {
val isClassObject = classKind == ProtoBuf.Class.Kind.CLASS_OBJECT val isDefaultObject = classKind == ProtoBuf.Class.Kind.CLASS_OBJECT
val fqName = outerContext.containerFqName.child(classId.getRelativeClassName().shortName()) val fqName = outerContext.containerFqName.child(classId.getRelativeClassName().shortName())
val shortName = fqName.shortName()?.ref() val shortName = fqName.shortName()?.ref()
val superTypeRefs = supertypeIds.filter { val superTypeRefs = supertypeIds.filter {
@@ -112,7 +112,7 @@ private class ClassClsStubBuilder(
KotlinObjectStubImpl( KotlinObjectStubImpl(
parentStub, shortName, fqName, superTypeRefs, parentStub, shortName, fqName, superTypeRefs,
isTopLevel = !classId.isNestedClass(), isTopLevel = !classId.isNestedClass(),
isClassObject = isClassObject, isDefault = isDefaultObject,
isLocal = false, isLocal = false,
isObjectLiteral = false isObjectLiteral = false
) )
@@ -163,19 +163,19 @@ private class ClassClsStubBuilder(
private fun createClassBodyAndMemberStubs() { private fun createClassBodyAndMemberStubs() {
val classBody = KotlinPlaceHolderStubImpl<JetClassBody>(classOrObjectStub, JetStubElementTypes.CLASS_BODY) val classBody = KotlinPlaceHolderStubImpl<JetClassBody>(classOrObjectStub, JetStubElementTypes.CLASS_BODY)
createClassObjectStub(classBody) createDefaultObjectStub(classBody)
createEnumEntryStubs(classBody) createEnumEntryStubs(classBody)
createCallableMemberStubs(classBody) createCallableMemberStubs(classBody)
createInnerAndNestedClasses(classBody) createInnerAndNestedClasses(classBody)
} }
private fun createClassObjectStub(classBody: KotlinPlaceHolderStubImpl<JetClassBody>) { private fun createDefaultObjectStub(classBody: KotlinPlaceHolderStubImpl<JetClassBody>) {
if (classObjectName == null) { if (defaultObjectName == null) {
return return
} }
val classObjectId = classId.createNestedClassId(classObjectName) val defaultObjectId = classId.createNestedClassId(defaultObjectName)
createNestedClassStub(classBody, classObjectId) createNestedClassStub(classBody, defaultObjectId)
} }
private fun createEnumEntryStubs(classBody: KotlinPlaceHolderStubImpl<JetClassBody>) { private fun createEnumEntryStubs(classBody: KotlinPlaceHolderStubImpl<JetClassBody>) {
@@ -211,7 +211,7 @@ private class ClassClsStubBuilder(
private fun createInnerAndNestedClasses(classBody: KotlinPlaceHolderStubImpl<JetClassBody>) { private fun createInnerAndNestedClasses(classBody: KotlinPlaceHolderStubImpl<JetClassBody>) {
classProto.getNestedClassNameList().forEach { id -> classProto.getNestedClassNameList().forEach { id ->
val nestedClassName = c.nameResolver.getName(id) val nestedClassName = c.nameResolver.getName(id)
if (nestedClassName != classObjectName) { if (nestedClassName != defaultObjectName) {
val nestedClassId = classId.createNestedClassId(nestedClassName) val nestedClassId = classId.createNestedClassId(nestedClassName)
createNestedClassStub(classBody, nestedClassId) createNestedClassStub(classBody, nestedClassId)
} }
@@ -210,7 +210,7 @@ class TypeClsStubBuilder(private val c: ClsStubBuilderContext) {
} }
val typeConstraintListStub = KotlinPlaceHolderStubImpl<JetTypeConstraintList>(parent, JetStubElementTypes.TYPE_CONSTRAINT_LIST) val typeConstraintListStub = KotlinPlaceHolderStubImpl<JetTypeConstraintList>(parent, JetStubElementTypes.TYPE_CONSTRAINT_LIST)
for ((name, type) in protosForTypeConstraintList) { for ((name, type) in protosForTypeConstraintList) {
val typeConstraintStub = KotlinTypeConstraintStubImpl(typeConstraintListStub, isClassObjectConstraint = false) val typeConstraintStub = KotlinTypeConstraintStubImpl(typeConstraintListStub, isDefaultObjectConstraint = false)
KotlinNameReferenceExpressionStubImpl(typeConstraintStub, name.ref()) KotlinNameReferenceExpressionStubImpl(typeConstraintStub, name.ref())
createTypeReferenceStub(typeConstraintStub, type) createTypeReferenceStub(typeConstraintStub, type)
} }
@@ -146,17 +146,17 @@ private fun buildDecompiledText(packageFqName: FqName, descriptors: List<Declara
builder.append(" {\n") builder.append(" {\n")
var firstPassed = false var firstPassed = false
val subindent = indent + " " val subindent = indent + " "
val classObject = descriptor.getDefaultObjectDescriptor() val defaultObject = descriptor.getDefaultObjectDescriptor()
if (classObject != null) { if (defaultObject != null) {
firstPassed = true firstPassed = true
builder.append(subindent) builder.append(subindent)
appendDescriptor(classObject, subindent) appendDescriptor(defaultObject, subindent)
} }
for (member in descriptor.getDefaultType().getMemberScope().getDescriptors()) { for (member in descriptor.getDefaultType().getMemberScope().getDescriptors()) {
if (member.getContainingDeclaration() != descriptor) { if (member.getContainingDeclaration() != descriptor) {
continue continue
} }
if (member == classObject) { if (member == defaultObject) {
continue continue
} }
if (member is CallableMemberDescriptor if (member is CallableMemberDescriptor
@@ -99,7 +99,7 @@ private object DeclarationKindDetector : JetVisitor<AnnotationHostKind?, Unit?>(
override fun visitParameter(d: JetParameter, _: Unit?) = detect(d, "parameter", newLineNeeded = false) override fun visitParameter(d: JetParameter, _: Unit?) = detect(d, "parameter", newLineNeeded = false)
override fun visitObjectDeclaration(d: JetObjectDeclaration, _: Unit?): AnnotationHostKind? { override fun visitObjectDeclaration(d: JetObjectDeclaration, _: Unit?): AnnotationHostKind? {
if (d.isClassObject()) return detect(d, "class object", name = "${d.getName()} of ${d.getStrictParentOfType<JetClass>()?.getName()}") if (d.isDefault()) return detect(d, "class object", name = "${d.getName()} of ${d.getStrictParentOfType<JetClass>()?.getName()}")
if (d.getParent() is JetObjectLiteralExpression) return null if (d.getParent() is JetObjectLiteralExpression) return null
return detect(d, "object") return detect(d, "object")
} }
@@ -36,14 +36,14 @@ import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
// Navigation element of the resolved reference // Navigation element of the resolved reference
// For property accessor return enclosing property // For property accessor return enclosing property
// For class object return enclosing class // For default object return enclosing class
public val PsiReference.unwrappedTargets: Set<PsiElement> public val PsiReference.unwrappedTargets: Set<PsiElement>
get() { get() {
fun PsiElement.adjust(): PsiElement? { fun PsiElement.adjust(): PsiElement? {
val target = unwrapped?.getOriginalElement() val target = unwrapped?.getOriginalElement()
return when { return when {
target is JetPropertyAccessor -> target.getNonStrictParentOfType<JetProperty>() target is JetPropertyAccessor -> target.getNonStrictParentOfType<JetProperty>()
target is JetObjectDeclaration && target.isClassObject() -> target.getNonStrictParentOfType<JetClass>() target is JetObjectDeclaration && target.isDefault() -> target.getNonStrictParentOfType<JetClass>()
else -> target else -> target
} }
} }
@@ -308,7 +308,7 @@ public abstract class OverrideImplementMethodsHandler implements LanguageCodeIns
PsiElement elementAtCaret = file.findElementAt(editor.getCaretModel().getOffset()); PsiElement elementAtCaret = file.findElementAt(editor.getCaretModel().getOffset());
JetClassOrObject classOrObject = PsiTreeUtil.getParentOfType(elementAtCaret, JetClassOrObject.class); JetClassOrObject classOrObject = PsiTreeUtil.getParentOfType(elementAtCaret, JetClassOrObject.class);
assert classOrObject != null : "ClassObject should be checked in isValidFor method"; assert classOrObject != null;
Set<CallableMemberDescriptor> missingImplementations = collectMethodsToGenerate(classOrObject); Set<CallableMemberDescriptor> missingImplementations = collectMethodsToGenerate(classOrObject);
if (missingImplementations.isEmpty() && !implementAll) { if (missingImplementations.isEmpty() && !implementAll) {
@@ -61,7 +61,7 @@ public class JetDeclarationMover extends AbstractJetUpDownMover {
@Override @Override
public void visitObjectDeclaration(@NotNull JetObjectDeclaration declaration) { public void visitObjectDeclaration(@NotNull JetObjectDeclaration declaration) {
if (declaration.isClassObject()) { if (declaration.isDefault()) {
memberSuspects.add(declaration.getClassKeyword()); memberSuspects.add(declaration.getClassKeyword());
} }
} }
@@ -144,7 +144,7 @@ private class JetDeclarationRemotenessWeigher(private val file: JetFile) : Looku
} }
val qualifiedName = qualifiedName(o) val qualifiedName = qualifiedName(o)
// Invalid name can be met for class object descriptor: Test.MyTest.A.<no name provided>.testOther // Invalid name can be met for default object descriptor: Test.MyTest.A.<no name provided>.testOther
if (qualifiedName != null && isValidJavaFqName(qualifiedName)) { if (qualifiedName != null && isValidJavaFqName(qualifiedName)) {
val importPath = ImportPath(qualifiedName) val importPath = ImportPath(qualifiedName)
val fqName = importPath.fqnPart() val fqName = importPath.fqnPart()
@@ -223,7 +223,7 @@ class SmartCompletion(
val typeParameter = type.type.getConstructor().getDeclarationDescriptor() as? TypeParameterDescriptor ?: return false val typeParameter = type.type.getConstructor().getDeclarationDescriptor() as? TypeParameterDescriptor ?: return false
if (!type.freeParameters.contains(typeParameter)) return false if (!type.freeParameters.contains(typeParameter)) return false
return KotlinBuiltIns.isAnyOrNullableAny(typeParameter.getUpperBoundsAsType()) return KotlinBuiltIns.isAnyOrNullableAny(typeParameter.getUpperBoundsAsType())
//TODO: check for class object constraint when there will be supported //TODO: check for default object constraint when they are supported
} }
private fun calcExpectedInfos(expression: JetExpression): Collection<ExpectedInfo>? { private fun calcExpectedInfos(expression: JetExpression): Collection<ExpectedInfo>? {
@@ -35,7 +35,7 @@ import org.jetbrains.kotlin.psi.JetSimpleNameExpression
import org.jetbrains.kotlin.idea.completion.isVisible import org.jetbrains.kotlin.idea.completion.isVisible
import org.jetbrains.kotlin.idea.completion.ExpectedInfo import org.jetbrains.kotlin.idea.completion.ExpectedInfo
// adds java static members, enum members and members from class object // adds java static members, enum members and members from default object
class StaticMembers( class StaticMembers(
val bindingContext: BindingContext, val bindingContext: BindingContext,
val resolutionFacade: ResolutionFacade, val resolutionFacade: ResolutionFacade,
@@ -85,9 +85,9 @@ class StaticMembers(
classDescriptor.getStaticScope().getAllDescriptors().forEach(::processMember) classDescriptor.getStaticScope().getAllDescriptors().forEach(::processMember)
val classObject = classDescriptor.getDefaultObjectDescriptor() val defaultObject = classDescriptor.getDefaultObjectDescriptor()
if (classObject != null) { if (defaultObject != null) {
classObject.getDefaultType().getMemberScope().getAllDescriptors() defaultObject.getDefaultType().getMemberScope().getAllDescriptors()
.filter { !it.isExtension } .filter { !it.isExtension }
.forEach(::processMember) .forEach(::processMember)
} }
@@ -249,7 +249,7 @@ public class JetPositionManager(private val myDebugProcess: DebugProcess) : Posi
element is JetClassInitializer -> { element is JetClassInitializer -> {
val parent = getElementToCalculateClassName(element.getParent()) val parent = getElementToCalculateClassName(element.getParent())
// Class-object initializer // Class-object initializer
if (parent is JetObjectDeclaration && parent.isClassObject()) { if (parent is JetObjectDeclaration && parent.isDefault()) {
return getClassNameForElement(parent.getParent(), typeMapper, file, isInLibrary) return getClassNameForElement(parent.getParent(), typeMapper, file, isInLibrary)
} }
return getClassNameForElement(element, typeMapper, file, isInLibrary) return getClassNameForElement(element, typeMapper, file, isInLibrary)
@@ -170,7 +170,7 @@ public class KotlinCallHierarchyNodeDescriptor extends HierarchyNodeDescriptor i
if (descriptor == null) return null; if (descriptor == null) return null;
if (element instanceof JetClassOrObject) { if (element instanceof JetClassOrObject) {
if (element instanceof JetObjectDeclaration && ((JetObjectDeclaration) element).isClassObject()) { if (element instanceof JetObjectDeclaration && ((JetObjectDeclaration) element).isDefault()) {
descriptor = descriptor.getContainingDeclaration(); descriptor = descriptor.getContainingDeclaration();
if (!(descriptor instanceof ClassDescriptor)) return null; if (!(descriptor instanceof ClassDescriptor)) return null;
@@ -126,8 +126,8 @@ public class UnusedSymbolInspection : AbstractKotlinInspection() {
if (declaration is JetProperty && declaration.isLocal()) return if (declaration is JetProperty && declaration.isLocal()) return
if (declaration is JetParameter && (declaration.getParent()?.getParent() !is JetClass || !declaration.hasValOrVarNode())) return if (declaration is JetParameter && (declaration.getParent()?.getParent() !is JetClass || !declaration.hasValOrVarNode())) return
if (declaration is JetNamedFunction && isConventionalName(declaration)) return if (declaration is JetNamedFunction && isConventionalName(declaration)) return
//TODO: support this inspection for class objects //TODO: support this inspection for default objects
if (declaration is JetObjectDeclaration && declaration.isClassObject()) return if (declaration is JetObjectDeclaration && declaration.isDefault()) return
// More expensive, resolve-based checks // More expensive, resolve-based checks
if (isEntryPoint(declaration)) return if (isEntryPoint(declaration)) return
@@ -851,7 +851,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
is ConstructorInfo -> with(callableInfo.classInfo) { is ConstructorInfo -> with(callableInfo.classInfo) {
!inner && kind != ClassKind.ENUM_ENTRY && kind != ClassKind.ENUM_CLASS !inner && kind != ClassKind.ENUM_ENTRY && kind != ClassKind.ENUM_CLASS
} }
else -> callableInfo.receiverTypeInfo.classObjectRequired else -> callableInfo.receiverTypeInfo.staticContextRequired
} }
modifierList.setModifierProperty(PsiModifier.STATIC, needStatic) modifierList.setModifierProperty(PsiModifier.STATIC, needStatic)
@@ -75,12 +75,12 @@ abstract class TypeInfo(val variance: Variance) {
override val substitutionsAllowed: Boolean = false override val substitutionsAllowed: Boolean = false
} }
class ClassObjectRequired(delegate: TypeInfo): DelegatingTypeInfo(delegate) { class StaticContextRequired(delegate: TypeInfo): DelegatingTypeInfo(delegate) {
override val classObjectRequired: Boolean = true override val staticContextRequired: Boolean = true
} }
open val substitutionsAllowed: Boolean = true open val substitutionsAllowed: Boolean = true
open val classObjectRequired: Boolean = false open val staticContextRequired: Boolean = false
open val possibleNamesFromExpression: Array<String> get() = ArrayUtil.EMPTY_STRING_ARRAY open val possibleNamesFromExpression: Array<String> get() = ArrayUtil.EMPTY_STRING_ARRAY
abstract fun getPossibleTypes(builder: CallableBuilder): List<JetType> abstract fun getPossibleTypes(builder: CallableBuilder): List<JetType>
@@ -79,8 +79,8 @@ public class CreateCallableFromUsageFix(
val receiverInfo = callableInfo.receiverTypeInfo val receiverInfo = callableInfo.receiverTypeInfo
if (receiverInfo is TypeInfo.Empty) return !isExtension if (receiverInfo is TypeInfo.Empty) return !isExtension
// TODO: Remove after class object extensions are supported // TODO: Remove after default object extensions are supported
if (isExtension && receiverInfo.classObjectRequired) return false if (isExtension && receiverInfo.staticContextRequired) return false
val file = element.getContainingFile() as JetFile val file = element.getContainingFile() as JetFile
val project = file.getProject() val project = file.getProject()
@@ -93,9 +93,9 @@ public class CreateCallableFromUsageFix(
val declaration = getDeclarationIfApplicable(project, it) val declaration = getDeclarationIfApplicable(project, it)
val insertToJavaInterface = declaration is PsiClass && declaration.isInterface() val insertToJavaInterface = declaration is PsiClass && declaration.isInterface()
when { when {
propertyInfo != null && insertToJavaInterface && (!receiverInfo.classObjectRequired || propertyInfo.writable) -> propertyInfo != null && insertToJavaInterface && (!receiverInfo.staticContextRequired || propertyInfo.writable) ->
false false
isFunction && insertToJavaInterface && receiverInfo.classObjectRequired -> isFunction && insertToJavaInterface && receiverInfo.staticContextRequired ->
false false
else -> else ->
declaration != null declaration != null

Some files were not shown because too many files have changed in this diff Show More