Use Java 8 lambdas instead of anonymous classes in compiler modules

This commit is contained in:
Alexander Udalov
2017-04-01 01:37:15 +03:00
parent 6aa0f7bb65
commit 5ebee6ceca
109 changed files with 1528 additions and 2754 deletions
@@ -88,14 +88,7 @@ public class RunUtils {
public static void executeOnSeparateThread(@NotNull RunSettings settings) { public static void executeOnSeparateThread(@NotNull RunSettings settings) {
assert !settings.waitForEnd : "Use execute() instead"; assert !settings.waitForEnd : "Use execute() instead";
Thread t = new Thread(new Runnable() { new Thread(() -> run(settings)).start();
@Override
public void run() {
RunUtils.run(settings);
}
});
t.start();
} }
private static RunResult run(RunSettings settings) { private static RunResult run(RunSettings settings) {
@@ -21,7 +21,6 @@ import com.google.common.collect.Sets;
import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Pair;
import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.IElementType;
import kotlin.Unit; import kotlin.Unit;
import kotlin.jvm.functions.Function1;
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.builtins.KotlinBuiltIns;
@@ -501,14 +500,11 @@ public class AsmUtil {
} }
public static StackValue genToString(StackValue receiver, Type receiverType) { public static StackValue genToString(StackValue receiver, Type receiverType) {
return StackValue.operation(JAVA_STRING_TYPE, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(JAVA_STRING_TYPE, v -> {
@Override Type type = stringValueOfType(receiverType);
public Unit invoke(InstructionAdapter v) { receiver.put(type, v);
Type type = stringValueOfType(receiverType); v.invokestatic("java/lang/String", "valueOf", "(" + type.getDescriptor() + ")Ljava/lang/String;", false);
receiver.put(type, v); return null;
v.invokestatic("java/lang/String", "valueOf", "(" + type.getDescriptor() + ")Ljava/lang/String;", false);
return null;
}
}); });
} }
@@ -573,18 +569,15 @@ public class AsmUtil {
return StackValue.cmp(opToken, leftType, left, right); return StackValue.cmp(opToken, leftType, left, right);
} }
return StackValue.operation(Type.BOOLEAN_TYPE, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(Type.BOOLEAN_TYPE, v -> {
@Override left.put(leftType, v);
public Unit invoke(InstructionAdapter v) { right.put(rightType, v);
left.put(leftType, v); genAreEqualCall(v);
right.put(rightType, v);
genAreEqualCall(v);
if (opToken == KtTokens.EXCLEQ || opToken == KtTokens.EXCLEQEQEQ) { if (opToken == KtTokens.EXCLEQ || opToken == KtTokens.EXCLEQEQEQ) {
genInvertBoolean(v); genInvertBoolean(v);
}
return Unit.INSTANCE;
} }
return Unit.INSTANCE;
}); });
} }
@@ -18,8 +18,6 @@ package org.jetbrains.kotlin.codegen;
import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFile;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -130,12 +128,7 @@ public class ClassFileFactory implements OutputFileCollection {
@NotNull @NotNull
public List<OutputFile> getCurrentOutput() { public List<OutputFile> getCurrentOutput() {
return ContainerUtil.map(generators.keySet(), new Function<String, OutputFile>() { return CollectionsKt.map(generators.keySet(), OutputClassFile::new);
@Override
public OutputFile fun(String relativeClassFilePath) {
return new OutputClassFile(relativeClassFilePath);
}
});
} }
@Override @Override
@@ -183,16 +176,13 @@ public class ClassFileFactory implements OutputFileCollection {
private PackagePartRegistry buildNewPackagePartRegistry(@NotNull FqName packageFqName) { private PackagePartRegistry buildNewPackagePartRegistry(@NotNull FqName packageFqName) {
String packageFqNameAsString = packageFqName.asString(); String packageFqNameAsString = packageFqName.asString();
return new PackagePartRegistry() { return (partShortName, facadeShortName) -> {
@Override PackageParts packageParts = partsGroupedByPackage.get(packageFqNameAsString);
public void addPart(@NotNull String partShortName, @Nullable String facadeShortName) { if (packageParts == null) {
PackageParts packageParts = partsGroupedByPackage.get(packageFqNameAsString); packageParts = new PackageParts(packageFqNameAsString);
if (packageParts == null) { partsGroupedByPackage.put(packageFqNameAsString, packageParts);
packageParts = new PackageParts(packageFqNameAsString);
partsGroupedByPackage.put(packageFqNameAsString, packageParts);
}
packageParts.addPart(partShortName, facadeShortName);
} }
packageParts.addPart(partShortName, facadeShortName);
}; };
} }
@@ -21,7 +21,6 @@ import com.intellij.util.ArrayUtil;
import kotlin.Pair; import kotlin.Pair;
import kotlin.Unit; import kotlin.Unit;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.codegen.binding.CalculatedClosure; import org.jetbrains.kotlin.codegen.binding.CalculatedClosure;
@@ -49,7 +48,6 @@ import org.jetbrains.kotlin.serialization.ProtoBuf;
import org.jetbrains.kotlin.types.KotlinType; import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils; import org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils;
import org.jetbrains.kotlin.util.OperatorNameConventions; import org.jetbrains.kotlin.util.OperatorNameConventions;
import org.jetbrains.org.objectweb.asm.AnnotationVisitor;
import org.jetbrains.org.objectweb.asm.MethodVisitor; import org.jetbrains.org.objectweb.asm.MethodVisitor;
import org.jetbrains.org.objectweb.asm.Type; import org.jetbrains.org.objectweb.asm.Type;
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter; import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
@@ -241,12 +239,9 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
ProtoBuf.Function functionProto = serializer.functionProto(freeLambdaDescriptor).build(); ProtoBuf.Function functionProto = serializer.functionProto(freeLambdaDescriptor).build();
WriteAnnotationUtilKt.writeKotlinMetadata(v, state, KotlinClassHeader.Kind.SYNTHETIC_CLASS, 0, new Function1<AnnotationVisitor, Unit>() { WriteAnnotationUtilKt.writeKotlinMetadata(v, state, KotlinClassHeader.Kind.SYNTHETIC_CLASS, 0, av -> {
@Override writeAnnotationData(av, serializer, functionProto);
public Unit invoke(AnnotationVisitor av) { return Unit.INSTANCE;
writeAnnotationData(av, serializer, functionProto);
return Unit.INSTANCE;
}
}); });
} }
@@ -284,22 +279,19 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
public StackValue putInstanceOnStack(@NotNull ExpressionCodegen codegen, @Nullable StackValue functionReferenceReceiver) { public StackValue putInstanceOnStack(@NotNull ExpressionCodegen codegen, @Nullable StackValue functionReferenceReceiver) {
return StackValue.operation( return StackValue.operation(
functionReferenceTarget != null ? K_FUNCTION : asmType, functionReferenceTarget != null ? K_FUNCTION : asmType,
new Function1<InstructionAdapter, Unit>() { v -> {
@Override if (isConst(closure)) {
public Unit invoke(InstructionAdapter v) { v.getstatic(asmType.getInternalName(), JvmAbi.INSTANCE_FIELD, asmType.getDescriptor());
if (isConst(closure)) {
v.getstatic(asmType.getInternalName(), JvmAbi.INSTANCE_FIELD, asmType.getDescriptor());
}
else {
v.anew(asmType);
v.dup();
codegen.pushClosureOnStack(classDescriptor, true, codegen.defaultCallGenerator, functionReferenceReceiver);
v.invokespecial(asmType.getInternalName(), "<init>", constructor.getDescriptor(), false);
}
return Unit.INSTANCE;
} }
else {
v.anew(asmType);
v.dup();
codegen.pushClosureOnStack(classDescriptor, true, codegen.defaultCallGenerator, functionReferenceReceiver);
v.invokespecial(asmType.getInternalName(), "<init>", constructor.getDescriptor(), false);
}
return Unit.INSTANCE;
} }
); );
} }
@@ -17,15 +17,11 @@
package org.jetbrains.kotlin.codegen; package org.jetbrains.kotlin.codegen;
public interface CompilationErrorHandler { public interface CompilationErrorHandler {
CompilationErrorHandler THROW_EXCEPTION = (exception, fileUrl) -> {
CompilationErrorHandler THROW_EXCEPTION = new CompilationErrorHandler() { if (exception instanceof RuntimeException) {
@Override throw (RuntimeException) exception;
public void reportException(Throwable exception, String fileUrl) {
if (exception instanceof RuntimeException) {
throw (RuntimeException) exception;
}
throw new IllegalStateException(exception);
} }
throw new IllegalStateException(exception);
}; };
void reportException(Throwable exception, String fileUrl); void reportException(Throwable exception, String fileUrl);
@@ -22,19 +22,11 @@ import org.jetbrains.kotlin.psi.KtParameter;
import static org.jetbrains.kotlin.resolve.DescriptorToSourceUtils.descriptorToDeclaration; import static org.jetbrains.kotlin.resolve.DescriptorToSourceUtils.descriptorToDeclaration;
public interface DefaultParameterValueLoader { public interface DefaultParameterValueLoader {
StackValue genValue(ValueParameterDescriptor descriptor, ExpressionCodegen codegen); StackValue genValue(ValueParameterDescriptor descriptor, ExpressionCodegen codegen);
DefaultParameterValueLoader DEFAULT = new DefaultParameterValueLoader() { DefaultParameterValueLoader DEFAULT = (descriptor, codegen) -> {
@Override KtParameter ktParameter = (KtParameter) descriptorToDeclaration(descriptor);
public StackValue genValue( assert ktParameter != null;
ValueParameterDescriptor descriptor, return codegen.gen(ktParameter.getDefaultValue());
ExpressionCodegen codegen
) {
KtParameter jetParameter = (KtParameter) descriptorToDeclaration(descriptor);
assert jetParameter != null;
return codegen.gen(jetParameter.getDefaultValue());
}
}; };
} }
File diff suppressed because it is too large Load Diff
@@ -20,8 +20,8 @@ import com.google.common.collect.Lists;
import com.intellij.openapi.util.Trinity; import com.intellij.openapi.util.Trinity;
import gnu.trove.TObjectIntHashMap; import gnu.trove.TObjectIntHashMap;
import gnu.trove.TObjectIntIterator; import gnu.trove.TObjectIntIterator;
import org.jetbrains.org.objectweb.asm.Type;
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor; import org.jetbrains.kotlin.descriptors.DeclarationDescriptor;
import org.jetbrains.org.objectweb.asm.Type;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
@@ -115,15 +115,7 @@ public class FrameMap {
descriptors.add(Trinity.create(descriptor, varIndex, varSize)); descriptors.add(Trinity.create(descriptor, varIndex, varSize));
} }
Collections.sort(descriptors, new Comparator<Trinity<DeclarationDescriptor, Integer, Integer>>() { Collections.sort(descriptors, Comparator.comparingInt(left -> left.second));
@Override
public int compare(
Trinity<DeclarationDescriptor, Integer, Integer> left,
Trinity<DeclarationDescriptor, Integer, Integer> right
) {
return left.second - right.second;
}
});
sb.append("size=").append(myMaxIndex); sb.append("size=").append(myMaxIndex);
@@ -19,9 +19,6 @@ package org.jetbrains.kotlin.codegen;
import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElement;
import com.intellij.util.ArrayUtil; import com.intellij.util.ArrayUtil;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import kotlin.Unit;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1; import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@@ -65,6 +62,7 @@ import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodParameterSignature
import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature; import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature;
import org.jetbrains.kotlin.types.KotlinType; import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.kotlin.types.TypeUtils; import org.jetbrains.kotlin.types.TypeUtils;
import org.jetbrains.kotlin.utils.StringsKt;
import org.jetbrains.org.objectweb.asm.*; import org.jetbrains.org.objectweb.asm.*;
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter; import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
import org.jetbrains.org.objectweb.asm.commons.Method; import org.jetbrains.org.objectweb.asm.commons.Method;
@@ -79,7 +77,8 @@ import java.util.Set;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.isNullableAny; 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.JvmCodegenUtil.*; import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isAnnotationOrJvmInterfaceWithoutDefaults;
import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isJvm8InterfaceWithDefaultsMember;
import static org.jetbrains.kotlin.codegen.serialization.JvmSerializationBindings.METHOD_FOR_FUNCTION; import static org.jetbrains.kotlin.codegen.serialization.JvmSerializationBindings.METHOD_FOR_FUNCTION;
import static org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.DECLARATION; import static org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.DECLARATION;
import static org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget.*; import static org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget.*;
@@ -277,20 +276,17 @@ public class FunctionCodegen {
v, "Default Impl delegate in interface", Opcodes.ACC_SYNTHETIC | Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC, v, "Default Impl delegate in interface", Opcodes.ACC_SYNTHETIC | Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC,
new Method(defaultImplMethod.getName() + JvmAbi.DEFAULT_IMPLS_DELEGATE_SUFFIX, defaultImplMethod.getDescriptor()), new Method(defaultImplMethod.getName() + JvmAbi.DEFAULT_IMPLS_DELEGATE_SUFFIX, defaultImplMethod.getDescriptor()),
element, JvmDeclarationOrigin.NO_ORIGIN, element, JvmDeclarationOrigin.NO_ORIGIN,
state, new Function1<InstructionAdapter, Unit>() { state, adapter -> {
@Override Method interfaceMethod = typeMapper.mapAsmMethod(functionDescriptor, OwnerKind.IMPLEMENTATION);
public Unit invoke(InstructionAdapter adapter) { Type type = typeMapper.mapOwner(functionDescriptor);
Method interfaceMethod = typeMapper.mapAsmMethod(functionDescriptor, OwnerKind.IMPLEMENTATION); generateDelegateToMethodBody(
Type type = typeMapper.mapOwner(functionDescriptor); -1, adapter,
generateDelegateToMethodBody( interfaceMethod,
-1, adapter, type.getInternalName(),
interfaceMethod, Opcodes.INVOKESPECIAL,
type.getInternalName(), true
Opcodes.INVOKESPECIAL, );
true return null;
);
return null;
}
} }
); );
} }
@@ -642,14 +638,11 @@ public class FunctionCodegen {
} }
private static String joinParameterNames(@NotNull List<VariableDescriptor> variables) { private static String joinParameterNames(@NotNull List<VariableDescriptor> variables) {
return org.jetbrains.kotlin.utils.StringsKt.join(CollectionsKt.map(variables, new Function1<VariableDescriptor, String>() { // stub for anonymous destructuring declaration entry
@Override return StringsKt.join(
public String invoke(VariableDescriptor descriptor) { CollectionsKt.map(variables, descriptor -> descriptor.getName().isSpecial() ? "$_$" : descriptor.getName().asString()),
// stub for anonymous destructuring declaration entry "_"
if (descriptor.getName().isSpecial()) return "$_$"; );
return descriptor.getName().asString();
}
}), "_");
} }
private static void generateFacadeDelegateMethodBody( private static void generateFacadeDelegateMethodBody(
@@ -815,23 +808,16 @@ public class FunctionCodegen {
} }
public static boolean isThereOverriddenInKotlinClass(@NotNull CallableMemberDescriptor descriptor) { public static boolean isThereOverriddenInKotlinClass(@NotNull CallableMemberDescriptor descriptor) {
return CollectionsKt.any(getAllOverriddenDescriptors(descriptor), new Function1<CallableMemberDescriptor, Boolean>() { return CollectionsKt.any(
@Override getAllOverriddenDescriptors(descriptor),
public Boolean invoke(CallableMemberDescriptor descriptor) { overridden -> !(overridden.getContainingDeclaration() instanceof JavaClassDescriptor) &&
return !(descriptor.getContainingDeclaration() instanceof JavaClassDescriptor) && isClass(overridden.getContainingDeclaration())
isClass(descriptor.getContainingDeclaration()); );
}
});
} }
@NotNull @NotNull
private static Function1<FunctionDescriptor, Method> getSignatureMapper(@NotNull KotlinTypeMapper typeMapper) { private static Function1<FunctionDescriptor, Method> getSignatureMapper(@NotNull KotlinTypeMapper typeMapper) {
return new Function1<FunctionDescriptor, Method>() { return typeMapper::mapAsmMethod;
@Override
public Method invoke(FunctionDescriptor descriptor) {
return typeMapper.mapAsmMethod(descriptor);
}
};
} }
public static boolean isMethodOfAny(@NotNull FunctionDescriptor descriptor) { public static boolean isMethodOfAny(@NotNull FunctionDescriptor descriptor) {
@@ -862,18 +848,15 @@ public class FunctionCodegen {
if (!(value instanceof ArrayValue)) return ArrayUtil.EMPTY_STRING_ARRAY; if (!(value instanceof ArrayValue)) return ArrayUtil.EMPTY_STRING_ARRAY;
ArrayValue arrayValue = (ArrayValue) value; ArrayValue arrayValue = (ArrayValue) value;
List<String> strings = ContainerUtil.mapNotNull( List<String> strings = CollectionsKt.mapNotNull(
arrayValue.getValue(), arrayValue.getValue(),
new Function<ConstantValue<?>, String>() { (ConstantValue<?> constant) -> {
@Override if (constant instanceof KClassValue) {
public String fun(ConstantValue<?> constant) { KClassValue classValue = (KClassValue) constant;
if (constant instanceof KClassValue) { ClassDescriptor classDescriptor = DescriptorUtils.getClassDescriptorForType(classValue.getValue());
KClassValue classValue = (KClassValue) constant; return mapper.mapClass(classDescriptor).getInternalName();
ClassDescriptor classDescriptor = DescriptorUtils.getClassDescriptorForType(classValue.getValue());
return mapper.mapClass(classDescriptor).getInternalName();
}
return null;
} }
return null;
} }
); );
return ArrayUtil.toStringArray(strings); return ArrayUtil.toStringArray(strings);
@@ -21,8 +21,6 @@ import com.intellij.psi.PsiElement;
import com.intellij.util.ArrayUtil; import com.intellij.util.ArrayUtil;
import kotlin.Unit; import kotlin.Unit;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1;
import kotlin.jvm.functions.Function2; import kotlin.jvm.functions.Function2;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -395,12 +393,11 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
KotlinBuiltIns builtIns = DescriptorUtilsKt.getBuiltIns(descriptor); KotlinBuiltIns builtIns = DescriptorUtilsKt.getBuiltIns(descriptor);
if (!isSubclass(descriptor, builtIns.getCollection())) return; if (!isSubclass(descriptor, builtIns.getCollection())) return;
if (CollectionsKt.any(DescriptorUtilsKt.getAllSuperclassesWithoutAny(descriptor), new Function1<ClassDescriptor, Boolean>() { if (CollectionsKt.any(DescriptorUtilsKt.getAllSuperclassesWithoutAny(descriptor),
@Override classDescriptor -> !(classDescriptor instanceof JavaClassDescriptor) &&
public Boolean invoke(ClassDescriptor classDescriptor) { isSubclass(classDescriptor, builtIns.getCollection()))) {
return !(classDescriptor instanceof JavaClassDescriptor) && isSubclass(classDescriptor, builtIns.getCollection()); return;
} }
})) return;
Collection<SimpleFunctionDescriptor> functions = descriptor.getDefaultType().getMemberScope().getContributedFunctions( Collection<SimpleFunctionDescriptor> functions = descriptor.getDefaultType().getMemberScope().getContributedFunctions(
Name.identifier("toArray"), NoLookupLocation.FROM_BACKEND Name.identifier("toArray"), NoLookupLocation.FROM_BACKEND
@@ -735,15 +732,12 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
functionCodegen.generateDefaultIfNeeded( functionCodegen.generateDefaultIfNeeded(
context.intoFunction(function), function, OwnerKind.IMPLEMENTATION, context.intoFunction(function), function, OwnerKind.IMPLEMENTATION,
new DefaultParameterValueLoader() { (valueParameter, codegen) -> {
@Override assert ((ClassDescriptor) function.getContainingDeclaration()).isData()
public StackValue genValue(ValueParameterDescriptor valueParameter, ExpressionCodegen codegen) { : "Function container must have [data] modifier: " + function;
assert ((ClassDescriptor) function.getContainingDeclaration()).isData() PropertyDescriptor property = bindingContext.get(BindingContext.VALUE_PARAMETER_AS_PROPERTY, valueParameter);
: "Function container must have [data] modifier: " + function; assert property != null : "Copy function doesn't correspond to any property: " + function;
PropertyDescriptor property = bindingContext.get(BindingContext.VALUE_PARAMETER_AS_PROPERTY, valueParameter); return codegen.intermediateValueForProperty(property, false, null, StackValue.LOCAL_0);
assert property != null : "Copy function doesn't correspond to any property: " + function;
return codegen.intermediateValueForProperty(property, false, null, StackValue.LOCAL_0);
}
}, },
null null
); );
@@ -785,14 +779,11 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
private void generateEnumValueOfMethod() { private void generateEnumValueOfMethod() {
FunctionDescriptor valueOfFunction = FunctionDescriptor valueOfFunction =
CollectionsKt.single(descriptor.getStaticScope().getContributedFunctions(ENUM_VALUE_OF, NoLookupLocation.FROM_BACKEND), new Function1<FunctionDescriptor, Boolean>() { CollectionsKt.single(descriptor.getStaticScope().getContributedFunctions(ENUM_VALUE_OF, NoLookupLocation.FROM_BACKEND),
@Override DescriptorUtilsKt::isEnumValueOfMethod);
public Boolean invoke(FunctionDescriptor descriptor) { MethodVisitor mv =
return DescriptorUtilsKt.isEnumValueOfMethod(descriptor); v.newMethod(JvmDeclarationOriginKt.OtherOrigin(myClass, valueOfFunction), ACC_PUBLIC | ACC_STATIC, ENUM_VALUE_OF.asString(),
} "(Ljava/lang/String;)" + classAsmType.getDescriptor(), null, null);
});
MethodVisitor mv = v.newMethod(JvmDeclarationOriginKt.OtherOrigin(myClass, valueOfFunction), ACC_PUBLIC | ACC_STATIC, ENUM_VALUE_OF.asString(),
"(Ljava/lang/String;)" + classAsmType.getDescriptor(), null, null);
if (!state.getClassBuilderMode().generateBodies) return; if (!state.getClassBuilderMode().generateBodies) return;
mv.visitCode(); mv.visitCode();
@@ -991,13 +982,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
} }
if (JvmAbi.isCompanionObjectWithBackingFieldsInOuter(descriptor)) { if (JvmAbi.isCompanionObjectWithBackingFieldsInOuter(descriptor)) {
ImplementationBodyCodegen parentCodegen = (ImplementationBodyCodegen) getParentCodegen(); generateInitializers(((ImplementationBodyCodegen) getParentCodegen())::createOrGetClInitCodegen);
generateInitializers(new Function0<ExpressionCodegen>() {
@Override
public ExpressionCodegen invoke() {
return parentCodegen.createOrGetClInitCodegen();
}
});
} }
else { else {
generateInitializers(codegen); generateInitializers(codegen);
@@ -1061,12 +1046,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
} }
private void generateInitializers(@NotNull ExpressionCodegen codegen) { private void generateInitializers(@NotNull ExpressionCodegen codegen) {
generateInitializers(new Function0<ExpressionCodegen>() { generateInitializers(() -> codegen);
@Override
public ExpressionCodegen invoke() {
return codegen;
}
});
} }
private void generateClosureInitialization(@NotNull InstructionAdapter iv) { private void generateClosureInitialization(@NotNull InstructionAdapter iv) {
@@ -19,7 +19,6 @@ package org.jetbrains.kotlin.codegen;
import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFile;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1;
import kotlin.text.StringsKt; import kotlin.text.StringsKt;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -176,14 +175,10 @@ public class JvmCodegenUtil {
} }
public static boolean hasAbstractMembers(@NotNull ClassDescriptor classDescriptor) { public static boolean hasAbstractMembers(@NotNull ClassDescriptor classDescriptor) {
return CollectionsKt.any(DescriptorUtils.getAllDescriptors(classDescriptor.getDefaultType().getMemberScope()), return CollectionsKt.any(
new Function1<DeclarationDescriptor, Boolean>() { DescriptorUtils.getAllDescriptors(classDescriptor.getDefaultType().getMemberScope()),
@Override descriptor -> descriptor instanceof CallableMemberDescriptor &&
public Boolean invoke(DeclarationDescriptor descriptor) { ((CallableMemberDescriptor) descriptor).getModality() == ABSTRACT
return descriptor instanceof CallableMemberDescriptor &&
((CallableMemberDescriptor) descriptor).getModality() == ABSTRACT;
}
}
); );
} }
@@ -816,12 +816,9 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
int flags = isScript ? JvmAnnotationNames.METADATA_SCRIPT_FLAG : 0; int flags = isScript ? JvmAnnotationNames.METADATA_SCRIPT_FLAG : 0;
WriteAnnotationUtilKt.writeKotlinMetadata(v, state, KotlinClassHeader.Kind.CLASS, flags, new Function1<AnnotationVisitor, Unit>() { WriteAnnotationUtilKt.writeKotlinMetadata(v, state, KotlinClassHeader.Kind.CLASS, flags, av -> {
@Override writeAnnotationData(av, serializer, classProto);
public Unit invoke(AnnotationVisitor av) { return Unit.INSTANCE;
writeAnnotationData(av, serializer, classProto);
return Unit.INSTANCE;
}
}); });
} }
} }
@@ -18,8 +18,6 @@ package org.jetbrains.kotlin.codegen;
import com.intellij.util.ArrayUtil; import com.intellij.util.ArrayUtil;
import kotlin.Unit; import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.codegen.annotation.AnnotatedSimple; import org.jetbrains.kotlin.codegen.annotation.AnnotatedSimple;
import org.jetbrains.kotlin.codegen.context.FieldOwnerContext; import org.jetbrains.kotlin.codegen.context.FieldOwnerContext;
@@ -38,7 +36,6 @@ import org.jetbrains.kotlin.psi.*;
import org.jetbrains.kotlin.resolve.BindingContext; import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.serialization.DescriptorSerializer; import org.jetbrains.kotlin.serialization.DescriptorSerializer;
import org.jetbrains.kotlin.serialization.ProtoBuf; import org.jetbrains.kotlin.serialization.ProtoBuf;
import org.jetbrains.org.objectweb.asm.AnnotationVisitor;
import org.jetbrains.org.objectweb.asm.Type; import org.jetbrains.org.objectweb.asm.Type;
import java.util.ArrayList; import java.util.ArrayList;
@@ -100,12 +97,7 @@ public class PackagePartCodegen extends MemberCodegen<KtFile> {
} }
if (state.getClassBuilderMode().generateBodies) { if (state.getClassBuilderMode().generateBodies) {
generateInitializers(new Function0<ExpressionCodegen>() { generateInitializers(this::createOrGetClInitCodegen);
@Override
public ExpressionCodegen invoke() {
return createOrGetClInitCodegen();
}
});
} }
} }
@@ -131,12 +123,9 @@ public class PackagePartCodegen extends MemberCodegen<KtFile> {
DescriptorSerializer.createTopLevel(new JvmSerializerExtension(v.getSerializationBindings(), state)); DescriptorSerializer.createTopLevel(new JvmSerializerExtension(v.getSerializationBindings(), state));
ProtoBuf.Package packageProto = serializer.packagePartProto(element.getPackageFqName(), members).build(); ProtoBuf.Package packageProto = serializer.packagePartProto(element.getPackageFqName(), members).build();
WriteAnnotationUtilKt.writeKotlinMetadata(v, state, KotlinClassHeader.Kind.FILE_FACADE, 0, new Function1<AnnotationVisitor, Unit>() { WriteAnnotationUtilKt.writeKotlinMetadata(v, state, KotlinClassHeader.Kind.FILE_FACADE, 0, av -> {
@Override writeAnnotationData(av, serializer, packageProto);
public Unit invoke(AnnotationVisitor av) { return Unit.INSTANCE;
writeAnnotationData(av, serializer, packageProto);
return Unit.INSTANCE;
}
}); });
} }
@@ -16,7 +16,6 @@
package org.jetbrains.kotlin.codegen; package org.jetbrains.kotlin.codegen;
import kotlin.jvm.functions.Function0;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.codegen.context.CodegenContext; import org.jetbrains.kotlin.codegen.context.CodegenContext;
import org.jetbrains.kotlin.codegen.context.MethodContext; import org.jetbrains.kotlin.codegen.context.MethodContext;
@@ -202,12 +201,7 @@ public class ScriptCodegen extends MemberCodegen<KtScript> {
ExpressionCodegen codegen = new ExpressionCodegen(mv, frameMap, Type.VOID_TYPE, methodContext, state, this); ExpressionCodegen codegen = new ExpressionCodegen(mv, frameMap, Type.VOID_TYPE, methodContext, state, this);
generateInitializers(new Function0<ExpressionCodegen>() { generateInitializers(() -> codegen);
@Override
public ExpressionCodegen invoke() {
return codegen;
}
});
iv.areturn(Type.VOID_TYPE); iv.areturn(Type.VOID_TYPE);
} }
@@ -65,12 +65,9 @@ public abstract class StackValue {
private static final String NULLABLE_LONG_TYPE_NAME = "java/lang/Long"; private static final String NULLABLE_LONG_TYPE_NAME = "java/lang/Long";
public static final StackValue.Local LOCAL_0 = local(0, OBJECT_TYPE); public static final StackValue.Local LOCAL_0 = local(0, OBJECT_TYPE);
private static final StackValue UNIT = operation(UNIT_TYPE, new Function1<InstructionAdapter, Unit>() { private static final StackValue UNIT = operation(UNIT_TYPE, v -> {
@Override v.visitFieldInsn(GETSTATIC, UNIT_TYPE.getInternalName(), JvmAbi.INSTANCE_FIELD, UNIT_TYPE.getDescriptor());
public Unit invoke(InstructionAdapter v) { return null;
v.visitFieldInsn(GETSTATIC, UNIT_TYPE.getInternalName(), JvmAbi.INSTANCE_FIELD, UNIT_TYPE.getDescriptor());
return null;
}
}); });
@NotNull @NotNull
@@ -22,7 +22,6 @@ import com.intellij.psi.tree.TokenSet;
import com.intellij.util.containers.Stack; import com.intellij.util.containers.Stack;
import kotlin.Pair; import kotlin.Pair;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1;
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.ReflectionTypes; import org.jetbrains.kotlin.builtins.ReflectionTypes;
@@ -675,12 +674,7 @@ class CodegenAnnotatingVisitor extends KtVisitorVoid {
expression, expression,
bindingContext, bindingContext,
shouldInlineConstVals, shouldInlineConstVals,
new Function1<ConstantValue<?>, Boolean>() { constant -> constant instanceof EnumValue || constant instanceof NullValue
@Override
public Boolean invoke(@NotNull ConstantValue<?> constant) {
return constant instanceof EnumValue || constant instanceof NullValue;
}
}
); );
} }
@@ -16,7 +16,6 @@
package org.jetbrains.kotlin.codegen.context; package org.jetbrains.kotlin.codegen.context;
import kotlin.jvm.functions.Function0;
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;
@@ -160,12 +159,7 @@ public abstract class CodegenContext<T extends DeclarationDescriptor> {
this.closure = closure; this.closure = closure;
this.thisDescriptor = thisDescriptor; this.thisDescriptor = thisDescriptor;
this.enclosingLocalLookup = localLookup; this.enclosingLocalLookup = localLookup;
this.outerExpression = LockBasedStorageManager.NO_LOCKS.createNullableLazyValue(new Function0<StackValue.Field>() { this.outerExpression = LockBasedStorageManager.NO_LOCKS.createNullableLazyValue(this::computeOuterExpression);
@Override
public StackValue.Field invoke() {
return computeOuterExpression();
}
});
if (parentContext != null) { if (parentContext != null) {
parentContext.addChild(this); parentContext.addChild(this);
@@ -17,7 +17,6 @@
package org.jetbrains.kotlin.codegen.inline; package org.jetbrains.kotlin.codegen.inline;
import com.intellij.util.ArrayUtil; import com.intellij.util.ArrayUtil;
import kotlin.jvm.functions.Function0;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.codegen.AsmUtil; import org.jetbrains.kotlin.codegen.AsmUtil;
import org.jetbrains.kotlin.codegen.ClassBuilder; import org.jetbrains.kotlin.codegen.ClassBuilder;
@@ -350,15 +349,10 @@ public class AnonymousObjectTransformer extends ObjectTransformer<AnonymousObjec
original.access, original.name, original.desc, original.signature, original.access, original.name, original.desc, original.signature,
ArrayUtil.toStringArray(original.exceptions) ArrayUtil.toStringArray(original.exceptions)
), ),
new Function0<MethodVisitor>() { () -> builder.newMethod(
@Override NO_ORIGIN, original.access, original.name, original.desc, original.signature,
public MethodVisitor invoke() { ArrayUtil.toStringArray(original.exceptions)
return builder.newMethod( )
NO_ORIGIN, original.access, original.name, original.desc, original.signature,
ArrayUtil.toStringArray(original.exceptions)
);
}
}
); );
} }
@@ -20,7 +20,6 @@ import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFile;
import com.intellij.util.ArrayUtil; import com.intellij.util.ArrayUtil;
import kotlin.jvm.functions.Function0;
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.CodegenUtil; import org.jetbrains.kotlin.backend.common.CodegenUtil;
@@ -272,15 +271,12 @@ public class InlineCodegen extends CallGenerator {
} }
SMAPAndMethodNode resultInCache = InlineCacheKt.getOrPut( SMAPAndMethodNode resultInCache = InlineCacheKt.getOrPut(
state.getInlineCache().getMethodNodeById(), methodId, new Function0<SMAPAndMethodNode>() { state.getInlineCache().getMethodNodeById(), methodId, () -> {
@Override SMAPAndMethodNode result = doCreateMethodNodeFromCompiled(directMember, state, asmMethod);
public SMAPAndMethodNode invoke() { if (result == null) {
SMAPAndMethodNode result = doCreateMethodNodeFromCompiled(directMember, state, asmMethod); throw new IllegalStateException("Couldn't obtain compiled function body for " + functionDescriptor);
if (result == null) {
throw new IllegalStateException("Couldn't obtain compiled function body for " + functionDescriptor);
}
return result;
} }
return result;
} }
); );
@@ -315,13 +311,8 @@ public class InlineCodegen extends CallGenerator {
) { ) {
if (isBuiltInArrayIntrinsic(callableDescriptor)) { if (isBuiltInArrayIntrinsic(callableDescriptor)) {
ClassId classId = IntrinsicArrayConstructorsKt.getClassId(); ClassId classId = IntrinsicArrayConstructorsKt.getClassId();
byte[] bytes = InlineCacheKt.getOrPut(state.getInlineCache().getClassBytes(), classId, new Function0<byte[]>() { byte[] bytes =
@Override InlineCacheKt.getOrPut(state.getInlineCache().getClassBytes(), classId, IntrinsicArrayConstructorsKt::getBytecode);
public byte[] invoke() {
return IntrinsicArrayConstructorsKt.getBytecode();
}
});
return InlineCodegenUtil.getMethodNode(bytes, asmMethod.getName(), asmMethod.getDescriptor(), classId); return InlineCodegenUtil.getMethodNode(bytes, asmMethod.getName(), asmMethod.getDescriptor(), classId);
} }
@@ -332,23 +323,19 @@ public class InlineCodegen extends CallGenerator {
ClassId containerId = containingClasses.getImplClassId(); ClassId containerId = containingClasses.getImplClassId();
byte[] bytes = InlineCacheKt.getOrPut(state.getInlineCache().getClassBytes(), containerId, new Function0<byte[]>() { byte[] bytes = InlineCacheKt.getOrPut(state.getInlineCache().getClassBytes(), containerId, () -> {
@Override VirtualFile file = InlineCodegenUtil.findVirtualFile(state, containerId);
public byte[] invoke() { if (file == null) {
VirtualFile file = InlineCodegenUtil.findVirtualFile(state, containerId); throw new IllegalStateException("Couldn't find declaration file for " + containerId);
if (file == null) { }
throw new IllegalStateException("Couldn't find declaration file for " + containerId); try {
} return file.contentsToByteArray();
try { }
return file.contentsToByteArray(); catch (IOException e) {
} throw new RuntimeException(e);
catch (IOException e) {
throw new RuntimeException(e);
}
} }
}); });
return InlineCodegenUtil.getMethodNode(bytes, asmMethod.getName(), asmMethod.getDescriptor(), containerId); return InlineCodegenUtil.getMethodNode(bytes, asmMethod.getName(), asmMethod.getDescriptor(), containerId);
} }
@@ -455,14 +442,8 @@ public class InlineCodegen extends CallGenerator {
CallableMemberDescriptor descriptor = getLabelOwnerDescriptor(codegen.getContext()); CallableMemberDescriptor descriptor = getLabelOwnerDescriptor(codegen.getContext());
Set<String> labels = getDeclarationLabels(DescriptorToSourceUtils.descriptorToDeclaration(descriptor), descriptor); Set<String> labels = getDeclarationLabels(DescriptorToSourceUtils.descriptorToDeclaration(descriptor), descriptor);
LabelOwner labelOwner = new LabelOwner() {
@Override
public boolean isMyLabel(@NotNull String name) {
return labels.contains(name);
}
};
List<MethodInliner.PointForExternalFinallyBlocks> infos = MethodInliner.processReturns(adapter, labelOwner, true, null); List<MethodInliner.PointForExternalFinallyBlocks> infos = MethodInliner.processReturns(adapter, labels::contains, true, null);
generateAndInsertFinallyBlocks( generateAndInsertFinallyBlocks(
adapter, infos, ((StackValue.Local) remapper.remap(parameters.getArgsSizeOnStack() + 1).value).index adapter, infos, ((StackValue.Local) remapper.remap(parameters.getArgsSizeOnStack() + 1).value).index
); );
@@ -759,19 +740,16 @@ public class InlineCodegen extends CallGenerator {
} }
} }
Runnable runnable = new Runnable() { Runnable runnable = () -> {
@Override for (int i = infos.length - 1; i >= 0; i--) {
public void run() { ParameterInfo info = infos[i];
for (int i = infos.length - 1; i >= 0; i--) { if (!info.isSkippedOrRemapped()) {
ParameterInfo info = infos[i]; Type type = info.type;
if (!info.isSkippedOrRemapped()) { StackValue.Local local = StackValue.local(index[i], type);
Type type = info.type; local.store(StackValue.onStack(type), codegen.v);
StackValue.Local local = StackValue.local(index[i], type); if (info instanceof CapturedParamInfo) {
local.store(StackValue.onStack(type), codegen.v); info.setRemapValue(local);
if (info instanceof CapturedParamInfo) { ((CapturedParamInfo) info).setSynthetic(true);
info.setRemapValue(local);
((CapturedParamInfo) info).setSynthetic(true);
}
} }
} }
} }
@@ -21,17 +21,9 @@ import org.jetbrains.annotations.NotNull;
public interface LabelOwner { public interface LabelOwner {
boolean isMyLabel(@NotNull String name); boolean isMyLabel(@NotNull String name);
LabelOwner SKIP_ALL = new LabelOwner() { LabelOwner SKIP_ALL = name -> false;
@Override
public boolean isMyLabel(@NotNull String name) {
return false;
}
};
LabelOwner NOT_APPLICABLE = new LabelOwner() { LabelOwner NOT_APPLICABLE = name -> {
@Override throw new RuntimeException("This operation not applicable for current context");
public boolean isMyLabel(@NotNull String name) {
throw new RuntimeException("This operation not applicable for current context");
}
}; };
} }
@@ -46,7 +46,6 @@
package org.jetbrains.kotlin.codegen.inline; package org.jetbrains.kotlin.codegen.inline;
import com.intellij.openapi.util.Factory;
import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.org.objectweb.asm.*; import org.jetbrains.org.objectweb.asm.*;
@@ -430,12 +429,7 @@ public class MaxStackFrameSizeAndLocalsCalculator extends MaxLocalsCalculator {
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
private LabelWrapper getLabelWrapper(Label label) { private LabelWrapper getLabelWrapper(Label label) {
return ContainerUtil.getOrCreate(labelWrappersMap, label, new Factory<LabelWrapper>() { return ContainerUtil.<Label, LabelWrapper>getOrCreate(labelWrappersMap, label, () -> new LabelWrapper(label));
@Override
public LabelWrapper create() {
return new LabelWrapper(label);
}
});
} }
private void increaseStackSize(int variation) { private void increaseStackSize(int variation) {
@@ -18,7 +18,6 @@ package org.jetbrains.kotlin.codegen.optimization.boxing;
import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Pair;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.codegen.optimization.common.StrictBasicValue; import org.jetbrains.kotlin.codegen.optimization.common.StrictBasicValue;
import org.jetbrains.kotlin.codegen.optimization.common.UtilKt; import org.jetbrains.kotlin.codegen.optimization.common.UtilKt;
@@ -100,12 +99,7 @@ public class RedundantBoxingMethodTransformer extends MethodTransformer {
List<BasicValue> variableValues = getValuesStoredOrLoadedToVariable(localVariableNode, node, frames); List<BasicValue> variableValues = getValuesStoredOrLoadedToVariable(localVariableNode, node, frames);
Collection<BasicValue> boxed = CollectionsKt.filter(variableValues, new Function1<BasicValue, Boolean>() { Collection<BasicValue> boxed = CollectionsKt.filter(variableValues, value -> value instanceof BoxedBasicValue);
@Override
public Boolean invoke(BasicValue value) {
return value instanceof BoxedBasicValue;
}
});
if (boxed.isEmpty()) continue; if (boxed.isEmpty()) continue;
@@ -127,16 +121,13 @@ public class RedundantBoxingMethodTransformer extends MethodTransformer {
} }
private static boolean isUnsafeToRemoveBoxingForConnectedValues(List<BasicValue> usedValues, Type unboxedType) { private static boolean isUnsafeToRemoveBoxingForConnectedValues(List<BasicValue> usedValues, Type unboxedType) {
return CollectionsKt.any(usedValues, new Function1<BasicValue, Boolean>() { return CollectionsKt.any(usedValues, input -> {
@Override if (input == StrictBasicValue.UNINITIALIZED_VALUE) return false;
public Boolean invoke(BasicValue input) { if (!(input instanceof BoxedBasicValue)) return true;
if (input == StrictBasicValue.UNINITIALIZED_VALUE) return false;
if (!(input instanceof BoxedBasicValue)) return true;
BoxedValueDescriptor descriptor = ((BoxedBasicValue) input).getDescriptor(); BoxedValueDescriptor descriptor = ((BoxedBasicValue) input).getDescriptor();
return !descriptor.isSafeToRemove() || return !descriptor.isSafeToRemove() ||
!(descriptor.getUnboxedType().equals(unboxedType)); !(descriptor.getUnboxedType().equals(unboxedType));
}
}); });
} }
@@ -22,7 +22,6 @@ import kotlin.Pair;
import kotlin.Unit; import kotlin.Unit;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function2; import kotlin.jvm.functions.Function2;
import kotlin.jvm.functions.Function3;
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.BuiltInsPackageFragment; import org.jetbrains.kotlin.builtins.BuiltInsPackageFragment;
@@ -469,13 +468,11 @@ public class KotlinTypeMapper {
) { ) {
return TypeSignatureMappingKt.mapType( return TypeSignatureMappingKt.mapType(
kotlinType, AsmTypeFactory.INSTANCE, mode, typeMappingConfiguration, signatureVisitor, kotlinType, AsmTypeFactory.INSTANCE, mode, typeMappingConfiguration, signatureVisitor,
new Function3<KotlinType, Type, TypeMappingMode, Unit>() { (ktType, asmType, typeMappingMode) -> {
@Override writeGenericType(ktType, asmType, signatureVisitor, typeMappingMode);
public Unit invoke(KotlinType kotlinType, Type type, TypeMappingMode mode) { return Unit.INSTANCE;
writeGenericType(kotlinType, type, signatureVisitor, mode); }
return Unit.INSTANCE; );
}
});
} }
@NotNull @NotNull
@@ -23,10 +23,7 @@ import java.io.File;
import java.util.Collection; import java.util.Collection;
public interface Progress { public interface Progress {
Progress DEAF = new Progress() { Progress DEAF = (sourceFiles, outputFile) -> {
@Override
public void reportOutput(@NotNull Collection<File> sourceFiles, @Nullable File outputFile) {
}
}; };
/** /**
@@ -158,14 +158,8 @@ public class SwitchCodegenUtil {
return false; return false;
} }
return checkAllItemsAreConstantsSatisfying(expression, bindingContext, shouldInlineConstVals, new Function1<ConstantValue<?>, Boolean>() { return checkAllItemsAreConstantsSatisfying(expression, bindingContext, shouldInlineConstVals,
@Override constant -> constant instanceof IntegerValueConstant);
public Boolean invoke(
@NotNull ConstantValue<?> constant
) {
return constant instanceof IntegerValueConstant;
}
});
} }
private static boolean isStringConstantsSwitch( private static boolean isStringConstantsSwitch(
@@ -179,13 +173,7 @@ public class SwitchCodegenUtil {
return false; return false;
} }
return checkAllItemsAreConstantsSatisfying(expression, bindingContext, shouldInlineConstVals, new Function1<ConstantValue<?>, Boolean>() { return checkAllItemsAreConstantsSatisfying(expression, bindingContext, shouldInlineConstVals,
@Override constant -> constant instanceof StringValue || constant instanceof NullValue);
public Boolean invoke(
@NotNull ConstantValue<?> constant
) {
return constant instanceof StringValue || constant instanceof NullValue;
}
});
} }
} }
@@ -81,14 +81,11 @@ public class GroupingMessageCollector implements MessageCollector {
private Collection<String> sortedKeys() { private Collection<String> sortedKeys() {
List<String> sortedKeys = new ArrayList<String>(groupedMessages.keySet()); List<String> sortedKeys = new ArrayList<String>(groupedMessages.keySet());
// ensure that messages with no location i.e. perf, incomplete hierarchy are always reported first // ensure that messages with no location i.e. perf, incomplete hierarchy are always reported first
Collections.sort(sortedKeys, new Comparator<String>() { Collections.sort(sortedKeys, (o1, o2) -> {
@Override if (o1 == o2) return 0;
public int compare(String o1, String o2) { if (o1 == null) return -1;
if (o1 == o2) return 0; if (o2 == null) return 1;
if (o1 == null) return -1; return o1.compareTo(o2);
if (o2 == null) return 1;
return o1.compareTo(o2);
}
}); });
return sortedKeys; return sortedKeys;
} }
@@ -20,7 +20,6 @@ import com.intellij.openapi.Disposable;
import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.SystemInfo;
import kotlin.collections.ArraysKt; import kotlin.collections.ArraysKt;
import kotlin.jvm.functions.Function1;
import org.fusesource.jansi.AnsiConsole; import org.fusesource.jansi.AnsiConsole;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -314,12 +313,7 @@ public abstract class CLICompiler<A extends CommonCompilerArguments> {
return version; return version;
} }
List<String> versionStrings = ArraysKt.map(LanguageVersion.values(), new Function1<LanguageVersion, String>() { List<String> versionStrings = ArraysKt.map(LanguageVersion.values(), LanguageVersion::getDescription);
@Override
public String invoke(LanguageVersion version) {
return version.getDescription();
}
});
String message = "Unknown " + versionOf + " version: " + value + "\n" + String message = "Unknown " + versionOf + " version: " + value + "\n" +
"Supported " + versionOf + " versions: " + StringsKt.join(versionStrings, ", "); "Supported " + versionOf + " versions: " + StringsKt.join(versionStrings, ", ");
configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY).report( configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY).report(
@@ -21,13 +21,12 @@ import com.intellij.openapi.Disposable;
import com.intellij.openapi.project.Project; import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.Function;
import com.intellij.util.SmartList; import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.HashMap; import com.intellij.util.containers.HashMap;
import kotlin.collections.ArraysKt; import kotlin.collections.ArraysKt;
import kotlin.collections.CollectionsKt;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.analyzer.AnalysisResult; import org.jetbrains.kotlin.analyzer.AnalysisResult;
import org.jetbrains.kotlin.backend.common.output.OutputFileCollection; import org.jetbrains.kotlin.backend.common.output.OutputFileCollection;
import org.jetbrains.kotlin.cli.common.CLICompiler; import org.jetbrains.kotlin.cli.common.CLICompiler;
@@ -226,16 +225,12 @@ public class K2JSCompiler extends CLICompiler<K2JSCompilerArguments> {
} }
private static void reportCompiledSourcesList(@NotNull MessageCollector messageCollector, @NotNull List<KtFile> sourceFiles) { private static void reportCompiledSourcesList(@NotNull MessageCollector messageCollector, @NotNull List<KtFile> sourceFiles) {
Iterable<String> fileNames = ContainerUtil.map(sourceFiles, new Function<KtFile, String>() { Iterable<String> fileNames = CollectionsKt.map(sourceFiles, file -> {
@Override VirtualFile virtualFile = file.getVirtualFile();
public String fun(@Nullable KtFile file) { if (virtualFile != null) {
assert file != null; return FileUtil.toSystemDependentName(virtualFile.getPath());
VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile != null) {
return FileUtil.toSystemDependentName(virtualFile.getPath());
}
return file.getName() + "(no virtual file)";
} }
return file.getName() + "(no virtual file)";
}); });
messageCollector.report(CompilerMessageSeverity.LOGGING, "Compiling source files: " + Joiner.on(", ").join(fileNames), messageCollector.report(CompilerMessageSeverity.LOGGING, "Compiling source files: " + Joiner.on(", ").join(fileNames),
CompilerMessageLocation.NO_LOCATION); CompilerMessageLocation.NO_LOCATION);
@@ -185,22 +185,19 @@ public class CompileEnvironmentUtil {
continue; continue;
} }
SequencesKt.forEach(FilesKt.walkTopDown(new File(sourceRootPath)), new Function1<File, Unit>() { SequencesKt.forEach(FilesKt.walkTopDown(new File(sourceRootPath)), file -> {
@Override if (file.isFile()) {
public Unit invoke(File file) { VirtualFile originalVirtualFile = localFileSystem.findFileByPath(file.getAbsolutePath());
if (file.isFile()) { VirtualFile virtualFile = originalVirtualFile != null ? virtualFileCreator.create(originalVirtualFile) : null;
VirtualFile originalVirtualFile = localFileSystem.findFileByPath(file.getAbsolutePath()); if (virtualFile != null && !processedFiles.contains(virtualFile)) {
VirtualFile virtualFile = originalVirtualFile != null ? virtualFileCreator.create(originalVirtualFile) : null; processedFiles.add(virtualFile);
if (virtualFile != null && !processedFiles.contains(virtualFile)) { PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
processedFiles.add(virtualFile); if (psiFile instanceof KtFile) {
PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile); result.add((KtFile) psiFile);
if (psiFile instanceof KtFile) {
result.add((KtFile) psiFile);
}
} }
} }
return Unit.INSTANCE;
} }
return Unit.INSTANCE;
}); });
} }
@@ -39,7 +39,6 @@ import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.messages.MessageBus; import com.intellij.util.messages.MessageBus;
import kotlin.collections.ArraysKt; import kotlin.collections.ArraysKt;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.idea.KotlinLanguage; import org.jetbrains.kotlin.idea.KotlinLanguage;
@@ -207,20 +206,14 @@ public class KotlinJavaPsiFacade {
); );
List<PsiElementFinder> nonKotlinFinders = ArraysKt.filter( List<PsiElementFinder> nonKotlinFinders = ArraysKt.filter(
getProject().getExtensions(PsiElementFinder.EP_NAME), new Function1<PsiElementFinder, Boolean>() { getProject().getExtensions(PsiElementFinder.EP_NAME),
@Override finder -> (finder instanceof KotlinSafeClassFinder) ||
public Boolean invoke(PsiElementFinder finder) { !(finder instanceof NonClasspathClassFinder ||
return (finder instanceof KotlinSafeClassFinder) || finder instanceof KotlinFinderMarker ||
!(finder instanceof NonClasspathClassFinder || finder instanceof KotlinFinderMarker || finder instanceof PsiElementFinderImpl); finder instanceof PsiElementFinderImpl)
} );
});
elementFinders.addAll(CollectionsKt.map(nonKotlinFinders, new Function1<PsiElementFinder, KotlinPsiElementFinderWrapper>() { elementFinders.addAll(CollectionsKt.map(nonKotlinFinders, KotlinJavaPsiFacade::wrap));
@Override
public KotlinPsiElementFinderWrapper invoke(PsiElementFinder finder) {
return wrap(finder);
}
}));
return elementFinders.toArray(new KotlinPsiElementFinderWrapper[elementFinders.size()]); return elementFinders.toArray(new KotlinPsiElementFinderWrapper[elementFinders.size()]);
} }
@@ -27,27 +27,24 @@ import java.util.List;
public class DefaultErrorMessagesJvm implements DefaultErrorMessages.Extension { public class DefaultErrorMessagesJvm implements DefaultErrorMessages.Extension {
private static final DiagnosticParameterRenderer<ConflictingJvmDeclarationsData> CONFLICTING_JVM_DECLARATIONS_DATA = new DiagnosticParameterRenderer<ConflictingJvmDeclarationsData>() { private static final DiagnosticParameterRenderer<ConflictingJvmDeclarationsData> CONFLICTING_JVM_DECLARATIONS_DATA =
@NotNull (data, context) -> {
@Override List<DeclarationDescriptor> renderedDescriptors = new ArrayList<DeclarationDescriptor>();
public String render(@NotNull ConflictingJvmDeclarationsData data, @NotNull RenderingContext context) { for (JvmDeclarationOrigin origin : data.getSignatureOrigins()) {
List<DeclarationDescriptor> renderedDescriptors = new ArrayList<DeclarationDescriptor>(); DeclarationDescriptor descriptor = origin.getDescriptor();
for (JvmDeclarationOrigin origin : data.getSignatureOrigins()) { if (descriptor != null) {
DeclarationDescriptor descriptor = origin.getDescriptor(); renderedDescriptors.add(descriptor);
if (descriptor != null) { }
renderedDescriptors.add(descriptor);
} }
} Collections.sort(renderedDescriptors, MemberComparator.INSTANCE);
Collections.sort(renderedDescriptors, MemberComparator.INSTANCE); RenderingContext.Impl renderingContext = new RenderingContext.Impl(renderedDescriptors);
RenderingContext.Impl renderingContext = new RenderingContext.Impl(renderedDescriptors);
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (DeclarationDescriptor descriptor : renderedDescriptors) { for (DeclarationDescriptor descriptor : renderedDescriptors) {
sb.append(" ").append(Renderers.COMPACT.render(descriptor, renderingContext)).append("\n"); sb.append(" ").append(Renderers.COMPACT.render(descriptor, renderingContext)).append("\n");
} }
return ("The following declarations have the same JVM signature (" + data.getSignature().getName() + data.getSignature().getDesc() + "):\n" + sb).trim(); return ("The following declarations have the same JVM signature (" + data.getSignature().getName() + data.getSignature().getDesc() + "):\n" + sb).trim();
} };
};
private static final DiagnosticFactoryToRendererMap MAP = new DiagnosticFactoryToRendererMap("JVM"); private static final DiagnosticFactoryToRendererMap MAP = new DiagnosticFactoryToRendererMap("JVM");
static { static {
@@ -17,10 +17,7 @@
package org.jetbrains.kotlin.resolve.jvm.kotlinSignature; package org.jetbrains.kotlin.resolve.jvm.kotlinSignature;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1;
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.builtins.KotlinBuiltIns;
@@ -130,20 +127,19 @@ public class SignaturesPropagationData {
for (ValueParameterDescriptor originalParam : parameters) { for (ValueParameterDescriptor originalParam : parameters) {
int originalIndex = originalParam.getIndex(); int originalIndex = originalParam.getIndex();
List<TypeAndName> typesFromSuperMethods = ContainerUtil.map(superFunctions, List<TypeAndName> typesFromSuperMethods = CollectionsKt.map(
new Function<FunctionDescriptor, TypeAndName>() { superFunctions,
@Override superFunction -> {
public TypeAndName fun(FunctionDescriptor superFunction) { ReceiverParameterDescriptor receiver = superFunction.getExtensionReceiverParameter();
ReceiverParameterDescriptor receiver = superFunction.getExtensionReceiverParameter(); int index = receiver != null ? originalIndex - 1 : originalIndex;
int index = receiver != null ? originalIndex - 1 : originalIndex; if (index == -1) {
if (index == -1) { assert receiver != null : "can't happen: index is -1, while function is not extension";
assert receiver != null : "can't happen: index is -1, while function is not extension"; return new TypeAndName(receiver.getType(), originalParam.getName());
return new TypeAndName(receiver.getType(), originalParam.getName());
}
ValueParameterDescriptor parameter = superFunction.getValueParameters().get(index);
return new TypeAndName(parameter.getType(), parameter.getName());
} }
}); ValueParameterDescriptor parameter = superFunction.getValueParameters().get(index);
return new TypeAndName(parameter.getType(), parameter.getName());
}
);
VarargCheckResult varargCheckResult = checkVarargInSuperFunctions(originalParam); VarargCheckResult varargCheckResult = checkVarargInSuperFunctions(originalParam);
@@ -180,12 +176,7 @@ public class SignaturesPropagationData {
} }
} }
boolean hasStableParameterNames = CollectionsKt.any(superFunctions, new Function1<FunctionDescriptor, Boolean>() { boolean hasStableParameterNames = CollectionsKt.any(superFunctions, CallableDescriptor::hasStableParameterNames);
@Override
public Boolean invoke(FunctionDescriptor descriptor) {
return descriptor.hasStableParameterNames();
}
});
return new ValueParameters(resultReceiverType, resultParameters, hasStableParameterNames); return new ValueParameters(resultReceiverType, resultParameters, hasStableParameterNames);
} }
@@ -224,13 +215,10 @@ public class SignaturesPropagationData {
} }
// sorting for diagnostic stability // sorting for diagnostic stability
Collections.sort(superFunctions, new Comparator<FunctionDescriptor>() { Collections.sort(superFunctions, (fun1, fun2) -> {
@Override FqNameUnsafe fqName1 = getFqName(fun1.getContainingDeclaration());
public int compare(@NotNull FunctionDescriptor fun1, @NotNull FunctionDescriptor fun2) { FqNameUnsafe fqName2 = getFqName(fun2.getContainingDeclaration());
FqNameUnsafe fqName1 = getFqName(fun1.getContainingDeclaration()); return fqName1.asString().compareTo(fqName2.asString());
FqNameUnsafe fqName2 = getFqName(fun2.getContainingDeclaration());
return fqName1.asString().compareTo(fqName2.asString());
}
}); });
return superFunctions; return superFunctions;
} }
@@ -31,7 +31,6 @@ import com.intellij.util.containers.Stack;
import kotlin.Pair; import kotlin.Pair;
import kotlin.TuplesKt; import kotlin.TuplesKt;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1;
import kotlin.text.StringsKt; import kotlin.text.StringsKt;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -55,30 +54,27 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class CheckerTestUtil { public class CheckerTestUtil {
public static final Comparator<ActualDiagnostic> DIAGNOSTIC_COMPARATOR = new Comparator<ActualDiagnostic>() { public static final Comparator<ActualDiagnostic> DIAGNOSTIC_COMPARATOR = (o1, o2) -> {
@Override List<TextRange> ranges1 = o1.diagnostic.getTextRanges();
public int compare(@NotNull ActualDiagnostic o1, @NotNull ActualDiagnostic o2) { List<TextRange> ranges2 = o2.diagnostic.getTextRanges();
List<TextRange> ranges1 = o1.diagnostic.getTextRanges(); int minNumberOfRanges = ranges1.size() < ranges2.size() ? ranges1.size() : ranges2.size();
List<TextRange> ranges2 = o2.diagnostic.getTextRanges(); for (int i = 0; i < minNumberOfRanges; i++) {
int minNumberOfRanges = ranges1.size() < ranges2.size() ? ranges1.size() : ranges2.size(); TextRange range1 = ranges1.get(i);
for (int i = 0; i < minNumberOfRanges; i++) { TextRange range2 = ranges2.get(i);
TextRange range1 = ranges1.get(i); int startOffset1 = range1.getStartOffset();
TextRange range2 = ranges2.get(i); int startOffset2 = range2.getStartOffset();
int startOffset1 = range1.getStartOffset(); if (startOffset1 != startOffset2) {
int startOffset2 = range2.getStartOffset(); // Start early -- go first
if (startOffset1 != startOffset2) { return startOffset1 - range2.getStartOffset();
// Start early -- go first }
return startOffset1 - range2.getStartOffset(); int endOffset1 = range1.getEndOffset();
} int endOffset2 = range2.getEndOffset();
int endOffset1 = range1.getEndOffset(); if (endOffset1 != endOffset2) {
int endOffset2 = range2.getEndOffset(); // start at the same offset, the one who end later is the outer, i.e. goes first
if (endOffset1 != endOffset2) { return endOffset2 - endOffset1;
// start at the same offset, the one who end later is the outer, i.e. goes first
return endOffset2 - endOffset1;
}
} }
return ranges1.size() - ranges2.size();
} }
return ranges1.size() - ranges2.size();
}; };
private static final String IGNORE_DIAGNOSTIC_PARAMETER = "IGNORE"; private static final String IGNORE_DIAGNOSTIC_PARAMETER = "IGNORE";
@@ -104,12 +100,7 @@ public class CheckerTestUtil {
List<Pair<MultiTargetPlatform, BindingContext>> sortedBindings = CollectionsKt.sortedWith( List<Pair<MultiTargetPlatform, BindingContext>> sortedBindings = CollectionsKt.sortedWith(
implementingModulesBindings, implementingModulesBindings,
new Comparator<Pair<MultiTargetPlatform, BindingContext>>() { (o1, o2) -> o1.getFirst().compareTo(o2.getFirst())
@Override
public int compare(Pair<MultiTargetPlatform, BindingContext> o1, Pair<MultiTargetPlatform, BindingContext> o2) {
return o1.getFirst().compareTo(o2.getFirst());
}
}
); );
for (Pair<MultiTargetPlatform, BindingContext> binding : sortedBindings) { for (Pair<MultiTargetPlatform, BindingContext> binding : sortedBindings) {
@@ -299,12 +290,7 @@ public class CheckerTestUtil {
for (TextDiagnostic expectedDiagnostic : expectedDiagnostics) { for (TextDiagnostic expectedDiagnostic : expectedDiagnostics) {
Map.Entry<ActualDiagnostic, TextDiagnostic> actualDiagnosticEntry = CollectionsKt.firstOrNull( Map.Entry<ActualDiagnostic, TextDiagnostic> actualDiagnosticEntry = CollectionsKt.firstOrNull(
actualDiagnostics.entrySet(), new Function1<Map.Entry<ActualDiagnostic, TextDiagnostic>, Boolean>() { actualDiagnostics.entrySet(), entry -> expectedDiagnostic.getDescription().equals(entry.getValue().getDescription())
@Override
public Boolean invoke(Map.Entry<ActualDiagnostic, TextDiagnostic> entry) {
return expectedDiagnostic.getDescription().equals(entry.getValue().getDescription());
}
}
); );
if (actualDiagnosticEntry != null) { if (actualDiagnosticEntry != null) {
@@ -403,12 +389,7 @@ public class CheckerTestUtil {
public static StringBuffer addDiagnosticMarkersToText(@NotNull PsiFile psiFile, @NotNull Collection<ActualDiagnostic> diagnostics) { public static StringBuffer addDiagnosticMarkersToText(@NotNull PsiFile psiFile, @NotNull Collection<ActualDiagnostic> diagnostics) {
return addDiagnosticMarkersToText( return addDiagnosticMarkersToText(
psiFile, diagnostics, Collections.<ActualDiagnostic, TextDiagnostic>emptyMap(), psiFile, diagnostics, Collections.<ActualDiagnostic, TextDiagnostic>emptyMap(),
new Function<PsiFile, String>() { PsiElement::getText
@Override
public String fun(PsiFile file) {
return file.getText();
}
}
); );
} }
@@ -623,12 +604,9 @@ public class CheckerTestUtil {
diagnosticDescriptors.add( diagnosticDescriptors.add(
new DiagnosticDescriptor(range.getStartOffset(), range.getEndOffset(), diagnosticsGroupedByRanges.get(range))); new DiagnosticDescriptor(range.getStartOffset(), range.getEndOffset(), diagnosticsGroupedByRanges.get(range)));
} }
Collections.sort(diagnosticDescriptors, new Comparator<DiagnosticDescriptor>() { Collections.sort(diagnosticDescriptors, (d1, d2) -> {
@Override // Start early -- go first; start at the same offset, the one who end later is the outer, i.e. goes first
public int compare(@NotNull DiagnosticDescriptor d1, @NotNull DiagnosticDescriptor d2) { return (d1.start != d2.start) ? d1.start - d2.start : d2.end - d1.end;
// Start early -- go first; start at the same offset, the one who end later is the outer, i.e. goes first
return (d1.start != d2.start) ? d1.start - d2.start : d2.end - d1.end;
}
}); });
return diagnosticDescriptors; return diagnosticDescriptors;
} }
@@ -746,12 +724,7 @@ public class CheckerTestUtil {
if (renderer instanceof AbstractDiagnosticWithParametersRenderer) { if (renderer instanceof AbstractDiagnosticWithParametersRenderer) {
//noinspection unchecked //noinspection unchecked
Object[] renderParameters = ((AbstractDiagnosticWithParametersRenderer) renderer).renderParameters(diagnostic); Object[] renderParameters = ((AbstractDiagnosticWithParametersRenderer) renderer).renderParameters(diagnostic);
List<String> parameters = ContainerUtil.map(renderParameters, new Function<Object, String>() { List<String> parameters = ContainerUtil.map(renderParameters, Object::toString);
@Override
public String fun(Object o) {
return o != null ? o.toString() : "null";
}
});
return new TextDiagnostic(diagnosticName, actualDiagnostic.platform, parameters); return new TextDiagnostic(diagnosticName, actualDiagnostic.platform, parameters);
} }
return new TextDiagnostic(diagnosticName, actualDiagnostic.platform, null); return new TextDiagnostic(diagnosticName, actualDiagnostic.platform, null);
@@ -817,12 +790,7 @@ public class CheckerTestUtil {
result.append(name); result.append(name);
if (parameters != null) { if (parameters != null) {
result.append("("); result.append("(");
result.append(StringUtil.join(parameters, new Function<String, String>() { result.append(StringUtil.join(parameters, TextDiagnostic::escape, "; "));
@Override
public String fun(String s) {
return escape(s);
}
}, "; "));
result.append(")"); result.append(")");
} }
return result.toString(); return result.toString();
@@ -38,14 +38,11 @@ import java.util.List;
public class DiagnosticUtils { public class DiagnosticUtils {
@NotNull @NotNull
private static final Comparator<TextRange> TEXT_RANGE_COMPARATOR = new Comparator<TextRange>() { private static final Comparator<TextRange> TEXT_RANGE_COMPARATOR = (o1, o2) -> {
@Override if (o1.getStartOffset() != o2.getStartOffset()) {
public int compare(@NotNull TextRange o1, @NotNull TextRange o2) { return o1.getStartOffset() - o2.getStartOffset();
if (o1.getStartOffset() != o2.getStartOffset()) {
return o1.getStartOffset() - o2.getStartOffset();
}
return o1.getEndOffset() - o2.getEndOffset();
} }
return o1.getEndOffset() - o2.getEndOffset();
}; };
private DiagnosticUtils() { private DiagnosticUtils() {
@@ -163,22 +160,19 @@ public class DiagnosticUtils {
@NotNull @NotNull
public static List<Diagnostic> sortedDiagnostics(@NotNull Collection<Diagnostic> diagnostics) { public static List<Diagnostic> sortedDiagnostics(@NotNull Collection<Diagnostic> diagnostics) {
Comparator<Diagnostic> diagnosticComparator = new Comparator<Diagnostic>() { Comparator<Diagnostic> diagnosticComparator = (d1, d2) -> {
@Override String path1 = d1.getPsiFile().getViewProvider().getVirtualFile().getPath();
public int compare(@NotNull Diagnostic d1, @NotNull Diagnostic d2) { String path2 = d2.getPsiFile().getViewProvider().getVirtualFile().getPath();
String path1 = d1.getPsiFile().getViewProvider().getVirtualFile().getPath(); if (!path1.equals(path2)) return path1.compareTo(path2);
String path2 = d2.getPsiFile().getViewProvider().getVirtualFile().getPath();
if (!path1.equals(path2)) return path1.compareTo(path2);
TextRange range1 = firstRange(d1.getTextRanges()); TextRange range1 = firstRange(d1.getTextRanges());
TextRange range2 = firstRange(d2.getTextRanges()); TextRange range2 = firstRange(d2.getTextRanges());
if (!range1.equals(range2)) { if (!range1.equals(range2)) {
return TEXT_RANGE_COMPARATOR.compare(range1, range2); return TEXT_RANGE_COMPARATOR.compare(range1, range2);
}
return d1.getFactory().getName().compareTo(d2.getFactory().getName());
} }
return d1.getFactory().getName().compareTo(d2.getFactory().getName());
}; };
List<Diagnostic> result = Lists.newArrayList(diagnostics); List<Diagnostic> result = Lists.newArrayList(diagnostics);
Collections.sort(result, diagnosticComparator); Collections.sort(result, diagnosticComparator);
@@ -19,7 +19,6 @@ package org.jetbrains.kotlin.diagnostics.rendering;
import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtil;
import kotlin.Pair; import kotlin.Pair;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly; import org.jetbrains.annotations.TestOnly;
@@ -27,14 +26,8 @@ import org.jetbrains.kotlin.config.LanguageVersion;
import org.jetbrains.kotlin.diagnostics.Diagnostic; import org.jetbrains.kotlin.diagnostics.Diagnostic;
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory; import org.jetbrains.kotlin.diagnostics.DiagnosticFactory;
import org.jetbrains.kotlin.diagnostics.Errors; import org.jetbrains.kotlin.diagnostics.Errors;
import org.jetbrains.kotlin.diagnostics.TypeMismatchDueToTypeProjectionsData;
import org.jetbrains.kotlin.psi.KtExpression;
import org.jetbrains.kotlin.psi.KtSimpleNameExpression;
import org.jetbrains.kotlin.psi.KtTypeConstraint;
import org.jetbrains.kotlin.resolve.VarianceConflictDiagnosticData; import org.jetbrains.kotlin.resolve.VarianceConflictDiagnosticData;
import org.jetbrains.kotlin.serialization.deserialization.IncompatibleVersionErrorData;
import org.jetbrains.kotlin.serialization.deserialization.descriptors.SinceKotlinInfo; import org.jetbrains.kotlin.serialization.deserialization.descriptors.SinceKotlinInfo;
import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.kotlin.util.MappedExtensionProvider; import org.jetbrains.kotlin.util.MappedExtensionProvider;
import org.jetbrains.kotlin.util.OperatorNameConventions; import org.jetbrains.kotlin.util.OperatorNameConventions;
@@ -59,16 +52,13 @@ public class DefaultErrorMessages {
private static final DiagnosticFactoryToRendererMap MAP = new DiagnosticFactoryToRendererMap("Default"); private static final DiagnosticFactoryToRendererMap MAP = new DiagnosticFactoryToRendererMap("Default");
private static final MappedExtensionProvider<Extension, List<DiagnosticFactoryToRendererMap>> RENDERER_MAPS = MappedExtensionProvider.create( private static final MappedExtensionProvider<Extension, List<DiagnosticFactoryToRendererMap>> RENDERER_MAPS = MappedExtensionProvider.create(
Extension.EP_NAME, Extension.EP_NAME,
new Function1<List<? extends Extension>, List<DiagnosticFactoryToRendererMap>>() { extensions -> {
@Override List<DiagnosticFactoryToRendererMap> result = new ArrayList<DiagnosticFactoryToRendererMap>(extensions.size() + 1);
public List<DiagnosticFactoryToRendererMap> invoke(List<? extends Extension> extensions) { for (Extension extension : extensions) {
List<DiagnosticFactoryToRendererMap> result = new ArrayList<DiagnosticFactoryToRendererMap>(extensions.size() + 1); result.add(extension.getMap());
for (Extension extension : extensions) {
result.add(extension.getMap());
}
result.add(MAP);
return result;
} }
result.add(MAP);
return result;
}); });
@NotNull @NotNull
@@ -133,19 +123,15 @@ public class DefaultErrorMessages {
RENDER_TYPE); RENDER_TYPE);
MAP.put(TYPE_MISMATCH_DUE_TO_TYPE_PROJECTIONS, MAP.put(TYPE_MISMATCH_DUE_TO_TYPE_PROJECTIONS,
"Type mismatch: inferred type is {1} but {0} was expected. Projected type {2} restricts use of {3}", "Type mismatch: inferred type is {1} but {0} was expected. Projected type {2} restricts use of {3}",
new MultiRenderer<TypeMismatchDueToTypeProjectionsData>() { object -> {
@NotNull RenderingContext context =
@Override of(object.getExpectedType(), object.getExpressionType(), object.getReceiverType(), object.getCallableDescriptor());
public String[] render(@NotNull TypeMismatchDueToTypeProjectionsData object) { return new String[] {
RenderingContext context = RENDER_TYPE.render(object.getExpectedType(), context),
of(object.getExpectedType(), object.getExpressionType(), object.getReceiverType(), object.getCallableDescriptor()); RENDER_TYPE.render(object.getExpressionType(), context),
return new String[] { RENDER_TYPE.render(object.getReceiverType(), context),
RENDER_TYPE.render(object.getExpectedType(), context), FQ_NAMES_IN_TYPES.render(object.getCallableDescriptor(), context)
RENDER_TYPE.render(object.getExpressionType(), context), };
RENDER_TYPE.render(object.getReceiverType(), context),
FQ_NAMES_IN_TYPES.render(object.getCallableDescriptor(), context)
};
}
}); });
MAP.put(MEMBER_PROJECTED_OUT, "Out-projected type ''{1}'' prohibits the use of ''{0}''", FQ_NAMES_IN_TYPES, RENDER_TYPE); MAP.put(MEMBER_PROJECTED_OUT, "Out-projected type ''{1}'' prohibits the use of ''{0}''", FQ_NAMES_IN_TYPES, RENDER_TYPE);
@@ -198,20 +184,16 @@ public class DefaultErrorMessages {
MAP.put(MIXING_NAMED_AND_POSITIONED_ARGUMENTS, "Mixing named and positioned arguments is not allowed"); MAP.put(MIXING_NAMED_AND_POSITIONED_ARGUMENTS, "Mixing named and positioned arguments is not allowed");
MAP.put(ARGUMENT_PASSED_TWICE, "An argument is already passed for this parameter"); MAP.put(ARGUMENT_PASSED_TWICE, "An argument is already passed for this parameter");
MAP.put(NAMED_PARAMETER_NOT_FOUND, "Cannot find a parameter with this name: {0}", ELEMENT_TEXT); MAP.put(NAMED_PARAMETER_NOT_FOUND, "Cannot find a parameter with this name: {0}", ELEMENT_TEXT);
MAP.put(NAMED_ARGUMENTS_NOT_ALLOWED, "Named arguments are not allowed for {0}", new DiagnosticParameterRenderer<BadNamedArgumentsTarget>() { MAP.put(NAMED_ARGUMENTS_NOT_ALLOWED, "Named arguments are not allowed for {0}", (target, context) -> {
@NotNull switch (target) {
@Override case NON_KOTLIN_FUNCTION:
public String render(@NotNull BadNamedArgumentsTarget target, @NotNull RenderingContext context) { return "non-Kotlin functions";
switch (target) { case INVOKE_ON_FUNCTION_TYPE:
case NON_KOTLIN_FUNCTION: return "function types";
return "non-Kotlin functions"; case HEADER_CLASS_MEMBER:
case INVOKE_ON_FUNCTION_TYPE: return "members of header classes";
return "function types"; default:
case HEADER_CLASS_MEMBER: throw new AssertionError(target);
return "members of header classes";
default:
throw new AssertionError(target);
}
} }
}); });
@@ -333,28 +315,14 @@ public class DefaultErrorMessages {
MAP.put(DEPRECATION, "''{0}'' is deprecated. {1}", DEPRECATION_RENDERER, STRING); MAP.put(DEPRECATION, "''{0}'' is deprecated. {1}", DEPRECATION_RENDERER, STRING);
MAP.put(DEPRECATION_ERROR, "Using ''{0}'' is an error. {1}", DEPRECATION_RENDERER, STRING); MAP.put(DEPRECATION_ERROR, "Using ''{0}'' is an error. {1}", DEPRECATION_RENDERER, STRING);
DiagnosticParameterRenderer<Pair<LanguageVersion, String>> sinceKotlinInfoMessage = new DiagnosticParameterRenderer<Pair<LanguageVersion, String>>() { DiagnosticParameterRenderer<Pair<LanguageVersion, String>> sinceKotlinInfoMessage = (pair, renderingContext) -> {
@NotNull String message = pair.getSecond();
@Override return pair.getFirst().getVersionString() + (message != null ? ". " + message : "");
public String render(@NotNull Pair<LanguageVersion, String> pair, @NotNull RenderingContext renderingContext) {
String message = pair.getSecond();
return pair.getFirst().getVersionString() + (message != null ? ". " + message : "");
}
}; };
MAP.put(SINCE_KOTLIN_INFO_DEPRECATION, "''{0}''{1} should not be used in Kotlin {2}", DEPRECATION_RENDERER, new DiagnosticParameterRenderer<SinceKotlinInfo.Version>() { MAP.put(SINCE_KOTLIN_INFO_DEPRECATION, "''{0}''{1} should not be used in Kotlin {2}", DEPRECATION_RENDERER,
@NotNull (obj, renderingContext) -> obj.equals(SinceKotlinInfo.Version.INFINITY) ? "" : " is only supported since Kotlin " + obj.asString() + " and", sinceKotlinInfoMessage);
@Override MAP.put(SINCE_KOTLIN_INFO_DEPRECATION_ERROR, "''{0}''{1} cannot be used in Kotlin {2}", DEPRECATION_RENDERER,
public String render(@NotNull SinceKotlinInfo.Version obj, @NotNull RenderingContext renderingContext) { (obj, renderingContext) -> obj.equals(SinceKotlinInfo.Version.INFINITY) ? "" : " is only available since Kotlin " + obj.asString() + " and", sinceKotlinInfoMessage);
return obj.equals(SinceKotlinInfo.Version.INFINITY) ? "" : " is only supported since Kotlin " + obj.asString() + " and";
}
}, sinceKotlinInfoMessage);
MAP.put(SINCE_KOTLIN_INFO_DEPRECATION_ERROR, "''{0}''{1} cannot be used in Kotlin {2}", DEPRECATION_RENDERER, new DiagnosticParameterRenderer<SinceKotlinInfo.Version>() {
@NotNull
@Override
public String render(@NotNull SinceKotlinInfo.Version obj, @NotNull RenderingContext renderingContext) {
return obj.equals(SinceKotlinInfo.Version.INFINITY) ? "" : " is only available since Kotlin " + obj.asString() + " and";
}
}, sinceKotlinInfoMessage);
MAP.put(API_NOT_AVAILABLE, "This declaration is only available since Kotlin {0} and cannot be used with the specified API version {1}", STRING, STRING); MAP.put(API_NOT_AVAILABLE, "This declaration is only available since Kotlin {0} and cannot be used with the specified API version {1}", STRING, STRING);
@@ -362,15 +330,12 @@ public class DefaultErrorMessages {
MAP.put(PRE_RELEASE_CLASS, "{0} is compiled by a pre-release version of Kotlin and cannot be loaded by this version of the compiler", TO_STRING); MAP.put(PRE_RELEASE_CLASS, "{0} is compiled by a pre-release version of Kotlin and cannot be loaded by this version of the compiler", TO_STRING);
MAP.put(INCOMPATIBLE_CLASS, MAP.put(INCOMPATIBLE_CLASS,
"{0} was compiled with an incompatible version of Kotlin. {1}", "{0} was compiled with an incompatible version of Kotlin. {1}",
TO_STRING, new DiagnosticParameterRenderer<IncompatibleVersionErrorData<?>>() { TO_STRING,
@NotNull (incompatibility, renderingContext) ->
@Override "The binary version of its metadata is " + incompatibility.getActualVersion() +
public String render(@NotNull IncompatibleVersionErrorData<?> incompatibility, @NotNull RenderingContext renderingContext) { ", expected version is " + incompatibility.getExpectedVersion() + ".\n" +
return "The binary version of its metadata is " + incompatibility.getActualVersion() + "The class is loaded from " + FileUtil.toSystemIndependentName(incompatibility.getFilePath())
", expected version is " + incompatibility.getExpectedVersion() + ".\n" + );
"The class is loaded from " + FileUtil.toSystemIndependentName(incompatibility.getFilePath());
}
});
MAP.put(LOCAL_OBJECT_NOT_ALLOWED, "Named object ''{0}'' is a singleton and cannot be local. Try to use anonymous object instead", NAME); MAP.put(LOCAL_OBJECT_NOT_ALLOWED, "Named object ''{0}'' is a singleton and cannot be local. Try to use anonymous object instead", NAME);
MAP.put(LOCAL_INTERFACE_NOT_ALLOWED, "''{0}'' is an interface so it cannot be local. Try to use anonymous object or abstract class instead", NAME); MAP.put(LOCAL_INTERFACE_NOT_ALLOWED, "''{0}'' is an interface so it cannot be local. Try to use anonymous object or abstract class instead", NAME);
@@ -493,14 +458,10 @@ public class DefaultErrorMessages {
MAP.put(IMPLICIT_CAST_TO_ANY, "Conditional branch result of type {0} is implicitly cast to {1}", MAP.put(IMPLICIT_CAST_TO_ANY, "Conditional branch result of type {0} is implicitly cast to {1}",
RENDER_TYPE, RENDER_TYPE); RENDER_TYPE, RENDER_TYPE);
MAP.put(EXPRESSION_EXPECTED, "{0} is not an expression, and only expressions are allowed here", new DiagnosticParameterRenderer<KtExpression>() { MAP.put(EXPRESSION_EXPECTED, "{0} is not an expression, and only expressions are allowed here", (expression, context) -> {
@NotNull String expressionType = expression.toString();
@Override return expressionType.substring(0, 1) +
public String render(@NotNull KtExpression expression, @NotNull RenderingContext context) { expressionType.substring(1).toLowerCase();
String expressionType = expression.toString();
return expressionType.substring(0, 1) +
expressionType.substring(1).toLowerCase();
}
}); });
MAP.put(UPPER_BOUND_VIOLATED, "Type argument is not within its bounds: should be subtype of ''{0}''", RENDER_TYPE, RENDER_TYPE); MAP.put(UPPER_BOUND_VIOLATED, "Type argument is not within its bounds: should be subtype of ''{0}''", RENDER_TYPE, RENDER_TYPE);
@@ -613,13 +574,9 @@ public class DefaultErrorMessages {
MAP.put(UNEXPECTED_SAFE_CALL, "Safe-call is not allowed here"); MAP.put(UNEXPECTED_SAFE_CALL, "Safe-call is not allowed here");
MAP.put(UNNECESSARY_NOT_NULL_ASSERTION, "Unnecessary non-null assertion (!!) on a non-null receiver of type {0}", RENDER_TYPE); MAP.put(UNNECESSARY_NOT_NULL_ASSERTION, "Unnecessary non-null assertion (!!) on a non-null receiver of type {0}", RENDER_TYPE);
MAP.put(NOT_NULL_ASSERTION_ON_LAMBDA_EXPRESSION, "Non-null assertion (!!) is called on a lambda expression"); MAP.put(NOT_NULL_ASSERTION_ON_LAMBDA_EXPRESSION, "Non-null assertion (!!) is called on a lambda expression");
MAP.put(NAME_IN_CONSTRAINT_IS_NOT_A_TYPE_PARAMETER, "{0} does not refer to a type parameter of {1}", new DiagnosticParameterRenderer<KtTypeConstraint>() { MAP.put(NAME_IN_CONSTRAINT_IS_NOT_A_TYPE_PARAMETER, "{0} does not refer to a type parameter of {1}", (typeConstraint, context) -> {
@NotNull //noinspection ConstantConditions
@Override return typeConstraint.getSubjectTypeParameterName().getReferencedName();
public String render(@NotNull KtTypeConstraint typeConstraint, @NotNull RenderingContext context) {
//noinspection ConstantConditions
return typeConstraint.getSubjectTypeParameterName().getReferencedName();
}
}, DECLARATION_NAME); }, DECLARATION_NAME);
MAP.put(SMARTCAST_IMPOSSIBLE, MAP.put(SMARTCAST_IMPOSSIBLE,
"Smart cast to ''{0}'' is impossible, because ''{1}'' is a {2}", RENDER_TYPE, STRING, STRING); "Smart cast to ''{0}'' is impossible, because ''{1}'' is a {2}", RENDER_TYPE, STRING, STRING);
@@ -637,20 +594,16 @@ public class DefaultErrorMessages {
MAP.put(MISPLACED_TYPE_PARAMETER_CONSTRAINTS, "If a type parameter has multiple constraints, they all need to be placed in the 'where' clause"); MAP.put(MISPLACED_TYPE_PARAMETER_CONSTRAINTS, "If a type parameter has multiple constraints, they all need to be placed in the 'where' clause");
MultiRenderer<VarianceConflictDiagnosticData> varianceConflictDataRenderer = new MultiRenderer<VarianceConflictDiagnosticData>() { MultiRenderer<VarianceConflictDiagnosticData> varianceConflictDataRenderer = data -> {
@NotNull RenderingContext context =
@Override of(data.getTypeParameter(), data.getTypeParameter().getVariance(), data.getOccurrencePosition(),
public String[] render(@NotNull VarianceConflictDiagnosticData data) { data.getContainingType());
RenderingContext context = return new String[] {
of(data.getTypeParameter(), data.getTypeParameter().getVariance(), data.getOccurrencePosition(), NAME.render(data.getTypeParameter(), context),
data.getContainingType()); RENDER_POSITION_VARIANCE.render(data.getTypeParameter().getVariance(), context),
return new String[] { RENDER_POSITION_VARIANCE.render(data.getOccurrencePosition(), context),
NAME.render(data.getTypeParameter(), context), RENDER_TYPE.render(data.getContainingType(), context)
RENDER_POSITION_VARIANCE.render(data.getTypeParameter().getVariance(), context), };
RENDER_POSITION_VARIANCE.render(data.getOccurrencePosition(), context),
RENDER_TYPE.render(data.getContainingType(), context)
};
}
}; };
MAP.put(TYPE_VARIANCE_CONFLICT, "Type parameter {0} is declared as ''{1}'' but occurs in ''{2}'' position in type {3}", MAP.put(TYPE_VARIANCE_CONFLICT, "Type parameter {0} is declared as ''{1}'' but occurs in ''{2}'' position in type {3}",
varianceConflictDataRenderer); varianceConflictDataRenderer);
@@ -687,13 +640,9 @@ public class DefaultErrorMessages {
MAP.put(INCONSISTENT_TYPE_PARAMETER_VALUES, "Type parameter {0} of ''{1}'' has inconsistent values: {2}", NAME, NAME, RENDER_COLLECTION_OF_TYPES); MAP.put(INCONSISTENT_TYPE_PARAMETER_VALUES, "Type parameter {0} of ''{1}'' has inconsistent values: {2}", NAME, NAME, RENDER_COLLECTION_OF_TYPES);
MAP.put(INCONSISTENT_TYPE_PARAMETER_BOUNDS, "Type parameter {0} of ''{1}'' has inconsistent bounds: {2}", NAME, NAME, RENDER_COLLECTION_OF_TYPES); MAP.put(INCONSISTENT_TYPE_PARAMETER_BOUNDS, "Type parameter {0} of ''{1}'' has inconsistent bounds: {2}", NAME, NAME, RENDER_COLLECTION_OF_TYPES);
MAP.put(EQUALITY_NOT_APPLICABLE, "Operator ''{0}'' cannot be applied to ''{1}'' and ''{2}''", new DiagnosticParameterRenderer<KtSimpleNameExpression>() { MAP.put(EQUALITY_NOT_APPLICABLE, "Operator ''{0}'' cannot be applied to ''{1}'' and ''{2}''", (nameExpression, context) -> {
@NotNull //noinspection ConstantConditions
@Override return nameExpression.getReferencedName();
public String render(@NotNull KtSimpleNameExpression nameExpression, @NotNull RenderingContext context) {
//noinspection ConstantConditions
return nameExpression.getReferencedName();
}
}, RENDER_TYPE, RENDER_TYPE); }, RENDER_TYPE, RENDER_TYPE);
MAP.put(SENSELESS_COMPARISON, "Condition ''{0}'' is always ''{1}''", ELEMENT_TEXT, TO_STRING); MAP.put(SENSELESS_COMPARISON, "Condition ''{0}'' is always ''{1}''", ELEMENT_TEXT, TO_STRING);
@@ -745,21 +694,12 @@ public class DefaultErrorMessages {
MAP.put(FUNCTION_EXPECTED, "Expression ''{0}''{1} cannot be invoked as a function. " + MAP.put(FUNCTION_EXPECTED, "Expression ''{0}''{1} cannot be invoked as a function. " +
"The function ''" + OperatorNameConventions.INVOKE.asString() + "()'' is not found", "The function ''" + OperatorNameConventions.INVOKE.asString() + "()'' is not found",
ELEMENT_TEXT, new DiagnosticParameterRenderer<KotlinType>() { ELEMENT_TEXT, (type, context) -> {
@NotNull if (type.isError()) return "";
@Override return " of type '" + RENDER_TYPE.render(type, context) + "'";
public String render(@NotNull KotlinType type, @NotNull RenderingContext context) {
if (type.isError()) return "";
return " of type '" + RENDER_TYPE.render(type, context) + "'";
}
}); });
MAP.put(FUNCTION_CALL_EXPECTED, "Function invocation ''{0}({1})'' expected", ELEMENT_TEXT, new DiagnosticParameterRenderer<Boolean>() { MAP.put(FUNCTION_CALL_EXPECTED, "Function invocation ''{0}({1})'' expected", ELEMENT_TEXT,
@NotNull (hasValueParameters, context) -> hasValueParameters ? "..." : "");
@Override
public String render(@NotNull Boolean hasValueParameters, @NotNull RenderingContext context) {
return hasValueParameters ? "..." : "";
}
});
MAP.put(NON_TAIL_RECURSIVE_CALL, "Recursive call is not a tail call"); MAP.put(NON_TAIL_RECURSIVE_CALL, "Recursive call is not a tail call");
MAP.put(TAIL_RECURSION_IN_TRY_IS_NOT_SUPPORTED, "Tail recursion optimization inside try/catch/finally is not supported"); MAP.put(TAIL_RECURSION_IN_TRY_IS_NOT_SUPPORTED, "Tail recursion optimization inside try/catch/finally is not supported");
@@ -17,20 +17,13 @@
package org.jetbrains.kotlin.psi; package org.jetbrains.kotlin.psi;
import com.intellij.util.ArrayFactory; import com.intellij.util.ArrayFactory;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.kdoc.psi.api.KDoc; import org.jetbrains.kotlin.kdoc.psi.api.KDoc;
public interface KtDeclaration extends KtExpression, KtModifierListOwner { public interface KtDeclaration extends KtExpression, KtModifierListOwner {
KtDeclaration[] EMPTY_ARRAY = new KtDeclaration[0]; KtDeclaration[] EMPTY_ARRAY = new KtDeclaration[0];
ArrayFactory<KtDeclaration> ARRAY_FACTORY = new ArrayFactory<KtDeclaration>() { ArrayFactory<KtDeclaration> ARRAY_FACTORY = count -> count == 0 ? EMPTY_ARRAY : new KtDeclaration[count];
@NotNull
@Override
public KtDeclaration[] create(int count) {
return count == 0 ? EMPTY_ARRAY : new KtDeclaration[count];
}
};
@Nullable @Nullable
KDoc getDocComment(); KDoc getDocComment();
@@ -22,13 +22,7 @@ import org.jetbrains.annotations.NotNull;
public interface KtExpression extends KtElement { public interface KtExpression extends KtElement {
KtExpression[] EMPTY_ARRAY = new KtExpression[0]; KtExpression[] EMPTY_ARRAY = new KtExpression[0];
ArrayFactory<KtExpression> ARRAY_FACTORY = new ArrayFactory<KtExpression>() { ArrayFactory<KtExpression> ARRAY_FACTORY = count -> count == 0 ? EMPTY_ARRAY : new KtExpression[count];
@NotNull
@Override
public KtExpression[] create(int count) {
return count == 0 ? EMPTY_ARRAY : new KtExpression[count];
}
};
@Override @Override
<R, D> R accept(@NotNull KtVisitor<R, D> visitor, D data); <R, D> R accept(@NotNull KtVisitor<R, D> visitor, D data);
@@ -21,7 +21,6 @@ import com.intellij.psi.PsiElement;
import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.IStubElementType;
import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubElement;
import com.intellij.util.IncorrectOperationException; import com.intellij.util.IncorrectOperationException;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public abstract class KtExpressionImplStub<T extends StubElement<?>> extends KtElementImplStub<T> implements KtExpression { public abstract class KtExpressionImplStub<T extends StubElement<?>> extends KtElementImplStub<T> implements KtExpression {
@@ -41,12 +40,7 @@ public abstract class KtExpressionImplStub<T extends StubElement<?>> extends KtE
@NotNull @NotNull
@Override @Override
public PsiElement replace(@NotNull PsiElement newElement) throws IncorrectOperationException { public PsiElement replace(@NotNull PsiElement newElement) throws IncorrectOperationException {
return KtExpressionImpl.Companion.replaceExpression(this, newElement, new Function1<PsiElement, PsiElement>() { return KtExpressionImpl.Companion.replaceExpression(this, newElement, this::rawReplace);
@Override
public PsiElement invoke(PsiElement element) {
return rawReplace(element);
}
});
} }
@NotNull @NotNull
@@ -28,7 +28,6 @@ import com.intellij.util.FileContentUtilCore;
import com.intellij.util.IncorrectOperationException; import com.intellij.util.IncorrectOperationException;
import kotlin.collections.ArraysKt; import kotlin.collections.ArraysKt;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.KtNodeTypes; import org.jetbrains.kotlin.KtNodeTypes;
@@ -258,19 +257,12 @@ public class KtFile extends PsiFileBase implements KtDeclarationContainer, KtAnn
public List<KtAnnotationEntry> getDanglingAnnotations() { public List<KtAnnotationEntry> getDanglingAnnotations() {
KotlinFileStub stub = getStub(); KotlinFileStub stub = getStub();
KtModifierList[] danglingModifierLists = stub == null KtModifierList[] danglingModifierLists = stub == null
? findChildrenByClass(KtModifierList.class) ? findChildrenByClass(KtModifierList.class)
: stub.getChildrenByType( : stub.getChildrenByType(
KtStubElementTypes.MODIFIER_LIST, KtStubElementTypes.MODIFIER_LIST,
KtStubElementTypes.MODIFIER_LIST.getArrayFactory() KtStubElementTypes.MODIFIER_LIST.getArrayFactory()
); );
return ArraysKt.flatMap( return ArraysKt.flatMap(danglingModifierLists, KtModifierList::getAnnotationEntries);
danglingModifierLists,
new Function1<KtModifierList, Iterable<KtAnnotationEntry>>() {
@Override
public Iterable<KtAnnotationEntry> invoke(KtModifierList modifierList) {
return modifierList.getAnnotationEntries();
}
});
} }
@Override @Override
@@ -16,12 +16,10 @@
package org.jetbrains.kotlin.psi; package org.jetbrains.kotlin.psi;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.intellij.openapi.project.Project; import com.intellij.openapi.project.Project;
import kotlin.collections.CollectionsKt;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.resolve.ImportPath; import org.jetbrains.kotlin.resolve.ImportPath;
import java.util.Collection; import java.util.Collection;
@@ -37,7 +35,7 @@ public class KtImportsFactory {
} }
@NotNull @NotNull
public KtImportDirective createImportDirective(@NotNull ImportPath importPath) { private KtImportDirective createImportDirective(@NotNull ImportPath importPath) {
KtImportDirective directive = importsCache.get(importPath); KtImportDirective directive = importsCache.get(importPath);
if (directive != null) { if (directive != null) {
return directive; return directive;
@@ -51,13 +49,6 @@ public class KtImportsFactory {
@NotNull @NotNull
public Collection<KtImportDirective> createImportDirectives(@NotNull Collection<ImportPath> importPaths) { public Collection<KtImportDirective> createImportDirectives(@NotNull Collection<ImportPath> importPaths) {
return Collections2.transform(importPaths, return CollectionsKt.map(importPaths, this::createImportDirective);
new Function<ImportPath, KtImportDirective>() {
@Override
public KtImportDirective apply(@Nullable ImportPath path) {
assert path != null;
return createImportDirective(path);
}
});
} }
} }
@@ -25,16 +25,9 @@ import org.jetbrains.kotlin.psi.stubs.KotlinPlaceHolderStub;
import org.jetbrains.kotlin.psi.stubs.elements.KtStubElementTypes; import org.jetbrains.kotlin.psi.stubs.elements.KtStubElementTypes;
public class KtSuperTypeListEntry extends KtElementImplStub<KotlinPlaceHolderStub<? extends KtSuperTypeListEntry>> { public class KtSuperTypeListEntry extends KtElementImplStub<KotlinPlaceHolderStub<? extends KtSuperTypeListEntry>> {
private static final KtSuperTypeListEntry[] EMPTY_ARRAY = new KtSuperTypeListEntry[0]; private static final KtSuperTypeListEntry[] EMPTY_ARRAY = new KtSuperTypeListEntry[0];
public static ArrayFactory<KtSuperTypeListEntry> ARRAY_FACTORY = new ArrayFactory<KtSuperTypeListEntry>() { public static ArrayFactory<KtSuperTypeListEntry> ARRAY_FACTORY = count -> count == 0 ? EMPTY_ARRAY : new KtSuperTypeListEntry[count];
@NotNull
@Override
public KtSuperTypeListEntry[] create(int count) {
return count == 0 ? EMPTY_ARRAY : new KtSuperTypeListEntry[count];
}
};
public KtSuperTypeListEntry(@NotNull ASTNode node) { public KtSuperTypeListEntry(@NotNull ASTNode node) {
super(node); super(node);
@@ -24,13 +24,7 @@ import java.util.List;
public interface KtTypeElement extends KtElement { public interface KtTypeElement extends KtElement {
KtTypeElement[] EMPTY_ARRAY = new KtTypeElement[0]; KtTypeElement[] EMPTY_ARRAY = new KtTypeElement[0];
ArrayFactory<KtTypeElement> ARRAY_FACTORY = new ArrayFactory<KtTypeElement>() { ArrayFactory<KtTypeElement> ARRAY_FACTORY = count -> count == 0 ? EMPTY_ARRAY : new KtTypeElement[count];
@NotNull
@Override
public KtTypeElement[] create(int count) {
return count == 0 ? EMPTY_ARRAY : new KtTypeElement[count];
}
};
// may contain null // may contain null
@NotNull @NotNull
@@ -58,16 +58,12 @@ public abstract class KtStubElementType<StubT extends StubElement, PsiT extends
} }
//noinspection unchecked //noinspection unchecked
emptyArray = (PsiT[]) Array.newInstance(psiClass, 0); emptyArray = (PsiT[]) Array.newInstance(psiClass, 0);
arrayFactory = new ArrayFactory<PsiT>() { arrayFactory = count -> {
@NotNull if (count == 0) {
@Override return emptyArray;
public PsiT[] create(int count) {
if (count == 0) {
return emptyArray;
}
//noinspection unchecked
return (PsiT[]) Array.newInstance(psiClass, count);
} }
//noinspection unchecked
return (PsiT[]) Array.newInstance(psiClass, count);
}; };
} }
@@ -20,7 +20,6 @@ import com.google.common.collect.Lists;
import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Pair;
import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiTreeUtil;
import kotlin.jvm.functions.Function3;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.descriptors.*; import org.jetbrains.kotlin.descriptors.*;
@@ -36,7 +35,8 @@ import org.jetbrains.kotlin.types.KotlinType;
import org.jetbrains.kotlin.types.TypeUtils; import org.jetbrains.kotlin.types.TypeUtils;
import org.jetbrains.kotlin.types.expressions.KotlinTypeInfo; import org.jetbrains.kotlin.types.expressions.KotlinTypeInfo;
import org.jetbrains.kotlin.types.expressions.typeInfoFactory.TypeInfoFactoryKt; import org.jetbrains.kotlin.types.expressions.typeInfoFactory.TypeInfoFactoryKt;
import org.jetbrains.kotlin.util.slicedMap.*; import org.jetbrains.kotlin.util.slicedMap.MutableSlicedMap;
import org.jetbrains.kotlin.util.slicedMap.ReadOnlySlice;
import java.util.Collection; import java.util.Collection;
@@ -233,15 +233,12 @@ public class BindingContextUtils {
@NotNull BindingTrace trace, @Nullable TraceEntryFilter filter, boolean commitDiagnostics, @NotNull BindingTrace trace, @Nullable TraceEntryFilter filter, boolean commitDiagnostics,
@NotNull MutableSlicedMap map, MutableDiagnosticsWithSuppression diagnostics @NotNull MutableSlicedMap map, MutableDiagnosticsWithSuppression diagnostics
) { ) {
map.forEach(new Function3<WritableSlice, Object, Object, Void>() { map.forEach((slice, key, value) -> {
@Override if (filter == null || filter.accept(slice, key)) {
public Void invoke(WritableSlice slice, Object key, Object value) { trace.record(slice, key, value);
if (filter == null || filter.accept(slice, key)) {
trace.record(slice, key, value);
}
return null;
} }
return null;
}); });
if (!commitDiagnostics) return; if (!commitDiagnostics) return;
@@ -50,7 +50,6 @@ import org.jetbrains.kotlin.types.expressions.ValueParameterResolver;
import org.jetbrains.kotlin.types.expressions.typeInfoFactory.TypeInfoFactoryKt; import org.jetbrains.kotlin.types.expressions.typeInfoFactory.TypeInfoFactoryKt;
import org.jetbrains.kotlin.util.Box; import org.jetbrains.kotlin.util.Box;
import org.jetbrains.kotlin.util.ReenteringLazyValueComputationException; import org.jetbrains.kotlin.util.ReenteringLazyValueComputationException;
import org.jetbrains.kotlin.util.slicedMap.WritableSlice;
import java.util.*; import java.util.*;
@@ -149,21 +148,13 @@ public class BodyResolver {
ForceResolveUtil.forceResolveAllContents(descriptor.getAnnotations()); ForceResolveUtil.forceResolveAllContents(descriptor.getAnnotations());
resolveFunctionBody(outerDataFlowInfo, trace, constructor, descriptor, declaringScope, resolveFunctionBody(outerDataFlowInfo, trace, constructor, descriptor, declaringScope,
new Function1<LexicalScope, DataFlowInfo>() { headerInnerScope -> resolveSecondaryConstructorDelegationCall(
@Override outerDataFlowInfo, trace, headerInnerScope, constructor, descriptor
public DataFlowInfo invoke(@NotNull LexicalScope headerInnerScope) { ),
return resolveSecondaryConstructorDelegationCall(outerDataFlowInfo, trace, headerInnerScope, scope -> new LexicalScopeImpl(
constructor, descriptor); scope, descriptor, scope.isOwnerDescriptorAccessibleByLabel(), scope.getImplicitReceiver(),
} LexicalScopeKind.CONSTRUCTOR_HEADER
}, ));
new Function1<LexicalScope, LexicalScope>() {
@Override
public LexicalScope invoke(LexicalScope scope) {
return new LexicalScopeImpl(
scope, descriptor, scope.isOwnerDescriptorAccessibleByLabel(), scope.getImplicitReceiver(),
LexicalScopeKind.CONSTRUCTOR_HEADER);
}
});
} }
@Nullable @Nullable
@@ -637,15 +628,11 @@ public class BodyResolver {
) { ) {
return new LexicalScopeImpl(originalScope, unsubstitutedPrimaryConstructor, false, null, return new LexicalScopeImpl(originalScope, unsubstitutedPrimaryConstructor, false, null,
LexicalScopeKind.DEFAULT_VALUE, LocalRedeclarationChecker.DO_NOTHING.INSTANCE, LexicalScopeKind.DEFAULT_VALUE, LocalRedeclarationChecker.DO_NOTHING.INSTANCE,
new Function1<LexicalScopeImpl.InitializeHandler, Unit>() { handler -> {
@Override for (ValueParameterDescriptor valueParameter : unsubstitutedPrimaryConstructor.getValueParameters()) {
public Unit invoke(LexicalScopeImpl.InitializeHandler handler) { handler.addVariableDescriptor(valueParameter);
for (ValueParameterDescriptor
valueParameterDescriptor : unsubstitutedPrimaryConstructor.getValueParameters()) {
handler.addVariableDescriptor(valueParameterDescriptor);
}
return Unit.INSTANCE;
} }
return Unit.INSTANCE;
}); });
} }
@@ -739,20 +726,14 @@ public class BodyResolver {
private ObservableBindingTrace createFieldTrackingTrace(PropertyDescriptor propertyDescriptor) { private ObservableBindingTrace createFieldTrackingTrace(PropertyDescriptor propertyDescriptor) {
return new ObservableBindingTrace(trace).addHandler( return new ObservableBindingTrace(trace).addHandler(
BindingContext.REFERENCE_TARGET, BindingContext.REFERENCE_TARGET,
new ObservableBindingTrace.RecordHandler<KtReferenceExpression, DeclarationDescriptor>() { (slice, expression, descriptor) -> {
@Override if (expression instanceof KtSimpleNameExpression &&
public void handleRecord( descriptor instanceof SyntheticFieldDescriptor) {
WritableSlice<KtReferenceExpression, DeclarationDescriptor> slice, trace.record(BindingContext.BACKING_FIELD_REQUIRED,
KtReferenceExpression expression, propertyDescriptor);
DeclarationDescriptor descriptor }
) {
if (expression instanceof KtSimpleNameExpression &&
descriptor instanceof SyntheticFieldDescriptor) {
trace.record(BindingContext.BACKING_FIELD_REQUIRED,
propertyDescriptor);
} }
} );
});
} }
private void resolvePropertyDelegate( private void resolvePropertyDelegate(
@@ -850,13 +831,10 @@ public class BodyResolver {
SyntheticFieldDescriptor fieldDescriptor = new SyntheticFieldDescriptor(accessorDescriptor, property); SyntheticFieldDescriptor fieldDescriptor = new SyntheticFieldDescriptor(accessorDescriptor, property);
innerScope = new LexicalScopeImpl(innerScope, functionDescriptor, true, null, innerScope = new LexicalScopeImpl(innerScope, functionDescriptor, true, null,
LexicalScopeKind.PROPERTY_ACCESSOR_BODY, LexicalScopeKind.PROPERTY_ACCESSOR_BODY,
LocalRedeclarationChecker.DO_NOTHING.INSTANCE, new Function1<LexicalScopeImpl.InitializeHandler, Unit>() { LocalRedeclarationChecker.DO_NOTHING.INSTANCE, handler -> {
@Override handler.addVariableDescriptor(fieldDescriptor);
public Unit invoke(LexicalScopeImpl.InitializeHandler handler) { return Unit.INSTANCE;
handler.addVariableDescriptor(fieldDescriptor); });
return Unit.INSTANCE;
}
});
// Check parameter name shadowing // Check parameter name shadowing
for (KtParameter parameter : function.getValueParameters()) { for (KtParameter parameter : function.getValueParameters()) {
if (SyntheticFieldDescriptor.NAME.equals(parameter.getNameAsName())) { if (SyntheticFieldDescriptor.NAME.equals(parameter.getNameAsName())) {
@@ -914,16 +892,7 @@ public class BodyResolver {
} }
// +1 is a work around against new Queue(0).addLast(...) bug // stepan.koltsov@ 2011-11-21 // +1 is a work around against new Queue(0).addLast(...) bug // stepan.koltsov@ 2011-11-21
Queue<DeferredType> queue = new Queue<DeferredType>(deferredTypes.size() + 1); Queue<DeferredType> queue = new Queue<DeferredType>(deferredTypes.size() + 1);
trace.addHandler(DEFERRED_TYPE, new ObservableBindingTrace.RecordHandler<Box<DeferredType>, Boolean>() { trace.addHandler(DEFERRED_TYPE, (deferredTypeKeyDeferredTypeWritableSlice, key, value) -> queue.addLast(key.getData()));
@Override
public void handleRecord(
WritableSlice<Box<DeferredType>, Boolean> deferredTypeKeyDeferredTypeWritableSlice,
Box<DeferredType> key,
Boolean value
) {
queue.addLast(key.getData());
}
});
for (Box<DeferredType> deferredType : deferredTypes) { for (Box<DeferredType> deferredType : deferredTypes) {
queue.addLast(deferredType.getData()); queue.addLast(deferredType.getData());
} }
@@ -26,7 +26,6 @@ import kotlin.TuplesKt;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import kotlin.collections.SetsKt; import kotlin.collections.SetsKt;
import kotlin.jvm.functions.Function0; import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1;
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.FunctionTypesKt; import org.jetbrains.kotlin.builtins.FunctionTypesKt;
@@ -35,7 +34,6 @@ import org.jetbrains.kotlin.config.LanguageFeature;
import org.jetbrains.kotlin.config.LanguageVersionSettings; import org.jetbrains.kotlin.config.LanguageVersionSettings;
import org.jetbrains.kotlin.descriptors.*; import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.annotations.AnnotationSplitter; import org.jetbrains.kotlin.descriptors.annotations.AnnotationSplitter;
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget;
import org.jetbrains.kotlin.descriptors.annotations.Annotations; import org.jetbrains.kotlin.descriptors.annotations.Annotations;
import org.jetbrains.kotlin.descriptors.annotations.CompositeAnnotations; import org.jetbrains.kotlin.descriptors.annotations.CompositeAnnotations;
import org.jetbrains.kotlin.descriptors.impl.*; import org.jetbrains.kotlin.descriptors.impl.*;
@@ -335,26 +333,23 @@ public class DescriptorResolver {
TuplesKt.to(LanguageFeature.DestructuringLambdaParameters, languageVersionSettings))); TuplesKt.to(LanguageFeature.DestructuringLambdaParameters, languageVersionSettings)));
} }
destructuringVariables = new Function0<List<VariableDescriptor>>() { destructuringVariables = () -> {
@Override assert owner.getDispatchReceiverParameter() == null
public List<VariableDescriptor> invoke() { : "Destructuring declarations are only be parsed for lambdas, and they must not have a dispatch receiver";
assert owner.getDispatchReceiverParameter() == null LexicalScope scopeForDestructuring =
: "Destructuring declarations are only be parsed for lambdas, and they must not have a dispatch receiver"; ScopeUtilsKt.createScopeForDestructuring(scope, owner.getExtensionReceiverParameter());
LexicalScope scopeForDestructuring =
ScopeUtilsKt.createScopeForDestructuring(scope, owner.getExtensionReceiverParameter());
List<VariableDescriptor> result = List<VariableDescriptor> result =
destructuringDeclarationResolver.resolveLocalVariablesFromDestructuringDeclaration( destructuringDeclarationResolver.resolveLocalVariablesFromDestructuringDeclaration(
scope, scope,
destructuringDeclaration, new TransientReceiver(type), /* initializer = */ null, destructuringDeclaration, new TransientReceiver(type), /* initializer = */ null,
ExpressionTypingContext.newContext( ExpressionTypingContext.newContext(
trace, scopeForDestructuring, DataFlowInfoFactory.EMPTY, TypeUtils.NO_EXPECTED_TYPE trace, scopeForDestructuring, DataFlowInfoFactory.EMPTY, TypeUtils.NO_EXPECTED_TYPE
) )
); );
modifiersChecker.withTrace(trace).checkModifiersForDestructuringDeclaration(destructuringDeclaration); modifiersChecker.withTrace(trace).checkModifiersForDestructuringDeclaration(destructuringDeclaration);
return result; return result;
}
}; };
} }
else { else {
@@ -460,17 +455,14 @@ public class DescriptorResolver {
KtPsiUtil.safeName(typeParameter.getName()), KtPsiUtil.safeName(typeParameter.getName()),
index, index,
KotlinSourceElementKt.toSourceElement(typeParameter), KotlinSourceElementKt.toSourceElement(typeParameter),
new Function1<KotlinType, Void>() { type -> {
@Override if (!(containingDescriptor instanceof TypeAliasDescriptor)) {
public Void invoke(KotlinType type) { trace.report(Errors.CYCLIC_GENERIC_UPPER_BOUND.on(typeParameter));
if (!(containingDescriptor instanceof TypeAliasDescriptor)) {
trace.report(Errors.CYCLIC_GENERIC_UPPER_BOUND.on(typeParameter));
}
return null;
} }
return null;
}, },
supertypeLoopsResolver supertypeLoopsResolver
); );
trace.record(BindingContext.TYPE_PARAMETER, typeParameter, typeParameterDescriptor); trace.record(BindingContext.TYPE_PARAMETER, typeParameter, typeParameterDescriptor);
return typeParameterDescriptor; return typeParameterDescriptor;
} }
@@ -761,21 +753,11 @@ public class DescriptorResolver {
typeAliasDescriptor.initialize( typeAliasDescriptor.initialize(
typeParameterDescriptors, typeParameterDescriptors,
storageManager.createRecursionTolerantLazyValue( storageManager.createRecursionTolerantLazyValue(
new Function0<SimpleType>() { () -> typeResolver.resolveAbbreviatedType(scopeWithTypeParameters, typeReference, trace),
@Override
public SimpleType invoke() {
return typeResolver.resolveAbbreviatedType(scopeWithTypeParameters, typeReference, trace);
}
},
ErrorUtils.createErrorType("Recursive type alias expansion for " + typeAliasDescriptor.getName().asString()) ErrorUtils.createErrorType("Recursive type alias expansion for " + typeAliasDescriptor.getName().asString())
), ),
storageManager.createRecursionTolerantLazyValue( storageManager.createRecursionTolerantLazyValue(
new Function0<SimpleType>() { () -> typeResolver.resolveExpandedTypeForTypeAlias(typeAliasDescriptor),
@Override
public SimpleType invoke() {
return typeResolver.resolveExpandedTypeForTypeAlias(typeAliasDescriptor);
}
},
ErrorUtils.createErrorType("Recursive type alias expansion for " + typeAliasDescriptor.getName().asString()) ErrorUtils.createErrorType("Recursive type alias expansion for " + typeAliasDescriptor.getName().asString())
) )
); );
@@ -817,12 +799,8 @@ public class DescriptorResolver {
Annotations allAnnotations = annotationResolver.resolveAnnotationsWithoutArguments(scopeForDeclarationResolution, modifierList, trace); Annotations allAnnotations = annotationResolver.resolveAnnotationsWithoutArguments(scopeForDeclarationResolution, modifierList, trace);
AnnotationSplitter annotationSplitter = AnnotationSplitter annotationSplitter =
new AnnotationSplitter(storageManager, allAnnotations, new Function0<Set<AnnotationUseSiteTarget>>() { new AnnotationSplitter(storageManager, allAnnotations,
@Override () -> AnnotationSplitter.getTargetSet(false, trace.getBindingContext(), wrapper));
public Set<AnnotationUseSiteTarget> invoke() {
return AnnotationSplitter.getTargetSet(false, trace.getBindingContext(), wrapper);
}
});
Annotations propertyAnnotations = new CompositeAnnotations(CollectionsKt.listOf( Annotations propertyAnnotations = new CompositeAnnotations(CollectionsKt.listOf(
annotationSplitter.getAnnotationsForTargets(PROPERTY, FIELD, PROPERTY_DELEGATE_FIELD), annotationSplitter.getAnnotationsForTargets(PROPERTY, FIELD, PROPERTY_DELEGATE_FIELD),
@@ -1117,16 +1095,13 @@ public class DescriptorResolver {
@NotNull KtDeclarationWithBody function, @NotNull KtDeclarationWithBody function,
@NotNull FunctionDescriptor functionDescriptor @NotNull FunctionDescriptor functionDescriptor
) { ) {
return wrappedTypeFactory.createRecursionIntolerantDeferredType(trace, new Function0<KotlinType>() { return wrappedTypeFactory.createRecursionIntolerantDeferredType(trace, () -> {
@Override PreliminaryDeclarationVisitor.Companion.createForDeclaration(function, trace);
public KotlinType invoke() { KotlinType type = expressionTypingServices.getBodyExpressionType(
PreliminaryDeclarationVisitor.Companion.createForDeclaration(function, trace); trace, scope, dataFlowInfo, function, functionDescriptor);
KotlinType type = expressionTypingServices.getBodyExpressionType( KotlinType result = transformAnonymousTypeIfNeeded(functionDescriptor, function, type, trace);
trace, scope, dataFlowInfo, function, functionDescriptor); functionsTypingVisitor.checkTypesForReturnStatements(function, trace, result);
KotlinType result = transformAnonymousTypeIfNeeded(functionDescriptor, function, type, trace); return result;
functionsTypingVisitor.checkTypesForReturnStatements(function, trace, result);
return result;
}
}); });
} }
@@ -1152,12 +1127,8 @@ public class DescriptorResolver {
AnnotationSplitter.PropertyWrapper propertyWrapper = new AnnotationSplitter.PropertyWrapper(parameter); AnnotationSplitter.PropertyWrapper propertyWrapper = new AnnotationSplitter.PropertyWrapper(parameter);
Annotations allAnnotations = annotationResolver.resolveAnnotationsWithoutArguments(scope, parameter.getModifierList(), trace); Annotations allAnnotations = annotationResolver.resolveAnnotationsWithoutArguments(scope, parameter.getModifierList(), trace);
AnnotationSplitter annotationSplitter = AnnotationSplitter annotationSplitter =
new AnnotationSplitter(storageManager, allAnnotations, new Function0<Set<AnnotationUseSiteTarget>>() { new AnnotationSplitter(storageManager, allAnnotations,
@Override () -> AnnotationSplitter.getTargetSet(true, trace.getBindingContext(), propertyWrapper));
public Set<AnnotationUseSiteTarget> invoke() {
return AnnotationSplitter.getTargetSet(true, trace.getBindingContext(), propertyWrapper);
}
});
Annotations propertyAnnotations = new CompositeAnnotations( Annotations propertyAnnotations = new CompositeAnnotations(
annotationSplitter.getAnnotationsForTargets(PROPERTY, FIELD), annotationSplitter.getAnnotationsForTargets(PROPERTY, FIELD),
@@ -17,7 +17,6 @@
package org.jetbrains.kotlin.resolve; package org.jetbrains.kotlin.resolve;
import kotlin.Unit; import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.descriptors.*; import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl; import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl;
@@ -66,31 +65,29 @@ public class FunctionDescriptorUtil {
@NotNull FunctionDescriptor descriptor, @NotNull FunctionDescriptor descriptor,
@NotNull LocalRedeclarationChecker redeclarationChecker @NotNull LocalRedeclarationChecker redeclarationChecker
) { ) {
ReceiverParameterDescriptor receiver = descriptor.getExtensionReceiverParameter(); return new LexicalScopeImpl(
outerScope, descriptor, true, descriptor.getExtensionReceiverParameter(),
return new LexicalScopeImpl(outerScope, descriptor, true, receiver, LexicalScopeKind.FUNCTION_INNER_SCOPE, redeclarationChecker, LexicalScopeKind.FUNCTION_INNER_SCOPE, redeclarationChecker,
new Function1<LexicalScopeImpl.InitializeHandler, Unit>() { handler -> {
@Override for (TypeParameterDescriptor typeParameter : descriptor.getTypeParameters()) {
public Unit invoke(LexicalScopeImpl.InitializeHandler handler) { handler.addClassifierDescriptor(typeParameter);
for (TypeParameterDescriptor typeParameter : descriptor.getTypeParameters()) { }
handler.addClassifierDescriptor(typeParameter); for (ValueParameterDescriptor valueParameterDescriptor : descriptor.getValueParameters()) {
} if (valueParameterDescriptor instanceof ValueParameterDescriptorImpl.WithDestructuringDeclaration) {
for (ValueParameterDescriptor valueParameterDescriptor : descriptor.getValueParameters()) { List<VariableDescriptor> entries =
if (valueParameterDescriptor instanceof ValueParameterDescriptorImpl.WithDestructuringDeclaration) { ((ValueParameterDescriptorImpl.WithDestructuringDeclaration) valueParameterDescriptor)
List<VariableDescriptor> entries = .getDestructuringVariables();
((ValueParameterDescriptorImpl.WithDestructuringDeclaration) valueParameterDescriptor) for (VariableDescriptor entry : entries) {
.getDestructuringVariables(); handler.addVariableDescriptor(entry);
for (VariableDescriptor entry : entries) { }
handler.addVariableDescriptor(entry); }
} else {
} handler.addVariableDescriptor(valueParameterDescriptor);
else { }
handler.addVariableDescriptor(valueParameterDescriptor); }
} return Unit.INSTANCE;
} }
return Unit.INSTANCE; );
}
});
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@@ -18,7 +18,6 @@ package org.jetbrains.kotlin.resolve.calls;
import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElement;
import kotlin.Pair; import kotlin.Pair;
import kotlin.jvm.functions.Function0;
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.FunctionTypesKt; import org.jetbrains.kotlin.builtins.FunctionTypesKt;
@@ -181,14 +180,9 @@ public class CallResolver {
@NotNull TracingStrategy tracing, @NotNull TracingStrategy tracing,
@NotNull NewResolutionOldInference.ResolutionKind<D> kind @NotNull NewResolutionOldInference.ResolutionKind<D> kind
) { ) {
return callResolvePerfCounter.time(new Function0<OverloadResolutionResults<D>>() { return callResolvePerfCounter.<OverloadResolutionResults<D>>time(() -> {
@Override ResolutionTask<D> resolutionTask = new ResolutionTask<>(kind, name, null);
public OverloadResolutionResults<D> invoke() { return doResolveCallOrGetCachedResults(context, resolutionTask, tracing);
ResolutionTask<D> resolutionTask = new ResolutionTask<D>(
kind, name, null
);
return doResolveCallOrGetCachedResults(context, resolutionTask, tracing);
}
}); });
} }
@@ -208,14 +202,11 @@ public class CallResolver {
@NotNull Collection<ResolutionCandidate<D>> candidates, @NotNull Collection<ResolutionCandidate<D>> candidates,
@NotNull TracingStrategy tracing @NotNull TracingStrategy tracing
) { ) {
return callResolvePerfCounter.time(new Function0<OverloadResolutionResults<D>>() { return callResolvePerfCounter.<OverloadResolutionResults<D>>time(() -> {
@Override ResolutionTask<D> resolutionTask = new ResolutionTask<>(
public OverloadResolutionResults<D> invoke() { new NewResolutionOldInference.ResolutionKind.GivenCandidates<>(), null, candidates
ResolutionTask<D> resolutionTask = new ResolutionTask<D>( );
new NewResolutionOldInference.ResolutionKind.GivenCandidates<D>(), null, candidates return doResolveCallOrGetCachedResults(context, resolutionTask, tracing);
);
return doResolveCallOrGetCachedResults(context, resolutionTask, tracing);
}
}); });
} }
@@ -498,22 +489,18 @@ public class CallResolver {
@NotNull ResolutionCandidate<FunctionDescriptor> candidate, @NotNull ResolutionCandidate<FunctionDescriptor> candidate,
@Nullable MutableDataFlowInfoForArguments dataFlowInfoForArguments @Nullable MutableDataFlowInfoForArguments dataFlowInfoForArguments
) { ) {
return callResolvePerfCounter.time(new Function0<OverloadResolutionResults<FunctionDescriptor>>() { return callResolvePerfCounter.<OverloadResolutionResults<FunctionDescriptor>>time(() -> {
@Override BasicCallResolutionContext basicCallResolutionContext =
public OverloadResolutionResults<FunctionDescriptor> invoke() { BasicCallResolutionContext.create(context, call, CheckArgumentTypesMode.CHECK_VALUE_ARGUMENTS, dataFlowInfoForArguments);
BasicCallResolutionContext basicCallResolutionContext =
BasicCallResolutionContext.create(context, call, CheckArgumentTypesMode.CHECK_VALUE_ARGUMENTS, dataFlowInfoForArguments);
Set<ResolutionCandidate<FunctionDescriptor>> candidates = Collections.singleton(candidate); Set<ResolutionCandidate<FunctionDescriptor>> candidates = Collections.singleton(candidate);
ResolutionTask<FunctionDescriptor> resolutionTask = ResolutionTask<FunctionDescriptor> resolutionTask =
new ResolutionTask<FunctionDescriptor>( new ResolutionTask<FunctionDescriptor>(
new NewResolutionOldInference.ResolutionKind.GivenCandidates<FunctionDescriptor>(), null, candidates new NewResolutionOldInference.ResolutionKind.GivenCandidates<FunctionDescriptor>(), null, candidates
); );
return doResolveCallOrGetCachedResults(basicCallResolutionContext, resolutionTask, tracing);
return doResolveCallOrGetCachedResults(basicCallResolutionContext, resolutionTask, tracing);
}
}); });
} }
@@ -70,12 +70,7 @@ public abstract class ResolutionContext<Context extends ResolutionContext<Contex
@NotNull @NotNull
public final Function1<KtExpression, KtExpression> expressionContextProvider; public final Function1<KtExpression, KtExpression> expressionContextProvider;
public static final Function1<KtExpression, KtExpression> DEFAULT_EXPRESSION_CONTEXT_PROVIDER = new Function1<KtExpression, KtExpression>() { public static final Function1<KtExpression, KtExpression> DEFAULT_EXPRESSION_CONTEXT_PROVIDER = expression -> null;
@Override
public KtExpression invoke(KtExpression expression) {
return null;
}
};
protected ResolutionContext( protected ResolutionContext(
@NotNull BindingTrace trace, @NotNull BindingTrace trace,
@@ -19,7 +19,6 @@ package org.jetbrains.kotlin.resolve.calls.inference;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor; import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor;
@@ -96,15 +95,8 @@ public class ConstraintsUtil {
KotlinType type = constraintSystem.getTypeBounds(typeVariable).getValue(); KotlinType type = constraintSystem.getTypeBounds(typeVariable).getValue();
if (type == null) return true; if (type == null) return true;
List<TypeParameterDescriptor> typeParametersUsedInSystem = CollectionsKt.map( List<TypeParameterDescriptor> typeParametersUsedInSystem =
constraintSystem.getTypeVariables(), CollectionsKt.map(constraintSystem.getTypeVariables(), TypeVariable::getOriginalTypeParameter);
new Function1<TypeVariable, TypeParameterDescriptor>() {
@Override
public TypeParameterDescriptor invoke(TypeVariable variable) {
return variable.getOriginalTypeParameter();
}
}
);
for (KotlinType upperBound : typeParameter.getUpperBounds()) { for (KotlinType upperBound : typeParameter.getUpperBounds()) {
if (!substituteOtherTypeParametersInBound && if (!substituteOtherTypeParametersInBound &&
@@ -131,12 +123,7 @@ public class ConstraintsUtil {
interestingMethods.add(method); interestingMethods.add(method);
} }
} }
Collections.sort(interestingMethods, new Comparator<Method>() { Collections.sort(interestingMethods, Comparator.comparing(Method::getName));
@Override
public int compare(@NotNull Method method1, @NotNull Method method2) {
return method1.getName().compareTo(method2.getName());
}
});
for (Iterator<Method> iterator = interestingMethods.iterator(); iterator.hasNext(); ) { for (Iterator<Method> iterator = interestingMethods.iterator(); iterator.hasNext(); ) {
Method method = iterator.next(); Method method = iterator.next();
try { try {
@@ -16,7 +16,6 @@
package org.jetbrains.kotlin.resolve.diagnostics; package org.jetbrains.kotlin.resolve.diagnostics;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.ModificationTracker; import com.intellij.openapi.util.ModificationTracker;
import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElement;
import com.intellij.util.containers.FilteringIterator; import com.intellij.util.containers.FilteringIterator;
@@ -49,12 +48,8 @@ public class DiagnosticsWithSuppression implements Diagnostics {
@NotNull @NotNull
@Override @Override
public Iterator<Diagnostic> iterator() { public Iterator<Diagnostic> iterator() {
return new FilteringIterator<Diagnostic, Diagnostic>(diagnostics.iterator(), new Condition<Diagnostic>() { return new FilteringIterator<Diagnostic, Diagnostic>(diagnostics.iterator(),
@Override diagnostic -> kotlinSuppressCache.getFilter().invoke(diagnostic));
public boolean value(Diagnostic diagnostic) {
return kotlinSuppressCache.getFilter().invoke(diagnostic);
}
});
} }
@NotNull @NotNull
@@ -18,7 +18,6 @@ package org.jetbrains.kotlin.resolve.lazy;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.intellij.openapi.project.Project; import com.intellij.openapi.project.Project;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.ContainerUtil;
import kotlin.jvm.functions.Function1; import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@@ -36,7 +35,6 @@ 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.extensions.SyntheticResolveExtension; import org.jetbrains.kotlin.resolve.extensions.SyntheticResolveExtension;
import org.jetbrains.kotlin.resolve.lazy.data.KtClassLikeInfo;
import org.jetbrains.kotlin.resolve.lazy.data.KtClassOrObjectInfo; import org.jetbrains.kotlin.resolve.lazy.data.KtClassOrObjectInfo;
import org.jetbrains.kotlin.resolve.lazy.data.KtScriptInfo; import org.jetbrains.kotlin.resolve.lazy.data.KtScriptInfo;
import org.jetbrains.kotlin.resolve.lazy.declarations.DeclarationProviderFactory; import org.jetbrains.kotlin.resolve.lazy.declarations.DeclarationProviderFactory;
@@ -165,14 +163,7 @@ public class ResolveSession implements KotlinCodeAnalyzer, LazyClassContext {
this.trace = lockBasedLazyResolveStorageManager.createSafeTrace(delegationTrace); this.trace = lockBasedLazyResolveStorageManager.createSafeTrace(delegationTrace);
this.module = rootDescriptor; this.module = rootDescriptor;
this.packages = this.packages = storageManager.createMemoizedFunctionWithNullableValues(this::createPackage);
storageManager.createMemoizedFunctionWithNullableValues(new Function1<FqName, LazyPackageDescriptor>() {
@Override
@Nullable
public LazyPackageDescriptor invoke(FqName fqName) {
return createPackage(fqName);
}
});
this.declarationProviderFactory = declarationProviderFactory; this.declarationProviderFactory = declarationProviderFactory;
@@ -196,19 +187,9 @@ public class ResolveSession implements KotlinCodeAnalyzer, LazyClassContext {
} }
}; };
fileAnnotations = storageManager.createMemoizedFunction(new Function1<KtFile, LazyAnnotations>() { fileAnnotations = storageManager.createMemoizedFunction(file -> createAnnotations(file, file.getAnnotationEntries()));
@Override
public LazyAnnotations invoke(KtFile file) {
return createAnnotations(file, file.getAnnotationEntries());
}
});
danglingAnnotations = storageManager.createMemoizedFunction(new Function1<KtFile, LazyAnnotations>() { danglingAnnotations = storageManager.createMemoizedFunction(file -> createAnnotations(file, file.getDanglingAnnotations()));
@Override
public LazyAnnotations invoke(KtFile file) {
return createAnnotations(file, file.getDanglingAnnotations());
}
});
syntheticResolveExtension = SyntheticResolveExtension.Companion.getInstance(project); syntheticResolveExtension = SyntheticResolveExtension.Companion.getInstance(project);
} }
@@ -271,33 +252,25 @@ public class ResolveSession implements KotlinCodeAnalyzer, LazyClassContext {
result.addAll(ContainerUtil.mapNotNull( result.addAll(ContainerUtil.mapNotNull(
provider.getClassOrObjectDeclarations(fqName.shortName()), provider.getClassOrObjectDeclarations(fqName.shortName()),
new Function<KtClassLikeInfo, ClassifierDescriptor>() { classLikeInfo -> {
@Override if (classLikeInfo instanceof KtClassOrObjectInfo) {
public ClassDescriptor fun(KtClassLikeInfo classLikeInfo) { //noinspection RedundantCast
if (classLikeInfo instanceof KtClassOrObjectInfo) { return getClassDescriptor(((KtClassOrObjectInfo) classLikeInfo).getCorrespondingClassOrObject(), location);
//noinspection RedundantCast }
return getClassDescriptor(((KtClassOrObjectInfo) classLikeInfo).getCorrespondingClassOrObject(), location); else if (classLikeInfo instanceof KtScriptInfo) {
} return getScriptDescriptor(((KtScriptInfo) classLikeInfo).getScript());
else if (classLikeInfo instanceof KtScriptInfo) { }
return getScriptDescriptor(((KtScriptInfo) classLikeInfo).getScript()); else {
} throw new IllegalStateException(
else { "Unexpected " + classLikeInfo + " of type " + classLikeInfo.getClass().getName()
throw new IllegalStateException( );
"Unexpected " + classLikeInfo + " of type " + classLikeInfo.getClass().getName()
);
}
} }
} }
)); ));
result.addAll(ContainerUtil.map( result.addAll(ContainerUtil.map(
provider.getTypeAliasDeclarations(fqName.shortName()), provider.getTypeAliasDeclarations(fqName.shortName()),
new Function<KtTypeAlias, ClassifierDescriptor>() { alias -> (ClassifierDescriptor) lazyDeclarationResolver.resolveToDescriptor(alias)
@Override
public ClassifierDescriptor fun(KtTypeAlias alias) {
return (ClassifierDescriptor) lazyDeclarationResolver.resolveToDescriptor(alias);
}
}
)); ));
return result; return result;
@@ -16,7 +16,6 @@
package org.jetbrains.kotlin.resolve.lazy.declarations; package org.jetbrains.kotlin.resolve.lazy.declarations;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.name.FqName; import org.jetbrains.kotlin.name.FqName;
@@ -29,12 +28,7 @@ public abstract class AbstractDeclarationProviderFactory implements DeclarationP
public AbstractDeclarationProviderFactory(@NotNull StorageManager storageManager) { public AbstractDeclarationProviderFactory(@NotNull StorageManager storageManager) {
this.packageDeclarationProviders = this.packageDeclarationProviders =
storageManager.createMemoizedFunctionWithNullableValues(new Function1<FqName, PackageMemberDeclarationProvider>() { storageManager.createMemoizedFunctionWithNullableValues(this::createPackageMemberDeclarationProvider);
@Override
public PackageMemberDeclarationProvider invoke(FqName fqName) {
return createPackageMemberDeclarationProvider(fqName);
}
});
} }
@Nullable @Nullable
@@ -20,7 +20,6 @@ import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap; import com.google.common.collect.Multimap;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function0;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.name.FqName; import org.jetbrains.kotlin.name.FqName;
@@ -45,12 +44,7 @@ public class FileBasedDeclarationProviderFactory extends AbstractDeclarationProv
public FileBasedDeclarationProviderFactory(@NotNull StorageManager storageManager, @NotNull Collection<KtFile> files) { public FileBasedDeclarationProviderFactory(@NotNull StorageManager storageManager, @NotNull Collection<KtFile> files) {
super(storageManager); super(storageManager);
this.storageManager = storageManager; this.storageManager = storageManager;
this.index = storageManager.createLazyValue(new Function0<Index>() { this.index = storageManager.createLazyValue(() -> computeFilesByPackage(files));
@Override
public Index invoke() {
return computeFilesByPackage(files);
}
});
} }
@NotNull @NotNull
@@ -19,7 +19,6 @@ package org.jetbrains.kotlin.resolve.lazy.descriptors;
import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiNameIdentifierOwner; import com.intellij.psi.PsiNameIdentifierOwner;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1; import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -142,24 +141,13 @@ public class LazyClassDescriptor extends ClassDescriptorBase implements ClassDes
KtModifierList modifierList = classLikeInfo.getModifierList(); KtModifierList modifierList = classLikeInfo.getModifierList();
if (kind.isSingleton()) { if (kind.isSingleton()) {
this.modality = storageManager.createLazyValue(new Function0<Modality>() { this.modality = storageManager.createLazyValue(() -> Modality.FINAL);
@Override
public Modality invoke() {
return Modality.FINAL;
}
});
} }
else { else {
Modality defaultModality = kind == ClassKind.INTERFACE ? Modality.ABSTRACT : Modality.FINAL; Modality defaultModality = kind == ClassKind.INTERFACE ? Modality.ABSTRACT : Modality.FINAL;
this.modality = storageManager.createLazyValue(new Function0<Modality>() { this.modality = storageManager.createLazyValue(
@Override () -> resolveModalityFromModifiers(classOrObject, defaultModality, c.getTrace().getBindingContext(),
public Modality invoke() { null, /* allowSealed = */ true));
return resolveModalityFromModifiers(classOrObject, defaultModality,
c.getTrace().getBindingContext(),
null,
/* allowSealed = */ true);
}
});
} }
boolean isLocal = classOrObject != null && KtPsiUtil.isLocal(classOrObject); boolean isLocal = classOrObject != null && KtPsiUtil.isLocal(classOrObject);
@@ -227,76 +215,49 @@ public class LazyClassDescriptor extends ClassDescriptorBase implements ClassDes
); );
} }
this.companionObjectDescriptor = storageManager.createNullableLazyValue(new Function0<ClassDescriptorWithResolutionScopes>() { this.companionObjectDescriptor = storageManager.createNullableLazyValue(
@Override () -> computeCompanionObjectDescriptor(getCompanionObjectIfAllowed())
public ClassDescriptorWithResolutionScopes invoke() { );
return computeCompanionObjectDescriptor(getCompanionObjectIfAllowed()); this.extraCompanionObjectDescriptors = storageManager.createMemoizedFunction(this::computeCompanionObjectDescriptor);
} this.forceResolveAllContents = storageManager.createRecursionTolerantNullableLazyValue(() -> {
}); doForceResolveAllContents();
this.extraCompanionObjectDescriptors = storageManager.createMemoizedFunction(new Function1<KtObjectDeclaration, ClassDescriptor>() { return null;
@Override
public ClassDescriptor invoke(KtObjectDeclaration companionObject) {
return computeCompanionObjectDescriptor(companionObject);
}
});
this.forceResolveAllContents = storageManager.createRecursionTolerantNullableLazyValue(new Function0<Void>() {
@Override
public Void invoke() {
doForceResolveAllContents();
return null;
}
}, null); }, null);
this.resolutionScopesSupport = new ClassResolutionScopesSupport(this, storageManager, new Function0<LexicalScope>() { this.resolutionScopesSupport = new ClassResolutionScopesSupport(this, storageManager, this::getOuterScope);
@Override
public LexicalScope invoke() { this.parameters = c.getStorageManager().createLazyValue(() -> {
return getOuterScope(); KtClassLikeInfo classInfo = declarationProvider.getOwnerInfo();
KtTypeParameterList typeParameterList = classInfo.getTypeParameterList();
if (typeParameterList == null) return Collections.emptyList();
if (classInfo.getClassKind() == ClassKind.ENUM_CLASS) {
c.getTrace().report(TYPE_PARAMETERS_IN_ENUM.on(typeParameterList));
} }
if (classInfo.getClassKind() == ClassKind.OBJECT) {
c.getTrace().report(TYPE_PARAMETERS_IN_OBJECT.on(typeParameterList));
}
List<KtTypeParameter> typeParameters = typeParameterList.getParameters();
if (typeParameters.isEmpty()) return Collections.emptyList();
List<TypeParameterDescriptor> parameters = new ArrayList<TypeParameterDescriptor>(typeParameters.size());
for (int i = 0; i < typeParameters.size(); i++) {
parameters.add(new LazyTypeParameterDescriptor(c, this, typeParameters.get(i), i));
}
return parameters;
}); });
this.parameters = c.getStorageManager().createLazyValue(new Function0<List<TypeParameterDescriptor>>() { this.scopeForInitializerResolution = storageManager.createLazyValue(
@Override () -> ClassResolutionScopesSupportKt.scopeForInitializerResolution(
public List<TypeParameterDescriptor> invoke() { this, createInitializerScopeParent(), classLikeInfo.getPrimaryConstructorParameters()
KtClassLikeInfo classInfo = declarationProvider.getOwnerInfo(); )
KtTypeParameterList typeParameterList = classInfo.getTypeParameterList(); );
if (typeParameterList == null) return Collections.emptyList();
if (classInfo.getClassKind() == ClassKind.ENUM_CLASS) { // TODO: only consider classes from the same file, not the whole package fragment
c.getTrace().report(TYPE_PARAMETERS_IN_ENUM.on(typeParameterList)); this.sealedSubclasses = storageManager.createLazyValue(() -> DescriptorUtilsKt.computeSealedSubclasses(this));
}
if (classInfo.getClassKind() == ClassKind.OBJECT) {
c.getTrace().report(TYPE_PARAMETERS_IN_OBJECT.on(typeParameterList));
}
List<KtTypeParameter> typeParameters = typeParameterList.getParameters();
if (typeParameters.isEmpty()) return Collections.emptyList();
List<TypeParameterDescriptor> parameters = new ArrayList<TypeParameterDescriptor>(typeParameters.size());
for (int i = 0; i < typeParameters.size(); i++) {
parameters.add(new LazyTypeParameterDescriptor(c, LazyClassDescriptor.this, typeParameters.get(i), i));
}
return parameters;
}
});
this.scopeForInitializerResolution = storageManager.createLazyValue(new Function0<LexicalScope>() {
@Override
public LexicalScope invoke() {
return ClassResolutionScopesSupportKt.scopeForInitializerResolution(LazyClassDescriptor.this,
createInitializerScopeParent(),
classLikeInfo.getPrimaryConstructorParameters());
}
});
this.sealedSubclasses = storageManager.createLazyValue(new Function0<Collection<ClassDescriptor>>() {
@Override
public Collection<ClassDescriptor> invoke() {
// TODO: only consider classes from the same file, not the whole package fragment
return DescriptorUtilsKt.computeSealedSubclasses(LazyClassDescriptor.this);
}
});
} }
@NotNull @NotNull
@@ -390,13 +351,8 @@ public class LazyClassDescriptor extends ClassDescriptorBase implements ClassDes
//noinspection unchecked //noinspection unchecked
return (Collection) CollectionsKt.filter( return (Collection) CollectionsKt.filter(
DescriptorUtils.getAllDescriptors(unsubstitutedMemberScope), DescriptorUtils.getAllDescriptors(unsubstitutedMemberScope),
new Function1<DeclarationDescriptor, Boolean>() { descriptor -> descriptor instanceof CallableMemberDescriptor
@Override && ((CallableMemberDescriptor) descriptor).getKind() != CallableMemberDescriptor.Kind.FAKE_OVERRIDE
public Boolean invoke(DeclarationDescriptor descriptor) {
return descriptor instanceof CallableMemberDescriptor
&& ((CallableMemberDescriptor) descriptor).getKind() != CallableMemberDescriptor.Kind.FAKE_OVERRIDE;
}
}
); );
} }
@@ -436,19 +392,9 @@ public class LazyClassDescriptor extends ClassDescriptorBase implements ClassDes
return CollectionsKt.map( return CollectionsKt.map(
CollectionsKt.filter( CollectionsKt.filter(
declarationProvider.getOwnerInfo().getCompanionObjects(), declarationProvider.getOwnerInfo().getCompanionObjects(),
new Function1<KtObjectDeclaration, Boolean>() { companionObject -> companionObject != allowedCompanionObject
@Override
public Boolean invoke(KtObjectDeclaration companionObject) {
return companionObject != allowedCompanionObject;
}
}
), ),
new Function1<KtObjectDeclaration, ClassDescriptor>() { extraCompanionObjectDescriptors
@Override
public ClassDescriptor invoke(KtObjectDeclaration companionObject) {
return extraCompanionObjectDescriptors.invoke(companionObject);
}
}
); );
} }
@@ -623,12 +569,9 @@ public class LazyClassDescriptor extends ClassDescriptorBase implements ClassDes
} }
private class LazyClassTypeConstructor extends AbstractClassTypeConstructor { private class LazyClassTypeConstructor extends AbstractClassTypeConstructor {
private final NotNullLazyValue<List<TypeParameterDescriptor>> parameters = c.getStorageManager().createLazyValue(new Function0<List<TypeParameterDescriptor>>() { private final NotNullLazyValue<List<TypeParameterDescriptor>> parameters = c.getStorageManager().createLazyValue(
@Override () -> TypeParameterUtilsKt.computeConstructorTypeParameters(LazyClassDescriptor.this)
public List<TypeParameterDescriptor> invoke() { );
return TypeParameterUtilsKt.computeConstructorTypeParameters(LazyClassDescriptor.this);
}
});
public LazyClassTypeConstructor() { public LazyClassTypeConstructor() {
super(LazyClassDescriptor.this.c.getStorageManager()); super(LazyClassDescriptor.this.c.getStorageManager());
@@ -16,10 +16,8 @@
package org.jetbrains.kotlin.types; package org.jetbrains.kotlin.types;
import com.google.common.base.Function; import kotlin.collections.CollectionsKt;
import com.google.common.collect.Collections2;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.descriptors.CallableDescriptor; import org.jetbrains.kotlin.descriptors.CallableDescriptor;
import org.jetbrains.kotlin.descriptors.ClassifierDescriptor; import org.jetbrains.kotlin.descriptors.ClassifierDescriptor;
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor; import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor;
@@ -31,13 +29,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
public class BoundsSubstitutor { public class BoundsSubstitutor {
private static final Function<TypeProjection,KotlinType> PROJECTIONS_TO_TYPES = new Function<TypeProjection, KotlinType>() {
@Override
public KotlinType apply(TypeProjection projection) {
return projection.getType();
}
};
private BoundsSubstitutor() { private BoundsSubstitutor() {
} }
@@ -79,14 +70,8 @@ public class BoundsSubstitutor {
// In the end, we want every parameter to have no references to those after it in the list // In the end, we want every parameter to have no references to those after it in the list
// This gives us the reversed order: the one that refers to everybody else comes first // This gives us the reversed order: the one that refers to everybody else comes first
List<TypeParameterDescriptor> topOrder = DFS.topologicalOrder( List<TypeParameterDescriptor> topOrder = DFS.topologicalOrder(
typeParameters, typeParameters, current -> getTypeParametersFromUpperBounds(current, typeParameters)
new DFS.Neighbors<TypeParameterDescriptor>() { );
@NotNull
@Override
public Iterable<TypeParameterDescriptor> getNeighbors(TypeParameterDescriptor current) {
return getTypeParametersFromUpperBounds(current, typeParameters);
}
});
assert topOrder.size() == typeParameters.size() : "All type parameters must be visited, but only " + topOrder + " were"; assert topOrder.size() == typeParameters.size() : "All type parameters must be visited, but only " + topOrder + " were";
@@ -102,13 +87,7 @@ public class BoundsSubstitutor {
) { ) {
return DFS.dfs( return DFS.dfs(
current.getUpperBounds(), current.getUpperBounds(),
new DFS.Neighbors<KotlinType>() { typeParameter -> CollectionsKt.map(typeParameter.getArguments(), TypeProjection::getType),
@NotNull
@Override
public Iterable<KotlinType> getNeighbors(KotlinType current) {
return Collections2.transform(current.getArguments(), PROJECTIONS_TO_TYPES);
}
},
new DFS.NodeHandlerWithListResult<KotlinType, TypeParameterDescriptor>() { new DFS.NodeHandlerWithListResult<KotlinType, TypeParameterDescriptor>() {
@Override @Override
public boolean beforeChildren(KotlinType current) { public boolean beforeChildren(KotlinType current) {
@@ -17,7 +17,6 @@
package org.jetbrains.kotlin.types; package org.jetbrains.kotlin.types;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1;
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.builtins.KotlinBuiltIns;
@@ -68,15 +67,12 @@ public class CommonSupertypes {
} }
private static int depth(@NotNull KotlinType type) { private static int depth(@NotNull KotlinType type) {
return 1 + maxDepth(CollectionsKt.map(type.getArguments(), new Function1<TypeProjection, KotlinType>() { return 1 + maxDepth(CollectionsKt.map(type.getArguments(), projection -> {
@Override if (projection.isStarProjection()) {
public KotlinType invoke(TypeProjection projection) { // any type is good enough for depth here
if (projection.isStarProjection()) { return type.getConstructor().getBuiltIns().getAnyType();
// any type is good enough for depth here
return type.getConstructor().getBuiltIns().getAnyType();
}
return projection.getType();
} }
return projection.getType();
})); }));
} }
@@ -336,28 +332,19 @@ public class CommonSupertypes {
) { ) {
return DFS.dfs( return DFS.dfs(
Collections.singletonList(type), Collections.singletonList(type),
new DFS.Neighbors<SimpleType>() { current -> {
@NotNull TypeSubstitutor substitutor = TypeSubstitutor.create(current);
@Override Collection<KotlinType> supertypes = current.getConstructor().getSupertypes();
public Iterable<? extends SimpleType> getNeighbors(SimpleType current) { List<SimpleType> result = new ArrayList<SimpleType>(supertypes.size());
TypeSubstitutor substitutor = TypeSubstitutor.create(current); for (KotlinType supertype : supertypes) {
Collection<KotlinType> supertypes = current.getConstructor().getSupertypes(); if (visited.contains(supertype.getConstructor())) {
List<SimpleType> result = new ArrayList<SimpleType>(supertypes.size()); continue;
for (KotlinType supertype : supertypes) {
if (visited.contains(supertype.getConstructor())) {
continue;
}
result.add(FlexibleTypesKt.lowerIfFlexible(substitutor.safeSubstitute(supertype, Variance.INVARIANT)));
} }
return result; result.add(FlexibleTypesKt.lowerIfFlexible(substitutor.safeSubstitute(supertype, Variance.INVARIANT)));
}
},
new DFS.Visited<SimpleType>() {
@Override
public boolean checkAndMarkVisited(SimpleType current) {
return visited.add(current.getConstructor());
} }
return result;
}, },
current -> visited.add(current.getConstructor()),
new DFS.NodeHandlerWithListResult<SimpleType, TypeConstructor>() { new DFS.NodeHandlerWithListResult<SimpleType, TypeConstructor>() {
@Override @Override
public boolean beforeChildren(SimpleType current) { public boolean beforeChildren(SimpleType current) {
@@ -28,20 +28,9 @@ import org.jetbrains.kotlin.util.ReenteringLazyValueComputationException;
import static org.jetbrains.kotlin.resolve.BindingContext.DEFERRED_TYPE; import static org.jetbrains.kotlin.resolve.BindingContext.DEFERRED_TYPE;
public class DeferredType extends WrappedType { public class DeferredType extends WrappedType {
private static final Function1<Boolean, KotlinType> RECURSION_PREVENTER = firstTime -> {
private static final Function1 EMPTY_CONSUMER = new Function1<Object, Void>() { if (firstTime) throw new ReenteringLazyValueComputationException();
@Override return ErrorUtils.createErrorType("Recursive dependency");
public Void invoke(Object t) {
return null;
}
};
private static final Function1<Boolean,KotlinType> RECURSION_PREVENTER = new Function1<Boolean, KotlinType>() {
@Override
public KotlinType invoke(Boolean firstTime) {
if (firstTime) throw new ReenteringLazyValueComputationException();
return ErrorUtils.createErrorType("Recursive dependency");
}
}; };
@NotNull @NotNull
@@ -62,11 +51,8 @@ public class DeferredType extends WrappedType {
@NotNull Function0<KotlinType> compute @NotNull Function0<KotlinType> compute
) { ) {
//noinspection unchecked //noinspection unchecked
DeferredType deferredType = new DeferredType(storageManager.createLazyValueWithPostCompute( DeferredType deferredType =
compute, new DeferredType(storageManager.createLazyValueWithPostCompute(compute, RECURSION_PREVENTER, t -> null));
RECURSION_PREVENTER,
EMPTY_CONSUMER
));
trace.record(DEFERRED_TYPE, new Box<DeferredType>(deferredType)); trace.record(DEFERRED_TYPE, new Box<DeferredType>(deferredType));
return deferredType; return deferredType;
} }
@@ -27,7 +27,6 @@ import org.jetbrains.kotlin.descriptors.annotations.Annotations;
import org.jetbrains.kotlin.resolve.calls.inference.CallHandle; import org.jetbrains.kotlin.resolve.calls.inference.CallHandle;
import org.jetbrains.kotlin.resolve.calls.inference.ConstraintSystem; import org.jetbrains.kotlin.resolve.calls.inference.ConstraintSystem;
import org.jetbrains.kotlin.resolve.calls.inference.ConstraintSystemBuilderImpl; import org.jetbrains.kotlin.resolve.calls.inference.ConstraintSystemBuilderImpl;
import org.jetbrains.kotlin.resolve.scopes.TypeIntersectionScope;
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker; import org.jetbrains.kotlin.types.checker.KotlinTypeChecker;
import java.util.*; import java.util.*;
@@ -174,17 +173,14 @@ public class TypeIntersector {
private static boolean unify(KotlinType withParameters, KotlinType expected) { private static boolean unify(KotlinType withParameters, KotlinType expected) {
// T -> how T is used // T -> how T is used
Map<TypeParameterDescriptor, Variance> parameters = new HashMap<TypeParameterDescriptor, Variance>(); Map<TypeParameterDescriptor, Variance> parameters = new HashMap<TypeParameterDescriptor, Variance>();
Function1<TypeParameterUsage, Unit> processor = new Function1<TypeParameterUsage, Unit>() { Function1<TypeParameterUsage, Unit> processor = parameterUsage -> {
@Override Variance howTheTypeIsUsedBefore = parameters.get(parameterUsage.typeParameterDescriptor);
public Unit invoke(TypeParameterUsage parameterUsage) { if (howTheTypeIsUsedBefore == null) {
Variance howTheTypeIsUsedBefore = parameters.get(parameterUsage.typeParameterDescriptor); howTheTypeIsUsedBefore = Variance.INVARIANT;
if (howTheTypeIsUsedBefore == null) {
howTheTypeIsUsedBefore = Variance.INVARIANT;
}
parameters.put(parameterUsage.typeParameterDescriptor,
parameterUsage.howTheTypeParameterIsUsed.superpose(howTheTypeIsUsedBefore));
return Unit.INSTANCE;
} }
parameters.put(parameterUsage.typeParameterDescriptor,
parameterUsage.howTheTypeParameterIsUsed.superpose(howTheTypeIsUsedBefore));
return Unit.INSTANCE;
}; };
processAllTypeParameters(withParameters, Variance.INVARIANT, processor); processAllTypeParameters(withParameters, Variance.INVARIANT, processor);
processAllTypeParameters(expected, Variance.INVARIANT, processor); processAllTypeParameters(expected, Variance.INVARIANT, processor);
@@ -23,8 +23,6 @@ import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet; import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiTreeUtil;
import kotlin.TuplesKt; import kotlin.TuplesKt;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.KtNodeTypes; import org.jetbrains.kotlin.KtNodeTypes;
@@ -73,7 +71,6 @@ import org.jetbrains.kotlin.types.expressions.ControlStructureTypingUtils.Resolv
import org.jetbrains.kotlin.types.expressions.typeInfoFactory.TypeInfoFactoryKt; import org.jetbrains.kotlin.types.expressions.typeInfoFactory.TypeInfoFactoryKt;
import org.jetbrains.kotlin.types.expressions.unqualifiedSuper.UnqualifiedSuperKt; import org.jetbrains.kotlin.types.expressions.unqualifiedSuper.UnqualifiedSuperKt;
import org.jetbrains.kotlin.util.OperatorNameConventions; import org.jetbrains.kotlin.util.OperatorNameConventions;
import org.jetbrains.kotlin.util.slicedMap.WritableSlice;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
@@ -720,30 +717,12 @@ public class BasicExpressionTypingVisitor extends ExpressionTypingVisitor {
KotlinType[] result = new KotlinType[1]; KotlinType[] result = new KotlinType[1];
TemporaryBindingTrace temporaryTrace = TemporaryBindingTrace.create(context.trace, TemporaryBindingTrace temporaryTrace = TemporaryBindingTrace.create(context.trace,
"trace to resolve object literal expression", expression); "trace to resolve object literal expression", expression);
ObservableBindingTrace.RecordHandler<PsiElement, ClassDescriptor> handler =
new ObservableBindingTrace.RecordHandler<PsiElement, ClassDescriptor>() {
@Override
public void handleRecord(
WritableSlice<PsiElement, ClassDescriptor> slice,
PsiElement declaration,
ClassDescriptor descriptor
) {
if (slice == CLASS && declaration == expression.getObjectDeclaration()) {
KotlinType defaultType = components.wrappedTypeFactory.createRecursionIntolerantDeferredType(
context.trace,
new Function0<KotlinType>() {
@Override
public KotlinType invoke() {
return descriptor.getDefaultType();
}
});
result[0] = defaultType;
}
}
};
ObservableBindingTrace traceAdapter = new ObservableBindingTrace(temporaryTrace); ObservableBindingTrace traceAdapter = new ObservableBindingTrace(temporaryTrace);
traceAdapter.addHandler(CLASS, handler); traceAdapter.addHandler(CLASS, (slice, declaration, descriptor) -> {
if (slice == CLASS && declaration == expression.getObjectDeclaration()) {
result[0] = components.wrappedTypeFactory.createRecursionIntolerantDeferredType(context.trace, descriptor::getDefaultType);
}
});
components.localClassifierAnalyzer.processClassOrObject(null, // don't need to add classifier of object literal to any scope components.localClassifierAnalyzer.processClassOrObject(null, // don't need to add classifier of object literal to any scope
context.replaceBindingTrace(traceAdapter) context.replaceBindingTrace(traceAdapter)
.replaceContextDependency(INDEPENDENT), .replaceContextDependency(INDEPENDENT),
@@ -1199,13 +1178,10 @@ public class BasicExpressionTypingVisitor extends ExpressionTypingVisitor {
OverloadResolutionResults<FunctionDescriptor> resolutionResults = OverloadResolutionResults<FunctionDescriptor> resolutionResults =
components.callResolver.resolveCallWithGivenName(newContext, call, operationSign, OperatorNameConventions.EQUALS); components.callResolver.resolveCallWithGivenName(newContext, call, operationSign, OperatorNameConventions.EQUALS);
traceInterpretingRightAsNullableAny.commit(new TraceEntryFilter() { traceInterpretingRightAsNullableAny.commit((slice, key) -> {
@Override // the type of the right (and sometimes left) expression isn't 'Any?' actually
public boolean accept(@Nullable WritableSlice<?, ?> slice, Object key) { if ((key == right || key == left) && slice == EXPRESSION_TYPE_INFO) return false;
// the type of the right (and sometimes left) expression isn't 'Any?' actually return true;
if ((key == right || key == left) && slice == EXPRESSION_TYPE_INFO) return false;
return true;
}
}, true); }, true);
if (resolutionResults.isSuccess()) { if (resolutionResults.isSuccess()) {
@@ -1462,18 +1438,9 @@ public class BasicExpressionTypingVisitor extends ExpressionTypingVisitor {
} }
SenselessComparisonChecker.checkSenselessComparisonWithNull( SenselessComparisonChecker.checkSenselessComparisonWithNull(
expression, left, right, context, expression, left, right, context,
new Function1<KtExpression, KotlinType>() { expr -> facade.getTypeInfo(expr, context).getType(),
@Override context.dataFlowInfo::getStableNullability
public KotlinType invoke(KtExpression expression) { );
return facade.getTypeInfo(expression, context).getType();
}
},
new Function1<DataFlowValue, Nullability>() {
@Override
public Nullability invoke(DataFlowValue value) {
return context.dataFlowInfo.getStableNullability(value);
}
});
} }
} }
} }
@@ -111,12 +111,7 @@ public class ExpressionTypingServices {
trace, scope, dataFlowInfo, expectedType, contextDependency, statementFilter trace, scope, dataFlowInfo, expectedType, contextDependency, statementFilter
); );
if (contextExpression != expression) { if (contextExpression != expression) {
context = context.replaceExpressionContextProvider(new Function1<KtExpression, KtExpression>() { context = context.replaceExpressionContextProvider(arg -> arg == expression ? contextExpression : null);
@Override
public KtExpression invoke(KtExpression arg) {
return arg == expression ? contextExpression : null;
}
});
} }
return expressionTypingFacade.getTypeInfo(expression, context, isStatement); return expressionTypingFacade.getTypeInfo(expression, context, isStatement);
} }
@@ -18,7 +18,6 @@ package org.jetbrains.kotlin.types.expressions;
import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProcessCanceledException;
import kotlin.jvm.functions.Function0;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.diagnostics.DiagnosticUtils; import org.jetbrains.kotlin.diagnostics.DiagnosticUtils;
@@ -169,64 +168,61 @@ public abstract class ExpressionTypingVisitorDispatcher extends KtVisitor<Kotlin
@NotNull @NotNull
private KotlinTypeInfo getTypeInfo(@NotNull KtExpression expression, ExpressionTypingContext context, KtVisitor<KotlinTypeInfo, ExpressionTypingContext> visitor) { private KotlinTypeInfo getTypeInfo(@NotNull KtExpression expression, ExpressionTypingContext context, KtVisitor<KotlinTypeInfo, ExpressionTypingContext> visitor) {
return typeInfoPerfCounter.time(new Function0<KotlinTypeInfo>() { return typeInfoPerfCounter.time(() -> {
@Override try {
public KotlinTypeInfo invoke() { KotlinTypeInfo recordedTypeInfo = BindingContextUtils.getRecordedTypeInfo(expression, context.trace.getBindingContext());
if (recordedTypeInfo != null) {
return recordedTypeInfo;
}
context.trace.record(BindingContext.DATA_FLOW_INFO_BEFORE, expression, context.dataFlowInfo);
KotlinTypeInfo result;
try { try {
KotlinTypeInfo recordedTypeInfo = BindingContextUtils.getRecordedTypeInfo(expression, context.trace.getBindingContext()); result = expression.accept(visitor, context);
if (recordedTypeInfo != null) { // Some recursive definitions (object expressions) must put their types in the cache manually:
return recordedTypeInfo; //noinspection ConstantConditions
if (context.trace.get(BindingContext.PROCESSED, expression) == Boolean.TRUE) {
KotlinType type = context.trace.getBindingContext().getType(expression);
return result.replaceType(type);
} }
context.trace.record(BindingContext.DATA_FLOW_INFO_BEFORE, expression, context.dataFlowInfo); if (result.getType() instanceof DeferredType) {
result = result.replaceType(((DeferredType) result.getType()).getDelegate());
KotlinTypeInfo result;
try {
result = expression.accept(visitor, context);
// Some recursive definitions (object expressions) must put their types in the cache manually:
//noinspection ConstantConditions
if (context.trace.get(BindingContext.PROCESSED, expression) == Boolean.TRUE) {
KotlinType type = context.trace.getBindingContext().getType(expression);
return result.replaceType(type);
}
if (result.getType() instanceof DeferredType) {
result = result.replaceType(((DeferredType) result.getType()).getDelegate());
}
context.trace.record(BindingContext.EXPRESSION_TYPE_INFO, expression, result);
} }
catch (ReenteringLazyValueComputationException e) { context.trace.record(BindingContext.EXPRESSION_TYPE_INFO, expression, result);
context.trace.report(TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM.on(expression));
result = TypeInfoFactoryKt.noTypeInfo(context);
}
context.trace.record(BindingContext.PROCESSED, expression);
// todo save scope before analyze and fix debugger: see CodeFragmentAnalyzer.correctContextForExpression
BindingContextUtilsKt.recordScope(context.trace, context.scope, expression);
BindingContextUtilsKt.recordDataFlowInfo(context.replaceDataFlowInfo(result.getDataFlowInfo()), expression);
try {
// Here we have to resolve some types, so the following exception is possible
// Example: val a = ::a, fun foo() = ::foo
recordTypeInfo(expression, result);
}
catch (ReenteringLazyValueComputationException e) {
context.trace.report(TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM.on(expression));
return TypeInfoFactoryKt.noTypeInfo(context);
}
return result;
} }
catch (ProcessCanceledException | KotlinFrontEndException e) { catch (ReenteringLazyValueComputationException e) {
throw e; context.trace.report(TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM.on(expression));
result = TypeInfoFactoryKt.noTypeInfo(context);
} }
catch (Throwable e) {
context.trace.report(Errors.EXCEPTION_FROM_ANALYZER.on(expression, e)); context.trace.record(BindingContext.PROCESSED, expression);
logOrThrowException(expression, e);
return TypeInfoFactoryKt.createTypeInfo( // todo save scope before analyze and fix debugger: see CodeFragmentAnalyzer.correctContextForExpression
ErrorUtils.createErrorType(e.getClass().getSimpleName() + " from analyzer"), BindingContextUtilsKt.recordScope(context.trace, context.scope, expression);
context BindingContextUtilsKt.recordDataFlowInfo(context.replaceDataFlowInfo(result.getDataFlowInfo()), expression);
); try {
// Here we have to resolve some types, so the following exception is possible
// Example: val a = ::a, fun foo() = ::foo
recordTypeInfo(expression, result);
} }
catch (ReenteringLazyValueComputationException e) {
context.trace.report(TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM.on(expression));
return TypeInfoFactoryKt.noTypeInfo(context);
}
return result;
}
catch (ProcessCanceledException | KotlinFrontEndException e) {
throw e;
}
catch (Throwable e) {
context.trace.report(Errors.EXCEPTION_FROM_ANALYZER.on(expression, e));
logOrThrowException(expression, e);
return TypeInfoFactoryKt.createTypeInfo(
ErrorUtils.createErrorType(e.getClass().getSimpleName() + " from analyzer"),
context
);
} }
}); });
} }
@@ -54,12 +54,9 @@ public class TrackingSlicedMap extends SlicedMapImpl {
@Override @Override
public void forEach(@NotNull Function3<WritableSlice, Object, Object, Void> f) { public void forEach(@NotNull Function3<WritableSlice, Object, Object, Void> f) {
super.forEach(new Function3<WritableSlice, Object, Object, Void>() { super.forEach((slice, key, value) -> {
@Override f.invoke(((SliceWithStackTrace) slice).getWritableDelegate(), key, ((TrackableValue<?>) value).value);
public Void invoke(WritableSlice slice, Object key, Object value) { return null;
f.invoke(((SliceWithStackTrace) slice).getWritableDelegate(), key, ((TrackableValue<?>) value).value);
return null;
}
}); });
} }
@@ -16,7 +16,6 @@
package org.jetbrains.kotlin.asJava.finder; package org.jetbrains.kotlin.asJava.finder;
import com.google.common.base.Function;
import com.google.common.collect.Collections2; import com.google.common.collect.Collections2;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.extensions.Extensions;
@@ -179,12 +178,7 @@ public class JavaElementFinder extends PsiElementFinder implements KotlinFinderM
Collection<FqName> subpackages = lightClassGenerationSupport.getSubPackages(packageFQN, scope); Collection<FqName> subpackages = lightClassGenerationSupport.getSubPackages(packageFQN, scope);
Collection<PsiPackage> answer = Collections2.transform(subpackages, new Function<FqName, PsiPackage>() { Collection<PsiPackage> answer = Collections2.transform(subpackages, input -> new KtLightPackage(psiManager, input, scope));
@Override
public PsiPackage apply(@Nullable FqName input) {
return new KtLightPackage(psiManager, input, scope);
}
});
return answer.toArray(new PsiPackage[answer.size()]); return answer.toArray(new PsiPackage[answer.size()]);
} }
@@ -219,29 +213,23 @@ public class JavaElementFinder extends PsiElementFinder implements KotlinFinderM
@Override @Override
@Nullable @Nullable
public Condition<PsiFile> getPackageFilesFilter(@NotNull PsiPackage psiPackage, @NotNull GlobalSearchScope scope) { public Condition<PsiFile> getPackageFilesFilter(@NotNull PsiPackage psiPackage, @NotNull GlobalSearchScope scope) {
return new Condition<PsiFile>() { return input -> {
@Override if (!(input instanceof KtFile)) {
public boolean value(PsiFile input) { return true;
if (!(input instanceof KtFile)) {
return true;
}
return psiPackage.getQualifiedName().equals(((KtFile) input).getPackageFqName().asString());
} }
return psiPackage.getQualifiedName().equals(((KtFile) input).getPackageFqName().asString());
}; };
} }
@NotNull @NotNull
public static Comparator<PsiElement> byClasspathComparator(@NotNull GlobalSearchScope searchScope) { public static Comparator<PsiElement> byClasspathComparator(@NotNull GlobalSearchScope searchScope) {
return new Comparator<PsiElement>() { return (o1, o2) -> {
@Override VirtualFile f1 = PsiUtilCore.getVirtualFile(o1);
public int compare(@NotNull PsiElement o1, @NotNull PsiElement o2) { VirtualFile f2 = PsiUtilCore.getVirtualFile(o2);
VirtualFile f1 = PsiUtilCore.getVirtualFile(o1); if (f1 == f2) return 0;
VirtualFile f2 = PsiUtilCore.getVirtualFile(o2); if (f1 == null) return -1;
if (f1 == f2) return 0; if (f2 == null) return 1;
if (f1 == null) return -1; return searchScope.compare(f2, f1);
if (f2 == null) return 1;
return searchScope.compare(f2, f1);
}
}; };
} }
@@ -107,12 +107,8 @@ public class InterceptionInstrumenter {
} }
if (enterData.isEmpty() && normalReturnData.isEmpty() && exceptionData.isEmpty()) { if (enterData.isEmpty() && normalReturnData.isEmpty() && exceptionData.isEmpty()) {
dumpTasks.add(new DumpAction() { dumpTasks.add(out -> out.println("WARNING: No relevant methods found in " + field +
@Override " of type " + interceptorClass.getCanonicalName()));
public void dump(PrintStream out) {
out.println("WARNING: No relevant methods found in " + field + " of type " + interceptorClass.getCanonicalName());
}
});
} }
String nameFromAnnotation = annotation.methodName(); String nameFromAnnotation = annotation.methodName();
@@ -215,24 +211,21 @@ public class InterceptionInstrumenter {
} }
private void addDumpTask(Object interceptor, Method method, MethodInstrumenter instrumenter) { private void addDumpTask(Object interceptor, Method method, MethodInstrumenter instrumenter) {
dumpTasks.add(new DumpAction() { dumpTasks.add(out -> {
@Override out.println("<<< " + instrumenter + ": " + interceptor.getClass().getName() + " says:");
public void dump(PrintStream out) { try {
out.println("<<< " + instrumenter + ": " + interceptor.getClass().getName() + " says:"); if (method.getParameterTypes().length == 0) {
try { method.invoke(interceptor);
if (method.getParameterTypes().length == 0) {
method.invoke(interceptor);
}
else {
method.invoke(interceptor, out);
}
} }
catch (IllegalAccessException | InvocationTargetException e) { else {
throw new IllegalStateException(e); method.invoke(interceptor, out);
} }
out.println(">>>");
out.println();
} }
catch (IllegalAccessException | InvocationTargetException e) {
throw new IllegalStateException(e);
}
out.println(">>>");
out.println();
}); });
} }
@@ -56,16 +56,13 @@ public class Preloader {
Method mainMethod = mainClass.getMethod("main", String[].class); Method mainMethod = mainClass.getMethod("main", String[].class);
Runtime.getRuntime().addShutdownHook( Runtime.getRuntime().addShutdownHook(
new Thread(new Runnable() { new Thread(() -> {
@Override if (options.measure) {
public void run() { System.out.println();
if (options.measure) { System.out.println("=== Preloader's measurements: ");
System.out.println(); System.out.format("Total time: %.3fs\n", (System.nanoTime() - startTime) / 1e9);
System.out.println("=== Preloader's measurements: ");
System.out.format("Total time: %.3fs\n", (System.nanoTime() - startTime) / 1e9);
}
handler.done();
} }
handler.done();
}) })
); );
@@ -17,7 +17,6 @@
package org.jetbrains.kotlin.resolve.scopes; package org.jetbrains.kotlin.resolve.scopes;
import kotlin.Unit; import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.descriptors.PropertyDescriptor; import org.jetbrains.kotlin.descriptors.PropertyDescriptor;
@@ -35,14 +34,11 @@ public final class ScopeUtils {
return new LexicalScopeImpl(parent, propertyDescriptor, false, null, LexicalScopeKind.PROPERTY_HEADER, return new LexicalScopeImpl(parent, propertyDescriptor, false, null, LexicalScopeKind.PROPERTY_HEADER,
// redeclaration on type parameters should be reported early, see: DescriptorResolver.resolvePropertyDescriptor() // redeclaration on type parameters should be reported early, see: DescriptorResolver.resolvePropertyDescriptor()
LocalRedeclarationChecker.DO_NOTHING.INSTANCE, LocalRedeclarationChecker.DO_NOTHING.INSTANCE,
new Function1<LexicalScopeImpl.InitializeHandler, Unit>() { handler -> {
@Override for (TypeParameterDescriptor typeParameterDescriptor : propertyDescriptor.getTypeParameters()) {
public Unit invoke(LexicalScopeImpl.InitializeHandler handler) { handler.addClassifierDescriptor(typeParameterDescriptor);
for (TypeParameterDescriptor typeParameterDescriptor : propertyDescriptor.getTypeParameters()) {
handler.addClassifierDescriptor(typeParameterDescriptor);
}
return Unit.INSTANCE;
} }
return Unit.INSTANCE;
}); });
} }
@@ -18,7 +18,6 @@ package org.jetbrains.kotlin.codegen;
import com.intellij.ide.highlighter.JavaFileType; import com.intellij.ide.highlighter.JavaFileType;
import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtil;
import com.intellij.util.Processor;
import kotlin.io.FilesKt; import kotlin.io.FilesKt;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -82,14 +81,11 @@ public abstract class AbstractBlackBoxCodegenTest extends CodegenTestCase {
protected static List<String> findJavaSourcesInDirectory(@NotNull File directory) { protected static List<String> findJavaSourcesInDirectory(@NotNull File directory) {
List<String> javaFilePaths = new ArrayList<String>(1); List<String> javaFilePaths = new ArrayList<String>(1);
FileUtil.processFilesRecursively(directory, new Processor<File>() { FileUtil.processFilesRecursively(directory, file -> {
@Override if (file.isFile() && FilesKt.getExtension(file).equals(JavaFileType.DEFAULT_EXTENSION)) {
public boolean process(File file) { javaFilePaths.add(file.getPath());
if (file.isFile() && FilesKt.getExtension(file).equals(JavaFileType.DEFAULT_EXTENSION)) {
javaFilePaths.add(file.getPath());
}
return true;
} }
return true;
}); });
return javaFilePaths; return javaFilePaths;
@@ -17,10 +17,8 @@
package org.jetbrains.kotlin.codegen; package org.jetbrains.kotlin.codegen;
import com.google.common.io.Files; import com.google.common.io.Files;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.backend.common.output.OutputFile; import org.jetbrains.kotlin.backend.common.output.OutputFile;
@@ -76,19 +74,9 @@ public abstract class AbstractCheckLocalVariablesTableTest extends TestCaseWithT
String classFileRegex = StringUtil.escapeToRegexp(split[0] + ".class").replace("\\*", ".+"); String classFileRegex = StringUtil.escapeToRegexp(split[0] + ".class").replace("\\*", ".+");
String methodName = split[1]; String methodName = split[1];
OutputFile outputFile = ContainerUtil.find(outputFiles.asList(), new Condition<OutputFile>() { OutputFile outputFile = ContainerUtil.find(outputFiles.asList(), file -> file.getRelativePath().matches(classFileRegex));
@Override
public boolean value(OutputFile outputFile) {
return outputFile.getRelativePath().matches(classFileRegex);
}
});
String pathsString = StringUtil.join(outputFiles.asList(), new Function<OutputFile, String>() { String pathsString = StringUtil.join(outputFiles.asList(), OutputFile::getRelativePath, ", ");
@Override
public String fun(OutputFile file) {
return file.getRelativePath();
}
}, ", ");
assertNotNull("Couldn't find class file for pattern " + classFileRegex + " in: " + pathsString, outputFile); assertNotNull("Couldn't find class file for pattern " + classFileRegex + " in: " + pathsString, outputFile);
ClassReader cr = new ClassReader(outputFile.asByteArray()); ClassReader cr = new ClassReader(outputFile.asByteArray());
@@ -22,7 +22,6 @@ import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.util.text.StringUtil;
import kotlin.Pair; import kotlin.Pair;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.backend.common.output.OutputFile; import org.jetbrains.kotlin.backend.common.output.OutputFile;
import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles; import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles;
@@ -115,12 +114,7 @@ public abstract class AbstractLineNumberTest extends TestCaseWithTmpdir {
} }
private static String getActualLineNumbersAsString(List<String> lines) { private static String getActualLineNumbersAsString(List<String> lines) {
return CollectionsKt.joinToString(lines, " ", "// ", "", -1, "...", new Function1<String, CharSequence>() { return CollectionsKt.joinToString(lines, " ", "// ", "", -1, "...", lineNumber -> lineNumber);
@Override
public CharSequence invoke(String lineNumber) {
return lineNumber;
}
});
} }
@NotNull @NotNull
@@ -18,7 +18,6 @@ package org.jetbrains.kotlin.codegen;
import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtil;
import com.intellij.util.ArrayUtil; import com.intellij.util.ArrayUtil;
import com.intellij.util.Processor;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles; import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles;
@@ -42,21 +41,13 @@ public abstract class AbstractTopLevelMembersInvocationTest extends AbstractByte
File root = new File(filename); File root = new File(filename);
List<String> sourceFiles = new ArrayList<String>(2); List<String> sourceFiles = new ArrayList<String>(2);
FileUtil.processFilesRecursively(root, new Processor<File>() { FileUtil.processFilesRecursively(root, file -> {
@Override if (file.getName().endsWith(".kt")) {
public boolean process(File file) { sourceFiles.add(relativePath(file));
if (file.getName().endsWith(".kt")) {
sourceFiles.add(relativePath(file));
return true;
}
return true; return true;
} }
}, new Processor<File>() { return true;
@Override }, file -> !LIBRARY.equals(file.getName()));
public boolean process(File file) {
return !LIBRARY.equals(file.getName());
}
});
File library = new File(root, LIBRARY); File library = new File(root, LIBRARY);
List<File> classPath = library.exists() ? List<File> classPath = library.exists() ?
@@ -17,7 +17,6 @@
package org.jetbrains.kotlin.codegen; package org.jetbrains.kotlin.codegen;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull; 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;
@@ -127,14 +126,7 @@ public class CodegenTestUtil {
)); ));
options.addAll(additionalOptions); options.addAll(additionalOptions);
List<File> fileList = CollectionsKt.map(fileNames, new Function1<String, File>() { KotlinTestUtils.compileJavaFiles(CollectionsKt.map(fileNames, File::new), options);
@Override
public File invoke(String input) {
return new File(input);
}
});
KotlinTestUtils.compileJavaFiles(fileList, options);
return javaClassesTempDirectory; return javaClassesTempDirectory;
} }
@@ -27,8 +27,6 @@ import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.util.text.StringUtil;
import kotlin.jvm.functions.Function1;
import kotlin.text.MatchResult;
import kotlin.text.Regex; import kotlin.text.Regex;
import org.intellij.lang.annotations.Language; import org.intellij.lang.annotations.Language;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@@ -71,12 +69,9 @@ public abstract class KotlinIntegrationTestBase extends TestCaseWithTmpdir {
@Language("RegExp") @Language("RegExp")
String RELATIVE_PATH_WITH_MIXED_SEPARATOR = Regex.Companion.escape(pathId) + "[-.\\w/\\\\]*"; String RELATIVE_PATH_WITH_MIXED_SEPARATOR = Regex.Companion.escape(pathId) + "[-.\\w/\\\\]*";
return new Regex(RELATIVE_PATH_WITH_MIXED_SEPARATOR).replace(contentWithRelativePaths, new Function1<MatchResult, String>() { return new Regex(RELATIVE_PATH_WITH_MIXED_SEPARATOR).replace(
@Override contentWithRelativePaths, mr -> FileUtil.toSystemIndependentName(mr.getValue())
public String invoke(MatchResult mr) { );
return FileUtil.toSystemIndependentName(mr.getValue());
}
});
} }
@NotNull @NotNull
@@ -18,9 +18,7 @@ package org.jetbrains.kotlin.jvm.compiler;
import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtil;
import com.intellij.psi.search.GlobalSearchScope;
import junit.framework.ComparisonFailure; import junit.framework.ComparisonFailure;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.analyzer.AnalysisResult; import org.jetbrains.kotlin.analyzer.AnalysisResult;
import org.jetbrains.kotlin.cli.jvm.compiler.CliLightClassGenerationSupport; import org.jetbrains.kotlin.cli.jvm.compiler.CliLightClassGenerationSupport;
@@ -31,7 +29,10 @@ import org.jetbrains.kotlin.cli.jvm.config.JvmContentRootsKt;
import org.jetbrains.kotlin.config.CompilerConfiguration; import org.jetbrains.kotlin.config.CompilerConfiguration;
import org.jetbrains.kotlin.config.ContentRootsKt; import org.jetbrains.kotlin.config.ContentRootsKt;
import org.jetbrains.kotlin.config.JVMConfigurationKeys; import org.jetbrains.kotlin.config.JVMConfigurationKeys;
import org.jetbrains.kotlin.descriptors.*; import org.jetbrains.kotlin.descriptors.ClassDescriptor;
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor;
import org.jetbrains.kotlin.descriptors.ModuleDescriptor;
import org.jetbrains.kotlin.descriptors.PackageViewDescriptor;
import org.jetbrains.kotlin.psi.KtFile; import org.jetbrains.kotlin.psi.KtFile;
import org.jetbrains.kotlin.resolve.BindingContext; import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.DescriptorUtils; import org.jetbrains.kotlin.resolve.DescriptorUtils;
@@ -46,7 +47,6 @@ import org.jetbrains.kotlin.test.util.DescriptorValidator;
import org.junit.Assert; import org.junit.Assert;
import java.io.File; import java.io.File;
import java.io.FileFilter;
import java.io.IOException; import java.io.IOException;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
@@ -142,12 +142,7 @@ public abstract class AbstractLoadJavaTest extends TestCaseWithTmpdir {
File expectedFile = new File(expectedFileName); File expectedFile = new File(expectedFileName);
File sourcesDir = new File(expectedFileName.replaceFirst("\\.txt$", "")); File sourcesDir = new File(expectedFileName.replaceFirst("\\.txt$", ""));
FileUtil.copyDir(sourcesDir, new File(tmpdir, "test"), new FileFilter() { FileUtil.copyDir(sourcesDir, new File(tmpdir, "test"), pathname -> pathname.getName().endsWith(".java"));
@Override
public boolean accept(@NotNull File pathname) {
return pathname.getName().endsWith(".java");
}
});
CompilerConfiguration configuration = KotlinTestUtils.newConfiguration(ConfigurationKind.JDK_ONLY, getJdkKind()); CompilerConfiguration configuration = KotlinTestUtils.newConfiguration(ConfigurationKind.JDK_ONLY, getJdkKind());
ContentRootsKt.addKotlinSourceRoot(configuration, sourcesDir.getAbsolutePath()); ContentRootsKt.addKotlinSourceRoot(configuration, sourcesDir.getAbsolutePath());
@@ -159,12 +154,7 @@ public abstract class AbstractLoadJavaTest extends TestCaseWithTmpdir {
AnalysisResult result = TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration( AnalysisResult result = TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(
environment.getProject(), environment.getSourceFiles(), new CliLightClassGenerationSupport.NoScopeRecordCliBindingTrace(), environment.getProject(), environment.getSourceFiles(), new CliLightClassGenerationSupport.NoScopeRecordCliBindingTrace(),
configuration, new Function1<GlobalSearchScope, PackagePartProvider>() { configuration, scope -> new JvmPackagePartProvider(environment, scope)
@Override
public PackagePartProvider invoke(GlobalSearchScope scope) {
return new JvmPackagePartProvider(environment, scope);
}
}
); );
PackageViewDescriptor packageView = result.getModuleDescriptor().getPackage(TEST_PACKAGE_FQNAME); PackageViewDescriptor packageView = result.getModuleDescriptor().getPackage(TEST_PACKAGE_FQNAME);
@@ -20,7 +20,6 @@ import com.intellij.openapi.Disposable;
import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtil;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.analyzer.AnalysisResult; import org.jetbrains.kotlin.analyzer.AnalysisResult;
import org.jetbrains.kotlin.cli.common.output.outputUtils.OutputUtilsKt; import org.jetbrains.kotlin.cli.common.output.outputUtils.OutputUtilsKt;
@@ -107,15 +106,12 @@ public class LoadDescriptorUtil {
@NotNull @NotNull
private static List<KtFile> createKtFiles(@NotNull List<File> kotlinFiles, @NotNull KotlinCoreEnvironment environment) { private static List<KtFile> createKtFiles(@NotNull List<File> kotlinFiles, @NotNull KotlinCoreEnvironment environment) {
return CollectionsKt.map(kotlinFiles, new Function1<File, KtFile>() { return CollectionsKt.map(kotlinFiles, kotlinFile -> {
@Override try {
public KtFile invoke(File kotlinFile) { return KotlinTestUtils.createFile(kotlinFile.getName(), FileUtil.loadFile(kotlinFile, true), environment.getProject());
try { }
return KotlinTestUtils.createFile(kotlinFile.getName(), FileUtil.loadFile(kotlinFile, true), environment.getProject()); catch (IOException e) {
} throw ExceptionUtilsKt.rethrow(e);
catch (IOException e) {
throw ExceptionUtilsKt.rethrow(e);
}
} }
}); });
} }
@@ -17,9 +17,7 @@
package org.jetbrains.kotlin.resolve.annotation; package org.jetbrains.kotlin.resolve.annotation;
import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.Function;
import kotlin.Unit; import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull; 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;
@@ -27,17 +25,18 @@ import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment;
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.descriptors.annotations.AnnotationUseSiteTarget; import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget;
import org.jetbrains.kotlin.descriptors.annotations.AnnotationWithTarget;
import org.jetbrains.kotlin.descriptors.annotations.Annotations; import org.jetbrains.kotlin.descriptors.annotations.Annotations;
import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor; import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor;
import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl; import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl;
import org.jetbrains.kotlin.incremental.components.NoLookupLocation; import org.jetbrains.kotlin.incremental.components.NoLookupLocation;
import org.jetbrains.kotlin.name.FqName; import org.jetbrains.kotlin.name.FqName;
import org.jetbrains.kotlin.name.Name; import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.psi.KtAnnotationEntry;
import org.jetbrains.kotlin.psi.KtAnnotationUseSiteTarget; import org.jetbrains.kotlin.psi.KtAnnotationUseSiteTarget;
import org.jetbrains.kotlin.psi.KtFile; import org.jetbrains.kotlin.psi.KtFile;
import org.jetbrains.kotlin.renderer.*; import org.jetbrains.kotlin.renderer.AnnotationArgumentsRenderingPolicy;
import org.jetbrains.kotlin.renderer.ClassifierNamePolicy;
import org.jetbrains.kotlin.renderer.DescriptorRenderer;
import org.jetbrains.kotlin.renderer.DescriptorRendererModifier;
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.scopes.MemberScope; import org.jetbrains.kotlin.resolve.scopes.MemberScope;
@@ -55,15 +54,12 @@ import static org.jetbrains.kotlin.resolve.DescriptorUtils.isNonCompanionObject;
public abstract class AbstractAnnotationDescriptorResolveTest extends KotlinTestWithEnvironment { public abstract class AbstractAnnotationDescriptorResolveTest extends KotlinTestWithEnvironment {
private static final DescriptorRenderer WITH_ANNOTATION_ARGUMENT_TYPES = DescriptorRenderer.Companion.withOptions( private static final DescriptorRenderer WITH_ANNOTATION_ARGUMENT_TYPES = DescriptorRenderer.Companion.withOptions(
new Function1<DescriptorRendererOptions, Unit>() { options -> {
@Override options.setVerbose(true);
public Unit invoke(DescriptorRendererOptions options) { options.setAnnotationArgumentsRenderingPolicy(AnnotationArgumentsRenderingPolicy.UNLESS_EMPTY);
options.setVerbose(true); options.setClassifierNamePolicy(ClassifierNamePolicy.SHORT.INSTANCE);
options.setAnnotationArgumentsRenderingPolicy(AnnotationArgumentsRenderingPolicy.UNLESS_EMPTY); options.setModifiers(DescriptorRendererModifier.ALL);
options.setClassifierNamePolicy(ClassifierNamePolicy.SHORT.INSTANCE); return Unit.INSTANCE;
options.setModifiers(DescriptorRendererModifier.ALL);
return Unit.INSTANCE;
}
} }
); );
@@ -126,21 +122,18 @@ public abstract class AbstractAnnotationDescriptorResolveTest extends KotlinTest
} }
private void checkAnnotationsOnFile(String expectedAnnotation, KtFile file) { private void checkAnnotationsOnFile(String expectedAnnotation, KtFile file) {
String actualAnnotation = StringUtil.join(file.getAnnotationEntries(), new Function<KtAnnotationEntry, String>() { String actualAnnotation = StringUtil.join(file.getAnnotationEntries(), annotationEntry -> {
@Override AnnotationDescriptor annotationDescriptor = context.get(BindingContext.ANNOTATION, annotationEntry);
public String fun(KtAnnotationEntry annotationEntry) { assertNotNull(annotationDescriptor);
AnnotationDescriptor annotationDescriptor = context.get(BindingContext.ANNOTATION, annotationEntry);
assertNotNull(annotationDescriptor);
KtAnnotationUseSiteTarget target = annotationEntry.getUseSiteTarget(); KtAnnotationUseSiteTarget target = annotationEntry.getUseSiteTarget();
if (target != null) { if (target != null) {
return WITH_ANNOTATION_ARGUMENT_TYPES.renderAnnotation( return WITH_ANNOTATION_ARGUMENT_TYPES.renderAnnotation(
annotationDescriptor, target.getAnnotationUseSiteTarget()); annotationDescriptor, target.getAnnotationUseSiteTarget());
}
return WITH_ANNOTATION_ARGUMENT_TYPES.renderAnnotation(annotationDescriptor, null);
} }
return WITH_ANNOTATION_ARGUMENT_TYPES.renderAnnotation(annotationDescriptor, null);
}, " "); }, " ");
String expectedAnnotationWithTarget = "@" + AnnotationUseSiteTarget.FILE.getRenderName() + ":" + expectedAnnotation.substring(1); String expectedAnnotationWithTarget = "@" + AnnotationUseSiteTarget.FILE.getRenderName() + ":" + expectedAnnotation.substring(1);
@@ -366,16 +359,13 @@ public abstract class AbstractAnnotationDescriptorResolveTest extends KotlinTest
} }
private static String renderAnnotations(Annotations annotations, @Nullable AnnotationUseSiteTarget defaultTarget) { private static String renderAnnotations(Annotations annotations, @Nullable AnnotationUseSiteTarget defaultTarget) {
return StringUtil.join(annotations.getAllAnnotations(), new Function<AnnotationWithTarget, String>() { return StringUtil.join(annotations.getAllAnnotations(), annotationWithTarget -> {
@Override AnnotationUseSiteTarget targetToRender = annotationWithTarget.getTarget();
public String fun(AnnotationWithTarget annotationWithTarget) { if (targetToRender == defaultTarget) {
AnnotationUseSiteTarget targetToRender = annotationWithTarget.getTarget(); targetToRender = null;
if (targetToRender == defaultTarget) {
targetToRender = null;
}
return WITH_ANNOTATION_ARGUMENT_TYPES.renderAnnotation(annotationWithTarget.getAnnotation(), targetToRender);
} }
return WITH_ANNOTATION_ARGUMENT_TYPES.renderAnnotation(annotationWithTarget.getAnnotation(), targetToRender);
}, " "); }, " ");
} }
@@ -36,8 +36,6 @@ import com.intellij.psi.impl.PsiFileFactoryImpl;
import com.intellij.rt.execution.junit.FileComparisonFailure; import com.intellij.rt.execution.junit.FileComparisonFailure;
import com.intellij.testFramework.LightVirtualFile; import com.intellij.testFramework.LightVirtualFile;
import com.intellij.testFramework.TestDataFile; import com.intellij.testFramework.TestDataFile;
import com.intellij.util.Function;
import com.intellij.util.Processor;
import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.ContainerUtil;
import junit.framework.TestCase; import junit.framework.TestCase;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
@@ -384,19 +382,11 @@ public class KotlinTestUtils {
public static void deleteOnShutdown(File file) { public static void deleteOnShutdown(File file) {
if (filesToDelete.isEmpty()) { if (filesToDelete.isEmpty()) {
ShutDownTracker.getInstance().registerShutdownTask(new Runnable() { ShutDownTracker.getInstance().registerShutdownTask(() -> ShutDownTracker.invokeAndWait(true, true, () -> {
@Override for (File victim : filesToDelete) {
public void run() { FileUtil.delete(victim);
ShutDownTracker.invokeAndWait(true, true, new Runnable() {
@Override
public void run() {
for (File victim : filesToDelete) {
FileUtil.delete(victim);
}
}
});
} }
}); }));
} }
filesToDelete.add(file); filesToDelete.add(file);
@@ -525,12 +515,7 @@ public class KotlinTestUtils {
} }
public static void assertEqualsToFile(@NotNull File expectedFile, @NotNull String actual) { public static void assertEqualsToFile(@NotNull File expectedFile, @NotNull String actual) {
assertEqualsToFile(expectedFile, actual, new Function1<String, String>() { assertEqualsToFile(expectedFile, actual, s -> s);
@Override
public String invoke(String s) {
return s;
}
});
} }
public static void assertEqualsToFile(@NotNull File expectedFile, @NotNull String actual, @NotNull Function1<String, String> sanitizer) { public static void assertEqualsToFile(@NotNull File expectedFile, @NotNull String actual, @NotNull Function1<String, String> sanitizer) {
@@ -916,15 +901,12 @@ public class KotlinTestUtils {
Set<String> filePaths = collectPathsMetadata(testCaseClass); Set<String> filePaths = collectPathsMetadata(testCaseClass);
FileUtil.processFilesRecursively(testDataDir, new Processor<File>() { FileUtil.processFilesRecursively(testDataDir, file -> {
@Override if (file.isFile() && filenamePattern.matcher(file.getName()).matches() && isCompatibleTarget(targetBackend, file)) {
public boolean process(File file) { assertFilePathPresent(file, rootFile, filePaths);
if (file.isFile() && filenamePattern.matcher(file.getName()).matches() && isCompatibleTarget(targetBackend, file)) {
assertFilePathPresent(file, rootFile, filePaths);
}
return true;
} }
return true;
}); });
} }
@@ -939,13 +921,7 @@ public class KotlinTestUtils {
} }
private static Set<String> collectPathsMetadata(Class<?> testCaseClass) { private static Set<String> collectPathsMetadata(Class<?> testCaseClass) {
return ContainerUtil.newHashSet( return ContainerUtil.newHashSet(ContainerUtil.map(collectMethodsMetadata(testCaseClass), KotlinTestUtils::nameToCompare));
ContainerUtil.map(collectMethodsMetadata(testCaseClass), new Function<String, String>() {
@Override
public String fun(String pathData) {
return nameToCompare(pathData);
}
}));
} }
@Nullable @Nullable
@@ -24,8 +24,6 @@ import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.extensions.ExtensionsArea; import com.intellij.openapi.extensions.ExtensionsArea;
import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.fileTypes.FileTypeRegistry;
import com.intellij.openapi.util.Getter;
import com.intellij.openapi.vfs.encoding.EncodingManager; import com.intellij.openapi.vfs.encoding.EncodingManager;
import org.picocontainer.MutablePicoContainer; import org.picocontainer.MutablePicoContainer;
@@ -46,14 +44,7 @@ public abstract class KtPlatformLiteFixture extends KtUsefulTestCase {
public void initApplication() { public void initApplication() {
MockApplicationEx instance = new MockApplicationEx(getTestRootDisposable()); MockApplicationEx instance = new MockApplicationEx(getTestRootDisposable());
ApplicationManager.setApplication(instance, ApplicationManager.setApplication(instance, FileTypeManager::getInstance, getTestRootDisposable());
new Getter<FileTypeRegistry>() {
@Override
public FileTypeRegistry get() {
return FileTypeManager.getInstance();
}
},
getTestRootDisposable());
getApplication().registerService(EncodingManager.class, CoreEncodingProjectManager.class); getApplication().registerService(EncodingManager.class, CoreEncodingProjectManager.class);
} }
@@ -27,7 +27,6 @@ import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.rt.execution.junit.FileComparisonFailure; import com.intellij.rt.execution.junit.FileComparisonFailure;
import com.intellij.util.Function;
import com.intellij.util.ReflectionUtil; import com.intellij.util.ReflectionUtil;
import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.hash.HashMap; import com.intellij.util.containers.hash.HashMap;
@@ -210,23 +209,20 @@ public abstract class KtUsefulTestCase extends TestCase {
protected void runTest() throws Throwable { protected void runTest() throws Throwable {
Throwable[] throwables = new Throwable[1]; Throwable[] throwables = new Throwable[1];
Runnable runnable = new Runnable() { Runnable runnable = () -> {
@Override try {
public void run() { super.runTest();
try { }
KtUsefulTestCase.super.runTest(); catch (InvocationTargetException e) {
} e.fillInStackTrace();
catch (InvocationTargetException e) { throwables[0] = e.getTargetException();
e.fillInStackTrace(); }
throwables[0] = e.getTargetException(); catch (IllegalAccessException e) {
} e.fillInStackTrace();
catch (IllegalAccessException e) { throwables[0] = e;
e.fillInStackTrace(); }
throwables[0] = e; catch (Throwable e) {
} throwables[0] = e;
catch (Throwable e) {
throwables[0] = e;
}
} }
}; };
@@ -352,12 +348,7 @@ public abstract class KtUsefulTestCase extends TestCase {
} }
public static String toString(Collection<?> collection, String separator) { public static String toString(Collection<?> collection, String separator) {
List<String> list = ContainerUtil.map2List(collection, new Function<Object, String>() { List<String> list = ContainerUtil.map2List(collection, String::valueOf);
@Override
public String fun(Object o) {
return String.valueOf(o);
}
});
Collections.sort(list); Collections.sort(list);
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
boolean flag = false; boolean flag = false;
@@ -19,7 +19,6 @@ package org.jetbrains.kotlin.test.util;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import kotlin.Unit; import kotlin.Unit;
import kotlin.jvm.functions.Function1;
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.builtins.KotlinBuiltIns;
@@ -50,19 +49,16 @@ import static org.jetbrains.kotlin.test.util.DescriptorValidator.ValidationVisit
public class RecursiveDescriptorComparator { public class RecursiveDescriptorComparator {
private static final DescriptorRenderer DEFAULT_RENDERER = DescriptorRenderer.Companion.withOptions( private static final DescriptorRenderer DEFAULT_RENDERER = DescriptorRenderer.Companion.withOptions(
new Function1<DescriptorRendererOptions, Unit>() { options -> {
@Override options.setWithDefinedIn(false);
public Unit invoke(DescriptorRendererOptions options) { options.setExcludedAnnotationClasses(Collections.singleton(new FqName(ExpectedLoadErrorsUtil.ANNOTATION_CLASS_NAME)));
options.setWithDefinedIn(false); options.setOverrideRenderingPolicy(OverrideRenderingPolicy.RENDER_OPEN_OVERRIDE);
options.setExcludedAnnotationClasses(Collections.singleton(new FqName(ExpectedLoadErrorsUtil.ANNOTATION_CLASS_NAME))); options.setIncludePropertyConstant(true);
options.setOverrideRenderingPolicy(OverrideRenderingPolicy.RENDER_OPEN_OVERRIDE); options.setClassifierNamePolicy(ClassifierNamePolicy.FULLY_QUALIFIED.INSTANCE);
options.setIncludePropertyConstant(true); options.setVerbose(true);
options.setClassifierNamePolicy(ClassifierNamePolicy.FULLY_QUALIFIED.INSTANCE); options.setAnnotationArgumentsRenderingPolicy(AnnotationArgumentsRenderingPolicy.UNLESS_EMPTY);
options.setVerbose(true); options.setModifiers(DescriptorRendererModifier.ALL);
options.setAnnotationArgumentsRenderingPolicy(AnnotationArgumentsRenderingPolicy.UNLESS_EMPTY); return Unit.INSTANCE;
options.setModifiers(DescriptorRendererModifier.ALL);
return Unit.INSTANCE;
}
} }
); );
@@ -16,9 +16,7 @@
package org.jetbrains.kotlin.asJava; package org.jetbrains.kotlin.asJava;
import com.intellij.psi.PsiClass;
import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.GlobalSearchScope;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.asJava.finder.JavaElementFinder; import org.jetbrains.kotlin.asJava.finder.JavaElementFinder;
import org.jetbrains.kotlin.checkers.KotlinMultiFileTestWithJava; import org.jetbrains.kotlin.checkers.KotlinMultiFileTestWithJava;
@@ -54,22 +52,14 @@ public abstract class AbstractCompilerLightClassTest extends KotlinMultiFileTest
@Override @Override
protected void doMultiFileTest(File file, Map<String, ModuleAndDependencies> modules, List<Void> files) throws IOException { protected void doMultiFileTest(File file, Map<String, ModuleAndDependencies> modules, List<Void> files) throws IOException {
LightClassTestCommon.INSTANCE.testLightClass(file, new Function1<String, PsiClass>() { LightClassTestCommon.INSTANCE.testLightClass(file, s -> {
@Override try {
public PsiClass invoke(String s) { return createFinder(getEnvironment()).findClass(s, GlobalSearchScope.allScope(getEnvironment().getProject()));
try {
return createFinder(getEnvironment()).findClass(s, GlobalSearchScope.allScope(getEnvironment().getProject()));
}
catch (IOException e) {
throw ExceptionUtilsKt.rethrow(e);
}
} }
}, new Function1<String, String>() { catch (IOException e) {
@Override throw ExceptionUtilsKt.rethrow(e);
public String invoke(String s) {
return LightClassTestCommon.INSTANCE.removeEmptyDefaultImpls(s);
} }
}); }, LightClassTestCommon.INSTANCE::removeEmptyDefaultImpls);
} }
@Override @Override
@@ -16,11 +16,10 @@
package org.jetbrains.kotlin.asJava; package org.jetbrains.kotlin.asJava;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.intellij.psi.*; import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.GlobalSearchScope;
import kotlin.collections.ArraysKt;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.cli.jvm.config.JvmContentRootsKt; import org.jetbrains.kotlin.cli.jvm.config.JvmContentRootsKt;
@@ -29,7 +28,6 @@ import org.jetbrains.kotlin.config.CompilerConfiguration;
import org.jetbrains.kotlin.name.SpecialNames; import org.jetbrains.kotlin.name.SpecialNames;
import java.io.File; import java.io.File;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@@ -237,15 +235,7 @@ public abstract class KotlinLightClassStructureTest extends KotlinAsJavaTestBase
assertEquals(name, typeParameter.getName()); assertEquals(name, typeParameter.getName());
assertEquals(index, typeParameter.getIndex()); assertEquals(index, typeParameter.getIndex());
Set<String> expectedBounds = Sets.newHashSet(bounds); Set<String> expectedBounds = Sets.newHashSet(bounds);
Set<String> actualBounds = Sets.newHashSet(Collections2.transform( Set<String> actualBounds = Sets.newHashSet(ArraysKt.map(typeParameter.getExtendsListTypes(), PsiType::getCanonicalText));
Arrays.asList(typeParameter.getExtendsListTypes()),
new Function<PsiClassType, String>() {
@Override
public String apply(PsiClassType input) {
return input.getCanonicalText();
}
}
));
assertEquals(expectedBounds, actualBounds); assertEquals(expectedBounds, actualBounds);
} }
@@ -16,7 +16,6 @@
package org.jetbrains.kotlin.cfg; package org.jetbrains.kotlin.cfg;
import kotlin.jvm.functions.Function3;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.cfg.pseudocode.PseudocodeImpl; import org.jetbrains.kotlin.cfg.pseudocode.PseudocodeImpl;
@@ -36,22 +35,19 @@ public abstract class AbstractControlFlowTest extends AbstractPseudocodeTest {
) { ) {
int nextInstructionsColumnWidth = countNextInstructionsColumnWidth(pseudocode.getInstructionsIncludingDeadCode()); int nextInstructionsColumnWidth = countNextInstructionsColumnWidth(pseudocode.getInstructionsIncludingDeadCode());
dumpInstructions(pseudocode, out, new Function3<Instruction, Instruction, Instruction, String>() { dumpInstructions(pseudocode, out, (instruction, next, prev) -> {
@Override StringBuilder result = new StringBuilder();
public String invoke(Instruction instruction, Instruction next, Instruction prev) { Collection<Instruction> nextInstructions = instruction.getNextInstructions();
StringBuilder result = new StringBuilder();
Collection<Instruction> nextInstructions = instruction.getNextInstructions();
if (!sameContents(next, nextInstructions)) { if (!sameContents(next, nextInstructions)) {
result.append(" NEXT:").append( result.append(" NEXT:").append(
String.format("%1$-" + nextInstructionsColumnWidth + "s", formatInstructionList(nextInstructions))); String.format("%1$-" + nextInstructionsColumnWidth + "s", formatInstructionList(nextInstructions)));
}
Collection<Instruction> previousInstructions = instruction.getPreviousInstructions();
if (!sameContents(prev, previousInstructions)) {
result.append(" PREV:").append(formatInstructionList(previousInstructions));
}
return result.toString();
} }
Collection<Instruction> previousInstructions = instruction.getPreviousInstructions();
if (!sameContents(prev, previousInstructions)) {
result.append(" PREV:").append(formatInstructionList(previousInstructions));
}
return result.toString();
}); });
} }
@@ -18,7 +18,6 @@ package org.jetbrains.kotlin.cfg;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.util.text.StringUtil;
import kotlin.jvm.functions.Function3;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.cfg.pseudocode.PseudocodeImpl; import org.jetbrains.kotlin.cfg.pseudocode.PseudocodeImpl;
import org.jetbrains.kotlin.cfg.pseudocode.instructions.Instruction; import org.jetbrains.kotlin.cfg.pseudocode.instructions.Instruction;
@@ -47,25 +46,22 @@ public abstract class AbstractDataFlowTest extends AbstractPseudocodeTest {
String usePrefix = " USE:"; String usePrefix = " USE:";
int initializersColumnWidth = countDataColumnWidth(initPrefix, pseudocode.getInstructionsIncludingDeadCode(), variableInitializers); int initializersColumnWidth = countDataColumnWidth(initPrefix, pseudocode.getInstructionsIncludingDeadCode(), variableInitializers);
dumpInstructions(pseudocode, out, new Function3<Instruction, Instruction, Instruction, String>() { dumpInstructions(pseudocode, out, (instruction, next, prev) -> {
@Override StringBuilder result = new StringBuilder();
public String invoke(Instruction instruction, Instruction next, Instruction prev) { Edges<InitControlFlowInfo> initializersEdges = variableInitializers.get(instruction);
StringBuilder result = new StringBuilder(); Edges<InitControlFlowInfo> previousInitializersEdges = variableInitializers.get(prev);
Edges<InitControlFlowInfo> initializersEdges = variableInitializers.get(instruction); String initializersData = "";
Edges<InitControlFlowInfo> previousInitializersEdges = variableInitializers.get(prev); if (initializersEdges != null && !initializersEdges.equals(previousInitializersEdges)) {
String initializersData = ""; initializersData = dumpEdgesData(initPrefix, initializersEdges);
if (initializersEdges != null && !initializersEdges.equals(previousInitializersEdges)) {
initializersData = dumpEdgesData(initPrefix, initializersEdges);
}
result.append(String.format("%1$-" + initializersColumnWidth + "s", initializersData));
Edges<UseControlFlowInfo> useStatusEdges = useStatusData.get(instruction);
Edges<UseControlFlowInfo> nextUseStatusEdges = useStatusData.get(next);
if (useStatusEdges != null && !useStatusEdges.equals(nextUseStatusEdges)) {
result.append(dumpEdgesData(usePrefix, useStatusEdges));
}
return result.toString();
} }
result.append(String.format("%1$-" + initializersColumnWidth + "s", initializersData));
Edges<UseControlFlowInfo> useStatusEdges = useStatusData.get(instruction);
Edges<UseControlFlowInfo> nextUseStatusEdges = useStatusData.get(next);
if (useStatusEdges != null && !useStatusEdges.equals(nextUseStatusEdges)) {
result.append(dumpEdgesData(usePrefix, useStatusEdges));
}
return result.toString();
}); });
} }
@@ -22,7 +22,6 @@ import com.intellij.util.ArrayUtil;
import kotlin.Pair; import kotlin.Pair;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import kotlin.io.FilesKt; import kotlin.io.FilesKt;
import kotlin.jvm.functions.Function1;
import kotlin.text.Charsets; import kotlin.text.Charsets;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.cli.common.CLICompiler; import org.jetbrains.kotlin.cli.common.CLICompiler;
@@ -130,23 +129,20 @@ public abstract class AbstractCliTest extends TestCaseWithTmpdir {
static List<String> readArgs(@NotNull String argsFilePath, @NotNull String tempDir) throws IOException { static List<String> readArgs(@NotNull String argsFilePath, @NotNull String tempDir) throws IOException {
List<String> lines = FilesKt.readLines(new File(argsFilePath), Charsets.UTF_8); List<String> lines = FilesKt.readLines(new File(argsFilePath), Charsets.UTF_8);
return CollectionsKt.mapNotNull(lines, new Function1<String, String>() { return CollectionsKt.mapNotNull(lines, arg -> {
@Override if (arg.isEmpty()) {
public String invoke(String arg) { return null;
if (arg.isEmpty()) {
return null;
}
// Do not replace ':' after '\' (used in compiler plugin tests)
String argsWithColonsReplaced = arg
.replace("\\:", "$COLON$")
.replace(":", File.pathSeparator)
.replace("$COLON$", ":");
return argsWithColonsReplaced
.replace("$TEMP_DIR$", tempDir)
.replace("$TESTDATA_DIR$", new File(argsFilePath).getParent());
} }
// Do not replace ':' after '\' (used in compiler plugin tests)
String argsWithColonsReplaced = arg
.replace("\\:", "$COLON$")
.replace(":", File.pathSeparator)
.replace("$COLON$", ":");
return argsWithColonsReplaced
.replace("$TEMP_DIR$", tempDir)
.replace("$TESTDATA_DIR$", new File(argsFilePath).getParent());
}); });
} }
@@ -17,7 +17,6 @@
package org.jetbrains.kotlin.codegen; package org.jetbrains.kotlin.codegen;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1;
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.output.OutputFile; import org.jetbrains.kotlin.backend.common.output.OutputFile;
@@ -121,14 +120,7 @@ public class InnerClassInfoGenTest extends CodegenTestCase {
private void checkAccess(@NotNull String outerName, @NotNull String innerName, int accessFlags) { private void checkAccess(@NotNull String outerName, @NotNull String innerName, int accessFlags) {
String name = outerName + "$" + innerName; String name = outerName + "$" + innerName;
InnerClassAttribute attribute = CollectionsKt.single(extractInnerClasses(name), InnerClassAttribute attribute = CollectionsKt.single(extractInnerClasses(name), value -> innerName.equals(value.innerName));
new Function1<InnerClassAttribute, Boolean>() {
@Override
public Boolean invoke(InnerClassAttribute attribute) {
return innerName.equals(attribute.innerName);
}
}
);
InnerClassAttribute expectedAttribute = new InnerClassAttribute(name, outerName, innerName, accessFlags); InnerClassAttribute expectedAttribute = new InnerClassAttribute(name, outerName, innerName, accessFlags);
@@ -17,13 +17,15 @@
package org.jetbrains.kotlin.jvm.compiler; package org.jetbrains.kotlin.jvm.compiler;
import kotlin.Unit; import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import org.jetbrains.kotlin.analyzer.AnalysisResult; import org.jetbrains.kotlin.analyzer.AnalysisResult;
import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles; import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles;
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment; import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment;
import org.jetbrains.kotlin.descriptors.PackageViewDescriptor; import org.jetbrains.kotlin.descriptors.PackageViewDescriptor;
import org.jetbrains.kotlin.name.FqName; import org.jetbrains.kotlin.name.FqName;
import org.jetbrains.kotlin.renderer.*; import org.jetbrains.kotlin.renderer.AnnotationArgumentsRenderingPolicy;
import org.jetbrains.kotlin.renderer.DescriptorRenderer;
import org.jetbrains.kotlin.renderer.DescriptorRendererModifier;
import org.jetbrains.kotlin.renderer.ParameterNameRenderingPolicy;
import org.jetbrains.kotlin.resolve.lazy.JvmResolveUtil; import org.jetbrains.kotlin.resolve.lazy.JvmResolveUtil;
import org.jetbrains.kotlin.test.ConfigurationKind; import org.jetbrains.kotlin.test.ConfigurationKind;
import org.jetbrains.kotlin.test.TestCaseWithTmpdir; import org.jetbrains.kotlin.test.TestCaseWithTmpdir;
@@ -46,17 +48,14 @@ public abstract class AbstractCompileJavaAgainstKotlinTest extends TestCaseWithT
private static final RecursiveDescriptorComparator.Configuration CONFIGURATION = private static final RecursiveDescriptorComparator.Configuration CONFIGURATION =
AbstractLoadJavaTest.COMPARATOR_CONFIGURATION.withRenderer( AbstractLoadJavaTest.COMPARATOR_CONFIGURATION.withRenderer(
DescriptorRenderer.Companion.withOptions( DescriptorRenderer.Companion.withOptions(
new Function1<DescriptorRendererOptions, Unit>() { options -> {
@Override options.setWithDefinedIn(false);
public Unit invoke(DescriptorRendererOptions options) { options.setParameterNameRenderingPolicy(ParameterNameRenderingPolicy.NONE);
options.setWithDefinedIn(false); options.setVerbose(true);
options.setParameterNameRenderingPolicy(ParameterNameRenderingPolicy.NONE); options.setAnnotationArgumentsRenderingPolicy(AnnotationArgumentsRenderingPolicy.UNLESS_EMPTY);
options.setVerbose(true); options.setExcludedAnnotationClasses(Collections.singleton(new FqName(Retention.class.getName())));
options.setAnnotationArgumentsRenderingPolicy(AnnotationArgumentsRenderingPolicy.UNLESS_EMPTY); options.setModifiers(DescriptorRendererModifier.ALL);
options.setExcludedAnnotationClasses(Collections.singleton(new FqName(Retention.class.getName()))); return Unit.INSTANCE;
options.setModifiers(DescriptorRendererModifier.ALL);
return Unit.INSTANCE;
}
} }
) )
); );
@@ -20,7 +20,6 @@ import com.google.common.collect.Iterables;
import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtil;
import com.intellij.util.ArrayUtil; import com.intellij.util.ArrayUtil;
import com.intellij.util.Processor;
import kotlin.Pair; import kotlin.Pair;
import kotlin.collections.SetsKt; import kotlin.collections.SetsKt;
import kotlin.io.FilesKt; import kotlin.io.FilesKt;
@@ -152,12 +151,7 @@ public class CompileKotlinAgainstCustomBinariesTest extends TestCaseWithTmpdir {
@NotNull @NotNull
private static File copyJarFileWithoutEntry(@NotNull File jarPath, @NotNull String... entriesToDelete) { private static File copyJarFileWithoutEntry(@NotNull File jarPath, @NotNull String... entriesToDelete) {
return transformJar(jarPath, new Function2<String, byte[], byte[]>() { return transformJar(jarPath, (s, bytes) -> bytes, entriesToDelete);
@Override
public byte[] invoke(String s, byte[] bytes) {
return bytes;
}
}, entriesToDelete);
} }
@NotNull @NotNull
@@ -292,21 +286,16 @@ public class CompileKotlinAgainstCustomBinariesTest extends TestCaseWithTmpdir {
@NotNull String... additionalOptions @NotNull String... additionalOptions
) throws Exception { ) throws Exception {
int[] version = new JvmMetadataVersion(42, 0, 0).toArray(); int[] version = new JvmMetadataVersion(42, 0, 0).toArray();
File library = transformJar(compileLibrary(libraryName), new Function2<String, byte[], byte[]>() { File library = transformJar(
@Override compileLibrary(libraryName),
public byte[] invoke(String name, byte[] bytes) { (entryName, bytes) -> WrongBytecodeVersionTest.Companion.transformMetadataInClassFile(bytes, (fieldName, value) -> {
return WrongBytecodeVersionTest.Companion.transformMetadataInClassFile(bytes, new Function2<String, Object, Object>() { if (additionalTransformation != null) {
@Override Object result = additionalTransformation.invoke(fieldName, value);
public Object invoke(String name, Object value) { if (result != null) return result;
if (additionalTransformation != null) {
Object result = additionalTransformation.invoke(name, value);
if (result != null) return result;
}
return JvmAnnotationNames.METADATA_VERSION_FIELD_NAME.equals(name) ? version : null;
} }
}); return JvmAnnotationNames.METADATA_VERSION_FIELD_NAME.equals(fieldName) ? version : null;
} })
}); );
Pair<String, ExitCode> output = compileKotlin("source.kt", tmpdir, Arrays.asList(additionalOptions), library); Pair<String, ExitCode> output = compileKotlin("source.kt", tmpdir, Arrays.asList(additionalOptions), library);
KotlinTestUtils.assertEqualsToFile(new File(getTestDataDirectory(), "output.txt"), normalizeOutput(output)); KotlinTestUtils.assertEqualsToFile(new File(getTestDataDirectory(), "output.txt"), normalizeOutput(output));
} }
@@ -509,20 +498,17 @@ public class CompileKotlinAgainstCustomBinariesTest extends TestCaseWithTmpdir {
public void testWrongMetadataVersionBadMetadata() throws Exception { public void testWrongMetadataVersionBadMetadata() throws Exception {
doTestKotlinLibraryWithWrongMetadataVersion( doTestKotlinLibraryWithWrongMetadataVersion(
"library", "library",
new Function2<String, Object, Object>() { (name, value) -> {
@Override if (JvmAnnotationNames.METADATA_DATA_FIELD_NAME.equals(name)) {
public Object invoke(String name, Object value) { String[] strings = (String[]) value;
if (JvmAnnotationNames.METADATA_DATA_FIELD_NAME.equals(name)) { for (int i = 0; i < strings.length; i++) {
String[] strings = (String[]) value; byte[] bytes = strings[i].getBytes();
for (int i = 0; i < strings.length; i++) { for (int j = 0; j < bytes.length; j++) bytes[j] ^= 42;
byte[] bytes = strings[i].getBytes(); strings[i] = new String(bytes);
for (int j = 0; j < bytes.length; j++) bytes[j] ^= 42;
strings[i] = new String(bytes);
}
return strings;
} }
return null; return strings;
} }
return null;
} }
); );
} }
@@ -530,14 +516,11 @@ public class CompileKotlinAgainstCustomBinariesTest extends TestCaseWithTmpdir {
public void testWrongMetadataVersionBadMetadata2() throws Exception { public void testWrongMetadataVersionBadMetadata2() throws Exception {
doTestKotlinLibraryWithWrongMetadataVersion( doTestKotlinLibraryWithWrongMetadataVersion(
"library", "library",
new Function2<String, Object, Object>() { (name, value) -> {
@Override if (JvmAnnotationNames.METADATA_STRINGS_FIELD_NAME.equals(name)) {
public Object invoke(String name, Object value) { return ArrayUtil.EMPTY_STRING_ARRAY;
if (JvmAnnotationNames.METADATA_STRINGS_FIELD_NAME.equals(name)) {
return ArrayUtil.EMPTY_STRING_ARRAY;
}
return null;
} }
return null;
} }
); );
} }
@@ -648,18 +631,15 @@ public class CompileKotlinAgainstCustomBinariesTest extends TestCaseWithTmpdir {
File library2 = compileJava("library2"); File library2 = compileJava("library2");
// Copy everything from library2 to library1 // Copy everything from library2 to library1
FileUtil.visitFiles(library2, new Processor<File>() { FileUtil.visitFiles(library2, file -> {
@Override if (!file.isDirectory()) {
public boolean process(File file) { File newFile = new File(library1, FilesKt.relativeTo(file, library2).getPath());
if (!file.isDirectory()) { if (!newFile.getParentFile().exists()) {
File newFile = new File(library1, FilesKt.relativeTo(file, library2).getPath()); assert newFile.getParentFile().mkdirs();
if (!newFile.getParentFile().exists()) {
assert newFile.getParentFile().mkdirs();
}
assert file.renameTo(newFile);
} }
return true; assert file.renameTo(newFile);
} }
return true;
}); });
Pair<String, ExitCode> output = compileKotlin("source.kt", tmpdir, library1); Pair<String, ExitCode> output = compileKotlin("source.kt", tmpdir, library1);
@@ -20,7 +20,6 @@ import com.intellij.openapi.util.io.FileUtil;
import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.ContainerUtil;
import kotlin.Unit; import kotlin.Unit;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.builtins.DefaultBuiltIns; import org.jetbrains.kotlin.builtins.DefaultBuiltIns;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns; import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
@@ -33,7 +32,10 @@ import org.jetbrains.kotlin.descriptors.PackageFragmentProvider;
import org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl; import org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl;
import org.jetbrains.kotlin.name.FqName; import org.jetbrains.kotlin.name.FqName;
import org.jetbrains.kotlin.psi.KtFile; import org.jetbrains.kotlin.psi.KtFile;
import org.jetbrains.kotlin.renderer.*; import org.jetbrains.kotlin.renderer.AnnotationArgumentsRenderingPolicy;
import org.jetbrains.kotlin.renderer.DescriptorRenderer;
import org.jetbrains.kotlin.renderer.DescriptorRendererModifier;
import org.jetbrains.kotlin.renderer.OverrideRenderingPolicy;
import org.jetbrains.kotlin.resolve.lazy.LazyResolveTestUtilsKt; import org.jetbrains.kotlin.resolve.lazy.LazyResolveTestUtilsKt;
import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyPackageDescriptor; import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyPackageDescriptor;
import org.jetbrains.kotlin.serialization.deserialization.AdditionalClassPartsProvider; import org.jetbrains.kotlin.serialization.deserialization.AdditionalClassPartsProvider;
@@ -46,7 +48,6 @@ import org.jetbrains.kotlin.test.TestJdkKind;
import org.jetbrains.kotlin.test.util.RecursiveDescriptorComparator; import org.jetbrains.kotlin.test.util.RecursiveDescriptorComparator;
import java.io.File; import java.io.File;
import java.io.InputStream;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@@ -64,16 +65,13 @@ public class LoadBuiltinsTest extends KotlinTestWithEnvironment {
RecursiveDescriptorComparator.Configuration configuration = RecursiveDescriptorComparator.Configuration configuration =
RecursiveDescriptorComparator.RECURSIVE_ALL.includeMethodsOfKotlinAny(false).withRenderer( RecursiveDescriptorComparator.RECURSIVE_ALL.includeMethodsOfKotlinAny(false).withRenderer(
DescriptorRenderer.Companion.withOptions( DescriptorRenderer.Companion.withOptions(
new Function1<DescriptorRendererOptions, Unit>() { options -> {
@Override options.setWithDefinedIn(false);
public Unit invoke(DescriptorRendererOptions options) { options.setOverrideRenderingPolicy(OverrideRenderingPolicy.RENDER_OPEN_OVERRIDE);
options.setWithDefinedIn(false); options.setVerbose(true);
options.setOverrideRenderingPolicy(OverrideRenderingPolicy.RENDER_OPEN_OVERRIDE); options.setAnnotationArgumentsRenderingPolicy(AnnotationArgumentsRenderingPolicy.UNLESS_EMPTY);
options.setVerbose(true); options.setModifiers(DescriptorRendererModifier.ALL);
options.setAnnotationArgumentsRenderingPolicy(AnnotationArgumentsRenderingPolicy.UNLESS_EMPTY); return Unit.INSTANCE;
options.setModifiers(DescriptorRendererModifier.ALL);
return Unit.INSTANCE;
}
} }
) )
); );
@@ -113,12 +111,7 @@ public class LoadBuiltinsTest extends KotlinTestWithEnvironment {
Collections.singletonList(new BuiltInFictitiousFunctionClassFactory(storageManager, builtInsModule)), Collections.singletonList(new BuiltInFictitiousFunctionClassFactory(storageManager, builtInsModule)),
PlatformDependentDeclarationFilter.All.INSTANCE, PlatformDependentDeclarationFilter.All.INSTANCE,
AdditionalClassPartsProvider.None.INSTANCE, AdditionalClassPartsProvider.None.INSTANCE,
new Function1<String, InputStream>() { ForTestCompileRuntime.runtimeJarClassLoader()::getResourceAsStream
@Override
public InputStream invoke(String path) {
return ForTestCompileRuntime.runtimeJarClassLoader().getResourceAsStream(path);
}
}
); );
builtInsModule.initialize(packageFragmentProvider); builtInsModule.initialize(packageFragmentProvider);
@@ -20,8 +20,6 @@ import junit.framework.TestCase;
import kotlin.Unit; import kotlin.Unit;
import kotlin.jvm.functions.Function0; import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1; import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.util.ReenteringLazyValueComputationException; import org.jetbrains.kotlin.util.ReenteringLazyValueComputationException;
import java.util.ArrayList; import java.util.ArrayList;
@@ -278,12 +276,7 @@ public class StorageManagerTest extends TestCase {
} }
}, },
null, null,
new Function1<String, Unit>() { s -> Unit.INSTANCE
@Override
public Unit invoke(String s) {
return Unit.INSTANCE;
}
}
); );
} }
@@ -306,19 +299,11 @@ public class StorageManagerTest extends TestCase {
return rec.invoke(); return rec.invoke();
} }
}, },
new Function1<Boolean, String>() { aBoolean -> "tolerant",
@Override s -> {
public String invoke(Boolean aBoolean) { counter.inc();
return "tolerant"; assertEquals("tolerant", s);
} return Unit.INSTANCE;
},
new Function1<String, Unit>() {
@Override
public Unit invoke(String s) {
counter.inc();
assertEquals("tolerant", s);
return Unit.INSTANCE;
}
} }
); );
} }
@@ -332,22 +317,16 @@ public class StorageManagerTest extends TestCase {
public void testPostComputeNoRecursion() throws Exception { public void testPostComputeNoRecursion() throws Exception {
CounterImpl counter = new CounterImpl(); CounterImpl counter = new CounterImpl();
NotNullLazyValue<Collection<String>> v = m.createLazyValueWithPostCompute( NotNullLazyValue<Collection<String>> v = m.createLazyValueWithPostCompute(
new Function0<Collection<String>>() { () -> {
@Override List<String> strings = new ArrayList<String>();
public Collection<String> invoke() { strings.add("first");
List<String> strings = new ArrayList<String>(); return strings;
strings.add("first");
return strings;
}
}, },
null, null,
new Function1<Collection<String>, Unit>() { strings -> {
@Override counter.inc();
public Unit invoke(Collection<String> strings) { strings.add("postComputed");
counter.inc(); return Unit.INSTANCE;
strings.add("postComputed");
return Unit.INSTANCE;
}
} }
); );
@@ -359,21 +338,15 @@ public class StorageManagerTest extends TestCase {
public void testNullablePostComputeNoRecursion() throws Exception { public void testNullablePostComputeNoRecursion() throws Exception {
CounterImpl counter = new CounterImpl(); CounterImpl counter = new CounterImpl();
NullableLazyValue<Collection<String>> v = m.createNullableLazyValueWithPostCompute( NullableLazyValue<Collection<String>> v = m.createNullableLazyValueWithPostCompute(
new Function0<Collection<String>>() { () -> {
@Override ArrayList<String> strings = new ArrayList<String>();
public Collection<String> invoke() { strings.add("first");
ArrayList<String> strings = new ArrayList<String>(); return strings;
strings.add("first");
return strings;
}
}, },
new Function1<Collection<String>, Unit>() { strings -> {
@Override counter.inc();
public Unit invoke(Collection<String> strings) { strings.add("postComputed");
counter.inc(); return Unit.INSTANCE;
strings.add("postComputed");
return Unit.INSTANCE;
}
} }
); );
@@ -392,21 +365,15 @@ public class StorageManagerTest extends TestCase {
return rec.invoke(); return rec.invoke();
} }
}, },
new Function1<Boolean, String>() { firstTime -> {
@Override if (firstTime) {
public String invoke(Boolean firstTime) { throw new ReenteringLazyValueComputationException();
if (firstTime) {
throw new ReenteringLazyValueComputationException();
}
return "second";
} }
return "second";
}, },
new Function1<String, Unit>() { s -> {
@Override fail("Recursion-tolerating value should not be post computed");
public Unit invoke(String s) { return Unit.INSTANCE;
fail("Recursion-tolerating value should not be post computed");
return Unit.INSTANCE;
}
} }
); );
} }
@@ -449,23 +416,13 @@ public class StorageManagerTest extends TestCase {
public void testExceptionHandlingStrategyForLazyValues() throws Exception { public void testExceptionHandlingStrategyForLazyValues() throws Exception {
class RethrownException extends RuntimeException {} class RethrownException extends RuntimeException {}
LockBasedStorageManager m = LockBasedStorageManager.createWithExceptionHandling(new LockBasedStorageManager.ExceptionHandlingStrategy() { LockBasedStorageManager m = LockBasedStorageManager.createWithExceptionHandling(throwable -> {
@NotNull throw new RethrownException();
@Override
public RuntimeException handleException(@NotNull Throwable throwable) {
throw new RethrownException();
}
}); });
try { try {
m.createLazyValue( m.createLazyValue(() -> {
new Function0<Object>() { throw new RuntimeException();
@Nullable }).invoke();
@Override
public Object invoke() {
throw new RuntimeException();
}
}
).invoke();
fail("Exception should have occurred"); fail("Exception should have occurred");
} }
catch (RethrownException ignored) { catch (RethrownException ignored) {
@@ -475,23 +432,13 @@ public class StorageManagerTest extends TestCase {
public void testExceptionHandlingStrategyForMemoizedFunctions() throws Exception { public void testExceptionHandlingStrategyForMemoizedFunctions() throws Exception {
class RethrownException extends RuntimeException {} class RethrownException extends RuntimeException {}
LockBasedStorageManager m = LockBasedStorageManager.createWithExceptionHandling(new LockBasedStorageManager.ExceptionHandlingStrategy() { LockBasedStorageManager m = LockBasedStorageManager.createWithExceptionHandling(throwable -> {
@NotNull throw new RethrownException();
@Override
public RuntimeException handleException(@NotNull Throwable throwable) {
throw new RethrownException();
}
}); });
try { try {
m.createMemoizedFunction( m.createMemoizedFunction(o -> {
new Function1<Object, Object>() { throw new RuntimeException();
@Nullable }).invoke("");
@Override
public Object invoke(@Nullable Object o) {
throw new RuntimeException();
}
}
).invoke("");
fail("Exception should have occurred"); fail("Exception should have occurred");
} }
catch (RethrownException ignored) { catch (RethrownException ignored) {
@@ -501,12 +448,7 @@ public class StorageManagerTest extends TestCase {
// Utilities // Utilities
private static <K, V> Function0<V> apply(Function1<K, V> f, K x) { private static <K, V> Function0<V> apply(Function1<K, V> f, K x) {
return new Function0<V>() { return () -> f.invoke(x);
@Override
public V invoke() {
return f.invoke(x);
}
};
} }
private interface Counter { private interface Counter {
@@ -17,7 +17,6 @@
package org.jetbrains.kotlin.types; package org.jetbrains.kotlin.types;
import kotlin.Unit; import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.analyzer.AnalysisResult; import org.jetbrains.kotlin.analyzer.AnalysisResult;
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment; import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment;
@@ -90,16 +89,16 @@ public class DefaultModalityModifiersTest extends KotlinTestWithEnvironment {
KtDeclaration aClass = file.getDeclarations().get(0); KtDeclaration aClass = file.getDeclarations().get(0);
assert aClass instanceof KtClass; assert aClass instanceof KtClass;
AnalysisResult bindingContext = JvmResolveUtil.analyzeAndCheckForErrors(file, getEnvironment()); AnalysisResult bindingContext = JvmResolveUtil.analyzeAndCheckForErrors(file, getEnvironment());
DeclarationDescriptor classDescriptor = bindingContext.getBindingContext().get(BindingContext.DECLARATION_TO_DESCRIPTOR, aClass); DeclarationDescriptor classDescriptor =
return new LexicalScopeImpl(ScopeUtilsKt.memberScopeAsImportingScope(libraryScope), root, false, null, bindingContext.getBindingContext().get(BindingContext.DECLARATION_TO_DESCRIPTOR, aClass);
LexicalScopeKind.SYNTHETIC, LocalRedeclarationChecker.DO_NOTHING.INSTANCE, return new LexicalScopeImpl(
new Function1<LexicalScopeImpl.InitializeHandler, Unit>() { ScopeUtilsKt.memberScopeAsImportingScope(libraryScope), root, false, null,
@Override LexicalScopeKind.SYNTHETIC, LocalRedeclarationChecker.DO_NOTHING.INSTANCE,
public Unit invoke(LexicalScopeImpl.InitializeHandler handler) { handler -> {
handler.addClassifierDescriptor((ClassifierDescriptor) classDescriptor); handler.addClassifierDescriptor((ClassifierDescriptor) classDescriptor);
return Unit.INSTANCE; return Unit.INSTANCE;
} }
}); );
} }
private ClassDescriptorWithResolutionScopes createClassDescriptor(ClassKind kind, KtClass aClass) { private ClassDescriptorWithResolutionScopes createClassDescriptor(ClassKind kind, KtClass aClass) {
@@ -20,9 +20,7 @@ import com.google.common.collect.Maps;
import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.Function;
import kotlin.Unit; import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull; 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;
@@ -31,7 +29,6 @@ import org.jetbrains.kotlin.descriptors.ClassDescriptor;
import org.jetbrains.kotlin.descriptors.ClassifierDescriptor; import org.jetbrains.kotlin.descriptors.ClassifierDescriptor;
import org.jetbrains.kotlin.descriptors.ModuleDescriptor; import org.jetbrains.kotlin.descriptors.ModuleDescriptor;
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor; import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor;
import org.jetbrains.kotlin.diagnostics.Diagnostic;
import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages; import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages;
import org.jetbrains.kotlin.incremental.components.NoLookupLocation; import org.jetbrains.kotlin.incremental.components.NoLookupLocation;
import org.jetbrains.kotlin.name.Name; import org.jetbrains.kotlin.name.Name;
@@ -96,14 +93,11 @@ public class TypeSubstitutorTest extends KotlinTestWithEnvironment {
LexicalScope typeParameters = new LexicalScopeImpl( LexicalScope typeParameters = new LexicalScopeImpl(
topLevelScope, module, false, null, LexicalScopeKind.SYNTHETIC, topLevelScope, module, false, null, LexicalScopeKind.SYNTHETIC,
redeclarationChecker, redeclarationChecker,
new Function1<LexicalScopeImpl.InitializeHandler, Unit>() { handler -> {
@Override for (TypeParameterDescriptor parameterDescriptor : contextClass.getTypeConstructor().getParameters()) {
public Unit invoke(LexicalScopeImpl.InitializeHandler handler) { handler.addClassifierDescriptor(parameterDescriptor);
for (TypeParameterDescriptor parameterDescriptor : contextClass.getTypeConstructor().getParameters()) {
handler.addClassifierDescriptor(parameterDescriptor);
}
return Unit.INSTANCE;
} }
return Unit.INSTANCE;
} }
); );
return new LexicalChainedScope( return new LexicalChainedScope(
@@ -157,15 +151,7 @@ public class TypeSubstitutorTest extends KotlinTestWithEnvironment {
BindingTrace trace = new BindingTraceContext(); BindingTrace trace = new BindingTraceContext();
KotlinType type = container.getTypeResolver().resolveType(scope, jetTypeReference, trace, true); KotlinType type = container.getTypeResolver().resolveType(scope, jetTypeReference, trace, true);
if (!trace.getBindingContext().getDiagnostics().isEmpty()) { if (!trace.getBindingContext().getDiagnostics().isEmpty()) {
fail("Errors:\n" + StringUtil.join( fail("Errors:\n" + StringUtil.join(trace.getBindingContext().getDiagnostics(), DefaultErrorMessages::render, "\n"));
trace.getBindingContext().getDiagnostics(),
new Function<Diagnostic, String>() {
@Override
public String fun(Diagnostic diagnostic) {
return DefaultErrorMessages.render(diagnostic);
}
},
"\n"));
} }
return type; return type;
} }
@@ -20,7 +20,6 @@ import com.google.common.collect.Maps;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import kotlin.Unit; import kotlin.Unit;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1;
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.builtins.KotlinBuiltIns;
@@ -31,7 +30,6 @@ import org.jetbrains.kotlin.descriptors.ModuleDescriptor;
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor; import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor;
import org.jetbrains.kotlin.descriptors.annotations.Annotations; import org.jetbrains.kotlin.descriptors.annotations.Annotations;
import org.jetbrains.kotlin.descriptors.impl.TypeParameterDescriptorImpl; import org.jetbrains.kotlin.descriptors.impl.TypeParameterDescriptorImpl;
import org.jetbrains.kotlin.name.FqName;
import org.jetbrains.kotlin.name.Name; import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.psi.KtPsiFactoryKt; import org.jetbrains.kotlin.psi.KtPsiFactoryKt;
import org.jetbrains.kotlin.psi.KtTypeProjection; import org.jetbrains.kotlin.psi.KtTypeProjection;
@@ -69,12 +67,8 @@ public class TypeUnifierTest extends KotlinTestWithEnvironment {
module = DslKt.getService(container, ModuleDescriptor.class); module = DslKt.getService(container, ModuleDescriptor.class);
builtinsImportingScope = ScopeUtilsKt.chainImportingScopes( builtinsImportingScope = ScopeUtilsKt.chainImportingScopes(
CollectionsKt.map(KotlinBuiltIns.BUILT_INS_PACKAGE_FQ_NAMES, new Function1<FqName, ImportingScope>() { CollectionsKt.map(KotlinBuiltIns.BUILT_INS_PACKAGE_FQ_NAMES,
@Override fqName -> ScopeUtilsKt.memberScopeAsImportingScope(module.getPackage(fqName).getMemberScope())), null);
public ImportingScope invoke(FqName fqName) {
return ScopeUtilsKt.memberScopeAsImportingScope(module.getPackage(fqName).getMemberScope());
}
}), null);
typeResolver = DslKt.getService(container, TypeResolver.class); typeResolver = DslKt.getService(container, TypeResolver.class);
x = createTypeVariable("X"); x = createTypeVariable("X");
y = createTypeVariable("Y"); y = createTypeVariable("Y");
@@ -202,13 +196,10 @@ public class TypeUnifierTest extends KotlinTestWithEnvironment {
LexicalScope withX = new LexicalScopeImpl( LexicalScope withX = new LexicalScopeImpl(
builtinsImportingScope, module, builtinsImportingScope, module,
false, null, LexicalScopeKind.SYNTHETIC, LocalRedeclarationChecker.DO_NOTHING.INSTANCE, false, null, LexicalScopeKind.SYNTHETIC, LocalRedeclarationChecker.DO_NOTHING.INSTANCE,
new Function1<LexicalScopeImpl.InitializeHandler, Unit>() { handler -> {
@Override handler.addClassifierDescriptor(x);
public Unit invoke(LexicalScopeImpl.InitializeHandler handler) { handler.addClassifierDescriptor(y);
handler.addClassifierDescriptor(x); return Unit.INSTANCE;
handler.addClassifierDescriptor(y);
return Unit.INSTANCE;
}
} }
); );
@@ -17,7 +17,6 @@
package org.jetbrains.kotlin.utils; package org.jetbrains.kotlin.utils;
import kotlin.collections.CollectionsKt; import kotlin.collections.CollectionsKt;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -61,12 +60,7 @@ public final class Interner<T> {
@NotNull @NotNull
public List<T> getAllInternedObjects() { public List<T> getAllInternedObjects() {
return CollectionsKt.sortedBy(interned.keySet(), new Function1<T, Integer>() { return CollectionsKt.sortedBy(interned.keySet(), interned::get);
@Override
public Integer invoke(T key) {
return interned.get(key);
}
});
} }
public boolean isEmpty() { public boolean isEmpty() {
@@ -19,7 +19,6 @@ package org.jetbrains.kotlin.generators.tests.generator;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.Processor;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.test.KotlinTestUtils; import org.jetbrains.kotlin.test.KotlinTestUtils;
@@ -31,12 +30,8 @@ import java.util.*;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class SimpleTestClassModel implements TestClassModel { public class SimpleTestClassModel implements TestClassModel {
private static final Comparator<TestEntityModel> BY_NAME = new Comparator<TestEntityModel>() { private static final Comparator<TestEntityModel> BY_NAME = Comparator.comparing(TestEntityModel::getName);
@Override
public int compare(@NotNull TestEntityModel o1, @NotNull TestEntityModel o2) {
return o1.getName().compareTo(o2.getName());
}
};
@NotNull @NotNull
private final File rootFile; private final File rootFile;
private final boolean recursive; private final boolean recursive;
@@ -123,12 +118,7 @@ public class SimpleTestClassModel implements TestClassModel {
} }
private static boolean dirHasFilesInside(@NotNull File dir) { private static boolean dirHasFilesInside(@NotNull File dir) {
return !FileUtil.processFilesRecursively(dir, new Processor<File>() { return !FileUtil.processFilesRecursively(dir, File::isDirectory);
@Override
public boolean process(File file) {
return file.isDirectory();
}
});
} }
private static boolean dirHasSubDirs(@NotNull File dir) { private static boolean dirHasSubDirs(@NotNull File dir) {
@@ -19,7 +19,6 @@ package org.jetbrains.kotlin.generators.tests.generator;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.Processor;
import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -30,7 +29,6 @@ import org.jetbrains.kotlin.utils.Printer;
import java.io.File; import java.io.File;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@@ -80,23 +78,15 @@ public class SingleClassTestModel implements TestClassModel {
result.add(new TestAllFilesPresentMethodModel()); result.add(new TestAllFilesPresentMethodModel());
FileUtil.processFilesRecursively(rootFile, new Processor<File>() { FileUtil.processFilesRecursively(rootFile, file -> {
@Override if (!file.isDirectory() && filenamePattern.matcher(file.getName()).matches()) {
public boolean process(File file) { result.addAll(getTestMethodsFromFile(file));
if (!file.isDirectory() && filenamePattern.matcher(file.getName()).matches()) {
result.addAll(getTestMethodsFromFile(file));
}
return true;
} }
return true;
}); });
ContainerUtil.sort(result, new Comparator<TestMethodModel>() { ContainerUtil.sort(result, (o1, o2) -> StringUtil.compare(o1.getName(), o2.getName(), true));
@Override
public int compare(@NotNull TestMethodModel o1, @NotNull TestMethodModel o2) {
return StringUtil.compare(o1.getName(), o2.getName(), true);
}
});
methods = Lists.<MethodModel>newArrayList(result); methods = Lists.<MethodModel>newArrayList(result);
} }
@@ -197,15 +197,12 @@ public class JsConfig {
if (initialized) return; if (initialized) return;
if (!getLibraries().isEmpty()) { if (!getLibraries().isEmpty()) {
Function1<VirtualFile, Unit> action = new Function1<VirtualFile, Unit>() { Function1<VirtualFile, Unit> action = file -> {
@Override String libraryPath = PathUtil.getLocalPath(file);
public Unit invoke(VirtualFile file) { assert libraryPath != null : "libraryPath for " + file + " should not be null";
String libraryPath = PathUtil.getLocalPath(file); metadata.addAll(KotlinJavascriptMetadataUtils.loadMetadata(libraryPath));
assert libraryPath != null : "libraryPath for " + file + " should not be null";
metadata.addAll(KotlinJavascriptMetadataUtils.loadMetadata(libraryPath));
return Unit.INSTANCE; return Unit.INSTANCE;
}
}; };
boolean hasErrors = checkLibFilesAndReportErrors(new Reporter() { boolean hasErrors = checkLibFilesAndReportErrors(new Reporter() {
@@ -18,8 +18,7 @@ package org.jetbrains.kotlin.js.patterns;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.intellij.util.Function; import kotlin.collections.CollectionsKt;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.builtins.PrimitiveType; import org.jetbrains.kotlin.builtins.PrimitiveType;
import org.jetbrains.kotlin.name.Name; import org.jetbrains.kotlin.name.Name;
@@ -34,23 +33,15 @@ public final class NamePredicate implements Predicate<Name> {
@NotNull @NotNull
public static final NamePredicate PRIMITIVE_NUMBERS = new NamePredicate( public static final NamePredicate PRIMITIVE_NUMBERS = new NamePredicate(
ContainerUtil.map(PrimitiveType.NUMBER_TYPES, CollectionsKt.map(PrimitiveType.NUMBER_TYPES, (PrimitiveType type) -> type.getTypeName().asString())
new Function<PrimitiveType, String>() { );
@Override
public String fun(PrimitiveType type) {
return type.getTypeName().asString();
}
}));
@NotNull @NotNull
public static final NamePredicate PRIMITIVE_NUMBERS_MAPPED_TO_PRIMITIVE_JS = new NamePredicate( public static final NamePredicate PRIMITIVE_NUMBERS_MAPPED_TO_PRIMITIVE_JS = new NamePredicate(
ContainerUtil.mapNotNull(PrimitiveType.NUMBER_TYPES, CollectionsKt.mapNotNull(PrimitiveType.NUMBER_TYPES, (PrimitiveType type) ->
new Function<PrimitiveType, String>() { type != PrimitiveType.LONG ? type.getTypeName().asString() : null
@Override )
public String fun(PrimitiveType type) { );
return type != PrimitiveType.LONG ? type.getTypeName().asString() : null;
}
}));
@NotNull @NotNull
public static final NamePredicate STRING = new NamePredicate("String"); public static final NamePredicate STRING = new NamePredicate("String");
@@ -58,15 +58,8 @@ public class JsInliner extends JsVisitorWithContextImpl {
// these are needed for error reporting, when inliner detects cycle // these are needed for error reporting, when inliner detects cycle
private final Stack<JsFunction> namedFunctionsStack = new Stack<JsFunction>(); private final Stack<JsFunction> namedFunctionsStack = new Stack<JsFunction>();
private final LinkedList<JsCallInfo> inlineCallInfos = new LinkedList<JsCallInfo>(); private final LinkedList<JsCallInfo> inlineCallInfos = new LinkedList<JsCallInfo>();
private final Function1<JsNode, Boolean> canBeExtractedByInliner = new Function1<JsNode, Boolean>() { private final Function1<JsNode, Boolean> canBeExtractedByInliner =
@Override node -> node instanceof JsInvocation && hasToBeInlined((JsInvocation) node);
public Boolean invoke(JsNode node) {
if (!(node instanceof JsInvocation)) return false;
JsInvocation call = (JsInvocation) node;
return hasToBeInlined(call);
}
};
public static JsProgram process(@NotNull TranslationContext context) { public static JsProgram process(@NotNull TranslationContext context) {
JsProgram program = context.program(); JsProgram program = context.program();
@@ -17,8 +17,7 @@
package org.jetbrains.kotlin.integration; package org.jetbrains.kotlin.integration;
import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtil;
import com.intellij.util.Function; import kotlin.collections.CollectionsKt;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.js.test.rhino.RhinoFunctionResultChecker; import org.jetbrains.kotlin.js.test.rhino.RhinoFunctionResultChecker;
@@ -58,12 +57,7 @@ public class AntTaskJsTest extends AbstractAntTaskTest {
List<String> fileNames = new ArrayList<String>(Arrays.asList(jsFiles)); List<String> fileNames = new ArrayList<String>(Arrays.asList(jsFiles));
fileNames.add(JS_OUT_FILE); fileNames.add(JS_OUT_FILE);
List<String> filePaths = ContainerUtil.map(fileNames, new Function<String, String>() { List<String> filePaths = CollectionsKt.map(fileNames, s -> getOutputFileByName(s).getAbsolutePath());
@Override
public String fun(String s) {
return getOutputFileByName(s).getAbsolutePath();
}
});
RhinoUtils.runRhinoTest(filePaths, new RhinoFunctionResultChecker("out", "foo", "box", "OK", withModuleSystem)); RhinoUtils.runRhinoTest(filePaths, new RhinoFunctionResultChecker("out", "foo", "box", "OK", withModuleSystem));
} }

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