Remove some usages of KotlinBuiltIns.getInstance()

Introduce DeclarationDescriptor.builtIns extension to get builtins where descriptors are available
Introduce various utilities in KotlinBuiltIns to check for primitive types and get fq names of builtins
This commit is contained in:
Pavel V. Talanov
2015-04-23 15:40:16 +03:00
parent 21d9c272c9
commit ac2cb9af74
71 changed files with 334 additions and 288 deletions
@@ -22,22 +22,24 @@ import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.backend.common.bridges.BridgesPackage;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.descriptors.*; import org.jetbrains.kotlin.descriptors.*;
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.DescriptorUtils; import org.jetbrains.kotlin.resolve.DescriptorUtils;
import org.jetbrains.kotlin.resolve.calls.CallResolverUtil; import org.jetbrains.kotlin.resolve.calls.CallResolverUtil;
import org.jetbrains.kotlin.resolve.calls.callUtil.CallUtilPackage; import org.jetbrains.kotlin.resolve.calls.callUtil.CallUtilPackage;
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall; import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.types.JetType; import org.jetbrains.kotlin.types.JetType;
import org.jetbrains.kotlin.types.TypeUtils; import org.jetbrains.kotlin.types.TypeUtils;
import org.jetbrains.kotlin.types.checker.JetTypeChecker; import org.jetbrains.kotlin.types.checker.JetTypeChecker;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.backend.common.bridges.BridgesPackage;
import java.util.*; import java.util.*;
import static org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilPackage.getBuiltIns;
/** /**
* Backend-independent utility class. * Backend-independent utility class.
*/ */
@@ -70,30 +72,25 @@ public class CodegenUtil {
return null; return null;
} }
public static FunctionDescriptor getAnyEqualsMethod() { public static FunctionDescriptor getAnyEqualsMethod(@NotNull KotlinBuiltIns builtIns) {
ClassDescriptor anyClass = KotlinBuiltIns.getInstance().getAny(); ClassDescriptor anyClass = builtIns.getAny();
FunctionDescriptor function = FunctionDescriptor function = getDeclaredFunctionByRawSignature(
getDeclaredFunctionByRawSignature(anyClass, Name.identifier(EQUALS_METHOD_NAME), anyClass, Name.identifier(EQUALS_METHOD_NAME), builtIns.getBoolean(), anyClass
KotlinBuiltIns.getInstance().getBoolean(), );
anyClass);
assert function != null; assert function != null;
return function; return function;
} }
public static FunctionDescriptor getAnyToStringMethod() { public static FunctionDescriptor getAnyToStringMethod(@NotNull KotlinBuiltIns builtIns) {
ClassDescriptor anyClass = KotlinBuiltIns.getInstance().getAny(); ClassDescriptor anyClass = builtIns.getAny();
FunctionDescriptor function = FunctionDescriptor function = getDeclaredFunctionByRawSignature(anyClass, Name.identifier(TO_STRING_METHOD_NAME), builtIns.getString());
getDeclaredFunctionByRawSignature(anyClass, Name.identifier(TO_STRING_METHOD_NAME),
KotlinBuiltIns.getInstance().getString());
assert function != null; assert function != null;
return function; return function;
} }
public static FunctionDescriptor getAnyHashCodeMethod() { public static FunctionDescriptor getAnyHashCodeMethod(@NotNull KotlinBuiltIns builtIns) {
ClassDescriptor anyClass = KotlinBuiltIns.getInstance().getAny(); ClassDescriptor anyClass = builtIns.getAny();
FunctionDescriptor function = FunctionDescriptor function = getDeclaredFunctionByRawSignature(anyClass, Name.identifier(HASH_CODE_METHOD_NAME), builtIns.getInt());
getDeclaredFunctionByRawSignature(anyClass, Name.identifier(HASH_CODE_METHOD_NAME),
KotlinBuiltIns.getInstance().getInt());
assert function != null; assert function != null;
return function; return function;
} }
@@ -206,7 +203,7 @@ public class CodegenUtil {
public static boolean isEnumValueOfMethod(@NotNull FunctionDescriptor functionDescriptor) { public static boolean isEnumValueOfMethod(@NotNull FunctionDescriptor functionDescriptor) {
List<ValueParameterDescriptor> methodTypeParameters = functionDescriptor.getValueParameters(); List<ValueParameterDescriptor> methodTypeParameters = functionDescriptor.getValueParameters();
JetType nullableString = TypeUtils.makeNullable(KotlinBuiltIns.getInstance().getStringType()); JetType nullableString = TypeUtils.makeNullable(getBuiltIns(functionDescriptor).getStringType());
return DescriptorUtils.ENUM_VALUE_OF.equals(functionDescriptor.getName()) return DescriptorUtils.ENUM_VALUE_OF.equals(functionDescriptor.getName())
&& methodTypeParameters.size() == 1 && methodTypeParameters.size() == 1
&& JetTypeChecker.DEFAULT.isSubtypeOf(methodTypeParameters.get(0).getType(), nullableString); && JetTypeChecker.DEFAULT.isSubtypeOf(methodTypeParameters.get(0).getType(), nullableString);
@@ -19,18 +19,19 @@ package org.jetbrains.kotlin.backend.common;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.descriptors.*; import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.psi.JetClass; import org.jetbrains.kotlin.psi.JetClass;
import org.jetbrains.kotlin.psi.JetClassOrObject; import org.jetbrains.kotlin.psi.JetClassOrObject;
import org.jetbrains.kotlin.psi.JetParameter; import org.jetbrains.kotlin.psi.JetParameter;
import org.jetbrains.kotlin.resolve.BindingContext; import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.BindingContextUtils; import org.jetbrains.kotlin.resolve.BindingContextUtils;
import org.jetbrains.kotlin.resolve.OverrideResolver; import org.jetbrains.kotlin.resolve.OverrideResolver;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilPackage.getBuiltIns;
/** /**
* A platform-independent logic for generating data class synthetic methods. * A platform-independent logic for generating data class synthetic methods.
* TODO: data class with zero components gets no toString/equals/hashCode methods. This is inconsistent and should be * TODO: data class with zero components gets no toString/equals/hashCode methods. This is inconsistent and should be
@@ -100,22 +101,22 @@ public abstract class DataClassMethodGenerator {
} }
private void generateDataClassToStringIfNeeded(@NotNull List<PropertyDescriptor> properties) { private void generateDataClassToStringIfNeeded(@NotNull List<PropertyDescriptor> properties) {
ClassDescriptor stringClass = KotlinBuiltIns.getInstance().getString(); ClassDescriptor stringClass = getBuiltIns(classDescriptor).getString();
if (!hasDeclaredNonTrivialMember(CodegenUtil.TO_STRING_METHOD_NAME, stringClass)) { if (!hasDeclaredNonTrivialMember(CodegenUtil.TO_STRING_METHOD_NAME, stringClass)) {
generateToStringMethod(properties); generateToStringMethod(properties);
} }
} }
private void generateDataClassHashCodeIfNeeded(@NotNull List<PropertyDescriptor> properties) { private void generateDataClassHashCodeIfNeeded(@NotNull List<PropertyDescriptor> properties) {
ClassDescriptor intClass = KotlinBuiltIns.getInstance().getInt(); ClassDescriptor intClass = getBuiltIns(classDescriptor).getInt();
if (!hasDeclaredNonTrivialMember(CodegenUtil.HASH_CODE_METHOD_NAME, intClass)) { if (!hasDeclaredNonTrivialMember(CodegenUtil.HASH_CODE_METHOD_NAME, intClass)) {
generateHashCodeMethod(properties); generateHashCodeMethod(properties);
} }
} }
private void generateDataClassEqualsIfNeeded(@NotNull List<PropertyDescriptor> properties) { private void generateDataClassEqualsIfNeeded(@NotNull List<PropertyDescriptor> properties) {
ClassDescriptor booleanClass = KotlinBuiltIns.getInstance().getBoolean(); ClassDescriptor booleanClass = getBuiltIns(classDescriptor).getBoolean();
ClassDescriptor anyClass = KotlinBuiltIns.getInstance().getAny(); ClassDescriptor anyClass = getBuiltIns(classDescriptor).getAny();
if (!hasDeclaredNonTrivialMember(CodegenUtil.EQUALS_METHOD_NAME, booleanClass, anyClass)) { if (!hasDeclaredNonTrivialMember(CodegenUtil.EQUALS_METHOD_NAME, booleanClass, anyClass)) {
generateEqualsMethod(properties); generateEqualsMethod(properties);
} }
@@ -162,7 +163,7 @@ public abstract class DataClassMethodGenerator {
for (CallableDescriptor overridden : OverrideResolver.getOverriddenDeclarations(function)) { for (CallableDescriptor overridden : OverrideResolver.getOverriddenDeclarations(function)) {
if (overridden instanceof CallableMemberDescriptor if (overridden instanceof CallableMemberDescriptor
&& ((CallableMemberDescriptor) overridden).getKind() == CallableMemberDescriptor.Kind.DECLARATION && ((CallableMemberDescriptor) overridden).getKind() == CallableMemberDescriptor.Kind.DECLARATION
&& !overridden.getContainingDeclaration().equals(KotlinBuiltIns.getInstance().getAny())) { && !overridden.getContainingDeclaration().equals(getBuiltIns(classDescriptor).getAny())) {
return true; return true;
} }
} }
@@ -57,6 +57,8 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.isBoolean;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.isPrimitiveClass;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isInterface; import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isInterface;
import static org.jetbrains.kotlin.load.java.JvmAnnotationNames.ABI_VERSION_FIELD_NAME; import static org.jetbrains.kotlin.load.java.JvmAnnotationNames.ABI_VERSION_FIELD_NAME;
import static org.jetbrains.kotlin.load.java.JvmAnnotationNames.KotlinSyntheticClass; import static org.jetbrains.kotlin.load.java.JvmAnnotationNames.KotlinSyntheticClass;
@@ -66,16 +68,6 @@ import static org.jetbrains.kotlin.types.TypeUtils.isNullableType;
import static org.jetbrains.org.objectweb.asm.Opcodes.*; import static org.jetbrains.org.objectweb.asm.Opcodes.*;
public class AsmUtil { public class AsmUtil {
private static final Set<ClassDescriptor> PRIMITIVE_NUMBER_CLASSES = Sets.newHashSet(
KotlinBuiltIns.getInstance().getByte(),
KotlinBuiltIns.getInstance().getShort(),
KotlinBuiltIns.getInstance().getInt(),
KotlinBuiltIns.getInstance().getLong(),
KotlinBuiltIns.getInstance().getFloat(),
KotlinBuiltIns.getInstance().getDouble(),
KotlinBuiltIns.getInstance().getChar()
);
private static final Set<Type> STRING_BUILDER_OBJECT_APPEND_ARG_TYPES = Sets.newHashSet( private static final Set<Type> STRING_BUILDER_OBJECT_APPEND_ARG_TYPES = Sets.newHashSet(
getType(String.class), getType(String.class),
getType(StringBuffer.class), getType(StringBuffer.class),
@@ -150,7 +142,7 @@ public class AsmUtil {
if (!(descriptor instanceof ClassDescriptor)) { if (!(descriptor instanceof ClassDescriptor)) {
return false; return false;
} }
return PRIMITIVE_NUMBER_CLASSES.contains(descriptor); return isPrimitiveClass((ClassDescriptor) descriptor) && !isBoolean((ClassDescriptor) descriptor);
} }
public static Type correctElementType(Type type) { public static Type correctElementType(Type type) {
@@ -22,7 +22,6 @@ import kotlin.Function1;
import kotlin.Unit; import kotlin.Unit;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.codegen.binding.CalculatedClosure; import org.jetbrains.kotlin.codegen.binding.CalculatedClosure;
import org.jetbrains.kotlin.codegen.context.ClosureContext; import org.jetbrains.kotlin.codegen.context.ClosureContext;
import org.jetbrains.kotlin.codegen.inline.InlineCodegenUtil; import org.jetbrains.kotlin.codegen.inline.InlineCodegenUtil;
@@ -51,6 +50,7 @@ import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isConst;
import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.CLOSURE; import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.CLOSURE;
import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.asmTypeForAnonymousClass; import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.asmTypeForAnonymousClass;
import static org.jetbrains.kotlin.load.java.JvmAnnotationNames.KotlinSyntheticClass; import static org.jetbrains.kotlin.load.java.JvmAnnotationNames.KotlinSyntheticClass;
import static org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilPackage.getBuiltIns;
import static org.jetbrains.kotlin.resolve.jvm.diagnostics.DiagnosticsPackage.OtherOrigin; import static org.jetbrains.kotlin.resolve.jvm.diagnostics.DiagnosticsPackage.OtherOrigin;
import static org.jetbrains.org.objectweb.asm.Opcodes.*; import static org.jetbrains.org.objectweb.asm.Opcodes.*;
@@ -107,7 +107,7 @@ public class ClosureCodegen extends MemberCodegen<JetElement> {
} }
else { else {
this.superInterfaceTypes = Collections.singletonList(samType.getType()); this.superInterfaceTypes = Collections.singletonList(samType.getType());
this.superClassType = KotlinBuiltIns.getInstance().getAnyType(); this.superClassType = getBuiltIns(funDescriptor).getAnyType();
} }
this.closure = bindingContext.get(CLOSURE, classDescriptor); this.closure = bindingContext.get(CLOSURE, classDescriptor);
@@ -364,8 +364,8 @@ public class ClosureCodegen extends MemberCodegen<JetElement> {
public static FunctionDescriptor getErasedInvokeFunction(@NotNull FunctionDescriptor elementDescriptor) { public static FunctionDescriptor getErasedInvokeFunction(@NotNull FunctionDescriptor elementDescriptor) {
int arity = elementDescriptor.getValueParameters().size(); int arity = elementDescriptor.getValueParameters().size();
ClassDescriptor elementClass = elementDescriptor.getExtensionReceiverParameter() == null ClassDescriptor elementClass = elementDescriptor.getExtensionReceiverParameter() == null
? KotlinBuiltIns.getInstance().getFunction(arity) ? getBuiltIns(elementDescriptor).getFunction(arity)
: KotlinBuiltIns.getInstance().getExtensionFunction(arity); : getBuiltIns(elementDescriptor).getExtensionFunction(arity);
return elementClass.getDefaultType().getMemberScope().getFunctions(OperatorConventions.INVOKE).iterator().next(); return elementClass.getDefaultType().getMemberScope().getFunctions(OperatorConventions.INVOKE).iterator().next();
} }
} }
@@ -85,6 +85,7 @@ import org.jetbrains.org.objectweb.asm.commons.Method;
import java.util.*; import java.util.*;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.isInt;
import static org.jetbrains.kotlin.codegen.AsmUtil.*; import static org.jetbrains.kotlin.codegen.AsmUtil.*;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.*; import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.*;
import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.*; import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.*;
@@ -97,6 +98,7 @@ import static org.jetbrains.kotlin.resolve.DescriptorUtils.isEnumEntry;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.isObject; import static org.jetbrains.kotlin.resolve.DescriptorUtils.isObject;
import static org.jetbrains.kotlin.resolve.calls.callUtil.CallUtilPackage.getResolvedCall; import static org.jetbrains.kotlin.resolve.calls.callUtil.CallUtilPackage.getResolvedCall;
import static org.jetbrains.kotlin.resolve.calls.callUtil.CallUtilPackage.getResolvedCallWithAssert; import static org.jetbrains.kotlin.resolve.calls.callUtil.CallUtilPackage.getResolvedCallWithAssert;
import static org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilPackage.getBuiltIns;
import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.*; import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.*;
import static org.jetbrains.kotlin.resolve.jvm.diagnostics.DiagnosticsPackage.OtherOrigin; import static org.jetbrains.kotlin.resolve.jvm.diagnostics.DiagnosticsPackage.OtherOrigin;
import static org.jetbrains.kotlin.resolve.jvm.diagnostics.DiagnosticsPackage.TraitImpl; import static org.jetbrains.kotlin.resolve.jvm.diagnostics.DiagnosticsPackage.TraitImpl;
@@ -105,8 +107,6 @@ import static org.jetbrains.kotlin.serialization.deserialization.Deserialization
import static org.jetbrains.org.objectweb.asm.Opcodes.*; import static org.jetbrains.org.objectweb.asm.Opcodes.*;
public class ExpressionCodegen extends JetVisitor<StackValue, StackValue> implements LocalLookup { public class ExpressionCodegen extends JetVisitor<StackValue, StackValue> implements LocalLookup {
private static final Set<DeclarationDescriptor> INTEGRAL_RANGES = KotlinBuiltIns.getInstance().getIntegralRanges();
private final GenerationState state; private final GenerationState state;
final JetTypeMapper typeMapper; final JetTypeMapper typeMapper;
private final BindingContext bindingContext; private final BindingContext bindingContext;
@@ -791,8 +791,9 @@ public class ExpressionCodegen extends JetVisitor<StackValue, StackValue> implem
StackValue result = invokeFunction(fakeCall, hasNextCall, StackValue.local(iteratorVarIndex, asmTypeForIterator)); StackValue result = invokeFunction(fakeCall, hasNextCall, StackValue.local(iteratorVarIndex, asmTypeForIterator));
result.put(result.type, v); result.put(result.type, v);
JetType type = hasNextCall.getResultingDescriptor().getReturnType(); FunctionDescriptor hasNext = hasNextCall.getResultingDescriptor();
assert type != null && JetTypeChecker.DEFAULT.isSubtypeOf(type, KotlinBuiltIns.getInstance().getBooleanType()); JetType type = hasNext.getReturnType();
assert type != null && JetTypeChecker.DEFAULT.isSubtypeOf(type, getBuiltIns(hasNext).getBooleanType());
Type asmType = asmType(type); Type asmType = asmType(type);
StackValue.coerce(asmType, Type.BOOLEAN_TYPE, v); StackValue.coerce(asmType, Type.BOOLEAN_TYPE, v);
@@ -3190,7 +3191,7 @@ public class ExpressionCodegen extends JetVisitor<StackValue, StackValue> implem
Type lhsType = expressionType(lhs); Type lhsType = expressionType(lhs);
boolean keepReturnValue = Boolean.TRUE.equals(bindingContext.get(VARIABLE_REASSIGNMENT, expression)) boolean keepReturnValue = Boolean.TRUE.equals(bindingContext.get(VARIABLE_REASSIGNMENT, expression))
|| !KotlinBuiltIns.getInstance().getUnitType().equals(descriptor.getReturnType()); || !KotlinBuiltIns.isUnit(descriptor.getReturnType());
callAugAssignMethod(expression, resolvedCall, callable, lhsType, keepReturnValue); callAugAssignMethod(expression, resolvedCall, callable, lhsType, keepReturnValue);
@@ -3527,7 +3528,7 @@ public class ExpressionCodegen extends JetVisitor<StackValue, StackValue> implem
assert operationDescriptor != null; assert operationDescriptor != null;
if (arrayType.getSort() == Type.ARRAY && if (arrayType.getSort() == Type.ARRAY &&
indices.size() == 1 && indices.size() == 1 &&
operationDescriptor.getValueParameters().get(0).getType().equals(KotlinBuiltIns.getInstance().getIntType())) { isInt(operationDescriptor.getValueParameters().get(0).getType())) {
assert type != null; assert type != null;
Type elementType; Type elementType;
if (KotlinBuiltIns.isArray(type)) { if (KotlinBuiltIns.isArray(type)) {
@@ -4043,7 +4044,7 @@ The "returned" value of try expression with no finally is either the last expres
JetType jetType = bindingContext.getType(rangeExpression); JetType jetType = bindingContext.getType(rangeExpression);
assert jetType != null; assert jetType != null;
DeclarationDescriptor descriptor = jetType.getConstructor().getDeclarationDescriptor(); DeclarationDescriptor descriptor = jetType.getConstructor().getDeclarationDescriptor();
return INTEGRAL_RANGES.contains(descriptor); return getBuiltIns(descriptor).getIntegralRanges().contains(descriptor);
} }
} }
return false; return false;
@@ -69,6 +69,7 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.isNullableAny;
import static org.jetbrains.kotlin.codegen.AsmUtil.*; import static org.jetbrains.kotlin.codegen.AsmUtil.*;
import static org.jetbrains.kotlin.codegen.JvmSerializationBindings.*; import static org.jetbrains.kotlin.codegen.JvmSerializationBindings.*;
import static org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.DECLARATION; import static org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.DECLARATION;
@@ -522,8 +523,7 @@ public class FunctionCodegen {
return name.equals("hashCode") || name.equals("toString"); return name.equals("hashCode") || name.equals("toString");
} }
else if (parameters.size() == 1 && name.equals("equals")) { else if (parameters.size() == 1 && name.equals("equals")) {
ValueParameterDescriptor parameter = parameters.get(0); return isNullableAny(parameters.get(0).getType());
return parameter.getType().equals(KotlinBuiltIns.getInstance().getNullableAnyType());
} }
return false; return false;
} }
@@ -77,6 +77,7 @@ import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.*;
import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.enumEntryNeedSubclass; import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.enumEntryNeedSubclass;
import static org.jetbrains.kotlin.resolve.DescriptorToSourceUtils.descriptorToDeclaration; import static org.jetbrains.kotlin.resolve.DescriptorToSourceUtils.descriptorToDeclaration;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.*; import static org.jetbrains.kotlin.resolve.DescriptorUtils.*;
import static org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilPackage.getBuiltIns;
import static org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilPackage.getSecondaryConstructors; import static org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilPackage.getSecondaryConstructors;
import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.*; import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.*;
import static org.jetbrains.kotlin.resolve.jvm.diagnostics.DiagnosticsPackage.*; import static org.jetbrains.kotlin.resolve.jvm.diagnostics.DiagnosticsPackage.*;
@@ -337,7 +338,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
if (superClassType == null) { if (superClassType == null) {
if (descriptor.getKind() == ClassKind.ENUM_CLASS) { if (descriptor.getKind() == ClassKind.ENUM_CLASS) {
superClassType = KotlinBuiltIns.getInstance().getEnumType(descriptor.getDefaultType()); superClassType = getBuiltIns(descriptor).getEnumType(descriptor.getDefaultType());
superClassAsmType = typeMapper.mapType(superClassType); superClassAsmType = typeMapper.mapType(superClassType);
} }
if (descriptor.getKind() == ClassKind.ENUM_ENTRY) { if (descriptor.getKind() == ClassKind.ENUM_ENTRY) {
@@ -422,8 +423,8 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
JetType paramType = function.getValueParameters().get(0).getType(); JetType paramType = function.getValueParameters().get(0).getType();
if (KotlinBuiltIns.isArray(returnType) && KotlinBuiltIns.isArray(paramType)) { if (KotlinBuiltIns.isArray(returnType) && KotlinBuiltIns.isArray(paramType)) {
JetType elementType = function.getTypeParameters().get(0).getDefaultType(); JetType elementType = function.getTypeParameters().get(0).getDefaultType();
if (JetTypeChecker.DEFAULT.equalTypes(elementType, KotlinBuiltIns.getInstance().getArrayElementType(returnType)) if (JetTypeChecker.DEFAULT.equalTypes(elementType, getBuiltIns(descriptor).getArrayElementType(returnType))
&& JetTypeChecker.DEFAULT.equalTypes(elementType, KotlinBuiltIns.getInstance().getArrayElementType(paramType))) { && JetTypeChecker.DEFAULT.equalTypes(elementType, getBuiltIns(descriptor).getArrayElementType(paramType))) {
return true; return true;
} }
} }
@@ -433,7 +434,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
} }
private void generateToArray() { private void generateToArray() {
KotlinBuiltIns builtIns = KotlinBuiltIns.getInstance(); KotlinBuiltIns builtIns = getBuiltIns(descriptor);
if (!isSubclass(descriptor, builtIns.getCollection())) return; if (!isSubclass(descriptor, builtIns.getCollection())) return;
int access = descriptor.getKind() == ClassKind.TRAIT ? int access = descriptor.getKind() == ClassKind.TRAIT ?
@@ -489,10 +490,9 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
@Override @Override
public void generateEqualsMethod(@NotNull List<PropertyDescriptor> properties) { public void generateEqualsMethod(@NotNull List<PropertyDescriptor> properties) {
KotlinBuiltIns builtins = getBuiltIns(descriptor);
FunctionDescriptor equalsFunction = CodegenUtil.getDeclaredFunctionByRawSignature( FunctionDescriptor equalsFunction = CodegenUtil.getDeclaredFunctionByRawSignature(
descriptor, Name.identifier(CodegenUtil.EQUALS_METHOD_NAME), descriptor, Name.identifier(CodegenUtil.EQUALS_METHOD_NAME), builtins.getBoolean(), builtins.getAny()
KotlinBuiltIns.getInstance().getBoolean(),
KotlinBuiltIns.getInstance().getAny()
); );
assert equalsFunction != null : String.format("Should be called only for classes with non-trivial '%s'. In %s, %s", assert equalsFunction != null : String.format("Should be called only for classes with non-trivial '%s'. In %s, %s",
@@ -564,8 +564,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
@Override @Override
public void generateHashCodeMethod(@NotNull List<PropertyDescriptor> properties) { public void generateHashCodeMethod(@NotNull List<PropertyDescriptor> properties) {
FunctionDescriptor hashCodeFunction = CodegenUtil.getDeclaredFunctionByRawSignature( FunctionDescriptor hashCodeFunction = CodegenUtil.getDeclaredFunctionByRawSignature(
descriptor, Name.identifier(CodegenUtil.HASH_CODE_METHOD_NAME), descriptor, Name.identifier(CodegenUtil.HASH_CODE_METHOD_NAME), getBuiltIns(descriptor).getInt()
KotlinBuiltIns.getInstance().getInt()
); );
assert hashCodeFunction != null : String.format("Should be called only for classes with non-trivial '%s'. In %s, %s", assert hashCodeFunction != null : String.format("Should be called only for classes with non-trivial '%s'. In %s, %s",
@@ -620,8 +619,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
@Override @Override
public void generateToStringMethod(@NotNull List<PropertyDescriptor> properties) { public void generateToStringMethod(@NotNull List<PropertyDescriptor> properties) {
FunctionDescriptor toString = CodegenUtil.getDeclaredFunctionByRawSignature( FunctionDescriptor toString = CodegenUtil.getDeclaredFunctionByRawSignature(
descriptor, Name.identifier(CodegenUtil.TO_STRING_METHOD_NAME), descriptor, Name.identifier(CodegenUtil.TO_STRING_METHOD_NAME), getBuiltIns(descriptor).getString()
KotlinBuiltIns.getInstance().getString()
); );
assert toString != null : String.format("Should be called only for classes with non-trivial '%s'. In %s, %s", assert toString != null : String.format("Should be called only for classes with non-trivial '%s'. In %s, %s",
@@ -795,7 +793,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
} }
private void generateEnumValuesMethod() { private void generateEnumValuesMethod() {
Type type = typeMapper.mapType(KotlinBuiltIns.getInstance().getArrayType(INVARIANT, descriptor.getDefaultType())); Type type = typeMapper.mapType(getBuiltIns(descriptor).getArrayType(INVARIANT, descriptor.getDefaultType()));
FunctionDescriptor valuesFunction = FunctionDescriptor valuesFunction =
KotlinPackage.single(descriptor.getStaticScope().getFunctions(ENUM_VALUES), new Function1<FunctionDescriptor, Boolean>() { KotlinPackage.single(descriptor.getStaticScope().getFunctions(ENUM_VALUES), new Function1<FunctionDescriptor, Boolean>() {
@@ -1445,7 +1443,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
reg += argTypes[i].getSize(); reg += argTypes[i].getSize();
} }
if (KotlinBuiltIns.getInstance().isCloneable(containingTrait) && traitMethod.getName().equals("clone")) { if (KotlinBuiltIns.isCloneable(containingTrait) && traitMethod.getName().equals("clone")) {
// A special hack for Cloneable: there's no kotlin/Cloneable$$TImpl class at runtime, // A special hack for Cloneable: there's no kotlin/Cloneable$$TImpl class at runtime,
// and its 'clone' method is actually located in java/lang/Object // and its 'clone' method is actually located in java/lang/Object
iv.invokespecial("java/lang/Object", "clone", "()Ljava/lang/Object;", false); iv.invokespecial("java/lang/Object", "clone", "()Ljava/lang/Object;", false);
@@ -1654,7 +1652,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
ExpressionCodegen codegen = createOrGetClInitCodegen(); ExpressionCodegen codegen = createOrGetClInitCodegen();
InstructionAdapter iv = codegen.v; InstructionAdapter iv = codegen.v;
Type arrayAsmType = typeMapper.mapType(KotlinBuiltIns.getInstance().getArrayType(INVARIANT, descriptor.getDefaultType())); Type arrayAsmType = typeMapper.mapType(getBuiltIns(descriptor).getArrayType(INVARIANT, descriptor.getDefaultType()));
v.newField(OtherOrigin(myClass), ACC_PRIVATE | ACC_STATIC | ACC_FINAL | ACC_SYNTHETIC, ENUM_VALUES_FIELD_NAME, v.newField(OtherOrigin(myClass), ACC_PRIVATE | ACC_STATIC | ACC_FINAL | ACC_SYNTHETIC, ENUM_VALUES_FIELD_NAME,
arrayAsmType.getDescriptor(), null, null); arrayAsmType.getDescriptor(), null, null);
@@ -17,7 +17,7 @@
package org.jetbrains.kotlin.codegen; package org.jetbrains.kotlin.codegen;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns; import org.jetbrains.kotlin.builtins.ReflectionTypes;
import org.jetbrains.kotlin.descriptors.*; import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.annotations.Annotations; import org.jetbrains.kotlin.descriptors.annotations.Annotations;
import org.jetbrains.kotlin.descriptors.impl.MutableClassDescriptor; import org.jetbrains.kotlin.descriptors.impl.MutableClassDescriptor;
@@ -27,13 +27,13 @@ import org.jetbrains.kotlin.name.FqName;
import org.jetbrains.kotlin.name.Name; import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.types.*; import org.jetbrains.kotlin.types.*;
import org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils; import org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils;
import org.jetbrains.kotlin.builtins.ReflectionTypes;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import static org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilPackage.getBuiltIns;
import static org.jetbrains.kotlin.resolve.jvm.TopDownAnalyzerFacadeForJVM.createJavaModule; import static org.jetbrains.kotlin.resolve.jvm.TopDownAnalyzerFacadeForJVM.createJavaModule;
public class JvmRuntimeTypes { public class JvmRuntimeTypes {
@@ -110,7 +110,7 @@ public class JvmRuntimeTypes {
classDescriptor.getMemberScope(typeArguments) classDescriptor.getMemberScope(typeArguments)
); );
JetType functionType = KotlinBuiltIns.getInstance().getFunctionType( JetType functionType = getBuiltIns(descriptor).getFunctionType(
Annotations.EMPTY, Annotations.EMPTY,
receiverParameter == null ? null : receiverParameter.getType(), receiverParameter == null ? null : receiverParameter.getType(),
ExpressionTypingUtils.getValueParametersTypes(descriptor.getValueParameters()), ExpressionTypingUtils.getValueParametersTypes(descriptor.getValueParameters()),
@@ -22,10 +22,8 @@ import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns; import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.builtins.PrimitiveType; import org.jetbrains.kotlin.builtins.PrimitiveType;
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor; import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor;
import org.jetbrains.kotlin.name.FqNameUnsafe;
import org.jetbrains.kotlin.name.Name; import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.resolve.CompileTimeConstantUtils; import org.jetbrains.kotlin.resolve.CompileTimeConstantUtils;
import org.jetbrains.kotlin.resolve.DescriptorUtils;
import org.jetbrains.kotlin.resolve.jvm.JvmPrimitiveType; import org.jetbrains.kotlin.resolve.jvm.JvmPrimitiveType;
import org.jetbrains.kotlin.types.expressions.OperatorConventions; import org.jetbrains.kotlin.types.expressions.OperatorConventions;
@@ -57,9 +55,6 @@ public class IntrinsicMethods {
private static final ToString TO_STRING = new ToString(); private static final ToString TO_STRING = new ToString();
private static final Clone CLONE = new Clone(); private static final Clone CLONE = new Clone();
private static final FqNameUnsafe KOTLIN_ANY_FQ_NAME = DescriptorUtils.getFqName(KotlinBuiltIns.getInstance().getAny());
private static final FqNameUnsafe KOTLIN_STRING_FQ_NAME = DescriptorUtils.getFqName(KotlinBuiltIns.getInstance().getString());
private final Map<String, IntrinsicMethod> namedMethods = new HashMap<String, IntrinsicMethod>(); private final Map<String, IntrinsicMethod> namedMethods = new HashMap<String, IntrinsicMethod>();
private static final IntrinsicMethod ARRAY_ITERATOR = new ArrayIterator(); private static final IntrinsicMethod ARRAY_ITERATOR = new ArrayIterator();
private final IntrinsicsMap intrinsicsMap = new IntrinsicsMap(); private final IntrinsicsMap intrinsicsMap = new IntrinsicsMap();
@@ -116,9 +111,9 @@ public class IntrinsicMethods {
declareIntrinsicFunction("Cloneable", "clone", 0, CLONE); declareIntrinsicFunction("Cloneable", "clone", 0, CLONE);
intrinsicsMap.registerIntrinsic(BUILT_INS_PACKAGE_FQ_NAME, KOTLIN_ANY_FQ_NAME, "toString", 0, TO_STRING); intrinsicsMap.registerIntrinsic(BUILT_INS_PACKAGE_FQ_NAME, KotlinBuiltIns.FQ_NAMES.any, "toString", 0, TO_STRING);
intrinsicsMap.registerIntrinsic(BUILT_INS_PACKAGE_FQ_NAME, KOTLIN_ANY_FQ_NAME, "identityEquals", 1, IDENTITY_EQUALS); intrinsicsMap.registerIntrinsic(BUILT_INS_PACKAGE_FQ_NAME, KotlinBuiltIns.FQ_NAMES.any, "identityEquals", 1, IDENTITY_EQUALS);
intrinsicsMap.registerIntrinsic(BUILT_INS_PACKAGE_FQ_NAME, KOTLIN_STRING_FQ_NAME, "plus", 1, STRING_PLUS); intrinsicsMap.registerIntrinsic(BUILT_INS_PACKAGE_FQ_NAME, KotlinBuiltIns.FQ_NAMES.string, "plus", 1, STRING_PLUS);
intrinsicsMap.registerIntrinsic(BUILT_INS_PACKAGE_FQ_NAME, null, "arrayOfNulls", 1, new NewArray()); intrinsicsMap.registerIntrinsic(BUILT_INS_PACKAGE_FQ_NAME, null, "arrayOfNulls", 1, new NewArray());
for (PrimitiveType type : PrimitiveType.values()) { for (PrimitiveType type : PrimitiveType.values()) {
@@ -67,11 +67,13 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.isUnit;
import static org.jetbrains.kotlin.codegen.AsmUtil.*; import static org.jetbrains.kotlin.codegen.AsmUtil.*;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.*; import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.*;
import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.*; import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.*;
import static org.jetbrains.kotlin.resolve.BindingContextUtils.isVarCapturedInClosure; import static org.jetbrains.kotlin.resolve.BindingContextUtils.isVarCapturedInClosure;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.*; import static org.jetbrains.kotlin.resolve.DescriptorUtils.*;
import static org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilPackage.getBuiltIns;
import static org.jetbrains.org.objectweb.asm.Opcodes.*; import static org.jetbrains.org.objectweb.asm.Opcodes.*;
public class JetTypeMapper { public class JetTypeMapper {
@@ -186,9 +188,7 @@ public class JetTypeMapper {
return Type.VOID_TYPE; return Type.VOID_TYPE;
} }
if (returnType.equals(KotlinBuiltIns.getInstance().getUnitType()) if (isUnit(returnType) && !TypeUtils.isNullableType(returnType) && !(descriptor instanceof PropertyGetterDescriptor)) {
&& !TypeUtils.isNullableType(returnType)
&& !(descriptor instanceof PropertyGetterDescriptor)) {
if (sw != null) { if (sw != null) {
sw.writeAsmType(Type.VOID_TYPE); sw.writeAsmType(Type.VOID_TYPE);
} }
@@ -936,8 +936,8 @@ public class JetTypeMapper {
ClassDescriptor containingDeclaration = descriptor.getContainingDeclaration(); ClassDescriptor containingDeclaration = descriptor.getContainingDeclaration();
if (containingDeclaration.getKind() == ClassKind.ENUM_CLASS || containingDeclaration.getKind() == ClassKind.ENUM_ENTRY) { if (containingDeclaration.getKind() == ClassKind.ENUM_CLASS || containingDeclaration.getKind() == ClassKind.ENUM_ENTRY) {
writeParameter(sw, JvmMethodParameterKind.ENUM_NAME_OR_ORDINAL, KotlinBuiltIns.getInstance().getStringType()); writeParameter(sw, JvmMethodParameterKind.ENUM_NAME_OR_ORDINAL, getBuiltIns(descriptor).getStringType());
writeParameter(sw, JvmMethodParameterKind.ENUM_NAME_OR_ORDINAL, KotlinBuiltIns.getInstance().getIntType()); writeParameter(sw, JvmMethodParameterKind.ENUM_NAME_OR_ORDINAL, getBuiltIns(descriptor).getIntType());
} }
if (closure == null) return; if (closure == null) return;
@@ -194,7 +194,7 @@ public class InjectorForLazyResolveWithJava {
this.argumentTypeResolver = new ArgumentTypeResolver(); this.argumentTypeResolver = new ArgumentTypeResolver();
this.expressionTypingComponents = new ExpressionTypingComponents(); this.expressionTypingComponents = new ExpressionTypingComponents();
this.expressionTypingServices = new ExpressionTypingServices(expressionTypingComponents); this.expressionTypingServices = new ExpressionTypingServices(expressionTypingComponents);
this.callExpressionResolver = new CallExpressionResolver(callResolver); this.callExpressionResolver = new CallExpressionResolver(callResolver, kotlinBuiltIns);
this.controlStructureTypingUtils = new ControlStructureTypingUtils(callResolver); this.controlStructureTypingUtils = new ControlStructureTypingUtils(callResolver);
this.descriptorResolver = new DescriptorResolver(); this.descriptorResolver = new DescriptorResolver();
this.delegatedPropertyResolver = new DelegatedPropertyResolver(); this.delegatedPropertyResolver = new DelegatedPropertyResolver();
@@ -221,7 +221,7 @@ public class InjectorForReplWithJava {
this.argumentTypeResolver = new ArgumentTypeResolver(); this.argumentTypeResolver = new ArgumentTypeResolver();
this.expressionTypingComponents = new ExpressionTypingComponents(); this.expressionTypingComponents = new ExpressionTypingComponents();
this.expressionTypingServices = new ExpressionTypingServices(expressionTypingComponents); this.expressionTypingServices = new ExpressionTypingServices(expressionTypingComponents);
this.callExpressionResolver = new CallExpressionResolver(callResolver); this.callExpressionResolver = new CallExpressionResolver(callResolver, kotlinBuiltIns);
this.controlStructureTypingUtils = new ControlStructureTypingUtils(callResolver); this.controlStructureTypingUtils = new ControlStructureTypingUtils(callResolver);
this.descriptorResolver = new DescriptorResolver(); this.descriptorResolver = new DescriptorResolver();
this.delegatedPropertyResolver = new DelegatedPropertyResolver(); this.delegatedPropertyResolver = new DelegatedPropertyResolver();
@@ -219,7 +219,7 @@ public class InjectorForTopDownAnalyzerForJvm {
this.argumentTypeResolver = new ArgumentTypeResolver(); this.argumentTypeResolver = new ArgumentTypeResolver();
this.expressionTypingComponents = new ExpressionTypingComponents(); this.expressionTypingComponents = new ExpressionTypingComponents();
this.expressionTypingServices = new ExpressionTypingServices(expressionTypingComponents); this.expressionTypingServices = new ExpressionTypingServices(expressionTypingComponents);
this.callExpressionResolver = new CallExpressionResolver(callResolver); this.callExpressionResolver = new CallExpressionResolver(callResolver, kotlinBuiltIns);
this.controlStructureTypingUtils = new ControlStructureTypingUtils(callResolver); this.controlStructureTypingUtils = new ControlStructureTypingUtils(callResolver);
this.descriptorResolver = new DescriptorResolver(); this.descriptorResolver = new DescriptorResolver();
this.delegatedPropertyResolver = new DelegatedPropertyResolver(); this.delegatedPropertyResolver = new DelegatedPropertyResolver();
@@ -35,6 +35,7 @@ import org.jetbrains.kotlin.types.*;
import java.util.*; import java.util.*;
import static org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilPackage.getBuiltIns;
import static org.jetbrains.kotlin.types.Variance.INVARIANT; import static org.jetbrains.kotlin.types.Variance.INVARIANT;
public class SingleAbstractMethodUtils { public class SingleAbstractMethodUtils {
@@ -121,8 +122,7 @@ public class SingleAbstractMethodUtils {
for (ValueParameterDescriptor parameter : valueParameters) { for (ValueParameterDescriptor parameter : valueParameters) {
parameterTypes.add(parameter.getType()); parameterTypes.add(parameter.getType());
} }
return KotlinBuiltIns.getInstance().getFunctionType( return getBuiltIns(function).getFunctionType(Annotations.EMPTY, null, parameterTypes, returnType);
Annotations.EMPTY, null, parameterTypes, returnType);
} }
private static boolean isSamInterface(@NotNull ClassDescriptor klass) { private static boolean isSamInterface(@NotNull ClassDescriptor klass) {
@@ -50,6 +50,7 @@ import java.util.*;
import static org.jetbrains.kotlin.load.java.components.TypeUsage.*; import static org.jetbrains.kotlin.load.java.components.TypeUsage.*;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.getFqName; import static org.jetbrains.kotlin.resolve.DescriptorUtils.getFqName;
import static org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilPackage.getBuiltIns;
import static org.jetbrains.kotlin.types.Variance.INVARIANT; import static org.jetbrains.kotlin.types.Variance.INVARIANT;
public class SignaturesPropagationData { public class SignaturesPropagationData {
@@ -263,7 +264,7 @@ public class SignaturesPropagationData {
stableName != null ? stableName : originalParam.getName(), stableName != null ? stableName : originalParam.getName(),
altType, altType,
originalParam.declaresDefaultValue(), originalParam.declaresDefaultValue(),
varargCheckResult.isVararg ? KotlinBuiltIns.getInstance().getArrayElementType(altType) : null, varargCheckResult.isVararg ? getBuiltIns(originalParam).getArrayElementType(altType) : null,
SourceElement.NO_SOURCE SourceElement.NO_SOURCE
)); ));
} }
@@ -128,7 +128,7 @@ public class InjectorForBodyResolve {
this.argumentTypeResolver = new ArgumentTypeResolver(); this.argumentTypeResolver = new ArgumentTypeResolver();
this.expressionTypingComponents = new ExpressionTypingComponents(); this.expressionTypingComponents = new ExpressionTypingComponents();
this.expressionTypingServices = new ExpressionTypingServices(expressionTypingComponents); this.expressionTypingServices = new ExpressionTypingServices(expressionTypingComponents);
this.callExpressionResolver = new CallExpressionResolver(callResolver); this.callExpressionResolver = new CallExpressionResolver(callResolver, kotlinBuiltIns);
this.controlStructureTypingUtils = new ControlStructureTypingUtils(callResolver); this.controlStructureTypingUtils = new ControlStructureTypingUtils(callResolver);
this.descriptorResolver = new DescriptorResolver(); this.descriptorResolver = new DescriptorResolver();
this.delegatedPropertyResolver = new DelegatedPropertyResolver(); this.delegatedPropertyResolver = new DelegatedPropertyResolver();
@@ -157,7 +157,7 @@ public class InjectorForLazyBodyResolve {
this.argumentTypeResolver = new ArgumentTypeResolver(); this.argumentTypeResolver = new ArgumentTypeResolver();
this.expressionTypingComponents = new ExpressionTypingComponents(); this.expressionTypingComponents = new ExpressionTypingComponents();
this.expressionTypingServices = new ExpressionTypingServices(expressionTypingComponents); this.expressionTypingServices = new ExpressionTypingServices(expressionTypingComponents);
this.callExpressionResolver = new CallExpressionResolver(callResolver); this.callExpressionResolver = new CallExpressionResolver(callResolver, kotlinBuiltIns);
this.controlStructureTypingUtils = new ControlStructureTypingUtils(callResolver); this.controlStructureTypingUtils = new ControlStructureTypingUtils(callResolver);
this.descriptorResolver = new DescriptorResolver(); this.descriptorResolver = new DescriptorResolver();
this.delegatedPropertyResolver = new DelegatedPropertyResolver(); this.delegatedPropertyResolver = new DelegatedPropertyResolver();
@@ -155,7 +155,7 @@ public class InjectorForLazyLocalClassifierAnalyzer {
this.argumentTypeResolver = new ArgumentTypeResolver(); this.argumentTypeResolver = new ArgumentTypeResolver();
this.expressionTypingComponents = new ExpressionTypingComponents(); this.expressionTypingComponents = new ExpressionTypingComponents();
this.expressionTypingServices = new ExpressionTypingServices(expressionTypingComponents); this.expressionTypingServices = new ExpressionTypingServices(expressionTypingComponents);
this.callExpressionResolver = new CallExpressionResolver(callResolver); this.callExpressionResolver = new CallExpressionResolver(callResolver, kotlinBuiltIns);
this.controlStructureTypingUtils = new ControlStructureTypingUtils(callResolver); this.controlStructureTypingUtils = new ControlStructureTypingUtils(callResolver);
this.descriptorResolver = new DescriptorResolver(); this.descriptorResolver = new DescriptorResolver();
this.delegatedPropertyResolver = new DelegatedPropertyResolver(); this.delegatedPropertyResolver = new DelegatedPropertyResolver();
@@ -136,7 +136,7 @@ public class InjectorForLazyResolve {
this.argumentTypeResolver = new ArgumentTypeResolver(); this.argumentTypeResolver = new ArgumentTypeResolver();
this.expressionTypingComponents = new ExpressionTypingComponents(); this.expressionTypingComponents = new ExpressionTypingComponents();
this.expressionTypingServices = new ExpressionTypingServices(expressionTypingComponents); this.expressionTypingServices = new ExpressionTypingServices(expressionTypingComponents);
this.callExpressionResolver = new CallExpressionResolver(callResolver); this.callExpressionResolver = new CallExpressionResolver(callResolver, kotlinBuiltIns);
this.controlStructureTypingUtils = new ControlStructureTypingUtils(callResolver); this.controlStructureTypingUtils = new ControlStructureTypingUtils(callResolver);
this.descriptorResolver = new DescriptorResolver(); this.descriptorResolver = new DescriptorResolver();
this.delegatedPropertyResolver = new DelegatedPropertyResolver(); this.delegatedPropertyResolver = new DelegatedPropertyResolver();
@@ -112,7 +112,7 @@ public class InjectorForMacros {
this.defaultProvider = DefaultProvider.INSTANCE$; this.defaultProvider = DefaultProvider.INSTANCE$;
this.symbolUsageValidator = defaultProvider.getSymbolUsageValidator(); this.symbolUsageValidator = defaultProvider.getSymbolUsageValidator();
this.statementFilter = new StatementFilter(); this.statementFilter = new StatementFilter();
this.callExpressionResolver = new CallExpressionResolver(getCallResolver()); this.callExpressionResolver = new CallExpressionResolver(getCallResolver(), kotlinBuiltIns);
this.controlStructureTypingUtils = new ControlStructureTypingUtils(getCallResolver()); this.controlStructureTypingUtils = new ControlStructureTypingUtils(getCallResolver());
this.descriptorResolver = new DescriptorResolver(); this.descriptorResolver = new DescriptorResolver();
this.delegatedPropertyResolver = new DelegatedPropertyResolver(); this.delegatedPropertyResolver = new DelegatedPropertyResolver();
@@ -34,6 +34,8 @@ import org.jetbrains.kotlin.types.checker.JetTypeChecker;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import static org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilPackage.getBuiltIns;
public class MainFunctionDetector { public class MainFunctionDetector {
private final NotNullFunction<JetNamedFunction, FunctionDescriptor> getFunctionDescriptor; private final NotNullFunction<JetNamedFunction, FunctionDescriptor> getFunctionDescriptor;
@@ -69,14 +71,13 @@ public class MainFunctionDetector {
ValueParameterDescriptor parameter = parameters.get(0); ValueParameterDescriptor parameter = parameters.get(0);
JetType parameterType = parameter.getType(); JetType parameterType = parameter.getType();
KotlinBuiltIns kotlinBuiltIns = KotlinBuiltIns.getInstance();
if (!KotlinBuiltIns.isArray(parameterType)) return false; if (!KotlinBuiltIns.isArray(parameterType)) return false;
List<TypeProjection> typeArguments = parameterType.getArguments(); List<TypeProjection> typeArguments = parameterType.getArguments();
if (typeArguments.size() != 1) return false; if (typeArguments.size() != 1) return false;
JetType typeArgument = typeArguments.get(0).getType(); JetType typeArgument = typeArguments.get(0).getType();
if (!JetTypeChecker.DEFAULT.equalTypes(typeArgument, kotlinBuiltIns.getStringType())) return false; if (!JetTypeChecker.DEFAULT.equalTypes(typeArgument, getBuiltIns(functionDescriptor).getStringType())) return false;
if (DescriptorUtils.isTopLevelDeclaration(functionDescriptor)) return true; if (DescriptorUtils.isTopLevelDeclaration(functionDescriptor)) return true;
@@ -20,7 +20,6 @@ import com.google.common.base.Function;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.intellij.lang.ASTNode; import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.Condition;
import com.intellij.psi.PsiComment; import com.intellij.psi.PsiComment;
import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFile;
@@ -241,7 +240,7 @@ public class JetPsiUtil {
List<JetAnnotationEntry> annotationEntries = modifierList.getAnnotationEntries(); List<JetAnnotationEntry> annotationEntries = modifierList.getAnnotationEntries();
for (JetAnnotationEntry annotation : annotationEntries) { for (JetAnnotationEntry annotation : annotationEntries) {
Name shortName = getShortName(annotation); Name shortName = getShortName(annotation);
if (KotlinBuiltIns.getInstance().getDeprecatedAnnotation().getName().equals(shortName)) { if (KotlinBuiltIns.FQ_NAMES.deprecated.shortName().equals(shortName)) {
return true; return true;
} }
} }
@@ -332,14 +331,6 @@ public class JetPsiUtil {
return qualifiedParent.getReceiverExpression() == expression || isLHSOfDot(qualifiedParent); return qualifiedParent.getReceiverExpression() == expression || isLHSOfDot(qualifiedParent);
} }
public static boolean isVoidType(@Nullable JetTypeReference typeReference) {
if (typeReference == null) {
return false;
}
return KotlinBuiltIns.getInstance().getUnit().getName().asString().equals(typeReference.getText());
}
// SCRIPT: is declaration in script? // SCRIPT: is declaration in script?
public static boolean isScriptDeclaration(@NotNull JetDeclaration namedDeclaration) { public static boolean isScriptDeclaration(@NotNull JetDeclaration namedDeclaration) {
return getScript(namedDeclaration) != null; return getScript(namedDeclaration) != null;
@@ -732,16 +723,6 @@ public class JetPsiUtil {
return null; return null;
} }
@Nullable
public static PsiElement skipSiblingsForwardByPredicate(@Nullable PsiElement element, Predicate<PsiElement> elementsToSkip) {
if (element == null) return null;
for (PsiElement e = element.getNextSibling(); e != null; e = e.getNextSibling()) {
if (elementsToSkip.apply(e)) continue;
return e;
}
return null;
}
// Delete given element and all the elements separating it from the neighboring elements of the same class // Delete given element and all the elements separating it from the neighboring elements of the same class
public static void deleteElementWithDelimiters(@NotNull PsiElement element) { public static void deleteElementWithDelimiters(@NotNull PsiElement element) {
PsiElement paramBefore = PsiTreeUtil.getPrevSiblingOfType(element, element.getClass()); PsiElement paramBefore = PsiTreeUtil.getPrevSiblingOfType(element, element.getClass());
@@ -30,7 +30,6 @@ import kotlin.Unit;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.ReadOnly; import org.jetbrains.annotations.ReadOnly;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.descriptors.*; import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor; import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor;
import org.jetbrains.kotlin.lexer.JetTokens; import org.jetbrains.kotlin.lexer.JetTokens;
@@ -50,6 +49,7 @@ import static org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.*;
import static org.jetbrains.kotlin.diagnostics.Errors.*; import static org.jetbrains.kotlin.diagnostics.Errors.*;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.classCanHaveAbstractMembers; import static org.jetbrains.kotlin.resolve.DescriptorUtils.classCanHaveAbstractMembers;
import static org.jetbrains.kotlin.resolve.OverridingUtil.OverrideCompatibilityInfo.Result.OVERRIDABLE; import static org.jetbrains.kotlin.resolve.OverridingUtil.OverrideCompatibilityInfo.Result.OVERRIDABLE;
import static org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilPackage.getBuiltIns;
public class OverrideResolver { public class OverrideResolver {
@@ -722,7 +722,7 @@ public class OverrideResolver {
@NotNull @NotNull
private JetAnnotationEntry findDataAnnotationForDataClass(@NotNull DeclarationDescriptor dataClass) { private JetAnnotationEntry findDataAnnotationForDataClass(@NotNull DeclarationDescriptor dataClass) {
ClassDescriptor stdDataClassAnnotation = KotlinBuiltIns.getInstance().getDataClassAnnotation(); ClassDescriptor stdDataClassAnnotation = getBuiltIns(dataClass).getDataClassAnnotation();
AnnotationDescriptor annotation = dataClass.getAnnotations().findAnnotation(DescriptorUtils.getFqNameSafe(stdDataClassAnnotation)); AnnotationDescriptor annotation = dataClass.getAnnotations().findAnnotation(DescriptorUtils.getFqNameSafe(stdDataClassAnnotation));
if (annotation == null) { if (annotation == null) {
throw new IllegalStateException("No data annotation is found for data class " + dataClass); throw new IllegalStateException("No data annotation is found for data class " + dataClass);
@@ -231,8 +231,8 @@ public class TypeResolver(
val returnTypeRef = type.getReturnTypeReference() val returnTypeRef = type.getReturnTypeReference()
val returnType = if (returnTypeRef != null) val returnType = if (returnTypeRef != null)
resolveType(c.noBareTypes(), returnTypeRef) resolveType(c.noBareTypes(), returnTypeRef)
else KotlinBuiltIns.getInstance().getUnitType() else moduleDescriptor.builtIns.getUnitType()
result = type(KotlinBuiltIns.getInstance().getFunctionType(annotations, receiverType, parameterTypes, returnType)) result = type(moduleDescriptor.builtIns.getFunctionType(annotations, receiverType, parameterTypes, returnType))
} }
override fun visitDynamicType(type: JetDynamicType) { override fun visitDynamicType(type: JetDynamicType) {
@@ -60,9 +60,11 @@ import static org.jetbrains.kotlin.types.TypeUtils.NO_EXPECTED_TYPE;
public class CallExpressionResolver { public class CallExpressionResolver {
private final CallResolver callResolver; private final CallResolver callResolver;
private final KotlinBuiltIns builtIns;
public CallExpressionResolver(@NotNull CallResolver callResolver) { public CallExpressionResolver(@NotNull CallResolver callResolver, @NotNull KotlinBuiltIns builtIns) {
this.callResolver = callResolver; this.callResolver = callResolver;
this.builtIns = builtIns;
} }
private ExpressionTypingServices expressionTypingServices; private ExpressionTypingServices expressionTypingServices;
@@ -349,7 +351,7 @@ public class CallExpressionResolver {
CompileTimeConstant<?> value = ConstantExpressionEvaluator.evaluate(expression, context.trace, context.expectedType); CompileTimeConstant<?> value = ConstantExpressionEvaluator.evaluate(expression, context.trace, context.expectedType);
if (value instanceof IntegerValueConstant && ((IntegerValueConstant) value).isPure()) { if (value instanceof IntegerValueConstant && ((IntegerValueConstant) value).isPure()) {
return BasicExpressionTypingVisitor.createCompileTimeConstantTypeInfo(value, expression, context); return ExpressionTypingUtils.createCompileTimeConstantTypeInfo(value, expression, context, builtIns);
} }
JetTypeInfo typeInfo; JetTypeInfo typeInfo;
@@ -20,7 +20,6 @@ import com.intellij.openapi.util.Pair;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.JetNodeTypes; import org.jetbrains.kotlin.JetNodeTypes;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.descriptors.*; import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor; import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor;
import org.jetbrains.kotlin.psi.*; import org.jetbrains.kotlin.psi.*;
@@ -34,6 +33,7 @@ import org.jetbrains.kotlin.resolve.scopes.receivers.*;
import org.jetbrains.kotlin.types.JetType; import org.jetbrains.kotlin.types.JetType;
import org.jetbrains.kotlin.types.TypeUtils; import org.jetbrains.kotlin.types.TypeUtils;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.isNullableNothing;
import static org.jetbrains.kotlin.resolve.BindingContext.REFERENCE_TARGET; import static org.jetbrains.kotlin.resolve.BindingContext.REFERENCE_TARGET;
/** /**
@@ -66,7 +66,7 @@ public class DataFlowValueFactory {
if (constantExpression.getNode().getElementType() == JetNodeTypes.NULL) return DataFlowValue.NULL; if (constantExpression.getNode().getElementType() == JetNodeTypes.NULL) return DataFlowValue.NULL;
} }
if (type.isError()) return DataFlowValue.ERROR; if (type.isError()) return DataFlowValue.ERROR;
if (KotlinBuiltIns.getInstance().getNullableNothingType().equals(type)) { if (isNullableNothing(type)) {
return DataFlowValue.NULL; // 'null' is the only inhabitant of 'Nothing?' return DataFlowValue.NULL; // 'null' is the only inhabitant of 'Nothing?'
} }
IdentifierInfo result = getIdForStableIdentifier(expression, bindingContext, containingDeclarationOrModule); IdentifierInfo result = getIdForStableIdentifier(expression, bindingContext, containingDeclarationOrModule);
@@ -55,6 +55,7 @@ import org.jetbrains.kotlin.psi.ValueArgument
import java.util.ArrayList import java.util.ArrayList
import org.jetbrains.kotlin.psi.JetFunctionLiteralExpression import org.jetbrains.kotlin.psi.JetFunctionLiteralExpression
import org.jetbrains.kotlin.psi.JetPsiUtil import org.jetbrains.kotlin.psi.JetPsiUtil
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
object DynamicCallableDescriptors { object DynamicCallableDescriptors {
@@ -195,7 +196,7 @@ object DynamicCallableDescriptors {
val receiverType = funLiteral.getReceiverTypeReference()?.let { DynamicType } val receiverType = funLiteral.getReceiverTypeReference()?.let { DynamicType }
val parameterTypes = funLiteral.getValueParameters().map { DynamicType } val parameterTypes = funLiteral.getValueParameters().map { DynamicType }
return KotlinBuiltIns.getInstance().getFunctionType(Annotations.EMPTY, receiverType, parameterTypes, DynamicType) return owner.builtIns.getFunctionType(Annotations.EMPTY, receiverType, parameterTypes, DynamicType)
} }
for (arg in call.getValueArguments()) { for (arg in call.getValueArguments()) {
@@ -213,7 +214,7 @@ object DynamicCallableDescriptors {
arg.getSpreadElement() != null -> { arg.getSpreadElement() != null -> {
hasSpreadOperator = true hasSpreadOperator = true
outType = KotlinBuiltIns.getInstance().getArrayType(Variance.OUT_VARIANCE, DynamicType) outType = owner.builtIns.getArrayType(Variance.OUT_VARIANCE, DynamicType)
varargElementType = DynamicType varargElementType = DynamicType
} }
@@ -27,7 +27,6 @@ import org.jetbrains.kotlin.psi.*;
import org.jetbrains.kotlin.resolve.BindingContext; import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.BindingTrace; import org.jetbrains.kotlin.resolve.BindingTrace;
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils; import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils;
import org.jetbrains.kotlin.resolve.DescriptorUtils;
import org.jetbrains.kotlin.resolve.calls.callUtil.CallUtilPackage; import org.jetbrains.kotlin.resolve.calls.callUtil.CallUtilPackage;
import org.jetbrains.kotlin.resolve.calls.model.ArgumentMapping; import org.jetbrains.kotlin.resolve.calls.model.ArgumentMapping;
import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch; import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch;
@@ -71,9 +70,7 @@ public class InlineUtil {
} }
private static boolean hasInlineOption(@NotNull ValueParameterDescriptor descriptor, @NotNull InlineOption option) { private static boolean hasInlineOption(@NotNull ValueParameterDescriptor descriptor, @NotNull InlineOption option) {
AnnotationDescriptor annotation = descriptor.getAnnotations().findAnnotation( AnnotationDescriptor annotation = descriptor.getAnnotations().findAnnotation(KotlinBuiltIns.FQ_NAMES.inlineOptions);
DescriptorUtils.getFqNameSafe(KotlinBuiltIns.getInstance().getInlineOptionsClassAnnotation())
);
if (annotation != null) { if (annotation != null) {
CompileTimeConstant<?> argument = firstOrNull(annotation.getAllValueArguments().values()); CompileTimeConstant<?> argument = firstOrNull(annotation.getAllValueArguments().values());
if (argument instanceof ArrayValue) { if (argument instanceof ArrayValue) {
@@ -33,7 +33,6 @@ import org.jetbrains.kotlin.resolve.DescriptorUtils
public class DeprecatedSymbolValidator : SymbolUsageValidator { public class DeprecatedSymbolValidator : SymbolUsageValidator {
private val JAVA_DEPRECATED = FqName(javaClass<Deprecated>().getName()) private val JAVA_DEPRECATED = FqName(javaClass<Deprecated>().getName())
private val KOTLIN_DEPRECATED = DescriptorUtils.getFqNameSafe(KotlinBuiltIns.getInstance().getDeprecatedAnnotation())
override fun validateCall(targetDescriptor: CallableDescriptor, trace: BindingTrace, element: PsiElement) { override fun validateCall(targetDescriptor: CallableDescriptor, trace: BindingTrace, element: PsiElement) {
val deprecated = targetDescriptor.getDeprecatedAnnotation() val deprecated = targetDescriptor.getDeprecatedAnnotation()
@@ -86,7 +85,7 @@ public class DeprecatedSymbolValidator : SymbolUsageValidator {
} }
private fun DeclarationDescriptor.getDeclaredDeprecatedAnnotation(): AnnotationDescriptor? { private fun DeclarationDescriptor.getDeclaredDeprecatedAnnotation(): AnnotationDescriptor? {
return getAnnotations().findAnnotation(KOTLIN_DEPRECATED) ?: getAnnotations().findAnnotation(JAVA_DEPRECATED) return getAnnotations().findAnnotation(KotlinBuiltIns.FQ_NAMES.deprecated) ?: getAnnotations().findAnnotation(JAVA_DEPRECATED)
} }
private fun createDeprecationDiagnostic(element: PsiElement, descriptor: DeclarationDescriptor, deprecated: AnnotationDescriptor): Diagnostic { private fun createDeprecationDiagnostic(element: PsiElement, descriptor: DeclarationDescriptor, deprecated: AnnotationDescriptor): Diagnostic {
@@ -36,7 +36,6 @@ import org.jetbrains.kotlin.lexer.JetTokens;
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.*; import org.jetbrains.kotlin.resolve.*;
import org.jetbrains.kotlin.resolve.calls.ArgumentTypeResolver;
import org.jetbrains.kotlin.resolve.calls.CallExpressionResolver; import org.jetbrains.kotlin.resolve.calls.CallExpressionResolver;
import org.jetbrains.kotlin.resolve.calls.context.BasicCallResolutionContext; import org.jetbrains.kotlin.resolve.calls.context.BasicCallResolutionContext;
import org.jetbrains.kotlin.resolve.calls.context.CheckValueArgumentsMode; import org.jetbrains.kotlin.resolve.calls.context.CheckValueArgumentsMode;
@@ -66,6 +65,7 @@ import org.jetbrains.kotlin.resolve.scopes.receivers.TransientReceiver;
import org.jetbrains.kotlin.resolve.validation.SymbolUsageValidator; import org.jetbrains.kotlin.resolve.validation.SymbolUsageValidator;
import org.jetbrains.kotlin.types.*; import org.jetbrains.kotlin.types.*;
import org.jetbrains.kotlin.types.checker.JetTypeChecker; import org.jetbrains.kotlin.types.checker.JetTypeChecker;
import org.jetbrains.kotlin.types.expressions.typeInfoFactory.TypeInfoFactoryPackage;
import org.jetbrains.kotlin.util.slicedMap.WritableSlice; import org.jetbrains.kotlin.util.slicedMap.WritableSlice;
import org.jetbrains.kotlin.utils.ThrowingList; import org.jetbrains.kotlin.utils.ThrowingList;
@@ -89,7 +89,6 @@ import static org.jetbrains.kotlin.types.TypeUtils.noExpectedType;
import static org.jetbrains.kotlin.types.expressions.ControlStructureTypingUtils.createCallForSpecialConstruction; import static org.jetbrains.kotlin.types.expressions.ControlStructureTypingUtils.createCallForSpecialConstruction;
import static org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils.*; import static org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils.*;
import static org.jetbrains.kotlin.types.expressions.TypeReconstructionUtil.reconstructBareType; import static org.jetbrains.kotlin.types.expressions.TypeReconstructionUtil.reconstructBareType;
import org.jetbrains.kotlin.types.expressions.typeInfoFactory.TypeInfoFactoryPackage;
@SuppressWarnings("SuspiciousMethodCalls") @SuppressWarnings("SuspiciousMethodCalls")
public class BasicExpressionTypingVisitor extends ExpressionTypingVisitor { public class BasicExpressionTypingVisitor extends ExpressionTypingVisitor {
@@ -132,7 +131,7 @@ public class BasicExpressionTypingVisitor extends ExpressionTypingVisitor {
} }
assert value != null : "CompileTimeConstant should be evaluated for constant expression or an error should be recorded " + expression.getText(); assert value != null : "CompileTimeConstant should be evaluated for constant expression or an error should be recorded " + expression.getText();
return createCompileTimeConstantTypeInfo(value, expression, context); return createCompileTimeConstantTypeInfo(value, expression, context, components.builtIns);
} }
@NotNull @NotNull
@@ -188,7 +187,7 @@ public class BasicExpressionTypingVisitor extends ExpressionTypingVisitor {
JetTypeInfo typeInfo = facade.getTypeInfo(left, contextWithNoExpectedType); JetTypeInfo typeInfo = facade.getTypeInfo(left, contextWithNoExpectedType);
JetType subjectType = typeInfo.getType(); JetType subjectType = typeInfo.getType();
JetType targetType = reconstructBareType(right, possiblyBareTarget, subjectType, context.trace); JetType targetType = reconstructBareType(right, possiblyBareTarget, subjectType, context.trace, components.builtIns);
if (subjectType != null) { if (subjectType != null) {
checkBinaryWithTypeRHS(expression, contextWithNoExpectedType, targetType, subjectType); checkBinaryWithTypeRHS(expression, contextWithNoExpectedType, targetType, subjectType);
@@ -911,27 +910,12 @@ public class BasicExpressionTypingVisitor extends ExpressionTypingVisitor {
CompileTimeConstant<?> value = ConstantExpressionEvaluator.evaluate(expression, contextWithExpectedType.trace, CompileTimeConstant<?> value = ConstantExpressionEvaluator.evaluate(expression, contextWithExpectedType.trace,
contextWithExpectedType.expectedType); contextWithExpectedType.expectedType);
if (value != null) { if (value != null) {
return createCompileTimeConstantTypeInfo(value, expression, contextWithExpectedType); return createCompileTimeConstantTypeInfo(value, expression, contextWithExpectedType, components.builtIns);
} }
return DataFlowUtils.checkType(typeInfo.replaceType(result), expression, contextWithExpectedType); return DataFlowUtils.checkType(typeInfo.replaceType(result), expression, contextWithExpectedType);
} }
@NotNull
public static JetTypeInfo createCompileTimeConstantTypeInfo(
@NotNull CompileTimeConstant<?> value,
@NotNull JetExpression expression,
@NotNull ExpressionTypingContext context
) {
JetType expressionType = value.getType(KotlinBuiltIns.getInstance());
if (value instanceof IntegerValueTypeConstant && context.contextDependency == INDEPENDENT) {
expressionType = ((IntegerValueTypeConstant) value).getType(context.expectedType);
ArgumentTypeResolver.updateNumberType(expressionType, expression, context);
}
return TypeInfoFactoryPackage.createCheckedTypeInfo(expressionType, context, expression);
}
private JetTypeInfo visitExclExclExpression(@NotNull JetUnaryExpression expression, @NotNull ExpressionTypingContext context) { private JetTypeInfo visitExclExclExpression(@NotNull JetUnaryExpression expression, @NotNull ExpressionTypingContext context) {
JetExpression baseExpression = expression.getBaseExpression(); JetExpression baseExpression = expression.getBaseExpression();
assert baseExpression != null; assert baseExpression != null;
@@ -1120,7 +1104,7 @@ public class BasicExpressionTypingVisitor extends ExpressionTypingVisitor {
expression, contextWithExpectedType.trace, contextWithExpectedType.expectedType expression, contextWithExpectedType.trace, contextWithExpectedType.expectedType
); );
if (value != null) { if (value != null) {
return createCompileTimeConstantTypeInfo(value, expression, contextWithExpectedType); return createCompileTimeConstantTypeInfo(value, expression, contextWithExpectedType, components.builtIns);
} }
return DataFlowUtils.checkType(result, expression, contextWithExpectedType); return DataFlowUtils.checkType(result, expression, contextWithExpectedType);
} }
@@ -39,7 +39,10 @@ import org.jetbrains.kotlin.resolve.scopes.WritableScope;
import org.jetbrains.kotlin.resolve.scopes.WritableScopeImpl; import org.jetbrains.kotlin.resolve.scopes.WritableScopeImpl;
import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver; import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver;
import org.jetbrains.kotlin.resolve.scopes.receivers.TransientReceiver; import org.jetbrains.kotlin.resolve.scopes.receivers.TransientReceiver;
import org.jetbrains.kotlin.types.*; import org.jetbrains.kotlin.types.CommonSupertypes;
import org.jetbrains.kotlin.types.ErrorUtils;
import org.jetbrains.kotlin.types.JetType;
import org.jetbrains.kotlin.types.TypeUtils;
import org.jetbrains.kotlin.types.checker.JetTypeChecker; import org.jetbrains.kotlin.types.checker.JetTypeChecker;
import org.jetbrains.kotlin.types.expressions.typeInfoFactory.TypeInfoFactoryPackage; import org.jetbrains.kotlin.types.expressions.typeInfoFactory.TypeInfoFactoryPackage;
@@ -51,6 +54,7 @@ import static org.jetbrains.kotlin.diagnostics.Errors.*;
import static org.jetbrains.kotlin.psi.PsiPackage.JetPsiFactory; import static org.jetbrains.kotlin.psi.PsiPackage.JetPsiFactory;
import static org.jetbrains.kotlin.resolve.BindingContext.*; import static org.jetbrains.kotlin.resolve.BindingContext.*;
import static org.jetbrains.kotlin.resolve.calls.context.ContextDependency.INDEPENDENT; import static org.jetbrains.kotlin.resolve.calls.context.ContextDependency.INDEPENDENT;
import static org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilPackage.getBuiltIns;
import static org.jetbrains.kotlin.types.TypeUtils.*; import static org.jetbrains.kotlin.types.TypeUtils.*;
import static org.jetbrains.kotlin.types.expressions.ControlStructureTypingUtils.createCallForSpecialConstruction; import static org.jetbrains.kotlin.types.expressions.ControlStructureTypingUtils.createCallForSpecialConstruction;
import static org.jetbrains.kotlin.types.expressions.ControlStructureTypingUtils.createDataFlowInfoForArgumentsForIfCall; import static org.jetbrains.kotlin.types.expressions.ControlStructureTypingUtils.createDataFlowInfoForArgumentsForIfCall;
@@ -605,7 +609,7 @@ public class ControlStructureTypingVisitor extends ExpressionTypingVisitor {
) { ) {
JetType expectedType; JetType expectedType;
if (function instanceof JetSecondaryConstructor) { if (function instanceof JetSecondaryConstructor) {
expectedType = KotlinBuiltIns.getInstance().getUnitType(); expectedType = getBuiltIns(descriptor).getUnitType();
} }
else if (function instanceof JetFunction) { else if (function instanceof JetFunction) {
JetFunction jetFunction = (JetFunction) function; JetFunction jetFunction = (JetFunction) function;
@@ -22,6 +22,7 @@ import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.descriptors.*; import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.diagnostics.Diagnostic; import org.jetbrains.kotlin.diagnostics.Diagnostic;
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory; import org.jetbrains.kotlin.diagnostics.DiagnosticFactory;
@@ -29,6 +30,9 @@ import org.jetbrains.kotlin.diagnostics.Errors;
import org.jetbrains.kotlin.lexer.JetTokens; import org.jetbrains.kotlin.lexer.JetTokens;
import org.jetbrains.kotlin.psi.*; import org.jetbrains.kotlin.psi.*;
import org.jetbrains.kotlin.resolve.*; import org.jetbrains.kotlin.resolve.*;
import org.jetbrains.kotlin.resolve.calls.ArgumentTypeResolver;
import org.jetbrains.kotlin.resolve.constants.CompileTimeConstant;
import org.jetbrains.kotlin.resolve.constants.IntegerValueTypeConstant;
import org.jetbrains.kotlin.resolve.scopes.WritableScope; import org.jetbrains.kotlin.resolve.scopes.WritableScope;
import org.jetbrains.kotlin.resolve.scopes.WritableScopeImpl; import org.jetbrains.kotlin.resolve.scopes.WritableScopeImpl;
import org.jetbrains.kotlin.resolve.scopes.receivers.ClassReceiver; import org.jetbrains.kotlin.resolve.scopes.receivers.ClassReceiver;
@@ -43,6 +47,7 @@ import java.util.List;
import static org.jetbrains.kotlin.diagnostics.Errors.*; import static org.jetbrains.kotlin.diagnostics.Errors.*;
import static org.jetbrains.kotlin.psi.PsiPackage.JetPsiFactory; import static org.jetbrains.kotlin.psi.PsiPackage.JetPsiFactory;
import static org.jetbrains.kotlin.resolve.BindingContext.PROCESSED; import static org.jetbrains.kotlin.resolve.BindingContext.PROCESSED;
import static org.jetbrains.kotlin.resolve.calls.context.ContextDependency.INDEPENDENT;
public class ExpressionTypingUtils { public class ExpressionTypingUtils {
@@ -236,4 +241,20 @@ public class ExpressionTypingUtils {
private ExpressionTypingUtils() { private ExpressionTypingUtils() {
} }
@NotNull
public static JetTypeInfo createCompileTimeConstantTypeInfo(
@NotNull CompileTimeConstant<?> value,
@NotNull JetExpression expression,
@NotNull ExpressionTypingContext context,
@NotNull KotlinBuiltIns kotlinBuiltIns
) {
JetType expressionType = value.getType(kotlinBuiltIns);
if (value instanceof IntegerValueTypeConstant && context.contextDependency == INDEPENDENT) {
expressionType = ((IntegerValueTypeConstant) value).getType(context.expectedType);
ArgumentTypeResolver.updateNumberType(expressionType, expression, context);
}
return TypeInfoFactoryPackage.createCheckedTypeInfo(expressionType, context, expression);
}
} }
@@ -38,6 +38,7 @@ import org.jetbrains.kotlin.types.expressions.typeInfoFactory.TypeInfoFactoryPac
import java.util.Collections; import java.util.Collections;
import java.util.Set; import java.util.Set;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.isBoolean;
import static org.jetbrains.kotlin.diagnostics.Errors.*; import static org.jetbrains.kotlin.diagnostics.Errors.*;
import static org.jetbrains.kotlin.resolve.calls.context.ContextDependency.INDEPENDENT; import static org.jetbrains.kotlin.resolve.calls.context.ContextDependency.INDEPENDENT;
import static org.jetbrains.kotlin.types.TypeUtils.NO_EXPECTED_TYPE; import static org.jetbrains.kotlin.types.TypeUtils.NO_EXPECTED_TYPE;
@@ -63,7 +64,7 @@ public class PatternMatchingTypingVisitor extends ExpressionTypingVisitor {
DataFlowInfo newDataFlowInfo = conditionInfo.and(typeInfo.getDataFlowInfo()); DataFlowInfo newDataFlowInfo = conditionInfo.and(typeInfo.getDataFlowInfo());
context.trace.record(BindingContext.DATAFLOW_INFO_AFTER_CONDITION, expression, newDataFlowInfo); context.trace.record(BindingContext.DATAFLOW_INFO_AFTER_CONDITION, expression, newDataFlowInfo);
} }
return DataFlowUtils.checkType(typeInfo.replaceType(KotlinBuiltIns.getInstance().getBooleanType()), expression, contextWithExpectedType); return DataFlowUtils.checkType(typeInfo.replaceType(components.builtIns.getBooleanType()), expression, contextWithExpectedType);
} }
@Override @Override
@@ -189,7 +190,8 @@ public class PatternMatchingTypingVisitor extends ExpressionTypingVisitor {
argumentForSubject, rangeExpression, context); argumentForSubject, rangeExpression, context);
DataFlowInfo dataFlowInfo = typeInfo.getDataFlowInfo(); DataFlowInfo dataFlowInfo = typeInfo.getDataFlowInfo();
newDataFlowInfo.set(new DataFlowInfos(dataFlowInfo, dataFlowInfo)); newDataFlowInfo.set(new DataFlowInfos(dataFlowInfo, dataFlowInfo));
if (!KotlinBuiltIns.getInstance().getBooleanType().equals(typeInfo.getType())) { JetType type = typeInfo.getType();
if (type == null || !isBoolean(type)) {
context.trace.report(TYPE_MISMATCH_IN_RANGE.on(condition)); context.trace.report(TYPE_MISMATCH_IN_RANGE.on(condition));
} }
} }
@@ -258,7 +260,7 @@ public class PatternMatchingTypingVisitor extends ExpressionTypingVisitor {
} }
context = context.replaceDataFlowInfo(typeInfo.getDataFlowInfo()); context = context.replaceDataFlowInfo(typeInfo.getDataFlowInfo());
if (conditionExpected) { if (conditionExpected) {
JetType booleanType = KotlinBuiltIns.getInstance().getBooleanType(); JetType booleanType = components.builtIns.getBooleanType();
if (!JetTypeChecker.DEFAULT.equalTypes(booleanType, type)) { if (!JetTypeChecker.DEFAULT.equalTypes(booleanType, type)) {
context.trace.report(TYPE_MISMATCH_IN_CONDITION.on(expression, type)); context.trace.report(TYPE_MISMATCH_IN_CONDITION.on(expression, type));
} }
@@ -291,7 +293,7 @@ public class PatternMatchingTypingVisitor extends ExpressionTypingVisitor {
} }
TypeResolutionContext typeResolutionContext = new TypeResolutionContext(context.scope, context.trace, true, /*allowBareTypes=*/ true); TypeResolutionContext typeResolutionContext = new TypeResolutionContext(context.scope, context.trace, true, /*allowBareTypes=*/ true);
PossiblyBareType possiblyBareTarget = components.typeResolver.resolvePossiblyBareType(typeResolutionContext, typeReferenceAfterIs); PossiblyBareType possiblyBareTarget = components.typeResolver.resolvePossiblyBareType(typeResolutionContext, typeReferenceAfterIs);
JetType targetType = TypeReconstructionUtil.reconstructBareType(typeReferenceAfterIs, possiblyBareTarget, subjectType, context.trace); JetType targetType = TypeReconstructionUtil.reconstructBareType(typeReferenceAfterIs, possiblyBareTarget, subjectType, context.trace, components.builtIns);
if (TypesPackage.isDynamic(targetType)) { if (TypesPackage.isDynamic(targetType)) {
context.trace.report(DYNAMIC_NOT_ALLOWED.on(typeReferenceAfterIs)); context.trace.report(DYNAMIC_NOT_ALLOWED.on(typeReferenceAfterIs));
@@ -37,11 +37,12 @@ public class TypeReconstructionUtil {
@NotNull JetTypeReference right, @NotNull JetTypeReference right,
@NotNull PossiblyBareType possiblyBareTarget, @NotNull PossiblyBareType possiblyBareTarget,
@Nullable JetType subjectType, @Nullable JetType subjectType,
@NotNull BindingTrace trace @NotNull BindingTrace trace,
@NotNull KotlinBuiltIns builtIns
) { ) {
if (subjectType == null) { if (subjectType == null) {
// Recovery: let's reconstruct as if we were casting from Any, to get some type there // Recovery: let's reconstruct as if we were casting from Any, to get some type there
subjectType = KotlinBuiltIns.getInstance().getAnyType(); subjectType = builtIns.getAnyType();
} }
TypeReconstructionResult reconstructionResult = possiblyBareTarget.reconstruct(subjectType); TypeReconstructionResult reconstructionResult = possiblyBareTarget.reconstruct(subjectType);
if (!reconstructionResult.isAllArgumentsInferred()) { if (!reconstructionResult.isAllArgumentsInferred()) {
@@ -477,9 +477,8 @@ public class KotlinLightClassForExplicitDeclaration extends KotlinWrappingLightC
return false; return false;
} }
ClassDescriptor deprecatedAnnotation = KotlinBuiltIns.getInstance().getDeprecatedAnnotation(); FqName deprecatedFqName = KotlinBuiltIns.FQ_NAMES.deprecated;
String deprecatedName = deprecatedAnnotation.getName().asString(); String deprecatedName = deprecatedFqName.shortName().asString();
FqNameUnsafe deprecatedFqName = DescriptorUtils.getFqName(deprecatedAnnotation);
for (JetAnnotationEntry annotationEntry : jetModifierList.getAnnotationEntries()) { for (JetAnnotationEntry annotationEntry : jetModifierList.getAnnotationEntries()) {
JetTypeReference typeReference = annotationEntry.getTypeReference(); JetTypeReference typeReference = annotationEntry.getTypeReference();
@@ -491,7 +490,7 @@ public class KotlinLightClassForExplicitDeclaration extends KotlinWrappingLightC
FqName fqName = JetPsiUtil.toQualifiedName((JetUserType) typeElement); FqName fqName = JetPsiUtil.toQualifiedName((JetUserType) typeElement);
if (fqName == null) continue; if (fqName == null) continue;
if (deprecatedFqName.equals(fqName.toUnsafe())) return true; if (deprecatedFqName.equals(fqName)) return true;
if (deprecatedName.equals(fqName.asString())) return true; if (deprecatedName.equals(fqName.asString())) return true;
} }
return false; return false;
@@ -23,6 +23,7 @@ import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.resolve.constants.NullValue import org.jetbrains.kotlin.resolve.constants.NullValue
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.serialization.AnnotationSerializer import org.jetbrains.kotlin.serialization.AnnotationSerializer
import org.jetbrains.kotlin.serialization.DescriptorSerializer import org.jetbrains.kotlin.serialization.DescriptorSerializer
@@ -59,9 +60,10 @@ public object BuiltInsSerializerExtension : SerializerExtension() {
for (annotation in callable.getAnnotations()) { for (annotation in callable.getAnnotations()) {
proto.addExtension(BuiltInsProtoBuf.callableAnnotation, AnnotationSerializer.serializeAnnotation(annotation, stringTable)) proto.addExtension(BuiltInsProtoBuf.callableAnnotation, AnnotationSerializer.serializeAnnotation(annotation, stringTable))
} }
val compileTimeConstant = (callable as? PropertyDescriptor)?.getCompileTimeInitializer() val propertyDescriptor = callable as? PropertyDescriptor ?: return
val compileTimeConstant = propertyDescriptor.getCompileTimeInitializer()
if (compileTimeConstant != null && compileTimeConstant !is NullValue) { if (compileTimeConstant != null && compileTimeConstant !is NullValue) {
val type = compileTimeConstant.getType(KotlinBuiltIns.getInstance()) val type = compileTimeConstant.getType(propertyDescriptor.builtIns)
proto.setExtension(BuiltInsProtoBuf.compileTimeValue, AnnotationSerializer.valueProto(compileTimeConstant, type, stringTable).build()) proto.setExtension(BuiltInsProtoBuf.compileTimeValue, AnnotationSerializer.valueProto(compileTimeConstant, type, stringTable).build())
} }
} }
@@ -119,7 +119,7 @@ public class InjectorForTests {
this.callCompleter = new CallCompleter(argumentTypeResolver, candidateResolver); this.callCompleter = new CallCompleter(argumentTypeResolver, candidateResolver);
this.taskPrioritizer = new TaskPrioritizer(storageManager); this.taskPrioritizer = new TaskPrioritizer(storageManager);
this.delegatedPropertyResolver = new DelegatedPropertyResolver(); this.delegatedPropertyResolver = new DelegatedPropertyResolver();
this.callExpressionResolver = new CallExpressionResolver(callResolver); this.callExpressionResolver = new CallExpressionResolver(callResolver, kotlinBuiltIns);
this.controlStructureTypingUtils = new ControlStructureTypingUtils(callResolver); this.controlStructureTypingUtils = new ControlStructureTypingUtils(callResolver);
this.forLoopConventionsChecker = new ForLoopConventionsChecker(); this.forLoopConventionsChecker = new ForLoopConventionsChecker();
this.localClassifierAnalyzer = new LocalClassifierAnalyzer(getDescriptorResolver(), getFunctionDescriptorResolver(), getTypeResolver(), annotationResolver); this.localClassifierAnalyzer = new LocalClassifierAnalyzer(getDescriptorResolver(), getFunctionDescriptorResolver(), getTypeResolver(), annotationResolver);
@@ -16,27 +16,27 @@
package org.jetbrains.kotlin.load.java.lazy.descriptors package org.jetbrains.kotlin.load.java.lazy.descriptors
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.load.java.structure.JavaClass
import org.jetbrains.kotlin.descriptors.impl.ClassDescriptorBase import org.jetbrains.kotlin.descriptors.impl.ClassDescriptorBase
import org.jetbrains.kotlin.resolve.scopes.JetScope import org.jetbrains.kotlin.load.java.components.TypeUsage
import org.jetbrains.kotlin.types.JetType import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor
import org.jetbrains.kotlin.types.TypeConstructor
import org.jetbrains.kotlin.load.java.lazy.LazyJavaResolverContext import org.jetbrains.kotlin.load.java.lazy.LazyJavaResolverContext
import org.jetbrains.kotlin.load.java.lazy.child import org.jetbrains.kotlin.load.java.lazy.child
import org.jetbrains.kotlin.load.java.components.TypeUsage
import org.jetbrains.kotlin.load.java.lazy.resolveAnnotations import org.jetbrains.kotlin.load.java.lazy.resolveAnnotations
import org.jetbrains.kotlin.load.java.lazy.types.toAttributes import org.jetbrains.kotlin.load.java.lazy.types.toAttributes
import org.jetbrains.kotlin.resolve.scopes.InnerClassesScopeWrapper import org.jetbrains.kotlin.load.java.structure.JavaClass
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.types.AbstractClassTypeConstructor
import java.util.ArrayList
import org.jetbrains.kotlin.utils.toReadOnlyList
import org.jetbrains.kotlin.load.java.structure.JavaType
import org.jetbrains.kotlin.load.java.structure.JavaClassifierType import org.jetbrains.kotlin.load.java.structure.JavaClassifierType
import org.jetbrains.kotlin.load.java.structure.JavaType
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.scopes.InnerClassesScopeWrapper
import org.jetbrains.kotlin.resolve.scopes.JetScope
import org.jetbrains.kotlin.types.AbstractClassTypeConstructor
import org.jetbrains.kotlin.types.JetType
import org.jetbrains.kotlin.types.TypeConstructor
import org.jetbrains.kotlin.utils.toReadOnlyList
import java.util.ArrayList
class LazyJavaClassDescriptor( class LazyJavaClassDescriptor(
private val outerC: LazyJavaResolverContext, private val outerC: LazyJavaResolverContext,
@@ -138,7 +138,7 @@ class LazyJavaClassDescriptor(
}) })
} }
if (result.isNotEmpty()) result.toReadOnlyList() else listOf(KotlinBuiltIns.getInstance().getAnyType()) if (result.isNotEmpty()) result.toReadOnlyList() else listOf(c.module.builtIns.getAnyType())
} }
override fun getSupertypes(): Collection<JetType> = supertypes() override fun getSupertypes(): Collection<JetType> = supertypes()
@@ -45,7 +45,7 @@ class LazyJavaTypeParameterDescriptor(
override fun resolveUpperBounds(): Set<JetType> { override fun resolveUpperBounds(): Set<JetType> {
val bounds = javaTypeParameter.getUpperBounds() val bounds = javaTypeParameter.getUpperBounds()
if (bounds.isEmpty()) { if (bounds.isEmpty()) {
return setOf(KotlinBuiltIns.getInstance().getDefaultBound()) return setOf(c.module.builtIns.getDefaultBound())
} }
else { else {
return bounds.map { return bounds.map {
@@ -56,8 +56,8 @@ class LazyJavaTypeResolver(
return when (javaType) { return when (javaType) {
is JavaPrimitiveType -> { is JavaPrimitiveType -> {
val primitiveType = javaType.getType() val primitiveType = javaType.getType()
if (primitiveType != null) KotlinBuiltIns.getInstance().getPrimitiveJetType(primitiveType) if (primitiveType != null) c.module.builtIns.getPrimitiveJetType(primitiveType)
else KotlinBuiltIns.getInstance().getUnitType() else c.module.builtIns.getUnitType()
} }
is JavaClassifierType -> is JavaClassifierType ->
if (PLATFORM_TYPES && attr.allowFlexible && attr.howThisTypeIsUsed != SUPERTYPE) if (PLATFORM_TYPES && attr.allowFlexible && attr.howThisTypeIsUsed != SUPERTYPE)
@@ -76,7 +76,7 @@ class LazyJavaTypeResolver(
val javaComponentType = arrayType.getComponentType() val javaComponentType = arrayType.getComponentType()
val primitiveType = (javaComponentType as? JavaPrimitiveType)?.getType() val primitiveType = (javaComponentType as? JavaPrimitiveType)?.getType()
if (primitiveType != null) { if (primitiveType != null) {
val jetType = KotlinBuiltIns.getInstance().getPrimitiveArrayJetType(primitiveType) val jetType = c.module.builtIns.getPrimitiveArrayJetType(primitiveType)
return@run if (PLATFORM_TYPES && attr.allowFlexible) return@run if (PLATFORM_TYPES && attr.allowFlexible)
FlexibleJavaClassifierTypeCapabilities.create(jetType, TypeUtils.makeNullable(jetType)) FlexibleJavaClassifierTypeCapabilities.create(jetType, TypeUtils.makeNullable(jetType))
else TypeUtils.makeNullableAsSpecified(jetType, !attr.isMarkedNotNull) else TypeUtils.makeNullableAsSpecified(jetType, !attr.isMarkedNotNull)
@@ -87,12 +87,12 @@ class LazyJavaTypeResolver(
if (PLATFORM_TYPES && attr.allowFlexible) { if (PLATFORM_TYPES && attr.allowFlexible) {
return@run FlexibleJavaClassifierTypeCapabilities.create( return@run FlexibleJavaClassifierTypeCapabilities.create(
KotlinBuiltIns.getInstance().getArrayType(INVARIANT, componentType), c.module.builtIns.getArrayType(INVARIANT, componentType),
TypeUtils.makeNullable(KotlinBuiltIns.getInstance().getArrayType(OUT_VARIANCE, componentType))) TypeUtils.makeNullable(c.module.builtIns.getArrayType(OUT_VARIANCE, componentType)))
} }
val projectionKind = if (attr.howThisTypeIsUsed == MEMBER_SIGNATURE_CONTRAVARIANT || isVararg) OUT_VARIANCE else INVARIANT val projectionKind = if (attr.howThisTypeIsUsed == MEMBER_SIGNATURE_CONTRAVARIANT || isVararg) OUT_VARIANCE else INVARIANT
val result = KotlinBuiltIns.getInstance().getArrayType(projectionKind, componentType) val result = c.module.builtIns.getArrayType(projectionKind, componentType)
return@run TypeUtils.makeNullableAsSpecified(result, !attr.isMarkedNotNull) return@run TypeUtils.makeNullableAsSpecified(result, !attr.isMarkedNotNull)
}.replaceAnnotations(attr.annotations) }.replaceAnnotations(attr.annotations)
} }
@@ -214,7 +214,7 @@ class LazyJavaTypeResolver(
// C<*> = C<out C<out C<...>>> // C<*> = C<out C<out C<...>>>
// this way we lose some type information, even when the case is not so bad, but it doesn't seem to matter // this way we lose some type information, even when the case is not so bad, but it doesn't seem to matter
val projectionKind = if (parameter.getVariance() == OUT_VARIANCE) INVARIANT else OUT_VARIANCE val projectionKind = if (parameter.getVariance() == OUT_VARIANCE) INVARIANT else OUT_VARIANCE
TypeProjectionImpl(projectionKind, KotlinBuiltIns.getInstance().getNullableAnyType()) TypeProjectionImpl(projectionKind, c.module.builtIns.getNullableAnyType())
} }
else else
makeStarProjection(parameter, attr) makeStarProjection(parameter, attr)
@@ -42,6 +42,7 @@ import java.util.*;
import static kotlin.KotlinPackage.single; import static kotlin.KotlinPackage.single;
import static org.jetbrains.kotlin.builtins.PrimitiveType.*; import static org.jetbrains.kotlin.builtins.PrimitiveType.*;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.getFqName;
public class KotlinBuiltIns { public class KotlinBuiltIns {
public static final Name BUILT_INS_PACKAGE_NAME = Name.identifier("kotlin"); public static final Name BUILT_INS_PACKAGE_NAME = Name.identifier("kotlin");
@@ -157,11 +158,23 @@ public class KotlinBuiltIns {
public final FqNameUnsafe string = fqNameUnsafe("String"); public final FqNameUnsafe string = fqNameUnsafe("String");
public final FqNameUnsafe array = fqNameUnsafe("Array"); public final FqNameUnsafe array = fqNameUnsafe("Array");
public final FqNameUnsafe _boolean = fqNameUnsafe("Boolean");
public final FqNameUnsafe _char = fqNameUnsafe("Char");
public final FqNameUnsafe _byte = fqNameUnsafe("Byte");
public final FqNameUnsafe _short = fqNameUnsafe("Short");
public final FqNameUnsafe _int = fqNameUnsafe("Int");
public final FqNameUnsafe _long = fqNameUnsafe("Long");
public final FqNameUnsafe _float = fqNameUnsafe("Float");
public final FqNameUnsafe _double = fqNameUnsafe("Double");
public final FqName data = fqName("data"); public final FqName data = fqName("data");
public final FqName deprecated = fqName("deprecated"); public final FqName deprecated = fqName("deprecated");
public final FqName tailRecursive = fqName("tailRecursive"); public final FqName tailRecursive = fqName("tailRecursive");
public final FqName inline = fqName("inline"); public final FqName inline = fqName("inline");
public final FqName noinline = fqName("noinline"); public final FqName noinline = fqName("noinline");
public final FqName inlineOptions = fqName("inlineOptions");
public final FqNameUnsafe kClass = new FqName("kotlin.reflect.KClass").toUnsafe(); public final FqNameUnsafe kClass = new FqName("kotlin.reflect.KClass").toUnsafe();
@@ -350,11 +363,6 @@ public class KotlinBuiltIns {
return getBuiltInClassByName("data"); return getBuiltInClassByName("data");
} }
@NotNull
public ClassDescriptor getInlineOptionsClassAnnotation() {
return getBuiltInClassByName("inlineOptions");
}
@NotNull @NotNull
public ClassDescriptor getDeprecatedAnnotation() { public ClassDescriptor getDeprecatedAnnotation() {
return getBuiltInClassByName("deprecated"); return getBuiltInClassByName("deprecated");
@@ -687,12 +695,16 @@ public class KotlinBuiltIns {
public static boolean isPrimitiveArray(@NotNull JetType type) { public static boolean isPrimitiveArray(@NotNull JetType type) {
ClassifierDescriptor descriptor = type.getConstructor().getDeclarationDescriptor(); ClassifierDescriptor descriptor = type.getConstructor().getDeclarationDescriptor();
return descriptor != null && getPrimitiveTypeByArrayClassFqName(DescriptorUtils.getFqName(descriptor)) != null; return descriptor != null && getPrimitiveTypeByArrayClassFqName(getFqName(descriptor)) != null;
} }
public static boolean isPrimitiveType(@NotNull JetType type) { public static boolean isPrimitiveType(@NotNull JetType type) {
ClassifierDescriptor descriptor = type.getConstructor().getDeclarationDescriptor(); ClassifierDescriptor descriptor = type.getConstructor().getDeclarationDescriptor();
return !type.isMarkedNullable() && descriptor != null && getPrimitiveTypeByFqName(DescriptorUtils.getFqName(descriptor)) != null; return !type.isMarkedNullable() && descriptor instanceof ClassDescriptor && isPrimitiveClass((ClassDescriptor) descriptor);
}
public static boolean isPrimitiveClass(@NotNull ClassDescriptor descriptor) {
return getPrimitiveTypeByFqName(getFqName(descriptor)) != null;
} }
// Functions // Functions
@@ -746,7 +758,7 @@ public class KotlinBuiltIns {
if (declarationDescriptor == null) return false; if (declarationDescriptor == null) return false;
FqNameUnsafe fqName = DescriptorUtils.getFqName(declarationDescriptor); FqNameUnsafe fqName = getFqName(declarationDescriptor);
return classes.contains(fqName); return classes.contains(fqName);
} }
@@ -799,7 +811,7 @@ public class KotlinBuiltIns {
private static boolean isConstructedFromGivenClass(@NotNull JetType type, @NotNull FqNameUnsafe fqName) { private static boolean isConstructedFromGivenClass(@NotNull JetType type, @NotNull FqNameUnsafe fqName) {
ClassifierDescriptor descriptor = type.getConstructor().getDeclarationDescriptor(); ClassifierDescriptor descriptor = type.getConstructor().getDeclarationDescriptor();
return descriptor != null && fqName.equals(DescriptorUtils.getFqName(descriptor)); return descriptor != null && fqName.equals(getFqName(descriptor));
} }
private static boolean isNotNullConstructedFromGivenClass(@NotNull JetType type, @NotNull FqNameUnsafe fqName) { private static boolean isNotNullConstructedFromGivenClass(@NotNull JetType type, @NotNull FqNameUnsafe fqName) {
@@ -807,12 +819,52 @@ public class KotlinBuiltIns {
} }
public static boolean isSpecialClassWithNoSupertypes(@NotNull ClassDescriptor descriptor) { public static boolean isSpecialClassWithNoSupertypes(@NotNull ClassDescriptor descriptor) {
FqNameUnsafe fqName = DescriptorUtils.getFqName(descriptor); FqNameUnsafe fqName = getFqName(descriptor);
return FQ_NAMES.any.equals(fqName) || FQ_NAMES.nothing.equals(fqName); return FQ_NAMES.any.equals(fqName) || FQ_NAMES.nothing.equals(fqName);
} }
public static boolean isAny(@NotNull ClassDescriptor descriptor) { public static boolean isAny(@NotNull ClassDescriptor descriptor) {
return isAny(DescriptorUtils.getFqName(descriptor)); return isAny(getFqName(descriptor));
}
public static boolean isBoolean(@NotNull JetType type) {
return isConstructedFromGivenClassAndNotNullable(type, FQ_NAMES._boolean);
}
public static boolean isBoolean(@NotNull ClassDescriptor classDescriptor) {
return FQ_NAMES._boolean.equals(getFqName(classDescriptor));
}
public static boolean isChar(@NotNull JetType type) {
return isConstructedFromGivenClassAndNotNullable(type, FQ_NAMES._char);
}
public static boolean isInt(@NotNull JetType type) {
return isConstructedFromGivenClassAndNotNullable(type, FQ_NAMES._int);
}
public static boolean isByte(@NotNull JetType type) {
return isConstructedFromGivenClassAndNotNullable(type, FQ_NAMES._byte);
}
public static boolean isLong(@NotNull JetType type) {
return isConstructedFromGivenClassAndNotNullable(type, FQ_NAMES._long);
}
public static boolean isShort(@NotNull JetType type) {
return isConstructedFromGivenClassAndNotNullable(type, FQ_NAMES._short);
}
public static boolean isFloat(@NotNull JetType type) {
return isConstructedFromGivenClassAndNotNullable(type, FQ_NAMES._float);
}
public static boolean isDouble(@NotNull JetType type) {
return isConstructedFromGivenClassAndNotNullable(type, FQ_NAMES._double);
}
private static boolean isConstructedFromGivenClassAndNotNullable(@NotNull JetType type, @NotNull FqNameUnsafe fqName) {
return isConstructedFromGivenClass(type, fqName) && !type.isMarkedNullable();
} }
public static boolean isAny(@NotNull FqNameUnsafe fqName) { public static boolean isAny(@NotNull FqNameUnsafe fqName) {
@@ -854,15 +906,15 @@ public class KotlinBuiltIns {
} }
public static boolean isKClass(@NotNull ClassDescriptor descriptor) { public static boolean isKClass(@NotNull ClassDescriptor descriptor) {
return FQ_NAMES.kClass.equals(DescriptorUtils.getFqName(descriptor)); return FQ_NAMES.kClass.equals(getFqName(descriptor));
} }
public static boolean isNonPrimitiveArray(@NotNull ClassDescriptor descriptor) { public static boolean isNonPrimitiveArray(@NotNull ClassDescriptor descriptor) {
return FQ_NAMES.array.equals(DescriptorUtils.getFqName(descriptor)); return FQ_NAMES.array.equals(getFqName(descriptor));
} }
public static boolean isCloneable(@NotNull ClassDescriptor descriptor) { public static boolean isCloneable(@NotNull ClassDescriptor descriptor) {
return FQ_NAMES.cloneable.equals(DescriptorUtils.getFqName(descriptor)); return FQ_NAMES.cloneable.equals(getFqName(descriptor));
} }
public static boolean isData(@NotNull ClassDescriptor classDescriptor) { public static boolean isData(@NotNull ClassDescriptor classDescriptor) {
@@ -18,7 +18,6 @@ package org.jetbrains.kotlin.descriptors.impl;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.descriptors.*; import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.annotations.Annotations; import org.jetbrains.kotlin.descriptors.annotations.Annotations;
import org.jetbrains.kotlin.name.Name; import org.jetbrains.kotlin.name.Name;
@@ -31,6 +30,8 @@ import org.jetbrains.kotlin.types.Variance;
import java.util.*; import java.util.*;
import static org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilPackage.getBuiltIns;
public class PropertyDescriptorImpl extends VariableDescriptorImpl implements PropertyDescriptor { public class PropertyDescriptorImpl extends VariableDescriptorImpl implements PropertyDescriptor {
private final Modality modality; private final Modality modality;
private Visibility visibility; private Visibility visibility;
@@ -263,7 +264,7 @@ public class PropertyDescriptorImpl extends VariableDescriptorImpl implements Pr
// it can not be assigned to because of the projection // it can not be assigned to because of the projection
substitutedDescriptor.setSetterProjectedOut(true); substitutedDescriptor.setSetterProjectedOut(true);
substitutedValueParameters = Collections.<ValueParameterDescriptor>singletonList( substitutedValueParameters = Collections.<ValueParameterDescriptor>singletonList(
PropertySetterDescriptorImpl.createSetterParameter(newSetter, KotlinBuiltIns.getInstance().getNothingType()) PropertySetterDescriptorImpl.createSetterParameter(newSetter, getBuiltIns(newOwner).getNothingType())
); );
} }
if (substitutedValueParameters.size() != 1) { if (substitutedValueParameters.size() != 1) {
@@ -22,12 +22,13 @@ import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.annotations.Annotations; import org.jetbrains.kotlin.descriptors.annotations.Annotations;
import org.jetbrains.kotlin.name.Name; import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.types.JetType; import org.jetbrains.kotlin.types.JetType;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import static org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilPackage.getBuiltIns;
public class PropertySetterDescriptorImpl extends PropertyAccessorDescriptorImpl implements PropertySetterDescriptor { public class PropertySetterDescriptorImpl extends PropertyAccessorDescriptorImpl implements PropertySetterDescriptor {
private ValueParameterDescriptor parameter; private ValueParameterDescriptor parameter;
@@ -87,7 +88,7 @@ public class PropertySetterDescriptorImpl extends PropertyAccessorDescriptorImpl
@NotNull @NotNull
@Override @Override
public JetType getReturnType() { public JetType getReturnType() {
return KotlinBuiltIns.getInstance().getUnitType(); return getBuiltIns(this).getUnitType();
} }
@Override @Override
@@ -17,7 +17,6 @@
package org.jetbrains.kotlin.descriptors.impl; package org.jetbrains.kotlin.descriptors.impl;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor; import org.jetbrains.kotlin.descriptors.DeclarationDescriptor;
import org.jetbrains.kotlin.descriptors.SourceElement; import org.jetbrains.kotlin.descriptors.SourceElement;
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor; import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor;
@@ -34,6 +33,8 @@ import java.util.Collections;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.Set; import java.util.Set;
import static org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilPackage.getBuiltIns;
public class TypeParameterDescriptorImpl extends AbstractTypeParameterDescriptor { public class TypeParameterDescriptorImpl extends AbstractTypeParameterDescriptor {
public static TypeParameterDescriptor createWithDefaultBound( public static TypeParameterDescriptor createWithDefaultBound(
@NotNull DeclarationDescriptor containingDeclaration, @NotNull DeclarationDescriptor containingDeclaration,
@@ -45,7 +46,7 @@ public class TypeParameterDescriptorImpl extends AbstractTypeParameterDescriptor
) { ) {
TypeParameterDescriptorImpl typeParameterDescriptor = TypeParameterDescriptorImpl typeParameterDescriptor =
createForFurtherModification(containingDeclaration, annotations, reified, variance, name, index, SourceElement.NO_SOURCE); createForFurtherModification(containingDeclaration, annotations, reified, variance, name, index, SourceElement.NO_SOURCE);
typeParameterDescriptor.addUpperBound(KotlinBuiltIns.getInstance().getDefaultBound()); typeParameterDescriptor.addUpperBound(getBuiltIns(containingDeclaration).getDefaultBound());
typeParameterDescriptor.setInitialized(); typeParameterDescriptor.setInitialized();
return typeParameterDescriptor; return typeParameterDescriptor;
} }
@@ -125,7 +126,7 @@ public class TypeParameterDescriptorImpl extends AbstractTypeParameterDescriptor
checkUninitialized(); checkUninitialized();
if (upperBounds.isEmpty()) { if (upperBounds.isEmpty()) {
doAddUpperBound(KotlinBuiltIns.getInstance().getDefaultBound()); doAddUpperBound(getBuiltIns(getContainingDeclaration()).getDefaultBound());
} }
} }
@@ -18,7 +18,6 @@ package org.jetbrains.kotlin.resolve;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.descriptors.*; import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.annotations.Annotations; import org.jetbrains.kotlin.descriptors.annotations.Annotations;
import org.jetbrains.kotlin.descriptors.impl.*; import org.jetbrains.kotlin.descriptors.impl.*;
@@ -31,6 +30,7 @@ import java.util.Collections;
import static org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor.NO_RECEIVER_PARAMETER; import static org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor.NO_RECEIVER_PARAMETER;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.getDefaultConstructorVisibility; import static org.jetbrains.kotlin.resolve.DescriptorUtils.getDefaultConstructorVisibility;
import static org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilPackage.getBuiltIns;
public class DescriptorFactory { public class DescriptorFactory {
private static class DefaultConstructorDescriptor extends ConstructorDescriptorImpl { private static class DefaultConstructorDescriptor extends ConstructorDescriptorImpl {
@@ -90,7 +90,7 @@ public class DescriptorFactory {
CallableMemberDescriptor.Kind.SYNTHESIZED, enumClass.getSource()); CallableMemberDescriptor.Kind.SYNTHESIZED, enumClass.getSource());
return values.initialize(null, NO_RECEIVER_PARAMETER, Collections.<TypeParameterDescriptor>emptyList(), return values.initialize(null, NO_RECEIVER_PARAMETER, Collections.<TypeParameterDescriptor>emptyList(),
Collections.<ValueParameterDescriptor>emptyList(), Collections.<ValueParameterDescriptor>emptyList(),
KotlinBuiltIns.getInstance().getArrayType(Variance.INVARIANT, enumClass.getDefaultType()), Modality.FINAL, getBuiltIns(enumClass).getArrayType(Variance.INVARIANT, enumClass.getDefaultType()), Modality.FINAL,
Visibilities.PUBLIC); Visibilities.PUBLIC);
} }
@@ -100,7 +100,7 @@ public class DescriptorFactory {
SimpleFunctionDescriptorImpl.create(enumClass, Annotations.EMPTY, DescriptorUtils.ENUM_VALUE_OF, SimpleFunctionDescriptorImpl.create(enumClass, Annotations.EMPTY, DescriptorUtils.ENUM_VALUE_OF,
CallableMemberDescriptor.Kind.SYNTHESIZED, enumClass.getSource()); CallableMemberDescriptor.Kind.SYNTHESIZED, enumClass.getSource());
ValueParameterDescriptor parameterDescriptor = new ValueParameterDescriptorImpl( ValueParameterDescriptor parameterDescriptor = new ValueParameterDescriptorImpl(
valueOf, null, 0, Annotations.EMPTY, Name.identifier("value"), KotlinBuiltIns.getInstance().getStringType(), false, null, valueOf, null, 0, Annotations.EMPTY, Name.identifier("value"), getBuiltIns(enumClass).getStringType(), false, null,
enumClass.getSource() enumClass.getSource()
); );
return valueOf.initialize(null, NO_RECEIVER_PARAMETER, Collections.<TypeParameterDescriptor>emptyList(), return valueOf.initialize(null, NO_RECEIVER_PARAMETER, Collections.<TypeParameterDescriptor>emptyList(),
@@ -39,8 +39,10 @@ import org.jetbrains.kotlin.types.checker.JetTypeChecker;
import java.util.*; import java.util.*;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.isAny;
import static org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.*; import static org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.*;
import static org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor.NO_RECEIVER_PARAMETER; import static org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor.NO_RECEIVER_PARAMETER;
import static org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilPackage.getBuiltIns;
public class DescriptorUtils { public class DescriptorUtils {
public static final Name ENUM_VALUES = Name.identifier("values"); public static final Name ENUM_VALUES = Name.identifier("values");
@@ -329,7 +331,7 @@ public class DescriptorUtils {
return type; return type;
} }
} }
return KotlinBuiltIns.getInstance().getAnyType(); return getBuiltIns(classDescriptor).getAnyType();
} }
@NotNull @NotNull
@@ -345,10 +347,6 @@ public class DescriptorUtils {
return (ClassDescriptor) descriptor; return (ClassDescriptor) descriptor;
} }
public static boolean isAny(@NotNull DeclarationDescriptor superClassDescriptor) {
return superClassDescriptor.equals(KotlinBuiltIns.getInstance().getAny());
}
@NotNull @NotNull
public static Visibility getDefaultConstructorVisibility(@NotNull ClassDescriptor classDescriptor) { public static Visibility getDefaultConstructorVisibility(@NotNull ClassDescriptor classDescriptor) {
ClassKind classKind = classDescriptor.getKind(); ClassKind classKind = classDescriptor.getKind();
@@ -429,7 +427,7 @@ public class DescriptorUtils {
if (type instanceof LazyType || type.isMarkedNullable()) return true; if (type instanceof LazyType || type.isMarkedNullable()) return true;
KotlinBuiltIns builtIns = KotlinBuiltIns.getInstance(); KotlinBuiltIns builtIns = getBuiltIns(variable);
return KotlinBuiltIns.isPrimitiveType(type) || return KotlinBuiltIns.isPrimitiveType(type) ||
JetTypeChecker.DEFAULT.equalTypes(builtIns.getStringType(), type) || JetTypeChecker.DEFAULT.equalTypes(builtIns.getStringType(), type) ||
JetTypeChecker.DEFAULT.equalTypes(builtIns.getNumber().getDefaultType(), type) || JetTypeChecker.DEFAULT.equalTypes(builtIns.getNumber().getDefaultType(), type) ||
@@ -102,11 +102,14 @@ public fun ClassDescriptor.getSuperClassNotAny(): ClassDescriptor? {
return null return null
} }
public fun ClassDescriptor.getSuperClassOrAny(): ClassDescriptor = getSuperClassNotAny() ?: KotlinBuiltIns.getInstance().getAny() public fun ClassDescriptor.getSuperClassOrAny(): ClassDescriptor = getSuperClassNotAny() ?: builtIns.getAny()
public val ClassDescriptor.secondaryConstructors: List<ConstructorDescriptor> public val ClassDescriptor.secondaryConstructors: List<ConstructorDescriptor>
get() = getConstructors().filterNot { it.isPrimary() } get() = getConstructors().filterNot { it.isPrimary() }
public val DeclarationDescriptor.builtIns: KotlinBuiltIns
get() = module.builtIns
/** /**
* Returns containing declaration of dispatch receiver for callable adjusted to fake-overridden cases * Returns containing declaration of dispatch receiver for callable adjusted to fake-overridden cases
* *
@@ -32,8 +32,8 @@ public class ArrayValue extends CompileTimeConstant<List<CompileTimeConstant<?>>
boolean canBeUsedInAnnotations, boolean canBeUsedInAnnotations,
boolean usesVariableAsConstant) { boolean usesVariableAsConstant) {
super(value, canBeUsedInAnnotations, false, usesVariableAsConstant); super(value, canBeUsedInAnnotations, false, usesVariableAsConstant);
assert KotlinBuiltIns.getInstance().isArray(type) || assert KotlinBuiltIns.isArray(type) || KotlinBuiltIns.isPrimitiveArray(type)
KotlinBuiltIns.getInstance().isPrimitiveArray(type) : "Type should be an array, but was " + type + ": " + value; : "Type should be an array, but was " + type + ": " + value;
this.type = type; this.type = type;
} }
@@ -64,19 +64,18 @@ private fun getIntegerValue(
return IntegerValueTypeConstant(value, canBeUsedInAnnotation, usesVariableAsConstant) return IntegerValueTypeConstant(value, canBeUsedInAnnotation, usesVariableAsConstant)
} }
val builtIns = KotlinBuiltIns.getInstance() val notNullExpected = TypeUtils.makeNotNullable(expectedType)
return when {
return when (TypeUtils.makeNotNullable(expectedType)) { KotlinBuiltIns.isLong(notNullExpected) -> LongValue(value, canBeUsedInAnnotation, isPureIntConstant, usesVariableAsConstant)
builtIns.getLongType() -> LongValue(value, canBeUsedInAnnotation, isPureIntConstant, usesVariableAsConstant) KotlinBuiltIns.isShort(notNullExpected) -> when (value) {
builtIns.getShortType() -> when (value) {
value.toShort().toLong() -> ShortValue(value.toShort(), canBeUsedInAnnotation, isPureIntConstant, usesVariableAsConstant) value.toShort().toLong() -> ShortValue(value.toShort(), canBeUsedInAnnotation, isPureIntConstant, usesVariableAsConstant)
else -> defaultIntegerValue(value) else -> defaultIntegerValue(value)
} }
builtIns.getByteType() -> when (value) { KotlinBuiltIns.isByte(notNullExpected) -> when (value) {
value.toByte().toLong() -> ByteValue(value.toByte(), canBeUsedInAnnotation, isPureIntConstant, usesVariableAsConstant) value.toByte().toLong() -> ByteValue(value.toByte(), canBeUsedInAnnotation, isPureIntConstant, usesVariableAsConstant)
else -> defaultIntegerValue(value) else -> defaultIntegerValue(value)
} }
builtIns.getCharType() -> IntValue(value.toInt(), canBeUsedInAnnotation, isPureIntConstant, usesVariableAsConstant) KotlinBuiltIns.isChar(notNullExpected) -> IntValue(value.toInt(), canBeUsedInAnnotation, isPureIntConstant, usesVariableAsConstant)
else -> defaultIntegerValue(value) else -> defaultIntegerValue(value)
} }
} }
@@ -33,6 +33,11 @@ public class EnumValue extends CompileTimeConstant<ClassDescriptor> {
@NotNull @NotNull
@Override @Override
public JetType getType(@NotNull KotlinBuiltIns kotlinBuiltIns) { public JetType getType(@NotNull KotlinBuiltIns kotlinBuiltIns) {
return getType();
}
@NotNull
private JetType getType() {
JetType type = getClassObjectType(value); JetType type = getClassObjectType(value);
assert type != null : "Enum entry must have a class object type: " + value; assert type != null : "Enum entry must have a class object type: " + value;
return type; return type;
@@ -53,7 +58,7 @@ public class EnumValue extends CompileTimeConstant<ClassDescriptor> {
@Override @Override
public String toString() { public String toString() {
return getType(KotlinBuiltIns.getInstance()) + "." + value.getName(); return getType() + "." + value.getName();
} }
@Override @Override
@@ -32,7 +32,7 @@ public class NullValue extends CompileTimeConstant<Void> {
@NotNull @NotNull
@Override @Override
public JetType getType(@NotNull KotlinBuiltIns kotlinBuiltIns) { public JetType getType(@NotNull KotlinBuiltIns kotlinBuiltIns) {
return KotlinBuiltIns.getInstance().getNullableNothingType(); return kotlinBuiltIns.getNullableNothingType();
} }
@Override @Override
@@ -24,6 +24,7 @@ import org.jetbrains.kotlin.types.*;
import java.util.List; import java.util.List;
import static org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilPackage.getBuiltIns;
import static org.jetbrains.kotlin.types.Variance.*; import static org.jetbrains.kotlin.types.Variance.*;
public class TypeCheckingProcedure { public class TypeCheckingProcedure {
@@ -57,9 +58,9 @@ public class TypeCheckingProcedure {
return isOutProjected ? parameter.getUpperBoundsAsType() : argument.getType(); return isOutProjected ? parameter.getUpperBoundsAsType() : argument.getType();
} }
public static JetType getInType(TypeParameterDescriptor parameter, TypeProjection argument) { public static JetType getInType(@NotNull TypeParameterDescriptor parameter, @NotNull TypeProjection argument) {
boolean isOutProjected = argument.getProjectionKind() == OUT_VARIANCE || parameter.getVariance() == OUT_VARIANCE; boolean isOutProjected = argument.getProjectionKind() == OUT_VARIANCE || parameter.getVariance() == OUT_VARIANCE;
return isOutProjected ? KotlinBuiltIns.getInstance().getNothingType() : argument.getType(); return isOutProjected ? getBuiltIns(parameter).getNothingType() : argument.getType();
} }
private final TypeCheckingProcedureCallbacks constraints; private final TypeCheckingProcedureCallbacks constraints;
@@ -103,7 +103,7 @@ public class TypeDeserializer(
fun typeArgument(parameter: TypeParameterDescriptor?, typeArgumentProto: ProtoBuf.Type.Argument): TypeProjection { fun typeArgument(parameter: TypeParameterDescriptor?, typeArgumentProto: ProtoBuf.Type.Argument): TypeProjection {
return if (typeArgumentProto.getProjection() == ProtoBuf.Type.Argument.Projection.STAR) return if (typeArgumentProto.getProjection() == ProtoBuf.Type.Argument.Projection.STAR)
if (parameter == null) if (parameter == null)
TypeBasedStarProjectionImpl(KotlinBuiltIns.getInstance().getNullableAnyType()) TypeBasedStarProjectionImpl(c.components.moduleDescriptor.builtIns.getNullableAnyType())
else else
StarProjectionImpl(parameter) StarProjectionImpl(parameter)
else TypeProjectionImpl(variance(typeArgumentProto.getProjection()), type(typeArgumentProto.getType())) else TypeProjectionImpl(variance(typeArgumentProto.getProjection()), type(typeArgumentProto.getType()))
@@ -17,7 +17,6 @@
package org.jetbrains.kotlin.serialization.deserialization.descriptors; package org.jetbrains.kotlin.serialization.deserialization.descriptors;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.descriptors.SourceElement; import org.jetbrains.kotlin.descriptors.SourceElement;
import org.jetbrains.kotlin.descriptors.impl.AbstractLazyTypeParameterDescriptor; import org.jetbrains.kotlin.descriptors.impl.AbstractLazyTypeParameterDescriptor;
import org.jetbrains.kotlin.serialization.ProtoBuf; import org.jetbrains.kotlin.serialization.ProtoBuf;
@@ -30,6 +29,8 @@ import java.util.Collections;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.Set; import java.util.Set;
import static org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilPackage.getBuiltIns;
public class DeserializedTypeParameterDescriptor extends AbstractLazyTypeParameterDescriptor { public class DeserializedTypeParameterDescriptor extends AbstractLazyTypeParameterDescriptor {
private final ProtoBuf.TypeParameter proto; private final ProtoBuf.TypeParameter proto;
private final TypeDeserializer typeDeserializer; private final TypeDeserializer typeDeserializer;
@@ -50,7 +51,7 @@ public class DeserializedTypeParameterDescriptor extends AbstractLazyTypeParamet
@Override @Override
protected Set<JetType> resolveUpperBounds() { protected Set<JetType> resolveUpperBounds() {
if (proto.getUpperBoundCount() == 0) { if (proto.getUpperBoundCount() == 0) {
return Collections.singleton(KotlinBuiltIns.getInstance().getDefaultBound()); return Collections.singleton(getBuiltIns(this).getDefaultBound());
} }
Set<JetType> result = new LinkedHashSet<JetType>(proto.getUpperBoundCount()); Set<JetType> result = new LinkedHashSet<JetType>(proto.getUpperBoundCount());
for (ProtoBuf.Type upperBound : proto.getUpperBoundList()) { for (ProtoBuf.Type upperBound : proto.getUpperBoundList()) {
@@ -49,7 +49,6 @@ public class DeprecatedAnnotationVisitor extends AfterAnalysisHighlightingVisito
TokenSet.create(JetTokens.EQ, JetTokens.PLUSEQ, JetTokens.MINUSEQ, JetTokens.MULTEQ, TokenSet.create(JetTokens.EQ, JetTokens.PLUSEQ, JetTokens.MINUSEQ, JetTokens.MULTEQ,
JetTokens.DIVEQ, JetTokens.PERCEQ, JetTokens.PLUSPLUS, JetTokens.MINUSMINUS); JetTokens.DIVEQ, JetTokens.PERCEQ, JetTokens.PLUSPLUS, JetTokens.MINUSMINUS);
private static final FqName JAVA_DEPRECATED = new FqName(Deprecated.class.getName()); private static final FqName JAVA_DEPRECATED = new FqName(Deprecated.class.getName());
private static final FqName KOTLIN_DEPRECATED = DescriptorUtils.getFqNameSafe(KotlinBuiltIns.getInstance().getDeprecatedAnnotation());
protected DeprecatedAnnotationVisitor(AnnotationHolder holder, BindingContext bindingContext) { protected DeprecatedAnnotationVisitor(AnnotationHolder holder, BindingContext bindingContext) {
super(holder, bindingContext); super(holder, bindingContext);
@@ -221,7 +220,7 @@ public class DeprecatedAnnotationVisitor extends AfterAnalysisHighlightingVisito
@Nullable @Nullable
private static AnnotationDescriptor getDeprecated(DeclarationDescriptor descriptor) { private static AnnotationDescriptor getDeprecated(DeclarationDescriptor descriptor) {
AnnotationDescriptor kotlinDeprecated = descriptor.getAnnotations().findAnnotation(KOTLIN_DEPRECATED); AnnotationDescriptor kotlinDeprecated = descriptor.getAnnotations().findAnnotation(KotlinBuiltIns.FQ_NAMES.deprecated);
return kotlinDeprecated != null ? kotlinDeprecated : descriptor.getAnnotations().findAnnotation(JAVA_DEPRECATED); return kotlinDeprecated != null ? kotlinDeprecated : descriptor.getAnnotations().findAnnotation(JAVA_DEPRECATED);
} }
@@ -44,6 +44,7 @@ import org.jetbrains.kotlin.idea.util.FuzzyType
import org.jetbrains.kotlin.idea.util.makeNotNullable import org.jetbrains.kotlin.idea.util.makeNotNullable
import org.jetbrains.kotlin.idea.util.nullability import org.jetbrains.kotlin.idea.util.nullability
import org.jetbrains.kotlin.idea.util.TypeNullability import org.jetbrains.kotlin.idea.util.TypeNullability
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
class ArtificialElementInsertHandler( class ArtificialElementInsertHandler(
val textBeforeCaret: String, val textAfterCaret: String, val shortenRefs: Boolean) : InsertHandler<LookupElement>{ val textBeforeCaret: String, val textAfterCaret: String, val shortenRefs: Boolean) : InsertHandler<LookupElement>{
@@ -233,10 +234,11 @@ fun functionType(function: FunctionDescriptor): JetType? {
null null
else else
extensionReceiverType ?: memberReceiverType extensionReceiverType ?: memberReceiverType
return KotlinBuiltIns.getInstance().getFunctionType(function.getAnnotations(), return function.builtIns.getFunctionType(
receiverType, function.getAnnotations(), receiverType,
function.getValueParameters().map { it.getType() }, function.getValueParameters().map { it.getType() },
function.getReturnType() ?: return null) function.getReturnType() ?: return null
)
} }
fun LookupElementFactory.createLookupElement( fun LookupElementFactory.createLookupElement(
@@ -268,9 +268,7 @@ public abstract class OverrideImplementMethodsHandler : LanguageCodeInsightActio
newDescriptor.addOverriddenDescriptor(descriptor) newDescriptor.addOverriddenDescriptor(descriptor)
val returnType = descriptor.getReturnType() val returnType = descriptor.getReturnType()
val builtIns = KotlinBuiltIns.getInstance() val returnsNotUnit = returnType != null && !KotlinBuiltIns.isUnit(returnType)
val returnsNotUnit = returnType != null && builtIns.getUnitType() != returnType
val isAbstract = descriptor.getModality() == Modality.ABSTRACT val isAbstract = descriptor.getModality() == Modality.ABSTRACT
val delegation = generateUnsupportedOrSuperCall(classOrObject, descriptor) val delegation = generateUnsupportedOrSuperCall(classOrObject, descriptor)
@@ -34,6 +34,8 @@ import org.jetbrains.kotlin.types.JetType;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.*;
public class CodeInsightUtils { public class CodeInsightUtils {
@Nullable @Nullable
@@ -186,30 +188,28 @@ public class CodeInsightUtils {
@Nullable @Nullable
public static String defaultInitializer(JetType type) { public static String defaultInitializer(JetType type) {
KotlinBuiltIns builtIns = KotlinBuiltIns.getInstance();
if (type.isMarkedNullable()) { if (type.isMarkedNullable()) {
return "null"; return "null";
} }
else if (type.equals(builtIns.getIntType()) || type.equals(builtIns.getLongType()) || else if (isInt(type) || isLong(type) || isShort(type) || isByte(type)) {
type.equals(builtIns.getShortType()) || type.equals(builtIns.getByteType())) {
return "0"; return "0";
} }
else if (type.equals(builtIns.getFloatType())) { else if (isFloat(type)) {
return "0.0f"; return "0.0f";
} }
else if (type.equals(builtIns.getDoubleType())) { else if (isDouble(type)) {
return "0.0"; return "0.0";
} }
else if (type.equals(builtIns.getCharType())) { else if (isChar(type)) {
return "'\\u0000'"; return "'\\u0000'";
} }
else if (type.equals(builtIns.getBooleanType())) { else if (isBoolean(type)) {
return "false"; return "false";
} }
else if (type.equals(builtIns.getUnitType())) { else if (isUnit(type)) {
return "Unit"; return "Unit";
} }
else if (type.equals(builtIns.getStringType())) { else if (isString(type)) {
return "\"\""; return "\"\"";
} }
@@ -44,6 +44,8 @@ import org.jetbrains.kotlin.types.JetType;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.isAny;
public class GotoSuperActionHandler implements CodeInsightActionHandler { public class GotoSuperActionHandler implements CodeInsightActionHandler {
@Override @Override
public void invoke(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) { public void invoke(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) {
@@ -96,7 +98,7 @@ public class GotoSuperActionHandler implements CodeInsightActionHandler {
List<PsiElement> superDeclarations = ContainerUtil.mapNotNull(superDescriptors, new Function<DeclarationDescriptor, PsiElement>() { List<PsiElement> superDeclarations = ContainerUtil.mapNotNull(superDescriptors, new Function<DeclarationDescriptor, PsiElement>() {
@Override @Override
public PsiElement fun(DeclarationDescriptor descriptor) { public PsiElement fun(DeclarationDescriptor descriptor) {
if (KotlinBuiltIns.getInstance().getAny() == descriptor) { if (descriptor instanceof ClassDescriptor && isAny((ClassDescriptor) descriptor)) {
return null; return null;
} }
return DescriptorToSourceUtils.descriptorToDeclaration(descriptor); return DescriptorToSourceUtils.descriptorToDeclaration(descriptor);
@@ -23,15 +23,15 @@ import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.idea.caches.resolve.ResolvePackage; import org.jetbrains.kotlin.idea.caches.resolve.ResolvePackage;
import org.jetbrains.kotlin.psi.JetCallExpression; import org.jetbrains.kotlin.psi.JetCallExpression;
import org.jetbrains.kotlin.psi.JetExpression; import org.jetbrains.kotlin.psi.JetExpression;
import org.jetbrains.kotlin.psi.JetQualifiedExpression; import org.jetbrains.kotlin.psi.JetQualifiedExpression;
import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode; import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode;
import org.jetbrains.kotlin.types.JetType; import org.jetbrains.kotlin.types.JetType;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.isUnit;
public abstract class KotlinExpressionSurrounder implements Surrounder { public abstract class KotlinExpressionSurrounder implements Surrounder {
@Override @Override
@@ -45,7 +45,7 @@ public abstract class KotlinExpressionSurrounder implements Surrounder {
return false; return false;
} }
JetType type = ResolvePackage.analyze(expression, BodyResolveMode.PARTIAL).getType(expression); JetType type = ResolvePackage.analyze(expression, BodyResolveMode.PARTIAL).getType(expression);
if (type == null || type.equals(KotlinBuiltIns.getInstance().getUnitType())) { if (type == null || isUnit(type)) {
return false; return false;
} }
return isApplicable(expression); return isApplicable(expression);
@@ -28,7 +28,6 @@ import org.jetbrains.kotlin.idea.caches.resolve.ResolvePackage;
import org.jetbrains.kotlin.psi.JetExpression; import org.jetbrains.kotlin.psi.JetExpression;
import org.jetbrains.kotlin.psi.JetParenthesizedExpression; import org.jetbrains.kotlin.psi.JetParenthesizedExpression;
import org.jetbrains.kotlin.psi.JetPrefixExpression; import org.jetbrains.kotlin.psi.JetPrefixExpression;
import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode; import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode;
import org.jetbrains.kotlin.types.JetType; import org.jetbrains.kotlin.types.JetType;
@@ -43,7 +42,7 @@ public class KotlinNotSurrounder extends KotlinExpressionSurrounder {
@Override @Override
public boolean isApplicable(@NotNull JetExpression expression) { public boolean isApplicable(@NotNull JetExpression expression) {
JetType type = ResolvePackage.analyze(expression, BodyResolveMode.PARTIAL).getType(expression); JetType type = ResolvePackage.analyze(expression, BodyResolveMode.PARTIAL).getType(expression);
return KotlinBuiltIns.getInstance().getBooleanType().equals(type); return type != null && KotlinBuiltIns.isBoolean(type);
} }
@Nullable @Nullable
@@ -24,6 +24,7 @@ import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.psi.JetPsiFactory import org.jetbrains.kotlin.psi.JetPsiFactory
import org.jetbrains.kotlin.psi.JetPsiUtil import org.jetbrains.kotlin.psi.JetPsiUtil
import org.jetbrains.kotlin.psi.JetFunctionLiteralExpression import org.jetbrains.kotlin.psi.JetFunctionLiteralExpression
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
public open class ReplaceContainsIntention : AttributeCallReplacementIntention("replace.contains.with.in") { public open class ReplaceContainsIntention : AttributeCallReplacementIntention("replace.contains.with.in") {
@@ -32,10 +33,11 @@ public open class ReplaceContainsIntention : AttributeCallReplacementIntention("
} }
override fun replaceCall(call: CallDescription, editor: Editor) { override fun replaceCall(call: CallDescription, editor: Editor) {
val ret = call.resolved.getResultingDescriptor().getReturnType() val resultingDescriptor = call.resolved.getResultingDescriptor()
val ret = resultingDescriptor.getReturnType()
?: return intentionFailed(editor, "undefined.returntype") ?: return intentionFailed(editor, "undefined.returntype")
if (!JetTypeChecker.DEFAULT.isSubtypeOf(ret, KotlinBuiltIns.getInstance().getBooleanType())) { if (!resultingDescriptor.builtIns.isBooleanOrSubtype(ret)) {
return intentionFailed(editor, "contains.returns.boolean") return intentionFailed(editor, "contains.returns.boolean")
} }
@@ -92,12 +92,11 @@ fun JetExpression.guessTypes(
module: ModuleDescriptor, module: ModuleDescriptor,
coerceUnusedToUnit: Boolean = true coerceUnusedToUnit: Boolean = true
): Array<JetType> { ): Array<JetType> {
val builtIns = KotlinBuiltIns.getInstance()
if (coerceUnusedToUnit if (coerceUnusedToUnit
&& this !is JetDeclaration && this !is JetDeclaration
&& isUsedAsStatement(context) && isUsedAsStatement(context)
&& getNonStrictParentOfType<JetAnnotationEntry>() == null) return array(builtIns.getUnitType()) && getNonStrictParentOfType<JetAnnotationEntry>() == null) return array(module.builtIns.getUnitType())
// if we know the actual type of the expression // if we know the actual type of the expression
val theType1 = context.getType(this) val theType1 = context.getType(this)
@@ -166,14 +165,14 @@ fun JetExpression.guessTypes(
val property = context[BindingContext.DECLARATION_TO_DESCRIPTOR, parent.getParent() as JetProperty] as PropertyDescriptor val property = context[BindingContext.DECLARATION_TO_DESCRIPTOR, parent.getParent() as JetProperty] as PropertyDescriptor
val delegateClassName = if (property.isVar()) "ReadWriteProperty" else "ReadOnlyProperty" val delegateClassName = if (property.isVar()) "ReadWriteProperty" else "ReadOnlyProperty"
val delegateClass = module.resolveTopLevelClass(FqName("kotlin.properties.$delegateClassName")) val delegateClass = module.resolveTopLevelClass(FqName("kotlin.properties.$delegateClassName"))
?: return array(builtIns.getAnyType()) ?: return array(module.builtIns.getAnyType())
val receiverType = (property.getExtensionReceiverParameter() ?: property.getDispatchReceiverParameter())?.getType() val receiverType = (property.getExtensionReceiverParameter() ?: property.getDispatchReceiverParameter())?.getType()
?: builtIns.getNullableNothingType() ?: module.builtIns.getNullableNothingType()
val typeArguments = listOf(TypeProjectionImpl(receiverType), TypeProjectionImpl(property.getType())) val typeArguments = listOf(TypeProjectionImpl(receiverType), TypeProjectionImpl(property.getType()))
array(TypeUtils.substituteProjectionsForParameters(delegateClass, typeArguments)) array(TypeUtils.substituteProjectionsForParameters(delegateClass, typeArguments))
} }
parent is JetStringTemplateEntryWithExpression && parent.getExpression() == this -> { parent is JetStringTemplateEntryWithExpression && parent.getExpression() == this -> {
array(KotlinBuiltIns.getInstance().getStringType()) array(module.builtIns.getStringType())
} }
else -> array() // can't infer anything else -> array() // can't infer anything
} }
@@ -37,12 +37,11 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.analyzer.AnalysisResult; import org.jetbrains.kotlin.analyzer.AnalysisResult;
import org.jetbrains.kotlin.analyzer.AnalyzerPackage; import org.jetbrains.kotlin.analyzer.AnalyzerPackage;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.idea.caches.resolve.ResolvePackage; import org.jetbrains.kotlin.idea.caches.resolve.ResolvePackage;
import org.jetbrains.kotlin.idea.codeInsight.CodeInsightUtils; import org.jetbrains.kotlin.idea.codeInsight.CodeInsightUtils;
import org.jetbrains.kotlin.idea.core.refactoring.JetNameSuggester;
import org.jetbrains.kotlin.idea.intentions.ConvertToBlockBodyIntention; import org.jetbrains.kotlin.idea.intentions.ConvertToBlockBodyIntention;
import org.jetbrains.kotlin.idea.intentions.RemoveCurlyBracesFromTemplateIntention; import org.jetbrains.kotlin.idea.intentions.RemoveCurlyBracesFromTemplateIntention;
import org.jetbrains.kotlin.idea.core.refactoring.JetNameSuggester;
import org.jetbrains.kotlin.idea.refactoring.JetNameValidatorImpl; import org.jetbrains.kotlin.idea.refactoring.JetNameValidatorImpl;
import org.jetbrains.kotlin.idea.refactoring.JetRefactoringBundle; import org.jetbrains.kotlin.idea.refactoring.JetRefactoringBundle;
import org.jetbrains.kotlin.idea.refactoring.JetRefactoringUtil; import org.jetbrains.kotlin.idea.refactoring.JetRefactoringUtil;
@@ -151,7 +150,7 @@ public class KotlinIntroduceVariableHandler extends KotlinIntroduceHandlerBase {
return; return;
} }
if (expressionType != null && if (expressionType != null &&
JetTypeChecker.DEFAULT.equalTypes(KotlinBuiltIns.getInstance().getUnitType(), expressionType)) { JetTypeChecker.DEFAULT.equalTypes(analysisResult.getModuleDescriptor().getBuiltIns().getUnitType(), expressionType)) {
showErrorHint(project, editor, JetRefactoringBundle.message("cannot.refactor.expression.has.unit.type")); showErrorHint(project, editor, JetRefactoringBundle.message("cannot.refactor.expression.has.unit.type"));
return; return;
} }
@@ -38,6 +38,7 @@ import org.jetbrains.kotlin.psi.JetParameter
import org.jetbrains.kotlin.psi.JetVariableDeclaration import org.jetbrains.kotlin.psi.JetVariableDeclaration
import org.jetbrains.kotlin.psi.psiUtil.isAncestor import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.source.PsiSourceElement import org.jetbrains.kotlin.resolve.source.PsiSourceElement
import org.jetbrains.kotlin.types.JetType import org.jetbrains.kotlin.types.JetType
import java.util.ArrayList import java.util.ArrayList
@@ -97,7 +98,7 @@ public class AutomaticVariableRenamer(
private fun JetType.isCollectionLikeOf(classPsiElement: PsiNamedElement): Boolean { private fun JetType.isCollectionLikeOf(classPsiElement: PsiNamedElement): Boolean {
val klass = this.getConstructor().getDeclarationDescriptor() as? ClassDescriptor ?: return false val klass = this.getConstructor().getDeclarationDescriptor() as? ClassDescriptor ?: return false
if (KotlinBuiltIns.isArray(this) || DescriptorUtils.isSubclass(klass, KotlinBuiltIns.getInstance().getCollection())) { if (KotlinBuiltIns.isArray(this) || DescriptorUtils.isSubclass(klass, klass.builtIns.getCollection())) {
val typeArgument = this.getArguments().singleOrNull()?.getType() ?: return false val typeArgument = this.getArguments().singleOrNull()?.getType() ?: return false
val typePsiElement = ((typeArgument.getConstructor().getDeclarationDescriptor() as? ClassDescriptor)?.getSource() as? PsiSourceElement)?.psi val typePsiElement = ((typeArgument.getConstructor().getDeclarationDescriptor() as? ClassDescriptor)?.getSource() as? PsiSourceElement)?.psi
return classPsiElement == typePsiElement || typeArgument.isCollectionLikeOf(classPsiElement) return classPsiElement == typePsiElement || typeArgument.isCollectionLikeOf(classPsiElement)
@@ -156,7 +156,7 @@ public class InjectorForTopDownAnalyzerForJs {
this.argumentTypeResolver = new ArgumentTypeResolver(); this.argumentTypeResolver = new ArgumentTypeResolver();
this.expressionTypingComponents = new ExpressionTypingComponents(); this.expressionTypingComponents = new ExpressionTypingComponents();
this.expressionTypingServices = new ExpressionTypingServices(expressionTypingComponents); this.expressionTypingServices = new ExpressionTypingServices(expressionTypingComponents);
this.callExpressionResolver = new CallExpressionResolver(callResolver); this.callExpressionResolver = new CallExpressionResolver(callResolver, kotlinBuiltIns);
this.controlStructureTypingUtils = new ControlStructureTypingUtils(callResolver); this.controlStructureTypingUtils = new ControlStructureTypingUtils(callResolver);
this.descriptorResolver = new DescriptorResolver(); this.descriptorResolver = new DescriptorResolver();
this.delegatedPropertyResolver = new DelegatedPropertyResolver(); this.delegatedPropertyResolver = new DelegatedPropertyResolver();
@@ -25,12 +25,13 @@ import org.jetbrains.kotlin.types.JetType
import org.jetbrains.kotlin.types.TypeProjection import org.jetbrains.kotlin.types.TypeProjection
import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
public val JetType.nameIfStandardType: Name? public val JetType.nameIfStandardType: Name?
get() { get() {
val descriptor = getConstructor().getDeclarationDescriptor() val descriptor = getConstructor().getDeclarationDescriptor()
if (descriptor?.getContainingDeclaration() == KotlinBuiltIns.getInstance().getBuiltInsPackageFragment()) { if (descriptor?.getContainingDeclaration() == descriptor?.builtIns?.getBuiltInsPackageFragment()) {
return descriptor?.getName() return descriptor?.getName()
} }
@@ -18,7 +18,6 @@ package org.jetbrains.kotlin.js.translate.callTranslator
import com.google.dart.compiler.backend.js.ast.* import com.google.dart.compiler.backend.js.ast.*
import com.intellij.util.SmartList import com.intellij.util.SmartList
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.ConstructorDescriptor import org.jetbrains.kotlin.descriptors.ConstructorDescriptor
import org.jetbrains.kotlin.descriptors.Visibilities import org.jetbrains.kotlin.descriptors.Visibilities
@@ -33,6 +32,7 @@ import org.jetbrains.kotlin.js.translate.utils.PsiUtils
import org.jetbrains.kotlin.lexer.JetTokens import org.jetbrains.kotlin.lexer.JetTokens
import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.calls.tasks.isDynamic import org.jetbrains.kotlin.resolve.calls.tasks.isDynamic
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.types.expressions.OperatorConventions import org.jetbrains.kotlin.types.expressions.OperatorConventions
import java.util.ArrayList import java.util.ArrayList
@@ -166,17 +166,18 @@ object NativeSetterCallCase : AnnotatedAsNativeXCallCase(PredefinedAnnotation.NA
object InvokeIntrinsic : FunctionCallCase { object InvokeIntrinsic : FunctionCallCase {
fun canApply(callInfo: FunctionCallInfo): Boolean { fun canApply(callInfo: FunctionCallInfo): Boolean {
if (callInfo.callableDescriptor.getName() != OperatorConventions.INVOKE) val callableDescriptor = callInfo.callableDescriptor
if (callableDescriptor.getName() != OperatorConventions.INVOKE)
return false return false
val parameterCount = callInfo.callableDescriptor.getValueParameters().size() val parameterCount = callableDescriptor.getValueParameters().size()
val funDeclaration = callInfo.callableDescriptor.getContainingDeclaration() val funDeclaration = callableDescriptor.getContainingDeclaration()
val reflectionTypes = callInfo.context.getReflectionTypes() val reflectionTypes = callInfo.context.getReflectionTypes()
return if (callInfo.callableDescriptor.getExtensionReceiverParameter() == null) return if (callableDescriptor.getExtensionReceiverParameter() == null)
funDeclaration == KotlinBuiltIns.getInstance().getFunction(parameterCount) || funDeclaration == callableDescriptor.builtIns.getFunction(parameterCount) ||
funDeclaration == reflectionTypes.getKFunction(parameterCount) funDeclaration == reflectionTypes.getKFunction(parameterCount)
else else
funDeclaration == KotlinBuiltIns.getInstance().getExtensionFunction(parameterCount) || funDeclaration == callableDescriptor.builtIns.getExtensionFunction(parameterCount) ||
funDeclaration == reflectionTypes.getKExtensionFunction(parameterCount) || funDeclaration == reflectionTypes.getKExtensionFunction(parameterCount) ||
funDeclaration == reflectionTypes.getKMemberFunction(parameterCount) funDeclaration == reflectionTypes.getKMemberFunction(parameterCount)
} }
@@ -30,6 +30,9 @@ import org.jetbrains.kotlin.psi.JetParameter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static kotlin.KotlinPackage.first;
import static org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilPackage.getBuiltIns;
class JsDataClassGenerator extends DataClassMethodGenerator { class JsDataClassGenerator extends DataClassMethodGenerator {
private final TranslationContext context; private final TranslationContext context;
private final List<? super JsPropertyInitializer> output; private final List<? super JsPropertyInitializer> output;
@@ -90,7 +93,7 @@ class JsDataClassGenerator extends DataClassMethodGenerator {
public void generateToStringMethod(@NotNull List<PropertyDescriptor> classProperties) { public void generateToStringMethod(@NotNull List<PropertyDescriptor> classProperties) {
// TODO: relax this limitation, with the data generation logic fixed. // TODO: relax this limitation, with the data generation logic fixed.
assert !classProperties.isEmpty(); assert !classProperties.isEmpty();
FunctionDescriptor prototypeFun = CodegenUtil.getAnyToStringMethod(); FunctionDescriptor prototypeFun = CodegenUtil.getAnyToStringMethod(getBuiltIns(first(classProperties)));
JsFunction functionObj = generateJsMethod(prototypeFun); JsFunction functionObj = generateJsMethod(prototypeFun);
JsProgram jsProgram = context.program(); JsProgram jsProgram = context.program();
@@ -115,7 +118,7 @@ class JsDataClassGenerator extends DataClassMethodGenerator {
@Override @Override
public void generateHashCodeMethod(@NotNull List<PropertyDescriptor> classProperties) { public void generateHashCodeMethod(@NotNull List<PropertyDescriptor> classProperties) {
FunctionDescriptor prototypeFun = CodegenUtil.getAnyHashCodeMethod(); FunctionDescriptor prototypeFun = CodegenUtil.getAnyHashCodeMethod(getBuiltIns(first(classProperties)));
JsFunction functionObj = generateJsMethod(prototypeFun); JsFunction functionObj = generateJsMethod(prototypeFun);
JsProgram jsProgram = context.program(); JsProgram jsProgram = context.program();
@@ -142,7 +145,7 @@ class JsDataClassGenerator extends DataClassMethodGenerator {
@Override @Override
public void generateEqualsMethod(@NotNull List<PropertyDescriptor> classProperties) { public void generateEqualsMethod(@NotNull List<PropertyDescriptor> classProperties) {
assert !classProperties.isEmpty(); assert !classProperties.isEmpty();
FunctionDescriptor prototypeFun = CodegenUtil.getAnyEqualsMethod(); FunctionDescriptor prototypeFun = CodegenUtil.getAnyEqualsMethod(getBuiltIns(first(classProperties)));
JsFunction functionObj = generateJsMethod(prototypeFun); JsFunction functionObj = generateJsMethod(prototypeFun);
JsFunctionScope funScope = functionObj.getScope(); JsFunctionScope funScope = functionObj.getScope();
@@ -28,7 +28,6 @@ import org.jetbrains.kotlin.js.descriptorUtils.DescriptorUtilsPackage;
import org.jetbrains.kotlin.js.translate.context.TranslationContext; import org.jetbrains.kotlin.js.translate.context.TranslationContext;
import org.jetbrains.kotlin.name.Name; import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.psi.JetExpression; import org.jetbrains.kotlin.psi.JetExpression;
import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.DescriptorUtils; import org.jetbrains.kotlin.resolve.DescriptorUtils;
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue; import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue;
import org.jetbrains.kotlin.resolve.scopes.receivers.ThisReceiver; import org.jetbrains.kotlin.resolve.scopes.receivers.ThisReceiver;
@@ -43,11 +42,12 @@ import static org.jetbrains.kotlin.js.config.LibrarySourcesConfig.BUILTINS_JS_MO
import static org.jetbrains.kotlin.js.translate.utils.AnnotationsUtils.isNativeObject; import static org.jetbrains.kotlin.js.translate.utils.AnnotationsUtils.isNativeObject;
import static org.jetbrains.kotlin.resolve.DescriptorToSourceUtils.descriptorToDeclaration; import static org.jetbrains.kotlin.resolve.DescriptorToSourceUtils.descriptorToDeclaration;
import static org.jetbrains.kotlin.resolve.DescriptorUtils.*; import static org.jetbrains.kotlin.resolve.DescriptorUtils.*;
import static org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilPackage.getBuiltIns;
public final class JsDescriptorUtils { public final class JsDescriptorUtils {
// TODO: maybe we should use external annotations or something else. // TODO: maybe we should use external annotations or something else.
private static final Set<String> FAKE_CLASSES = ContainerUtil.immutableSet( private static final Set<String> FAKE_CLASSES = ContainerUtil.immutableSet(
getFqNameSafe(KotlinBuiltIns.getInstance().getAny()).asString() KotlinBuiltIns.FQ_NAMES.any.asString()
); );
private JsDescriptorUtils() { private JsDescriptorUtils() {
@@ -157,7 +157,7 @@ public final class JsDescriptorUtils {
public static boolean isBuiltin(@NotNull DeclarationDescriptor descriptor) { public static boolean isBuiltin(@NotNull DeclarationDescriptor descriptor) {
PackageFragmentDescriptor containingPackageFragment = DescriptorUtils.getParentOfType(descriptor, PackageFragmentDescriptor.class); PackageFragmentDescriptor containingPackageFragment = DescriptorUtils.getParentOfType(descriptor, PackageFragmentDescriptor.class);
return containingPackageFragment == KotlinBuiltIns.getInstance().getBuiltInsPackageFragment(); return containingPackageFragment == getBuiltIns(descriptor).getBuiltInsPackageFragment();
} }
@Nullable @Nullable
@@ -215,8 +215,7 @@ public final class TranslationUtils {
if (operationDescriptor == null || !(operationDescriptor instanceof FunctionDescriptor)) return true; if (operationDescriptor == null || !(operationDescriptor instanceof FunctionDescriptor)) return true;
JetType returnType = operationDescriptor.getReturnType(); JetType returnType = operationDescriptor.getReturnType();
if (returnType != null && if (returnType != null && (KotlinBuiltIns.isChar(returnType) || KotlinBuiltIns.isLong(returnType))) return false;
KotlinBuiltIns.getInstance().getCharType().equals(returnType) || (KotlinBuiltIns.getInstance().getLongType().equals(returnType))) return false;
if (context.intrinsics().getFunctionIntrinsic((FunctionDescriptor) operationDescriptor).exists()) return true; if (context.intrinsics().getFunctionIntrinsic((FunctionDescriptor) operationDescriptor).exists()) return true;