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
public Unit invoke(InstructionAdapter v) {
Type type = stringValueOfType(receiverType); Type type = stringValueOfType(receiverType);
receiver.put(type, v); receiver.put(type, v);
v.invokestatic("java/lang/String", "valueOf", "(" + type.getDescriptor() + ")Ljava/lang/String;", false); v.invokestatic("java/lang/String", "valueOf", "(" + type.getDescriptor() + ")Ljava/lang/String;", false);
return null; return null;
}
}); });
} }
@@ -573,9 +569,7 @@ 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
public Unit invoke(InstructionAdapter v) {
left.put(leftType, v); left.put(leftType, v);
right.put(rightType, v); right.put(rightType, v);
genAreEqualCall(v); genAreEqualCall(v);
@@ -584,7 +578,6 @@ public class AsmUtil {
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
public void addPart(@NotNull String partShortName, @Nullable String facadeShortName) {
PackageParts packageParts = partsGroupedByPackage.get(packageFqNameAsString); PackageParts packageParts = partsGroupedByPackage.get(packageFqNameAsString);
if (packageParts == null) { if (packageParts == null) {
packageParts = new PackageParts(packageFqNameAsString); packageParts = new PackageParts(packageFqNameAsString);
partsGroupedByPackage.put(packageFqNameAsString, packageParts); 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
public Unit invoke(AnnotationVisitor av) {
writeAnnotationData(av, serializer, functionProto); writeAnnotationData(av, serializer, functionProto);
return Unit.INSTANCE; return Unit.INSTANCE;
}
}); });
} }
@@ -284,9 +279,7 @@ 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
public Unit invoke(InstructionAdapter v) {
if (isConst(closure)) { if (isConst(closure)) {
v.getstatic(asmType.getInternalName(), JvmAbi.INSTANCE_FIELD, asmType.getDescriptor()); v.getstatic(asmType.getInternalName(), JvmAbi.INSTANCE_FIELD, asmType.getDescriptor());
} }
@@ -300,7 +293,6 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
return Unit.INSTANCE; 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() {
@Override
public void reportException(Throwable exception, String fileUrl) {
if (exception instanceof RuntimeException) { if (exception instanceof RuntimeException) {
throw (RuntimeException) exception; 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());
}
}; };
} }
@@ -28,8 +28,6 @@ import com.intellij.util.containers.Stack;
import kotlin.Pair; import kotlin.Pair;
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 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;
@@ -496,9 +494,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
} }
} }
return StackValue.operation(asmType, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(asmType, v -> {
@Override
public Unit invoke(InstructionAdapter v) {
Label elseLabel = new Label(); Label elseLabel = new Label();
BranchedValue.Companion.condJump(condition, elseLabel, true, v); BranchedValue.Companion.condJump(condition, elseLabel, true, v);
@@ -514,18 +510,14 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
markLineNumber(expression, isStatement); markLineNumber(expression, isStatement);
v.mark(end); v.mark(end);
return Unit.INSTANCE; return Unit.INSTANCE;
}
}); });
} }
@Override @Override
public StackValue visitWhileExpression(@NotNull KtWhileExpression expression, StackValue receiver) { public StackValue visitWhileExpression(@NotNull KtWhileExpression expression, StackValue receiver) {
return StackValue.operation(Type.VOID_TYPE, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(Type.VOID_TYPE, adapter -> {
@Override
public Unit invoke(InstructionAdapter adapter) {
generateWhile(expression); generateWhile(expression);
return Unit.INSTANCE; return Unit.INSTANCE;
}
}); });
} }
@@ -551,12 +543,9 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
@Override @Override
public StackValue visitDoWhileExpression(@NotNull KtDoWhileExpression expression, StackValue receiver) { public StackValue visitDoWhileExpression(@NotNull KtDoWhileExpression expression, StackValue receiver) {
return StackValue.operation(Type.VOID_TYPE, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(Type.VOID_TYPE, adapter -> {
@Override
public Unit invoke(InstructionAdapter adapter) {
generateDoWhile(expression); generateDoWhile(expression);
return Unit.INSTANCE; return Unit.INSTANCE;
}
}); });
} }
@@ -609,12 +598,9 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
@Override @Override
public StackValue visitForExpression(@NotNull KtForExpression forExpression, StackValue receiver) { public StackValue visitForExpression(@NotNull KtForExpression forExpression, StackValue receiver) {
return StackValue.operation(Type.VOID_TYPE, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(Type.VOID_TYPE, adapter -> {
@Override
public Unit invoke(InstructionAdapter adapter) {
generateFor(forExpression); generateFor(forExpression);
return Unit.INSTANCE; return Unit.INSTANCE;
}
}); });
} }
@@ -765,15 +751,12 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
VariableDescriptor parameterDescriptor = bindingContext.get(VALUE_PARAMETER, loopParameter); VariableDescriptor parameterDescriptor = bindingContext.get(VALUE_PARAMETER, loopParameter);
loopParameterType = asmType(parameterDescriptor.getType()); loopParameterType = asmType(parameterDescriptor.getType());
loopParameterVar = myFrameMap.enter(parameterDescriptor, loopParameterType); loopParameterVar = myFrameMap.enter(parameterDescriptor, loopParameterType);
scheduleLeaveVariable(new Runnable() { scheduleLeaveVariable(() -> {
@Override
public void run() {
myFrameMap.leave(parameterDescriptor); myFrameMap.leave(parameterDescriptor);
v.visitLocalVariable(parameterDescriptor.getName().asString(), v.visitLocalVariable(parameterDescriptor.getName().asString(),
loopParameterType.getDescriptor(), null, loopParameterType.getDescriptor(), null,
loopParameterStartLabel, bodyEnd, loopParameterStartLabel, bodyEnd,
loopParameterVar); loopParameterVar);
}
}); });
} }
} }
@@ -796,28 +779,17 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
Label destructuringStartLabel = new Label(); Label destructuringStartLabel = new Label();
List<VariableDescriptor> componentDescriptors = List<VariableDescriptor> componentDescriptors =
CollectionsKt.map( CollectionsKt.map(destructuringDeclaration.getEntries(), ExpressionCodegen.this::getVariableDescriptorNotNull);
destructuringDeclaration.getEntries(),
new Function1<KtDestructuringDeclarationEntry, VariableDescriptor>() {
@Override
public VariableDescriptor invoke(KtDestructuringDeclarationEntry entry) {
return getVariableDescriptorNotNull(entry);
}
}
);
for (VariableDescriptor componentDescriptor : CodegenUtilKt.filterOutDescriptorsWithSpecialNames(componentDescriptors)) { for (VariableDescriptor componentDescriptor : CodegenUtilKt.filterOutDescriptorsWithSpecialNames(componentDescriptors)) {
@SuppressWarnings("ConstantConditions") Type componentAsmType = asmType(componentDescriptor.getReturnType()); @SuppressWarnings("ConstantConditions") Type componentAsmType = asmType(componentDescriptor.getReturnType());
int componentVarIndex = myFrameMap.enter(componentDescriptor, componentAsmType); int componentVarIndex = myFrameMap.enter(componentDescriptor, componentAsmType);
scheduleLeaveVariable(new Runnable() { scheduleLeaveVariable(() -> {
@Override
public void run() {
myFrameMap.leave(componentDescriptor); myFrameMap.leave(componentDescriptor);
v.visitLocalVariable(componentDescriptor.getName().asString(), v.visitLocalVariable(componentDescriptor.getName().asString(),
componentAsmType.getDescriptor(), null, componentAsmType.getDescriptor(), null,
destructuringStartLabel, bodyEnd, destructuringStartLabel, bodyEnd,
componentVarIndex); componentVarIndex);
}
}); });
} }
@@ -843,12 +815,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
protected int createLoopTempVariable(Type type) { protected int createLoopTempVariable(Type type) {
int varIndex = myFrameMap.enterTemp(type); int varIndex = myFrameMap.enterTemp(type);
scheduleLeaveVariable(new Runnable() { scheduleLeaveVariable(() -> myFrameMap.leaveTemp(type));
@Override
public void run() {
myFrameMap.leaveTemp(type);
}
});
return varIndex; return varIndex;
} }
@@ -1387,14 +1354,12 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
loopBlockStackElement.targetLabel != null && loopBlockStackElement.targetLabel != null &&
labelElement.getReferencedName().equals(loopBlockStackElement.targetLabel.getReferencedName())) { labelElement.getReferencedName().equals(loopBlockStackElement.targetLabel.getReferencedName())) {
Label label = isBreak ? loopBlockStackElement.breakLabel : loopBlockStackElement.continueLabel; Label label = isBreak ? loopBlockStackElement.breakLabel : loopBlockStackElement.continueLabel;
return StackValue.operation(Type.VOID_TYPE, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(
@Override Type.VOID_TYPE, adapter -> {
public Unit invoke(InstructionAdapter adapter) {
PseudoInsnsKt.fixStackAndJump(v, label); PseudoInsnsKt.fixStackAndJump(v, label);
v.mark(afterBreakContinueLabel); v.mark(afterBreakContinueLabel);
return Unit.INSTANCE; return Unit.INSTANCE;
} }
}
); );
} }
} }
@@ -1416,9 +1381,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
boolean isStatement boolean isStatement
) { ) {
Type targetType = isStatement ? Type.VOID_TYPE : expressionType(ifExpression); Type targetType = isStatement ? Type.VOID_TYPE : expressionType(ifExpression);
return StackValue.operation(targetType, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(targetType, v -> {
@Override
public Unit invoke(InstructionAdapter v) {
Label elseLabel = new Label(); Label elseLabel = new Label();
BranchedValue.Companion.condJump(condition, elseLabel, inverse, v); BranchedValue.Companion.condJump(condition, elseLabel, inverse, v);
@@ -1427,7 +1390,6 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
v.mark(elseLabel); v.mark(elseLabel);
} }
else { else {
Type targetType = expressionType(ifExpression);
gen(expression, targetType); gen(expression, targetType);
Label end = new Label(); Label end = new Label();
v.goTo(end); v.goTo(end);
@@ -1439,7 +1401,6 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
v.mark(end); v.mark(end);
} }
return null; return null;
}
}); });
} }
@@ -1549,9 +1510,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
return StackValue.constant(constantValue.toString(), type); return StackValue.constant(constantValue.toString(), type);
} }
else { else {
return StackValue.operation(JAVA_STRING_TYPE, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(JAVA_STRING_TYPE, v -> {
@Override
public Unit invoke(InstructionAdapter v) {
genStringBuilderConstructor(v); genStringBuilderConstructor(v);
for (KtStringTemplateEntry entry : entries) { for (KtStringTemplateEntry entry : entries) {
if (entry instanceof KtStringTemplateEntryWithExpression) { if (entry instanceof KtStringTemplateEntryWithExpression) {
@@ -1567,7 +1526,6 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
} }
v.invokevirtual("java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false); v.invokevirtual("java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false);
return Unit.INSTANCE; return Unit.INSTANCE;
}
}); });
} }
} }
@@ -1667,9 +1625,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
ClassDescriptor classDescriptor = objectLiteralResult.classDescriptor; ClassDescriptor classDescriptor = objectLiteralResult.classDescriptor;
Type type = typeMapper.mapType(classDescriptor); Type type = typeMapper.mapType(classDescriptor);
return StackValue.operation(type, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(type, v -> {
@Override
public Unit invoke(InstructionAdapter v) {
if (objectLiteralResult.wereReifiedMarkers) { if (objectLiteralResult.wereReifiedMarkers) {
ReifiedTypeInliner.putNeedClassReificationMarker(v); ReifiedTypeInliner.putNeedClassReificationMarker(v);
} }
@@ -1704,7 +1660,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
} }
} }
ArgumentGenerator argumentGenerator = ArgumentGenerator argumentGenerator =
new CallBasedArgumentGenerator(ExpressionCodegen.this, defaultCallGenerator, valueParameters, mappedTypes); new CallBasedArgumentGenerator(this, defaultCallGenerator, valueParameters, mappedTypes);
argumentGenerator.generate(valueArguments, valueArguments, null); argumentGenerator.generate(valueArguments, valueArguments, null);
} }
@@ -1716,7 +1672,6 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
Method constructor = typeMapper.mapAsmMethod(SamCodegenUtil.resolveSamAdapter(constructorDescriptor)); Method constructor = typeMapper.mapAsmMethod(SamCodegenUtil.resolveSamAdapter(constructorDescriptor));
v.invokespecial(type.getInternalName(), "<init>", constructor.getDescriptor(), false); v.invokespecial(type.getInternalName(), "<init>", constructor.getDescriptor(), false);
return Unit.INSTANCE; return Unit.INSTANCE;
}
}); });
} }
@@ -1869,9 +1824,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
assert blockResult != null : "Block result should be initialized in the loop or the condition above"; assert blockResult != null : "Block result should be initialized in the loop or the condition above";
return new StackValueWithLeaveTask(blockResult, new Function1<StackValue, Unit>() { return new StackValueWithLeaveTask(blockResult, value -> {
@Override
public Unit invoke(StackValue value) {
if (labelBlockEnd == null) { if (labelBlockEnd == null) {
v.mark(blockEnd); v.mark(blockEnd);
} }
@@ -1879,7 +1832,6 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
task.fun(value); task.fun(value);
} }
return Unit.INSTANCE; return Unit.INSTANCE;
}
}); });
} }
@@ -1995,9 +1947,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
Label scopeStart = new Label(); Label scopeStart = new Label();
v.mark(scopeStart); v.mark(scopeStart);
leaveTasks.add(new Function<StackValue, Void>() { leaveTasks.add(answer -> {
@Override
public Void fun(StackValue answer) {
if (isDelegatedLocalVariable(variableDescriptor)) { if (isDelegatedLocalVariable(variableDescriptor)) {
myFrameMap.leave(getDelegatedLocalVariableMetadata(variableDescriptor, bindingContext)); myFrameMap.leave(getDelegatedLocalVariableMetadata(variableDescriptor, bindingContext));
} }
@@ -2010,7 +1960,6 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
} }
v.visitLocalVariable(variableDescriptor.getName().asString(), type.getDescriptor(), null, scopeStart, blockEnd, index); v.visitLocalVariable(variableDescriptor.getName().asString(), type.getDescriptor(), null, scopeStart, blockEnd, index);
return null; return null;
}
}); });
} }
@@ -2027,15 +1976,12 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
Label scopeStart = new Label(); Label scopeStart = new Label();
v.mark(scopeStart); v.mark(scopeStart);
leaveTasks.add(new Function<StackValue, Void>() { leaveTasks.add(answer -> {
@Override
public Void fun(StackValue answer) {
int index = myFrameMap.leave(functionDescriptor); int index = myFrameMap.leave(functionDescriptor);
assert !functionDescriptor.getName().isSpecial() : "Local variable should be generated only for function with name: " + statement.getText(); assert !functionDescriptor.getName().isSpecial() : "Local variable should be generated only for function with name: " + statement.getText();
v.visitLocalVariable(functionDescriptor.getName().asString() + "$", type.getDescriptor(), null, scopeStart, blockEnd, index); v.visitLocalVariable(functionDescriptor.getName().asString() + "$", type.getDescriptor(), null, scopeStart, blockEnd, index);
return null; return null;
}
}); });
} }
@@ -2157,9 +2103,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
@Override @Override
public StackValue visitReturnExpression(@NotNull KtReturnExpression expression, StackValue receiver) { public StackValue visitReturnExpression(@NotNull KtReturnExpression expression, StackValue receiver) {
return StackValue.operation(Type.VOID_TYPE, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(Type.VOID_TYPE, adapter -> {
@Override
public Unit invoke(InstructionAdapter adapter) {
KtExpression returnedExpression = expression.getReturnedExpression(); KtExpression returnedExpression = expression.getReturnedExpression();
CallableMemberDescriptor descriptor = getContext().getContextDescriptor(); CallableMemberDescriptor descriptor = getContext().getContextDescriptor();
NonLocalReturnInfo nonLocalReturn = getNonLocalReturnInfo(descriptor, expression); NonLocalReturnInfo nonLocalReturn = getNonLocalReturnInfo(descriptor, expression);
@@ -2171,7 +2115,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
return Unit.INSTANCE; return Unit.INSTANCE;
} }
Type returnType = isNonLocalReturn ? nonLocalReturn.returnType : ExpressionCodegen.this.returnType; Type returnType = isNonLocalReturn ? nonLocalReturn.returnType : this.returnType;
StackValue valueToReturn = returnedExpression != null ? gen(returnedExpression) : StackValue.none(); StackValue valueToReturn = returnedExpression != null ? gen(returnedExpression) : StackValue.none();
putStackValue(returnedExpression, returnType, valueToReturn); putStackValue(returnedExpression, returnType, valueToReturn);
@@ -2184,12 +2128,11 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
v.visitInsn(returnType.getOpcode(Opcodes.IRETURN)); v.visitInsn(returnType.getOpcode(Opcodes.IRETURN));
} }
else { else {
v.areturn(ExpressionCodegen.this.returnType); v.areturn(this.returnType);
} }
v.mark(afterReturnLabel); v.mark(afterReturnLabel);
return Unit.INSTANCE; return Unit.INSTANCE;
}
}); });
} }
@@ -2698,9 +2641,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
Type asmType = Type asmType =
state.getSamWrapperClasses().getSamWrapperClass(samType, expression.getContainingKtFile(), this); state.getSamWrapperClasses().getSamWrapperClass(samType, expression.getContainingKtFile(), this);
return StackValue.operation(asmType, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(asmType, v -> {
@Override
public Unit invoke(InstructionAdapter v) {
v.anew(asmType); v.anew(asmType);
v.dup(); v.dup();
@@ -2724,7 +2665,6 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
v.mark(afterAll); v.mark(afterAll);
return null; return null;
}
}); });
} }
@@ -3405,13 +3345,10 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
); );
codegen.generate(); codegen.generate();
return codegen.putInstanceOnStack(receiverValue == null ? null : new Function0<Unit>() { return codegen.putInstanceOnStack(receiverValue == null ? null : () -> {
@Override
public Unit invoke() {
assert receiverAsmType != null : "Receiver type should not be null when receiver value is not null: " + receiverValue; assert receiverAsmType != null : "Receiver type should not be null when receiver value is not null: " + receiverValue;
receiverValue.put(receiverAsmType, v); receiverValue.put(receiverAsmType, v);
return Unit.INSTANCE; return Unit.INSTANCE;
}
}); });
} }
@@ -3421,9 +3358,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
@Nullable KtExpression receiverExpression, @Nullable KtExpression receiverExpression,
boolean wrapIntoKClass boolean wrapIntoKClass
) { ) {
return StackValue.operation(wrapIntoKClass ? K_CLASS_TYPE : JAVA_CLASS_TYPE, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(wrapIntoKClass ? K_CLASS_TYPE : JAVA_CLASS_TYPE, v -> {
@Override
public Unit invoke(InstructionAdapter v) {
KotlinType type = lhs.getType(); KotlinType type = lhs.getType();
if (lhs instanceof DoubleColonLHS.Expression && !((DoubleColonLHS.Expression) lhs).isObjectQualifier()) { if (lhs instanceof DoubleColonLHS.Expression && !((DoubleColonLHS.Expression) lhs).isObjectQualifier()) {
JavaClassProperty.INSTANCE.generateImpl(v, gen(receiverExpression)); JavaClassProperty.INSTANCE.generateImpl(v, gen(receiverExpression));
@@ -3443,7 +3378,6 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
} }
return Unit.INSTANCE; return Unit.INSTANCE;
}
}); });
} }
@@ -3551,9 +3485,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
assert deparenthesized != null : "For with empty range expression"; assert deparenthesized != null : "For with empty range expression";
boolean isInverted = operationReference.getReferencedNameElementType() == KtTokens.NOT_IN; boolean isInverted = operationReference.getReferencedNameElementType() == KtTokens.NOT_IN;
return StackValue.operation(Type.BOOLEAN_TYPE, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(Type.BOOLEAN_TYPE, v -> {
@Override
public Unit invoke(InstructionAdapter v) {
if (RangeCodegenUtil.isPrimitiveRangeSpecializationOfType(leftValue.type, deparenthesized, bindingContext) || if (RangeCodegenUtil.isPrimitiveRangeSpecializationOfType(leftValue.type, deparenthesized, bindingContext) ||
RangeCodegenUtil.isPrimitiveRangeToExtension(operationReference, bindingContext)) { RangeCodegenUtil.isPrimitiveRangeToExtension(operationReference, bindingContext)) {
generateInPrimitiveRange(leftValue, (KtBinaryExpression) deparenthesized, isInverted); generateInPrimitiveRange(leftValue, (KtBinaryExpression) deparenthesized, isInverted);
@@ -3568,7 +3500,6 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
} }
} }
return null; return null;
}
}); });
} }
@@ -3682,21 +3613,15 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
//check nullability cause there is some optimizations in codegen for non-nullable case //check nullability cause there is some optimizations in codegen for non-nullable case
if (left754Type.isNullable || right754Type.isNullable) { if (left754Type.isNullable || right754Type.isNullable) {
if (state.getLanguageVersionSettings().getApiVersion().compareTo(ApiVersion.KOTLIN_1_1) >= 0) { if (state.getLanguageVersionSettings().getApiVersion().compareTo(ApiVersion.KOTLIN_1_1) >= 0) {
return StackValue.operation(Type.BOOLEAN_TYPE, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(Type.BOOLEAN_TYPE, v -> {
@Override
public Unit invoke(InstructionAdapter v) {
generate754EqualsForNullableTypesViaIntrinsic(v, opToken, pregeneratedLeft, left, left754Type, right, right754Type); generate754EqualsForNullableTypesViaIntrinsic(v, opToken, pregeneratedLeft, left, left754Type, right, right754Type);
return Unit.INSTANCE; return Unit.INSTANCE;
}
}); });
} }
else { else {
return StackValue.operation(Type.BOOLEAN_TYPE, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(Type.BOOLEAN_TYPE, v -> {
@Override
public Unit invoke(InstructionAdapter v) {
generate754EqualsForNullableTypes(v, opToken, pregeneratedLeft, left, left754Type, right, right754Type); generate754EqualsForNullableTypes(v, opToken, pregeneratedLeft, left, left754Type, right, right754Type);
return Unit.INSTANCE; return Unit.INSTANCE;
}
}); });
} }
} }
@@ -3861,9 +3786,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
return value; return value;
} }
return StackValue.operation(exprType, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(exprType, v -> {
@Override
public Unit invoke(InstructionAdapter v) {
value.put(value.type, v); value.put(value.type, v);
v.dup(); v.dup();
@@ -3878,7 +3801,6 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
gen(expression.getRight(), exprType); gen(expression.getRight(), exprType);
v.mark(end); v.mark(end);
return null; return null;
}
}); });
} }
@@ -3915,23 +3837,18 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
} }
private StackValue generateAssignmentExpression(KtBinaryExpression expression) { private StackValue generateAssignmentExpression(KtBinaryExpression expression) {
return StackValue.operation(Type.VOID_TYPE, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(Type.VOID_TYPE, adapter -> {
@Override
public Unit invoke(InstructionAdapter adapter) {
StackValue stackValue = gen(expression.getLeft()); StackValue stackValue = gen(expression.getLeft());
KtExpression right = expression.getRight(); KtExpression right = expression.getRight();
assert right != null : expression.getText(); assert right != null : expression.getText();
stackValue.store(gen(right), v); stackValue.store(gen(right), v);
return Unit.INSTANCE; return Unit.INSTANCE;
}
}); });
} }
private StackValue generateAugmentedAssignment(KtBinaryExpression expression) { private StackValue generateAugmentedAssignment(KtBinaryExpression expression) {
return StackValue.operation(Type.VOID_TYPE, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(Type.VOID_TYPE, adapter -> {
@Override
public Unit invoke(InstructionAdapter adapter) {
ResolvedCall<?> resolvedCall = CallUtilKt.getResolvedCallWithAssert(expression, bindingContext); ResolvedCall<?> resolvedCall = CallUtilKt.getResolvedCallWithAssert(expression, bindingContext);
FunctionDescriptor descriptor = accessibleFunctionDescriptor(resolvedCall); FunctionDescriptor descriptor = accessibleFunctionDescriptor(resolvedCall);
Callable callable = resolveToCallable(descriptor, false, resolvedCall); Callable callable = resolveToCallable(descriptor, false, resolvedCall);
@@ -3944,7 +3861,6 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
putCallAugAssignMethod(expression, resolvedCall, callable, lhsType, keepReturnValue); putCallAugAssignMethod(expression, resolvedCall, callable, lhsType, keepReturnValue);
return Unit.INSTANCE; return Unit.INSTANCE;
}
}); });
} }
@@ -4038,12 +3954,9 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
public StackValue visitPostfixExpression(@NotNull KtPostfixExpression expression, StackValue receiver) { public StackValue visitPostfixExpression(@NotNull KtPostfixExpression expression, StackValue receiver) {
if (expression.getOperationReference().getReferencedNameElementType() == KtTokens.EXCLEXCL) { if (expression.getOperationReference().getReferencedNameElementType() == KtTokens.EXCLEXCL) {
StackValue base = genQualified(receiver, expression.getBaseExpression()); StackValue base = genQualified(receiver, expression.getBaseExpression());
if (isPrimitive(base.type)) { if (isPrimitive(base.type)) return base;
return base;
} else { return StackValue.operation(base.type, v -> {
return StackValue.operation(base.type, new Function1<InstructionAdapter, Unit>() {
@Override
public Unit invoke(InstructionAdapter v) {
base.put(base.type, v); base.put(base.type, v);
v.dup(); v.dup();
Label ok = new Label(); Label ok = new Label();
@@ -4051,10 +3964,8 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
v.invokestatic(IntrinsicMethods.INTRINSICS_CLASS_NAME, "throwNpe", "()V", false); v.invokestatic(IntrinsicMethods.INTRINSICS_CLASS_NAME, "throwNpe", "()V", false);
v.mark(ok); v.mark(ok);
return null; return null;
}
}); });
} }
}
DeclarationDescriptor originalOperation = bindingContext.get(REFERENCE_TARGET, expression.getOperationReference()); DeclarationDescriptor originalOperation = bindingContext.get(REFERENCE_TARGET, expression.getOperationReference());
String originalOperationName = originalOperation != null ? originalOperation.getName().asString() : null; String originalOperationName = originalOperation != null ? originalOperation.getName().asString() : null;
@@ -4094,9 +4005,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
} }
} }
return StackValue.operation(asmBaseType, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(asmBaseType, v -> {
@Override
public Unit invoke(InstructionAdapter v) {
StackValue value = StackValue.complexWriteReadReceiver(gen(expression.getBaseExpression())); StackValue value = StackValue.complexWriteReadReceiver(gen(expression.getBaseExpression()));
value.put(asmBaseType, v); value.put(asmBaseType, v);
@@ -4123,7 +4032,6 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
myFrameMap.leaveTemp(asmBaseType); myFrameMap.leaveTemp(asmBaseType);
return Unit.INSTANCE; return Unit.INSTANCE;
}
}); });
} }
@@ -4337,9 +4245,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
@NotNull @NotNull
public StackValue generateConstructorCall(@NotNull ResolvedCall<?> resolvedCall, @NotNull Type objectType) { public StackValue generateConstructorCall(@NotNull ResolvedCall<?> resolvedCall, @NotNull Type objectType) {
return StackValue.functionCall(objectType, new Function1<InstructionAdapter, Unit>() { return StackValue.functionCall(objectType, v -> {
@Override
public Unit invoke(InstructionAdapter v) {
v.anew(objectType); v.anew(objectType);
v.dup(); v.dup();
@@ -4365,7 +4271,6 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
invokeMethodWithArguments(method, resolvedCall, StackValue.none()); invokeMethodWithArguments(method, resolvedCall, StackValue.none());
return Unit.INSTANCE; return Unit.INSTANCE;
}
}); });
} }
@@ -4377,13 +4282,10 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
if (args.size() == 1) { if (args.size() == 1) {
KtExpression sizeExpression = args.get(0).getArgumentExpression(); KtExpression sizeExpression = args.get(0).getArgumentExpression();
return StackValue.operation(typeMapper.mapType(arrayType), new Function1<InstructionAdapter, Unit>() { return StackValue.operation(typeMapper.mapType(arrayType), v -> {
@Override
public Unit invoke(InstructionAdapter v) {
gen(sizeExpression, Type.INT_TYPE); gen(sizeExpression, Type.INT_TYPE);
newArrayInstruction(arrayType); newArrayInstruction(arrayType);
return Unit.INSTANCE; return Unit.INSTANCE;
}
}); });
} }
@@ -4478,13 +4380,10 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
@Override @Override
public StackValue visitThrowExpression(@NotNull KtThrowExpression expression, StackValue receiver) { public StackValue visitThrowExpression(@NotNull KtThrowExpression expression, StackValue receiver) {
return StackValue.operation(Type.VOID_TYPE, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(Type.VOID_TYPE, adapter -> {
@Override
public Unit invoke(InstructionAdapter adapter) {
gen(expression.getThrownExpression(), JAVA_THROWABLE_TYPE); gen(expression.getThrownExpression(), JAVA_THROWABLE_TYPE);
v.athrow(); v.athrow();
return Unit.INSTANCE; return Unit.INSTANCE;
}
}); });
} }
@@ -4514,9 +4413,7 @@ The "returned" value of try expression with no finally is either the last expres
Type expectedAsmType = isStatement ? Type.VOID_TYPE : expressionTypeForBranchingOperation(expression); Type expectedAsmType = isStatement ? Type.VOID_TYPE : expressionTypeForBranchingOperation(expression);
return StackValue.operation(expectedAsmType, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(expectedAsmType, v -> {
@Override
public Unit invoke(InstructionAdapter v) {
KtFinallySection finallyBlock = expression.getFinallyBlock(); KtFinallySection finallyBlock = expression.getFinallyBlock();
FinallyBlockStackElement finallyBlockStackElement = null; FinallyBlockStackElement finallyBlockStackElement = null;
if (finallyBlock != null) { if (finallyBlock != null) {
@@ -4627,7 +4524,6 @@ The "returned" value of try expression with no finally is either the last expres
blockStackElements.pop(); blockStackElements.pop();
} }
return Unit.INSTANCE; return Unit.INSTANCE;
}
}); });
} }
@@ -4665,9 +4561,7 @@ The "returned" value of try expression with no finally is either the last expres
StackValue value = genQualified(receiver, left); StackValue value = genQualified(receiver, left);
return StackValue.operation(boxType(asmType(rightType)), new Function1<InstructionAdapter, Unit>() { return StackValue.operation(boxType(asmType(rightType)), v -> {
@Override
public Unit invoke(InstructionAdapter v) {
value.put(boxType(value.type), v); value.put(boxType(value.type), v);
if (value.type == Type.VOID_TYPE) { if (value.type == Type.VOID_TYPE) {
@@ -4687,7 +4581,6 @@ The "returned" value of try expression with no finally is either the last expres
CodegenUtilKt.generateAsCast(v, rightType, type, safeAs); CodegenUtilKt.generateAsCast(v, rightType, type, safeAs);
return Unit.INSTANCE; return Unit.INSTANCE;
}
}); });
} }
@@ -4729,9 +4622,7 @@ The "returned" value of try expression with no finally is either the last expres
} }
private StackValue generateIsCheck(StackValue expressionToGen, KotlinType kotlinType, boolean leaveExpressionOnStack) { private StackValue generateIsCheck(StackValue expressionToGen, KotlinType kotlinType, boolean leaveExpressionOnStack) {
return StackValue.operation(Type.BOOLEAN_TYPE, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(Type.BOOLEAN_TYPE, v -> {
@Override
public Unit invoke(InstructionAdapter v) {
expressionToGen.put(OBJECT_TYPE, v); expressionToGen.put(OBJECT_TYPE, v);
if (leaveExpressionOnStack) { if (leaveExpressionOnStack) {
v.dup(); v.dup();
@@ -4746,7 +4637,6 @@ The "returned" value of try expression with no finally is either the last expres
CodegenUtilKt.generateIsCheck(v, kotlinType, type); CodegenUtilKt.generateIsCheck(v, kotlinType, type);
return null; return null;
}
}); });
} }
@@ -4790,12 +4680,9 @@ The "returned" value of try expression with no finally is either the last expres
Type resultType = isStatement ? Type.VOID_TYPE : expressionTypeForBranchingOperation(expression); Type resultType = isStatement ? Type.VOID_TYPE : expressionTypeForBranchingOperation(expression);
return StackValue.operation(resultType, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(resultType, v -> {
@Override
public Unit invoke(InstructionAdapter v) {
SwitchCodegen switchCodegen = SwitchCodegenUtil.buildAppropriateSwitchCodegenIfPossible( SwitchCodegen switchCodegen = SwitchCodegenUtil.buildAppropriateSwitchCodegenIfPossible(
expression, isStatement, CodegenUtil.isExhaustive(bindingContext, expression, isStatement), expression, isStatement, CodegenUtil.isExhaustive(bindingContext, expression, isStatement), this
ExpressionCodegen.this
); );
if (switchCodegen != null) { if (switchCodegen != null) {
switchCodegen.generate(); switchCodegen.generate();
@@ -4851,7 +4738,6 @@ The "returned" value of try expression with no finally is either the last expres
myFrameMap.leaveTemp(subjectType); myFrameMap.leaveTemp(subjectType);
tempVariables.remove(expr); tempVariables.remove(expr);
return null; return null;
}
}); });
} }
@@ -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,9 +276,7 @@ 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
public Unit invoke(InstructionAdapter adapter) {
Method interfaceMethod = typeMapper.mapAsmMethod(functionDescriptor, OwnerKind.IMPLEMENTATION); Method interfaceMethod = typeMapper.mapAsmMethod(functionDescriptor, OwnerKind.IMPLEMENTATION);
Type type = typeMapper.mapOwner(functionDescriptor); Type type = typeMapper.mapOwner(functionDescriptor);
generateDelegateToMethodBody( generateDelegateToMethodBody(
@@ -291,7 +288,6 @@ public class FunctionCodegen {
); );
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>() {
@Override
public String invoke(VariableDescriptor descriptor) {
// stub for anonymous destructuring declaration entry // stub for anonymous destructuring declaration entry
if (descriptor.getName().isSpecial()) return "$_$"; return StringsKt.join(
return descriptor.getName().asString(); CollectionsKt.map(variables, descriptor -> descriptor.getName().isSpecial() ? "$_$" : 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,11 +848,9 @@ 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
public String fun(ConstantValue<?> constant) {
if (constant instanceof KClassValue) { if (constant instanceof KClassValue) {
KClassValue classValue = (KClassValue) constant; KClassValue classValue = (KClassValue) constant;
ClassDescriptor classDescriptor = DescriptorUtils.getClassDescriptorForType(classValue.getValue()); ClassDescriptor classDescriptor = DescriptorUtils.getClassDescriptorForType(classValue.getValue());
@@ -874,7 +858,6 @@ public class FunctionCodegen {
} }
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
public StackValue genValue(ValueParameterDescriptor valueParameter, ExpressionCodegen codegen) {
assert ((ClassDescriptor) function.getContainingDeclaration()).isData() assert ((ClassDescriptor) function.getContainingDeclaration()).isData()
: "Function container must have [data] modifier: " + function; : "Function container must have [data] modifier: " + function;
PropertyDescriptor property = bindingContext.get(BindingContext.VALUE_PARAMETER_AS_PROPERTY, valueParameter); PropertyDescriptor property = bindingContext.get(BindingContext.VALUE_PARAMETER_AS_PROPERTY, valueParameter);
assert property != null : "Copy function doesn't correspond to any property: " + function; assert property != null : "Copy function doesn't correspond to any property: " + function;
return codegen.intermediateValueForProperty(property, false, null, StackValue.LOCAL_0); return codegen.intermediateValueForProperty(property, false, null, StackValue.LOCAL_0);
}
}, },
null null
); );
@@ -785,13 +779,10 @@ 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(),
}
});
MethodVisitor mv = v.newMethod(JvmDeclarationOriginKt.OtherOrigin(myClass, valueOfFunction), ACC_PUBLIC | ACC_STATIC, ENUM_VALUE_OF.asString(),
"(Ljava/lang/String;)" + classAsmType.getDescriptor(), null, null); "(Ljava/lang/String;)" + classAsmType.getDescriptor(), null, null);
if (!state.getClassBuilderMode().generateBodies) return; if (!state.getClassBuilderMode().generateBodies) return;
@@ -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
public Unit invoke(AnnotationVisitor av) {
writeAnnotationData(av, serializer, classProto); writeAnnotationData(av, serializer, classProto);
return Unit.INSTANCE; 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
public Unit invoke(AnnotationVisitor av) {
writeAnnotationData(av, serializer, packageProto); writeAnnotationData(av, serializer, packageProto);
return Unit.INSTANCE; 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
public Unit invoke(InstructionAdapter v) {
v.visitFieldInsn(GETSTATIC, UNIT_TYPE.getInternalName(), JvmAbi.INSTANCE_FIELD, UNIT_TYPE.getDescriptor()); v.visitFieldInsn(GETSTATIC, UNIT_TYPE.getInternalName(), JvmAbi.INSTANCE_FIELD, UNIT_TYPE.getDescriptor());
return null; 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
public MethodVisitor invoke() {
return builder.newMethod(
NO_ORIGIN, original.access, original.name, original.desc, original.signature, NO_ORIGIN, original.access, original.name, original.desc, original.signature,
ArrayUtil.toStringArray(original.exceptions) 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,16 +271,13 @@ 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
public SMAPAndMethodNode invoke() {
SMAPAndMethodNode result = doCreateMethodNodeFromCompiled(directMember, state, asmMethod); SMAPAndMethodNode result = doCreateMethodNodeFromCompiled(directMember, state, asmMethod);
if (result == null) { if (result == null) {
throw new IllegalStateException("Couldn't obtain compiled function body for " + functionDescriptor); throw new IllegalStateException("Couldn't obtain compiled function body for " + functionDescriptor);
} }
return result; return result;
} }
}
); );
return resultInCache.copyWithNewNode(cloneMethodNode(resultInCache.getNode())); return resultInCache.copyWithNewNode(cloneMethodNode(resultInCache.getNode()));
@@ -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,9 +323,7 @@ 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
public byte[] invoke() {
VirtualFile file = InlineCodegenUtil.findVirtualFile(state, containerId); VirtualFile file = InlineCodegenUtil.findVirtualFile(state, containerId);
if (file == null) { if (file == null) {
throw new IllegalStateException("Couldn't find declaration file for " + containerId); throw new IllegalStateException("Couldn't find declaration file for " + containerId);
@@ -345,10 +334,8 @@ public class InlineCodegen extends CallGenerator {
catch (IOException e) { catch (IOException e) {
throw new RuntimeException(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,9 +740,7 @@ public class InlineCodegen extends CallGenerator {
} }
} }
Runnable runnable = new Runnable() { Runnable runnable = () -> {
@Override
public void run() {
for (int i = infos.length - 1; i >= 0; i--) { for (int i = infos.length - 1; i >= 0; i--) {
ParameterInfo info = infos[i]; ParameterInfo info = infos[i];
if (!info.isSkippedOrRemapped()) { if (!info.isSkippedOrRemapped()) {
@@ -774,7 +753,6 @@ public class InlineCodegen extends CallGenerator {
} }
} }
} }
}
}; };
if (delayedWritingToLocals) return runnable; if (delayedWritingToLocals) return runnable;
@@ -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
public boolean isMyLabel(@NotNull String name) {
throw new RuntimeException("This operation not applicable for current context"); 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
public Boolean invoke(BasicValue input) {
if (input == StrictBasicValue.UNINITIALIZED_VALUE) return false; if (input == StrictBasicValue.UNINITIALIZED_VALUE) return false;
if (!(input instanceof BoxedBasicValue)) return true; 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) {
writeGenericType(kotlinType, type, signatureVisitor, mode);
return Unit.INSTANCE; 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
public int compare(String o1, String o2) {
if (o1 == o2) return 0; if (o1 == o2) return 0;
if (o1 == null) return -1; if (o1 == null) return -1;
if (o2 == null) return 1; if (o2 == null) return 1;
return o1.compareTo(o2); 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
public String fun(@Nullable KtFile file) {
assert file != null;
VirtualFile virtualFile = file.getVirtualFile(); VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile != null) { if (virtualFile != null) {
return FileUtil.toSystemDependentName(virtualFile.getPath()); 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,9 +185,7 @@ 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
public Unit invoke(File file) {
if (file.isFile()) { if (file.isFile()) {
VirtualFile originalVirtualFile = localFileSystem.findFileByPath(file.getAbsolutePath()); VirtualFile originalVirtualFile = localFileSystem.findFileByPath(file.getAbsolutePath());
VirtualFile virtualFile = originalVirtualFile != null ? virtualFileCreator.create(originalVirtualFile) : null; VirtualFile virtualFile = originalVirtualFile != null ? virtualFileCreator.create(originalVirtualFile) : null;
@@ -200,7 +198,6 @@ public class CompileEnvironmentUtil {
} }
} }
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,10 +27,8 @@ 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
public String render(@NotNull ConflictingJvmDeclarationsData data, @NotNull RenderingContext context) {
List<DeclarationDescriptor> renderedDescriptors = new ArrayList<DeclarationDescriptor>(); List<DeclarationDescriptor> renderedDescriptors = new ArrayList<DeclarationDescriptor>();
for (JvmDeclarationOrigin origin : data.getSignatureOrigins()) { for (JvmDeclarationOrigin origin : data.getSignatureOrigins()) {
DeclarationDescriptor descriptor = origin.getDescriptor(); DeclarationDescriptor descriptor = origin.getDescriptor();
@@ -46,7 +44,6 @@ public class DefaultErrorMessagesJvm implements DefaultErrorMessages.Extension {
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");
@@ -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,10 +127,9 @@ 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) {
@@ -143,7 +139,7 @@ public class SignaturesPropagationData {
ValueParameterDescriptor parameter = superFunction.getValueParameters().get(index); ValueParameterDescriptor parameter = superFunction.getValueParameters().get(index);
return new TypeAndName(parameter.getType(), parameter.getName()); 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
public int compare(@NotNull FunctionDescriptor fun1, @NotNull FunctionDescriptor fun2) {
FqNameUnsafe fqName1 = getFqName(fun1.getContainingDeclaration()); FqNameUnsafe fqName1 = getFqName(fun1.getContainingDeclaration());
FqNameUnsafe fqName2 = getFqName(fun2.getContainingDeclaration()); FqNameUnsafe fqName2 = getFqName(fun2.getContainingDeclaration());
return fqName1.asString().compareTo(fqName2.asString()); 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,9 +54,7 @@ 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
public int compare(@NotNull ActualDiagnostic o1, @NotNull ActualDiagnostic o2) {
List<TextRange> ranges1 = o1.diagnostic.getTextRanges(); List<TextRange> ranges1 = o1.diagnostic.getTextRanges();
List<TextRange> ranges2 = o2.diagnostic.getTextRanges(); List<TextRange> ranges2 = o2.diagnostic.getTextRanges();
int minNumberOfRanges = ranges1.size() < ranges2.size() ? ranges1.size() : ranges2.size(); int minNumberOfRanges = ranges1.size() < ranges2.size() ? ranges1.size() : ranges2.size();
@@ -78,7 +75,6 @@ public class CheckerTestUtil {
} }
} }
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
public int compare(@NotNull DiagnosticDescriptor d1, @NotNull DiagnosticDescriptor d2) {
// Start early -- go first; start at the same offset, the one who end later is the outer, i.e. goes first // 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 (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
public int compare(@NotNull TextRange o1, @NotNull TextRange o2) {
if (o1.getStartOffset() != o2.getStartOffset()) { if (o1.getStartOffset() != o2.getStartOffset()) {
return o1.getStartOffset() - o2.getStartOffset(); return o1.getStartOffset() - o2.getStartOffset();
} }
return o1.getEndOffset() - o2.getEndOffset(); return o1.getEndOffset() - o2.getEndOffset();
}
}; };
private DiagnosticUtils() { private DiagnosticUtils() {
@@ -163,9 +160,7 @@ 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
public int compare(@NotNull Diagnostic d1, @NotNull Diagnostic d2) {
String path1 = d1.getPsiFile().getViewProvider().getVirtualFile().getPath(); String path1 = d1.getPsiFile().getViewProvider().getVirtualFile().getPath();
String path2 = d2.getPsiFile().getViewProvider().getVirtualFile().getPath(); String path2 = d2.getPsiFile().getViewProvider().getVirtualFile().getPath();
if (!path1.equals(path2)) return path1.compareTo(path2); if (!path1.equals(path2)) return path1.compareTo(path2);
@@ -178,7 +173,6 @@ public class DiagnosticUtils {
} }
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
public List<DiagnosticFactoryToRendererMap> invoke(List<? extends Extension> extensions) {
List<DiagnosticFactoryToRendererMap> result = new ArrayList<DiagnosticFactoryToRendererMap>(extensions.size() + 1); List<DiagnosticFactoryToRendererMap> result = new ArrayList<DiagnosticFactoryToRendererMap>(extensions.size() + 1);
for (Extension extension : extensions) { for (Extension extension : extensions) {
result.add(extension.getMap()); result.add(extension.getMap());
} }
result.add(MAP); result.add(MAP);
return result; return result;
}
}); });
@NotNull @NotNull
@@ -133,10 +123,7 @@ 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
@Override
public String[] render(@NotNull TypeMismatchDueToTypeProjectionsData object) {
RenderingContext context = RenderingContext context =
of(object.getExpectedType(), object.getExpressionType(), object.getReceiverType(), object.getCallableDescriptor()); of(object.getExpectedType(), object.getExpressionType(), object.getReceiverType(), object.getCallableDescriptor());
return new String[] { return new String[] {
@@ -145,7 +132,6 @@ public class DefaultErrorMessages {
RENDER_TYPE.render(object.getReceiverType(), context), RENDER_TYPE.render(object.getReceiverType(), context),
FQ_NAMES_IN_TYPES.render(object.getCallableDescriptor(), 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,10 +184,7 @@ 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
@Override
public String render(@NotNull BadNamedArgumentsTarget target, @NotNull RenderingContext context) {
switch (target) { switch (target) {
case NON_KOTLIN_FUNCTION: case NON_KOTLIN_FUNCTION:
return "non-Kotlin functions"; return "non-Kotlin functions";
@@ -212,7 +195,6 @@ public class DefaultErrorMessages {
default: default:
throw new AssertionError(target); throw new AssertionError(target);
} }
}
}); });
MAP.put(VARARG_OUTSIDE_PARENTHESES, "Passing value as a vararg is only allowed inside a parenthesized argument list"); MAP.put(VARARG_OUTSIDE_PARENTHESES, "Passing value as a vararg is only allowed inside a parenthesized argument list");
@@ -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
@Override
public String render(@NotNull Pair<LanguageVersion, String> pair, @NotNull RenderingContext renderingContext) {
String message = pair.getSecond(); String message = pair.getSecond();
return pair.getFirst().getVersionString() + (message != null ? ". " + message : ""); 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) {
return "The binary version of its metadata is " + incompatibility.getActualVersion() +
", expected version is " + incompatibility.getExpectedVersion() + ".\n" + ", expected version is " + incompatibility.getExpectedVersion() + ".\n" +
"The class is loaded from " + FileUtil.toSystemIndependentName(incompatibility.getFilePath()); "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
@Override
public String render(@NotNull KtExpression expression, @NotNull RenderingContext context) {
String expressionType = expression.toString(); String expressionType = expression.toString();
return expressionType.substring(0, 1) + return expressionType.substring(0, 1) +
expressionType.substring(1).toLowerCase(); 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
@Override
public String render(@NotNull KtTypeConstraint typeConstraint, @NotNull RenderingContext context) {
//noinspection ConstantConditions //noinspection ConstantConditions
return typeConstraint.getSubjectTypeParameterName().getReferencedName(); 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,10 +594,7 @@ 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
@Override
public String[] render(@NotNull VarianceConflictDiagnosticData data) {
RenderingContext context = RenderingContext context =
of(data.getTypeParameter(), data.getTypeParameter().getVariance(), data.getOccurrencePosition(), of(data.getTypeParameter(), data.getTypeParameter().getVariance(), data.getOccurrencePosition(),
data.getContainingType()); data.getContainingType());
@@ -650,7 +604,6 @@ public class DefaultErrorMessages {
RENDER_POSITION_VARIANCE.render(data.getOccurrencePosition(), context), RENDER_POSITION_VARIANCE.render(data.getOccurrencePosition(), context),
RENDER_TYPE.render(data.getContainingType(), 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
@Override
public String render(@NotNull KtSimpleNameExpression nameExpression, @NotNull RenderingContext context) {
//noinspection ConstantConditions //noinspection ConstantConditions
return nameExpression.getReferencedName(); 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
@Override
public String render(@NotNull KotlinType type, @NotNull RenderingContext context) {
if (type.isError()) return ""; if (type.isError()) return "";
return " of type '" + RENDER_TYPE.render(type, context) + "'"; return " of type '" + RENDER_TYPE.render(type, context) + "'";
}
});
MAP.put(FUNCTION_CALL_EXPECTED, "Function invocation ''{0}({1})'' expected", ELEMENT_TEXT, new DiagnosticParameterRenderer<Boolean>() {
@NotNull
@Override
public String render(@NotNull Boolean hasValueParameters, @NotNull RenderingContext context) {
return hasValueParameters ? "..." : "";
}
}); });
MAP.put(FUNCTION_CALL_EXPECTED, "Function invocation ''{0}({1})'' expected", ELEMENT_TEXT,
(hasValueParameters, context) -> 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;
@@ -263,14 +262,7 @@ public class KtFile extends PsiFileBase implements KtDeclarationContainer, KtAnn
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
@Override
public PsiT[] create(int count) {
if (count == 0) { if (count == 0) {
return emptyArray; return emptyArray;
} }
//noinspection unchecked //noinspection unchecked
return (PsiT[]) Array.newInstance(psiClass, count); 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
public Void invoke(WritableSlice slice, Object key, Object value) {
if (filter == null || filter.accept(slice, key)) { if (filter == null || filter.accept(slice, key)) {
trace.record(slice, key, value); 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);
}
},
new Function1<LexicalScope, LexicalScope>() {
@Override
public LexicalScope invoke(LexicalScope scope) {
return new LexicalScopeImpl(
scope, descriptor, scope.isOwnerDescriptorAccessibleByLabel(), scope.getImplicitReceiver(), scope, descriptor, scope.isOwnerDescriptorAccessibleByLabel(), scope.getImplicitReceiver(),
LexicalScopeKind.CONSTRUCTOR_HEADER); 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
public void handleRecord(
WritableSlice<KtReferenceExpression, DeclarationDescriptor> slice,
KtReferenceExpression expression,
DeclarationDescriptor descriptor
) {
if (expression instanceof KtSimpleNameExpression && if (expression instanceof KtSimpleNameExpression &&
descriptor instanceof SyntheticFieldDescriptor) { descriptor instanceof SyntheticFieldDescriptor) {
trace.record(BindingContext.BACKING_FIELD_REQUIRED, trace.record(BindingContext.BACKING_FIELD_REQUIRED,
propertyDescriptor); propertyDescriptor);
} }
} }
}); );
} }
private void resolvePropertyDelegate( private void resolvePropertyDelegate(
@@ -850,12 +831,9 @@ 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
public Unit invoke(LexicalScopeImpl.InitializeHandler handler) {
handler.addVariableDescriptor(fieldDescriptor); handler.addVariableDescriptor(fieldDescriptor);
return Unit.INSTANCE; return Unit.INSTANCE;
}
}); });
// Check parameter name shadowing // Check parameter name shadowing
for (KtParameter parameter : function.getValueParameters()) { for (KtParameter parameter : function.getValueParameters()) {
@@ -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,9 +333,7 @@ public class DescriptorResolver {
TuplesKt.to(LanguageFeature.DestructuringLambdaParameters, languageVersionSettings))); TuplesKt.to(LanguageFeature.DestructuringLambdaParameters, languageVersionSettings)));
} }
destructuringVariables = new Function0<List<VariableDescriptor>>() { destructuringVariables = () -> {
@Override
public List<VariableDescriptor> invoke() {
assert owner.getDispatchReceiverParameter() == null assert owner.getDispatchReceiverParameter() == null
: "Destructuring declarations are only be parsed for lambdas, and they must not have a dispatch receiver"; : "Destructuring declarations are only be parsed for lambdas, and they must not have a dispatch receiver";
LexicalScope scopeForDestructuring = LexicalScope scopeForDestructuring =
@@ -354,7 +350,6 @@ public class DescriptorResolver {
modifiersChecker.withTrace(trace).checkModifiersForDestructuringDeclaration(destructuringDeclaration); modifiersChecker.withTrace(trace).checkModifiersForDestructuringDeclaration(destructuringDeclaration);
return result; return result;
}
}; };
} }
else { else {
@@ -460,14 +455,11 @@ 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
public Void invoke(KotlinType type) {
if (!(containingDescriptor instanceof TypeAliasDescriptor)) { if (!(containingDescriptor instanceof TypeAliasDescriptor)) {
trace.report(Errors.CYCLIC_GENERIC_UPPER_BOUND.on(typeParameter)); trace.report(Errors.CYCLIC_GENERIC_UPPER_BOUND.on(typeParameter));
} }
return null; return null;
}
}, },
supertypeLoopsResolver supertypeLoopsResolver
); );
@@ -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
public KotlinType invoke() {
PreliminaryDeclarationVisitor.Companion.createForDeclaration(function, trace); PreliminaryDeclarationVisitor.Companion.createForDeclaration(function, trace);
KotlinType type = expressionTypingServices.getBodyExpressionType( KotlinType type = expressionTypingServices.getBodyExpressionType(
trace, scope, dataFlowInfo, function, functionDescriptor); trace, scope, dataFlowInfo, function, functionDescriptor);
KotlinType result = transformAnonymousTypeIfNeeded(functionDescriptor, function, type, trace); KotlinType result = transformAnonymousTypeIfNeeded(functionDescriptor, function, type, trace);
functionsTypingVisitor.checkTypesForReturnStatements(function, trace, result); functionsTypingVisitor.checkTypesForReturnStatements(function, trace, result);
return 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,12 +65,10 @@ 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
public Unit invoke(LexicalScopeImpl.InitializeHandler handler) {
for (TypeParameterDescriptor typeParameter : descriptor.getTypeParameters()) { for (TypeParameterDescriptor typeParameter : descriptor.getTypeParameters()) {
handler.addClassifierDescriptor(typeParameter); handler.addClassifierDescriptor(typeParameter);
} }
@@ -90,7 +87,7 @@ public class FunctionDescriptorUtil {
} }
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() {
ResolutionTask<D> resolutionTask = new ResolutionTask<D>(
kind, name, null
);
return doResolveCallOrGetCachedResults(context, resolutionTask, tracing); 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,9 +489,7 @@ 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
public OverloadResolutionResults<FunctionDescriptor> invoke() {
BasicCallResolutionContext basicCallResolutionContext = BasicCallResolutionContext basicCallResolutionContext =
BasicCallResolutionContext.create(context, call, CheckArgumentTypesMode.CHECK_VALUE_ARGUMENTS, dataFlowInfoForArguments); BasicCallResolutionContext.create(context, call, CheckArgumentTypesMode.CHECK_VALUE_ARGUMENTS, dataFlowInfoForArguments);
@@ -511,9 +500,7 @@ public class CallResolver {
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,9 +252,7 @@ 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
public ClassDescriptor fun(KtClassLikeInfo classLikeInfo) {
if (classLikeInfo instanceof KtClassOrObjectInfo) { if (classLikeInfo instanceof KtClassOrObjectInfo) {
//noinspection RedundantCast //noinspection RedundantCast
return getClassDescriptor(((KtClassOrObjectInfo) classLikeInfo).getCorrespondingClassOrObject(), location); return getClassDescriptor(((KtClassOrObjectInfo) classLikeInfo).getCorrespondingClassOrObject(), location);
@@ -287,17 +266,11 @@ public class ResolveSession implements KotlinCodeAnalyzer, LazyClassContext {
); );
} }
} }
}
)); ));
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,36 +215,18 @@ 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(() -> {
});
this.extraCompanionObjectDescriptors = storageManager.createMemoizedFunction(new Function1<KtObjectDeclaration, ClassDescriptor>() {
@Override
public ClassDescriptor invoke(KtObjectDeclaration companionObject) {
return computeCompanionObjectDescriptor(companionObject);
}
});
this.forceResolveAllContents = storageManager.createRecursionTolerantNullableLazyValue(new Function0<Void>() {
@Override
public Void invoke() {
doForceResolveAllContents(); doForceResolveAllContents();
return null; 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() {
return getOuterScope();
}
});
this.parameters = c.getStorageManager().createLazyValue(new Function0<List<TypeParameterDescriptor>>() { this.parameters = c.getStorageManager().createLazyValue(() -> {
@Override
public List<TypeParameterDescriptor> invoke() {
KtClassLikeInfo classInfo = declarationProvider.getOwnerInfo(); KtClassLikeInfo classInfo = declarationProvider.getOwnerInfo();
KtTypeParameterList typeParameterList = classInfo.getTypeParameterList(); KtTypeParameterList typeParameterList = classInfo.getTypeParameterList();
if (typeParameterList == null) return Collections.emptyList(); if (typeParameterList == null) return Collections.emptyList();
@@ -274,29 +244,20 @@ public class LazyClassDescriptor extends ClassDescriptorBase implements ClassDes
List<TypeParameterDescriptor> parameters = new ArrayList<TypeParameterDescriptor>(typeParameters.size()); List<TypeParameterDescriptor> parameters = new ArrayList<TypeParameterDescriptor>(typeParameters.size());
for (int i = 0; i < typeParameters.size(); i++) { for (int i = 0; i < typeParameters.size(); i++) {
parameters.add(new LazyTypeParameterDescriptor(c, LazyClassDescriptor.this, typeParameters.get(i), i)); parameters.add(new LazyTypeParameterDescriptor(c, this, typeParameters.get(i), i));
} }
return parameters; return parameters;
}
}); });
this.scopeForInitializerResolution = storageManager.createLazyValue(new Function0<LexicalScope>() { this.scopeForInitializerResolution = storageManager.createLazyValue(
@Override () -> ClassResolutionScopesSupportKt.scopeForInitializerResolution(
public LexicalScope invoke() { this, createInitializerScopeParent(), classLikeInfo.getPrimaryConstructorParameters()
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 // TODO: only consider classes from the same file, not the whole package fragment
return DescriptorUtilsKt.computeSealedSubclasses(LazyClassDescriptor.this); this.sealedSubclasses = storageManager.createLazyValue(() -> DescriptorUtilsKt.computeSealedSubclasses(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
public KotlinType invoke(TypeProjection projection) {
if (projection.isStarProjection()) { if (projection.isStarProjection()) {
// any type is good enough for depth here // any type is good enough for depth here
return type.getConstructor().getBuiltIns().getAnyType(); return type.getConstructor().getBuiltIns().getAnyType();
} }
return projection.getType(); return projection.getType();
}
})); }));
} }
@@ -336,10 +332,7 @@ public class CommonSupertypes {
) { ) {
return DFS.dfs( return DFS.dfs(
Collections.singletonList(type), Collections.singletonList(type),
new DFS.Neighbors<SimpleType>() { current -> {
@NotNull
@Override
public Iterable<? extends SimpleType> getNeighbors(SimpleType current) {
TypeSubstitutor substitutor = TypeSubstitutor.create(current); TypeSubstitutor substitutor = TypeSubstitutor.create(current);
Collection<KotlinType> supertypes = current.getConstructor().getSupertypes(); Collection<KotlinType> supertypes = current.getConstructor().getSupertypes();
List<SimpleType> result = new ArrayList<SimpleType>(supertypes.size()); List<SimpleType> result = new ArrayList<SimpleType>(supertypes.size());
@@ -350,14 +343,8 @@ public class CommonSupertypes {
result.add(FlexibleTypesKt.lowerIfFlexible(substitutor.safeSubstitute(supertype, Variance.INVARIANT))); result.add(FlexibleTypesKt.lowerIfFlexible(substitutor.safeSubstitute(supertype, Variance.INVARIANT)));
} }
return result; return result;
}
},
new DFS.Visited<SimpleType>() {
@Override
public boolean checkAndMarkVisited(SimpleType current) {
return visited.add(current.getConstructor());
}
}, },
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>() {
@Override
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(); if (firstTime) throw new ReenteringLazyValueComputationException();
return ErrorUtils.createErrorType("Recursive dependency"); 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,9 +173,7 @@ 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
public Unit invoke(TypeParameterUsage parameterUsage) {
Variance howTheTypeIsUsedBefore = parameters.get(parameterUsage.typeParameterDescriptor); Variance howTheTypeIsUsedBefore = parameters.get(parameterUsage.typeParameterDescriptor);
if (howTheTypeIsUsedBefore == null) { if (howTheTypeIsUsedBefore == null) {
howTheTypeIsUsedBefore = Variance.INVARIANT; howTheTypeIsUsedBefore = Variance.INVARIANT;
@@ -184,7 +181,6 @@ public class TypeIntersector {
parameters.put(parameterUsage.typeParameterDescriptor, parameters.put(parameterUsage.typeParameterDescriptor,
parameterUsage.howTheTypeParameterIsUsed.superpose(howTheTypeIsUsedBefore)); parameterUsage.howTheTypeParameterIsUsed.superpose(howTheTypeIsUsedBefore));
return Unit.INSTANCE; 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 = ObservableBindingTrace traceAdapter = new ObservableBindingTrace(temporaryTrace);
new ObservableBindingTrace.RecordHandler<PsiElement, ClassDescriptor>() { traceAdapter.addHandler(CLASS, (slice, declaration, descriptor) -> {
@Override
public void handleRecord(
WritableSlice<PsiElement, ClassDescriptor> slice,
PsiElement declaration,
ClassDescriptor descriptor
) {
if (slice == CLASS && declaration == expression.getObjectDeclaration()) { if (slice == CLASS && declaration == expression.getObjectDeclaration()) {
KotlinType defaultType = components.wrappedTypeFactory.createRecursionIntolerantDeferredType( result[0] = components.wrappedTypeFactory.createRecursionIntolerantDeferredType(context.trace, descriptor::getDefaultType);
context.trace,
new Function0<KotlinType>() {
@Override
public KotlinType invoke() {
return descriptor.getDefaultType();
} }
}); });
result[0] = defaultType;
}
}
};
ObservableBindingTrace traceAdapter = new ObservableBindingTrace(temporaryTrace);
traceAdapter.addHandler(CLASS, handler);
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
public boolean accept(@Nullable WritableSlice<?, ?> slice, Object key) {
// the type of the right (and sometimes left) expression isn't 'Any?' actually // the type of the right (and sometimes left) expression isn't 'Any?' actually
if ((key == right || key == left) && slice == EXPRESSION_TYPE_INFO) return false; if ((key == right || key == left) && slice == EXPRESSION_TYPE_INFO) return false;
return true; 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,9 +168,7 @@ 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
public KotlinTypeInfo invoke() {
try { try {
KotlinTypeInfo recordedTypeInfo = BindingContextUtils.getRecordedTypeInfo(expression, context.trace.getBindingContext()); KotlinTypeInfo recordedTypeInfo = BindingContextUtils.getRecordedTypeInfo(expression, context.trace.getBindingContext());
if (recordedTypeInfo != null) { if (recordedTypeInfo != null) {
@@ -227,7 +224,6 @@ public abstract class ExpressionTypingVisitorDispatcher extends KtVisitor<Kotlin
context 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
public Void invoke(WritableSlice slice, Object key, Object value) {
f.invoke(((SliceWithStackTrace) slice).getWritableDelegate(), key, ((TrackableValue<?>) value).value); f.invoke(((SliceWithStackTrace) slice).getWritableDelegate(), key, ((TrackableValue<?>) value).value);
return null; 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
public boolean value(PsiFile input) {
if (!(input instanceof KtFile)) { if (!(input instanceof KtFile)) {
return true; 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
public int compare(@NotNull PsiElement o1, @NotNull PsiElement o2) {
VirtualFile f1 = PsiUtilCore.getVirtualFile(o1); VirtualFile f1 = PsiUtilCore.getVirtualFile(o1);
VirtualFile f2 = PsiUtilCore.getVirtualFile(o2); VirtualFile f2 = PsiUtilCore.getVirtualFile(o2);
if (f1 == f2) return 0; if (f1 == f2) return 0;
if (f1 == null) return -1; if (f1 == null) return -1;
if (f2 == null) return 1; if (f2 == null) return 1;
return searchScope.compare(f2, f1); 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,9 +211,7 @@ 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
public void dump(PrintStream out) {
out.println("<<< " + instrumenter + ": " + interceptor.getClass().getName() + " says:"); out.println("<<< " + instrumenter + ": " + interceptor.getClass().getName() + " says:");
try { try {
if (method.getParameterTypes().length == 0) { if (method.getParameterTypes().length == 0) {
@@ -232,7 +226,6 @@ public class InterceptionInstrumenter {
} }
out.println(">>>"); out.println(">>>");
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
public void run() {
if (options.measure) { if (options.measure) {
System.out.println(); System.out.println();
System.out.println("=== Preloader's measurements: "); System.out.println("=== Preloader's measurements: ");
System.out.format("Total time: %.3fs\n", (System.nanoTime() - startTime) / 1e9); 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
public Unit invoke(LexicalScopeImpl.InitializeHandler handler) {
for (TypeParameterDescriptor typeParameterDescriptor : propertyDescriptor.getTypeParameters()) { for (TypeParameterDescriptor typeParameterDescriptor : propertyDescriptor.getTypeParameters()) {
handler.addClassifierDescriptor(typeParameterDescriptor); 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
public boolean process(File file) {
if (file.isFile() && FilesKt.getExtension(file).equals(JavaFileType.DEFAULT_EXTENSION)) { if (file.isFile() && FilesKt.getExtension(file).equals(JavaFileType.DEFAULT_EXTENSION)) {
javaFilePaths.add(file.getPath()); 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
public boolean process(File file) {
if (file.getName().endsWith(".kt")) { if (file.getName().endsWith(".kt")) {
sourceFiles.add(relativePath(file)); sourceFiles.add(relativePath(file));
return true; return true;
} }
return true; return true;
} }, file -> !LIBRARY.equals(file.getName()));
}, new Processor<File>() {
@Override
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,16 +106,13 @@ 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
public KtFile invoke(File kotlinFile) {
try { try {
return KotlinTestUtils.createFile(kotlinFile.getName(), FileUtil.loadFile(kotlinFile, true), environment.getProject()); return KotlinTestUtils.createFile(kotlinFile.getName(), FileUtil.loadFile(kotlinFile, true), environment.getProject());
} }
catch (IOException e) { catch (IOException e) {
throw ExceptionUtilsKt.rethrow(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,16 +54,13 @@ 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
public Unit invoke(DescriptorRendererOptions options) {
options.setVerbose(true); options.setVerbose(true);
options.setAnnotationArgumentsRenderingPolicy(AnnotationArgumentsRenderingPolicy.UNLESS_EMPTY); options.setAnnotationArgumentsRenderingPolicy(AnnotationArgumentsRenderingPolicy.UNLESS_EMPTY);
options.setClassifierNamePolicy(ClassifierNamePolicy.SHORT.INSTANCE); options.setClassifierNamePolicy(ClassifierNamePolicy.SHORT.INSTANCE);
options.setModifiers(DescriptorRendererModifier.ALL); options.setModifiers(DescriptorRendererModifier.ALL);
return Unit.INSTANCE; return Unit.INSTANCE;
} }
}
); );
private static final String PATH = "compiler/testData/resolveAnnotations/testFile.kt"; private static final String PATH = "compiler/testData/resolveAnnotations/testFile.kt";
@@ -126,9 +122,7 @@ 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
public String fun(KtAnnotationEntry annotationEntry) {
AnnotationDescriptor annotationDescriptor = context.get(BindingContext.ANNOTATION, annotationEntry); AnnotationDescriptor annotationDescriptor = context.get(BindingContext.ANNOTATION, annotationEntry);
assertNotNull(annotationDescriptor); assertNotNull(annotationDescriptor);
@@ -140,7 +134,6 @@ public abstract class AbstractAnnotationDescriptorResolveTest extends KotlinTest
} }
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
public String fun(AnnotationWithTarget annotationWithTarget) {
AnnotationUseSiteTarget targetToRender = annotationWithTarget.getTarget(); AnnotationUseSiteTarget targetToRender = annotationWithTarget.getTarget();
if (targetToRender == defaultTarget) { if (targetToRender == defaultTarget) {
targetToRender = null; 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
public void run() {
ShutDownTracker.invokeAndWait(true, true, new Runnable() {
@Override
public void run() {
for (File victim : filesToDelete) { for (File victim : filesToDelete) {
FileUtil.delete(victim); 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
public boolean process(File file) {
if (file.isFile() && filenamePattern.matcher(file.getName()).matches() && isCompatibleTarget(targetBackend, file)) { if (file.isFile() && filenamePattern.matcher(file.getName()).matches() && isCompatibleTarget(targetBackend, file)) {
assertFilePathPresent(file, rootFile, filePaths); 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,11 +209,9 @@ 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
public void run() {
try { try {
KtUsefulTestCase.super.runTest(); super.runTest();
} }
catch (InvocationTargetException e) { catch (InvocationTargetException e) {
e.fillInStackTrace(); e.fillInStackTrace();
@@ -227,7 +224,6 @@ public abstract class KtUsefulTestCase extends TestCase {
catch (Throwable e) { catch (Throwable e) {
throwables[0] = e; throwables[0] = e;
} }
}
}; };
invokeTestRunnable(runnable); invokeTestRunnable(runnable);
@@ -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,9 +49,7 @@ 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
public Unit invoke(DescriptorRendererOptions options) {
options.setWithDefinedIn(false); options.setWithDefinedIn(false);
options.setExcludedAnnotationClasses(Collections.singleton(new FqName(ExpectedLoadErrorsUtil.ANNOTATION_CLASS_NAME))); options.setExcludedAnnotationClasses(Collections.singleton(new FqName(ExpectedLoadErrorsUtil.ANNOTATION_CLASS_NAME)));
options.setOverrideRenderingPolicy(OverrideRenderingPolicy.RENDER_OPEN_OVERRIDE); options.setOverrideRenderingPolicy(OverrideRenderingPolicy.RENDER_OPEN_OVERRIDE);
@@ -63,7 +60,6 @@ public class RecursiveDescriptorComparator {
options.setModifiers(DescriptorRendererModifier.ALL); options.setModifiers(DescriptorRendererModifier.ALL);
return Unit.INSTANCE; return Unit.INSTANCE;
} }
}
); );
public static final Configuration DONT_INCLUDE_METHODS_OF_OBJECT = new Configuration(false, false, false, false, public static final Configuration DONT_INCLUDE_METHODS_OF_OBJECT = new Configuration(false, false, false, false,
@@ -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
public PsiClass invoke(String s) {
try { try {
return createFinder(getEnvironment()).findClass(s, GlobalSearchScope.allScope(getEnvironment().getProject())); return createFinder(getEnvironment()).findClass(s, GlobalSearchScope.allScope(getEnvironment().getProject()));
} }
catch (IOException e) { catch (IOException e) {
throw ExceptionUtilsKt.rethrow(e); throw ExceptionUtilsKt.rethrow(e);
} }
} }, LightClassTestCommon.INSTANCE::removeEmptyDefaultImpls);
}, new Function1<String, String>() {
@Override
public String invoke(String s) {
return LightClassTestCommon.INSTANCE.removeEmptyDefaultImpls(s);
}
});
} }
@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,9 +35,7 @@ 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
public String invoke(Instruction instruction, Instruction next, Instruction prev) {
StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder();
Collection<Instruction> nextInstructions = instruction.getNextInstructions(); Collection<Instruction> nextInstructions = instruction.getNextInstructions();
@@ -51,7 +48,6 @@ public abstract class AbstractControlFlowTest extends AbstractPseudocodeTest {
result.append(" PREV:").append(formatInstructionList(previousInstructions)); result.append(" PREV:").append(formatInstructionList(previousInstructions));
} }
return result.toString(); 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,9 +46,7 @@ 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
public String invoke(Instruction instruction, Instruction next, Instruction prev) {
StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder();
Edges<InitControlFlowInfo> initializersEdges = variableInitializers.get(instruction); Edges<InitControlFlowInfo> initializersEdges = variableInitializers.get(instruction);
Edges<InitControlFlowInfo> previousInitializersEdges = variableInitializers.get(prev); Edges<InitControlFlowInfo> previousInitializersEdges = variableInitializers.get(prev);
@@ -65,7 +62,6 @@ public abstract class AbstractDataFlowTest extends AbstractPseudocodeTest {
result.append(dumpEdgesData(usePrefix, useStatusEdges)); result.append(dumpEdgesData(usePrefix, useStatusEdges));
} }
return result.toString(); 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,9 +129,7 @@ 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
public String invoke(String arg) {
if (arg.isEmpty()) { if (arg.isEmpty()) {
return null; return null;
} }
@@ -146,7 +143,6 @@ public abstract class AbstractCliTest extends TestCaseWithTmpdir {
return argsWithColonsReplaced return argsWithColonsReplaced
.replace("$TEMP_DIR$", tempDir) .replace("$TEMP_DIR$", tempDir)
.replace("$TESTDATA_DIR$", new File(argsFilePath).getParent()); .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,9 +48,7 @@ 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
public Unit invoke(DescriptorRendererOptions options) {
options.setWithDefinedIn(false); options.setWithDefinedIn(false);
options.setParameterNameRenderingPolicy(ParameterNameRenderingPolicy.NONE); options.setParameterNameRenderingPolicy(ParameterNameRenderingPolicy.NONE);
options.setVerbose(true); options.setVerbose(true);
@@ -57,7 +57,6 @@ public abstract class AbstractCompileJavaAgainstKotlinTest extends TestCaseWithT
options.setModifiers(DescriptorRendererModifier.ALL); options.setModifiers(DescriptorRendererModifier.ALL);
return Unit.INSTANCE; 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>() {
@Override
public Object invoke(String name, Object value) {
if (additionalTransformation != null) { if (additionalTransformation != null) {
Object result = additionalTransformation.invoke(name, value); Object result = additionalTransformation.invoke(fieldName, value);
if (result != null) return result; 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,9 +498,7 @@ 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
public Object invoke(String name, Object value) {
if (JvmAnnotationNames.METADATA_DATA_FIELD_NAME.equals(name)) { if (JvmAnnotationNames.METADATA_DATA_FIELD_NAME.equals(name)) {
String[] strings = (String[]) value; String[] strings = (String[]) value;
for (int i = 0; i < strings.length; i++) { for (int i = 0; i < strings.length; i++) {
@@ -523,22 +510,18 @@ public class CompileKotlinAgainstCustomBinariesTest extends TestCaseWithTmpdir {
} }
return null; return null;
} }
}
); );
} }
public void testWrongMetadataVersionBadMetadata2() throws Exception { public void testWrongMetadataVersionBadMetadata2() throws Exception {
doTestKotlinLibraryWithWrongMetadataVersion( doTestKotlinLibraryWithWrongMetadataVersion(
"library", "library",
new Function2<String, Object, Object>() { (name, value) -> {
@Override
public Object invoke(String name, Object value) {
if (JvmAnnotationNames.METADATA_STRINGS_FIELD_NAME.equals(name)) { if (JvmAnnotationNames.METADATA_STRINGS_FIELD_NAME.equals(name)) {
return ArrayUtil.EMPTY_STRING_ARRAY; return ArrayUtil.EMPTY_STRING_ARRAY;
} }
return null; return null;
} }
}
); );
} }
@@ -648,9 +631,7 @@ 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
public boolean process(File file) {
if (!file.isDirectory()) { if (!file.isDirectory()) {
File newFile = new File(library1, FilesKt.relativeTo(file, library2).getPath()); File newFile = new File(library1, FilesKt.relativeTo(file, library2).getPath());
if (!newFile.getParentFile().exists()) { if (!newFile.getParentFile().exists()) {
@@ -659,7 +640,6 @@ public class CompileKotlinAgainstCustomBinariesTest extends TestCaseWithTmpdir {
assert file.renameTo(newFile); assert file.renameTo(newFile);
} }
return true; 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,9 +65,7 @@ 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
public Unit invoke(DescriptorRendererOptions options) {
options.setWithDefinedIn(false); options.setWithDefinedIn(false);
options.setOverrideRenderingPolicy(OverrideRenderingPolicy.RENDER_OPEN_OVERRIDE); options.setOverrideRenderingPolicy(OverrideRenderingPolicy.RENDER_OPEN_OVERRIDE);
options.setVerbose(true); options.setVerbose(true);
@@ -74,7 +73,6 @@ public class LoadBuiltinsTest extends KotlinTestWithEnvironment {
options.setModifiers(DescriptorRendererModifier.ALL); options.setModifiers(DescriptorRendererModifier.ALL);
return Unit.INSTANCE; 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,20 +299,12 @@ public class StorageManagerTest extends TestCase {
return rec.invoke(); return rec.invoke();
} }
}, },
new Function1<Boolean, String>() { aBoolean -> "tolerant",
@Override s -> {
public String invoke(Boolean aBoolean) {
return "tolerant";
}
},
new Function1<String, Unit>() {
@Override
public Unit invoke(String s) {
counter.inc(); counter.inc();
assertEquals("tolerant", s); assertEquals("tolerant", s);
return Unit.INSTANCE; return Unit.INSTANCE;
} }
}
); );
} }
@@ -332,23 +317,17 @@ 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
public Collection<String> invoke() {
List<String> strings = new ArrayList<String>(); List<String> strings = new ArrayList<String>();
strings.add("first"); strings.add("first");
return strings; return strings;
}
}, },
null, null,
new Function1<Collection<String>, Unit>() { strings -> {
@Override
public Unit invoke(Collection<String> strings) {
counter.inc(); counter.inc();
strings.add("postComputed"); strings.add("postComputed");
return Unit.INSTANCE; return Unit.INSTANCE;
} }
}
); );
assertEquals(Arrays.asList("first", "postComputed"), v.invoke()); assertEquals(Arrays.asList("first", "postComputed"), v.invoke());
@@ -359,22 +338,16 @@ 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
public Collection<String> invoke() {
ArrayList<String> strings = new ArrayList<String>(); ArrayList<String> strings = new ArrayList<String>();
strings.add("first"); strings.add("first");
return strings; return strings;
}
}, },
new Function1<Collection<String>, Unit>() { strings -> {
@Override
public Unit invoke(Collection<String> strings) {
counter.inc(); counter.inc();
strings.add("postComputed"); strings.add("postComputed");
return Unit.INSTANCE; return Unit.INSTANCE;
} }
}
); );
assertEquals(Arrays.asList("first", "postComputed"), v.invoke()); assertEquals(Arrays.asList("first", "postComputed"), v.invoke());
@@ -392,22 +365,16 @@ public class StorageManagerTest extends TestCase {
return rec.invoke(); return rec.invoke();
} }
}, },
new Function1<Boolean, String>() { firstTime -> {
@Override
public String invoke(Boolean firstTime) {
if (firstTime) { if (firstTime) {
throw new ReenteringLazyValueComputationException(); throw new ReenteringLazyValueComputationException();
} }
return "second"; return "second";
}
}, },
new Function1<String, Unit>() { s -> {
@Override
public Unit invoke(String s) {
fail("Recursion-tolerating value should not be post computed"); fail("Recursion-tolerating value should not be post computed");
return Unit.INSTANCE; 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
@Override
public RuntimeException handleException(@NotNull Throwable throwable) {
throw new RethrownException(); throw new RethrownException();
}
}); });
try { try {
m.createLazyValue( m.createLazyValue(() -> {
new Function0<Object>() {
@Nullable
@Override
public Object invoke() {
throw new RuntimeException(); throw new RuntimeException();
} }).invoke();
}
).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
@Override
public RuntimeException handleException(@NotNull Throwable throwable) {
throw new RethrownException(); throw new RethrownException();
}
}); });
try { try {
m.createMemoizedFunction( m.createMemoizedFunction(o -> {
new Function1<Object, Object>() {
@Nullable
@Override
public Object invoke(@Nullable Object o) {
throw new RuntimeException(); throw new RuntimeException();
} }).invoke("");
}
).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);
return new LexicalScopeImpl(
ScopeUtilsKt.memberScopeAsImportingScope(libraryScope), root, false, null,
LexicalScopeKind.SYNTHETIC, LocalRedeclarationChecker.DO_NOTHING.INSTANCE, LexicalScopeKind.SYNTHETIC, LocalRedeclarationChecker.DO_NOTHING.INSTANCE,
new Function1<LexicalScopeImpl.InitializeHandler, Unit>() { handler -> {
@Override
public Unit invoke(LexicalScopeImpl.InitializeHandler 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,15 +93,12 @@ 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
public Unit invoke(LexicalScopeImpl.InitializeHandler handler) {
for (TypeParameterDescriptor parameterDescriptor : contextClass.getTypeConstructor().getParameters()) { for (TypeParameterDescriptor parameterDescriptor : contextClass.getTypeConstructor().getParameters()) {
handler.addClassifierDescriptor(parameterDescriptor); handler.addClassifierDescriptor(parameterDescriptor);
} }
return Unit.INSTANCE; return Unit.INSTANCE;
} }
}
); );
return new LexicalChainedScope( return new LexicalChainedScope(
typeParameters, module, false, null, LexicalScopeKind.SYNTHETIC, typeParameters, module, false, null, LexicalScopeKind.SYNTHETIC,
@@ -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,14 +196,11 @@ 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
public Unit invoke(LexicalScopeImpl.InitializeHandler handler) {
handler.addClassifierDescriptor(x); handler.addClassifierDescriptor(x);
handler.addClassifierDescriptor(y); handler.addClassifierDescriptor(y);
return Unit.INSTANCE; return Unit.INSTANCE;
} }
}
); );
KtTypeProjection projection = KtPsiFactoryKt KtTypeProjection projection = KtPsiFactoryKt
@@ -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
public boolean process(File file) {
if (!file.isDirectory() && filenamePattern.matcher(file.getName()).matches()) { if (!file.isDirectory() && filenamePattern.matcher(file.getName()).matches()) {
result.addAll(getTestMethodsFromFile(file)); 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
public Unit invoke(VirtualFile file) {
String libraryPath = PathUtil.getLocalPath(file); String libraryPath = PathUtil.getLocalPath(file);
assert libraryPath != null : "libraryPath for " + file + " should not be null"; assert libraryPath != null : "libraryPath for " + file + " should not be null";
metadata.addAll(KotlinJavascriptMetadataUtils.loadMetadata(libraryPath)); 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