Invoke "remove unnecessary final" intention in compiler modules

This commit is contained in:
Alexander Udalov
2017-04-01 00:23:37 +03:00
parent 463bbbd386
commit 34f0576135
96 changed files with 407 additions and 404 deletions
@@ -151,7 +151,7 @@ public class CodegenTestsOnAndroidRunner {
for (int i = 0; i < testCases.getLength(); i++) { for (int i = 0; i < testCases.getLength(); i++) {
Element item = (Element) testCases.item(i); Element item = (Element) testCases.item(i);
final NodeList failure = item.getElementsByTagName("failure"); NodeList failure = item.getElementsByTagName("failure");
String name = item.getAttribute("name"); String name = item.getAttribute("name");
String clazz = item.getAttribute("classname"); String clazz = item.getAttribute("classname");
@@ -86,7 +86,7 @@ public class RunUtils {
return run(settings); return run(settings);
} }
public static void executeOnSeparateThread(@NotNull final 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() { Thread t = new Thread(new Runnable() {
@Override @Override
@@ -98,10 +98,10 @@ public class RunUtils {
t.start(); t.start();
} }
private static RunResult run(final RunSettings settings) { private static RunResult run(RunSettings settings) {
System.out.println("RUN COMMAND: " + settings); System.out.println("RUN COMMAND: " + settings);
final StringBuilder stdOut = new StringBuilder(); StringBuilder stdOut = new StringBuilder();
final StringBuilder stdErr = new StringBuilder(); StringBuilder stdErr = new StringBuilder();
OSProcessHandler handler; OSProcessHandler handler;
try { try {
@@ -308,9 +308,9 @@ public abstract class AnnotationCodegen {
} }
private void genCompileTimeValue( private void genCompileTimeValue(
@Nullable final String name, @Nullable String name,
@NotNull ConstantValue<?> value, @NotNull ConstantValue<?> value,
@NotNull final AnnotationVisitor annotationVisitor @NotNull AnnotationVisitor annotationVisitor
) { ) {
AnnotationArgumentVisitor argumentVisitor = new AnnotationArgumentVisitor<Void, Void>() { AnnotationArgumentVisitor argumentVisitor = new AnnotationArgumentVisitor<Void, Void>() {
@Override @Override
@@ -485,7 +485,7 @@ public abstract class AnnotationCodegen {
abstract AnnotationVisitor visitAnnotation(String descr, boolean visible); abstract AnnotationVisitor visitAnnotation(String descr, boolean visible);
public static AnnotationCodegen forClass( public static AnnotationCodegen forClass(
final @NotNull ClassVisitor cv, @NotNull ClassVisitor cv,
@NotNull InnerClassConsumer innerClassConsumer, @NotNull InnerClassConsumer innerClassConsumer,
@NotNull KotlinTypeMapper mapper @NotNull KotlinTypeMapper mapper
) { ) {
@@ -499,7 +499,7 @@ public abstract class AnnotationCodegen {
} }
public static AnnotationCodegen forMethod( public static AnnotationCodegen forMethod(
final @NotNull MethodVisitor mv, @NotNull MethodVisitor mv,
@NotNull InnerClassConsumer innerClassConsumer, @NotNull InnerClassConsumer innerClassConsumer,
@NotNull KotlinTypeMapper mapper @NotNull KotlinTypeMapper mapper
) { ) {
@@ -513,7 +513,7 @@ public abstract class AnnotationCodegen {
} }
public static AnnotationCodegen forField( public static AnnotationCodegen forField(
final @NotNull FieldVisitor fv, @NotNull FieldVisitor fv,
@NotNull InnerClassConsumer innerClassConsumer, @NotNull InnerClassConsumer innerClassConsumer,
@NotNull KotlinTypeMapper mapper @NotNull KotlinTypeMapper mapper
) { ) {
@@ -527,8 +527,8 @@ public abstract class AnnotationCodegen {
} }
public static AnnotationCodegen forParameter( public static AnnotationCodegen forParameter(
final int parameter, int parameter,
final @NotNull MethodVisitor mv, @NotNull MethodVisitor mv,
@NotNull InnerClassConsumer innerClassConsumer, @NotNull InnerClassConsumer innerClassConsumer,
@NotNull KotlinTypeMapper mapper @NotNull KotlinTypeMapper mapper
) { ) {
@@ -542,7 +542,7 @@ public abstract class AnnotationCodegen {
} }
public static AnnotationCodegen forAnnotationDefaultValue( public static AnnotationCodegen forAnnotationDefaultValue(
final @NotNull MethodVisitor mv, @NotNull MethodVisitor mv,
@NotNull InnerClassConsumer innerClassConsumer, @NotNull InnerClassConsumer innerClassConsumer,
@NotNull KotlinTypeMapper mapper @NotNull KotlinTypeMapper mapper
) { ) {
@@ -500,7 +500,7 @@ public class AsmUtil {
v.invokevirtual("java/lang/StringBuilder", "append", "(" + type.getDescriptor() + ")Ljava/lang/StringBuilder;", false); v.invokevirtual("java/lang/StringBuilder", "append", "(" + type.getDescriptor() + ")Ljava/lang/StringBuilder;", false);
} }
public static StackValue genToString(final StackValue receiver, final 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, new Function1<InstructionAdapter, Unit>() {
@Override @Override
public Unit invoke(InstructionAdapter v) { public Unit invoke(InstructionAdapter v) {
@@ -563,12 +563,12 @@ public class AsmUtil {
@NotNull @NotNull
public static StackValue genEqualsForExpressionsOnStack( public static StackValue genEqualsForExpressionsOnStack(
final @NotNull IElementType opToken, @NotNull IElementType opToken,
final @NotNull StackValue left, @NotNull StackValue left,
final @NotNull StackValue right @NotNull StackValue right
) { ) {
final Type leftType = left.type; Type leftType = left.type;
final Type rightType = right.type; Type rightType = right.type;
if (isPrimitive(leftType) && leftType == rightType) { if (isPrimitive(leftType) && leftType == rightType) {
return StackValue.cmp(opToken, leftType, left, right); return StackValue.cmp(opToken, leftType, left, right);
} }
@@ -686,8 +686,8 @@ public class AsmUtil {
@NotNull @NotNull
public static StackValue genNotNullAssertions( public static StackValue genNotNullAssertions(
@NotNull GenerationState state, @NotNull GenerationState state,
@NotNull final StackValue stackValue, @NotNull StackValue stackValue,
@Nullable final RuntimeAssertionInfo runtimeAssertionInfo @Nullable RuntimeAssertionInfo runtimeAssertionInfo
) { ) {
if (state.isCallAssertionsDisabled()) return stackValue; if (state.isCallAssertionsDisabled()) return stackValue;
if (runtimeAssertionInfo == null || !runtimeAssertionInfo.getNeedNotNullAssertion()) return stackValue; if (runtimeAssertionInfo == null || !runtimeAssertionInfo.getNeedNotNullAssertion()) return stackValue;
@@ -101,7 +101,7 @@ public class ClassBuilderFactories {
} }
@NotNull @NotNull
public static ClassBuilderFactory binaries(final boolean generateSourceRetentionAnnotations) { public static ClassBuilderFactory binaries(boolean generateSourceRetentionAnnotations) {
return new ClassBuilderFactory() { return new ClassBuilderFactory() {
@NotNull @NotNull
@Override @Override
@@ -94,7 +94,7 @@ public class ClassFileFactory implements OutputFileCollection {
} }
private void writeModuleMappings() { private void writeModuleMappings() {
final JvmPackageTable.PackageTable.Builder builder = JvmPackageTable.PackageTable.newBuilder(); JvmPackageTable.PackageTable.Builder builder = JvmPackageTable.PackageTable.newBuilder();
String outputFilePath = getMappingFileName(state.getModuleName()); String outputFilePath = getMappingFileName(state.getModuleName());
for (PackageParts part : ClassFileUtilsKt.addCompiledPartsAndSort(partsGroupedByPackage.values(), state)) { for (PackageParts part : ClassFileUtilsKt.addCompiledPartsAndSort(partsGroupedByPackage.values(), state)) {
@@ -182,7 +182,7 @@ public class ClassFileFactory implements OutputFileCollection {
} }
private PackagePartRegistry buildNewPackagePartRegistry(@NotNull FqName packageFqName) { private PackagePartRegistry buildNewPackagePartRegistry(@NotNull FqName packageFqName) {
final String packageFqNameAsString = packageFqName.asString(); String packageFqNameAsString = packageFqName.asString();
return new PackagePartRegistry() { return new PackagePartRegistry() {
@Override @Override
public void addPart(@NotNull String partShortName, @Nullable String facadeShortName) { public void addPart(@NotNull String partShortName, @Nullable String facadeShortName) {
@@ -236,10 +236,10 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
assert method != null : "No method for " + frontendFunDescriptor; assert method != null : "No method for " + frontendFunDescriptor;
v.getSerializationBindings().put(METHOD_FOR_FUNCTION, freeLambdaDescriptor, method); v.getSerializationBindings().put(METHOD_FOR_FUNCTION, freeLambdaDescriptor, method);
final DescriptorSerializer serializer = DescriptorSerializer serializer =
DescriptorSerializer.createForLambda(new JvmSerializerExtension(v.getSerializationBindings(), state)); DescriptorSerializer.createForLambda(new JvmSerializerExtension(v.getSerializationBindings(), state));
final 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, new Function1<AnnotationVisitor, Unit>() {
@Override @Override
@@ -281,7 +281,7 @@ public class ClosureCodegen extends MemberCodegen<KtElement> {
} }
@NotNull @NotNull
public StackValue putInstanceOnStack(@NotNull final ExpressionCodegen codegen, @Nullable final 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>() { new Function1<InstructionAdapter, Unit>() {
@@ -480,12 +480,12 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
return generateIfExpression(expression, false); return generateIfExpression(expression, false);
} }
/* package */ StackValue generateIfExpression(@NotNull final KtIfExpression expression, final boolean isStatement) { /* package */ StackValue generateIfExpression(@NotNull KtIfExpression expression, boolean isStatement) {
final Type asmType = isStatement ? Type.VOID_TYPE : expressionTypeForBranchingOperation(expression); Type asmType = isStatement ? Type.VOID_TYPE : expressionTypeForBranchingOperation(expression);
final StackValue condition = gen(expression.getCondition()); StackValue condition = gen(expression.getCondition());
final KtExpression thenExpression = expression.getThen(); KtExpression thenExpression = expression.getThen();
final KtExpression elseExpression = expression.getElse(); KtExpression elseExpression = expression.getElse();
if (isEmptyExpression(thenExpression)) { if (isEmptyExpression(thenExpression)) {
if (isEmptyExpression(elseExpression)) { if (isEmptyExpression(elseExpression)) {
@@ -522,7 +522,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
} }
@Override @Override
public StackValue visitWhileExpression(@NotNull final 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, new Function1<InstructionAdapter, Unit>() {
@Override @Override
public Unit invoke(InstructionAdapter adapter) { public Unit invoke(InstructionAdapter adapter) {
@@ -553,7 +553,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
} }
@Override @Override
public StackValue visitDoWhileExpression(@NotNull final 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, new Function1<InstructionAdapter, Unit>() {
@Override @Override
public Unit invoke(InstructionAdapter adapter) { public Unit invoke(InstructionAdapter adapter) {
@@ -611,7 +611,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
} }
@Override @Override
public StackValue visitForExpression(@NotNull final 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, new Function1<InstructionAdapter, Unit>() {
@Override @Override
public Unit invoke(InstructionAdapter adapter) { public Unit invoke(InstructionAdapter adapter) {
@@ -765,7 +765,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
} }
else { else {
// E e = tmp<iterator>.next() // E e = tmp<iterator>.next()
final 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(new Runnable() {
@@ -796,7 +796,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
} }
private void generateDestructuringDeclaration(@NotNull KtDestructuringDeclaration destructuringDeclaration) { private void generateDestructuringDeclaration(@NotNull KtDestructuringDeclaration destructuringDeclaration) {
final Label destructuringStartLabel = new Label(); Label destructuringStartLabel = new Label();
List<VariableDescriptor> componentDescriptors = List<VariableDescriptor> componentDescriptors =
CollectionsKt.map( CollectionsKt.map(
@@ -809,9 +809,9 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
} }
); );
for (final VariableDescriptor componentDescriptor : CodegenUtilKt.filterOutDescriptorsWithSpecialNames(componentDescriptors)) { for (VariableDescriptor componentDescriptor : CodegenUtilKt.filterOutDescriptorsWithSpecialNames(componentDescriptors)) {
@SuppressWarnings("ConstantConditions") final Type componentAsmType = asmType(componentDescriptor.getReturnType()); @SuppressWarnings("ConstantConditions") Type componentAsmType = asmType(componentDescriptor.getReturnType());
final int componentVarIndex = myFrameMap.enter(componentDescriptor, componentAsmType); int componentVarIndex = myFrameMap.enter(componentDescriptor, componentAsmType);
scheduleLeaveVariable(new Runnable() { scheduleLeaveVariable(new Runnable() {
@Override @Override
public void run() { public void run() {
@@ -844,7 +844,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
leaveVariableTasks.add(runnable); leaveVariableTasks.add(runnable);
} }
protected int createLoopTempVariable(final Type type) { protected int createLoopTempVariable(Type type) {
int varIndex = myFrameMap.enterTemp(type); int varIndex = myFrameMap.enterTemp(type);
scheduleLeaveVariable(new Runnable() { scheduleLeaveVariable(new Runnable() {
@Override @Override
@@ -1367,7 +1367,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
private StackValue generateBreakOrContinueExpression( private StackValue generateBreakOrContinueExpression(
@NotNull KtExpressionWithLabel expression, @NotNull KtExpressionWithLabel expression,
boolean isBreak, boolean isBreak,
final @NotNull Label afterBreakContinueLabel @NotNull Label afterBreakContinueLabel
) { ) {
assert expression instanceof KtContinueExpression || expression instanceof KtBreakExpression; assert expression instanceof KtContinueExpression || expression instanceof KtBreakExpression;
@@ -1389,7 +1389,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
if (labelElement == null || if (labelElement == null ||
loopBlockStackElement.targetLabel != null && loopBlockStackElement.targetLabel != null &&
labelElement.getReferencedName().equals(loopBlockStackElement.targetLabel.getReferencedName())) { labelElement.getReferencedName().equals(loopBlockStackElement.targetLabel.getReferencedName())) {
final 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(Type.VOID_TYPE, new Function1<InstructionAdapter, Unit>() {
@Override @Override
public Unit invoke(InstructionAdapter adapter) { public Unit invoke(InstructionAdapter adapter) {
@@ -1412,11 +1412,11 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
} }
private StackValue generateSingleBranchIf( private StackValue generateSingleBranchIf(
final StackValue condition, StackValue condition,
final KtIfExpression ifExpression, KtIfExpression ifExpression,
final KtExpression expression, KtExpression expression,
final boolean inverse, boolean inverse,
final 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, new Function1<InstructionAdapter, Unit>() {
@@ -1476,7 +1476,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
@Nullable @Nullable
public static ConstantValue<?> getCompileTimeConstant( public static ConstantValue<?> getCompileTimeConstant(
@NotNull KtExpression expression, @NotNull KtExpression expression,
@NotNull final BindingContext bindingContext, @NotNull BindingContext bindingContext,
boolean takeUpConstValsAsConst, boolean takeUpConstValsAsConst,
boolean shouldInlineConstVals boolean shouldInlineConstVals
) { ) {
@@ -1486,7 +1486,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
} }
if (!shouldInlineConstVals && !takeUpConstValsAsConst && compileTimeValue.getUsesVariableAsConstant()) { if (!shouldInlineConstVals && !takeUpConstValsAsConst && compileTimeValue.getUsesVariableAsConstant()) {
final Ref<Boolean> containsNonInlinedVals = new Ref<Boolean>(false); Ref<Boolean> containsNonInlinedVals = new Ref<Boolean>(false);
KtVisitor constantChecker = new KtVisitor() { KtVisitor constantChecker = new KtVisitor() {
@Override @Override
public Object visitSimpleNameExpression(@NotNull KtSimpleNameExpression expression, Object data) { public Object visitSimpleNameExpression(@NotNull KtSimpleNameExpression expression, Object data) {
@@ -1528,7 +1528,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
@Override @Override
public StackValue visitStringTemplateExpression(@NotNull KtStringTemplateExpression expression, StackValue receiver) { public StackValue visitStringTemplateExpression(@NotNull KtStringTemplateExpression expression, StackValue receiver) {
StringBuilder constantValue = new StringBuilder(""); StringBuilder constantValue = new StringBuilder("");
final KtStringTemplateEntry[] entries = expression.getEntries(); KtStringTemplateEntry[] entries = expression.getEntries();
if (entries.length == 1 && entries[0] instanceof KtStringTemplateEntryWithExpression) { if (entries.length == 1 && entries[0] instanceof KtStringTemplateEntryWithExpression) {
KtExpression expr = entries[0].getExpression(); KtExpression expr = entries[0].getExpression();
@@ -1666,9 +1666,9 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
@Override @Override
public StackValue visitObjectLiteralExpression(@NotNull KtObjectLiteralExpression expression, StackValue receiver) { public StackValue visitObjectLiteralExpression(@NotNull KtObjectLiteralExpression expression, StackValue receiver) {
final ObjectLiteralResult objectLiteralResult = generateObjectLiteral(expression); ObjectLiteralResult objectLiteralResult = generateObjectLiteral(expression);
final ClassDescriptor classDescriptor = objectLiteralResult.classDescriptor; ClassDescriptor classDescriptor = objectLiteralResult.classDescriptor;
final Type type = typeMapper.mapType(classDescriptor); Type type = typeMapper.mapType(classDescriptor);
return StackValue.operation(type, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(type, new Function1<InstructionAdapter, Unit>() {
@Override @Override
@@ -1824,11 +1824,11 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
@NotNull List<KtExpression> statements, @NotNull List<KtExpression> statements,
boolean isStatement, boolean isStatement,
@Nullable Label labelBeforeLastExpression, @Nullable Label labelBeforeLastExpression,
@Nullable final Label labelBlockEnd @Nullable Label labelBlockEnd
) { ) {
final Label blockEnd = labelBlockEnd != null ? labelBlockEnd : new Label(); Label blockEnd = labelBlockEnd != null ? labelBlockEnd : new Label();
final List<Function<StackValue, Void>> leaveTasks = Lists.newArrayList(); List<Function<StackValue, Void>> leaveTasks = Lists.newArrayList();
@Nullable @Nullable
StackValue blockResult = null; StackValue blockResult = null;
@@ -1984,18 +1984,18 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
private void addLeaveTaskToRemoveLocalVariableFromFrameMap( private void addLeaveTaskToRemoveLocalVariableFromFrameMap(
@NotNull KtVariableDeclaration statement, @NotNull KtVariableDeclaration statement,
final Label blockEnd, Label blockEnd,
@NotNull List<Function<StackValue, Void>> leaveTasks @NotNull List<Function<StackValue, Void>> leaveTasks
) { ) {
final VariableDescriptor variableDescriptor = getVariableDescriptorNotNull(statement); VariableDescriptor variableDescriptor = getVariableDescriptorNotNull(statement);
// Do not modify local variables table for variables like _ in val (_, y) = pair // Do not modify local variables table for variables like _ in val (_, y) = pair
// They always will have special name // They always will have special name
if (variableDescriptor.getName().isSpecial()) return; if (variableDescriptor.getName().isSpecial()) return;
final Type type = getVariableType(variableDescriptor); Type type = getVariableType(variableDescriptor);
final Label scopeStart = new Label(); Label scopeStart = new Label();
v.mark(scopeStart); v.mark(scopeStart);
leaveTasks.add(new Function<StackValue, Void>() { leaveTasks.add(new Function<StackValue, Void>() {
@@ -2018,16 +2018,16 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
} }
private void addLeaveTaskToRemoveNamedFunctionFromFrameMap( private void addLeaveTaskToRemoveNamedFunctionFromFrameMap(
@NotNull final KtNamedFunction statement, @NotNull KtNamedFunction statement,
final Label blockEnd, Label blockEnd,
@NotNull List<Function<StackValue, Void>> leaveTasks @NotNull List<Function<StackValue, Void>> leaveTasks
) { ) {
final FunctionDescriptor functionDescriptor = (FunctionDescriptor) bindingContext.get(DECLARATION_TO_DESCRIPTOR, statement); FunctionDescriptor functionDescriptor = (FunctionDescriptor) bindingContext.get(DECLARATION_TO_DESCRIPTOR, statement);
assert functionDescriptor != null; assert functionDescriptor != null;
final Type type = asmTypeForAnonymousClass(bindingContext, functionDescriptor); Type type = asmTypeForAnonymousClass(bindingContext, functionDescriptor);
final Label scopeStart = new Label(); Label scopeStart = new Label();
v.mark(scopeStart); v.mark(scopeStart);
leaveTasks.add(new Function<StackValue, Void>() { leaveTasks.add(new Function<StackValue, Void>() {
@@ -2159,7 +2159,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
} }
@Override @Override
public StackValue visitReturnExpression(@NotNull final KtReturnExpression expression, final 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, new Function1<InstructionAdapter, Unit>() {
@Override @Override
public Unit invoke(InstructionAdapter adapter) { public Unit invoke(InstructionAdapter adapter) {
@@ -2684,10 +2684,10 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
@Nullable @Nullable
private StackValue genSamInterfaceValue( private StackValue genSamInterfaceValue(
@NotNull KtExpression probablyParenthesizedExpression, @NotNull KtExpression probablyParenthesizedExpression,
@NotNull final KtVisitor<StackValue, StackValue> visitor @NotNull KtVisitor<StackValue, StackValue> visitor
) { ) {
final KtExpression expression = KtPsiUtil.deparenthesize(probablyParenthesizedExpression); KtExpression expression = KtPsiUtil.deparenthesize(probablyParenthesizedExpression);
final SamType samType = bindingContext.get(SAM_VALUE, probablyParenthesizedExpression); SamType samType = bindingContext.get(SAM_VALUE, probablyParenthesizedExpression);
if (samType == null || expression == null) return null; if (samType == null || expression == null) return null;
if (expression instanceof KtLambdaExpression) { if (expression instanceof KtLambdaExpression) {
@@ -2698,7 +2698,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
return genClosure((KtNamedFunction) expression, samType); return genClosure((KtNamedFunction) expression, samType);
} }
final 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, new Function1<InstructionAdapter, Unit>() {
@@ -3391,8 +3391,8 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
@NotNull KtElement element, @NotNull KtElement element,
@NotNull VariableDescriptor variableDescriptor, @NotNull VariableDescriptor variableDescriptor,
@NotNull VariableDescriptor target, @NotNull VariableDescriptor target,
@Nullable final Type receiverAsmType, @Nullable Type receiverAsmType,
@Nullable final StackValue receiverValue @Nullable StackValue receiverValue
) { ) {
ClassDescriptor classDescriptor = CodegenBinding.anonymousClassForCallable(bindingContext, variableDescriptor); ClassDescriptor classDescriptor = CodegenBinding.anonymousClassForCallable(bindingContext, variableDescriptor);
@@ -3420,9 +3420,9 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
@NotNull @NotNull
public StackValue generateClassLiteralReference( public StackValue generateClassLiteralReference(
@NotNull final DoubleColonLHS lhs, @NotNull DoubleColonLHS lhs,
@Nullable final KtExpression receiverExpression, @Nullable KtExpression receiverExpression,
final 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, new Function1<InstructionAdapter, Unit>() {
@Override @Override
@@ -3549,11 +3549,11 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
} }
} }
private StackValue generateIn(final StackValue leftValue, KtExpression rangeExpression, final KtSimpleNameExpression operationReference) { private StackValue generateIn(StackValue leftValue, KtExpression rangeExpression, KtSimpleNameExpression operationReference) {
final KtExpression deparenthesized = KtPsiUtil.deparenthesize(rangeExpression); KtExpression deparenthesized = KtPsiUtil.deparenthesize(rangeExpression);
assert deparenthesized != null : "For with empty range expression"; assert deparenthesized != null : "For with empty range expression";
final 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, new Function1<InstructionAdapter, Unit>() {
@Override @Override
public Unit invoke(InstructionAdapter v) { public Unit invoke(InstructionAdapter v) {
@@ -3670,17 +3670,17 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
/*tries to use IEEE 754 arithmetic*/ /*tries to use IEEE 754 arithmetic*/
private StackValue genEqualsForExpressionsPreferIEEE754Arithmetic( private StackValue genEqualsForExpressionsPreferIEEE754Arithmetic(
@Nullable final KtExpression left, @Nullable KtExpression left,
@Nullable final KtExpression right, @Nullable KtExpression right,
@NotNull final IElementType opToken, @NotNull IElementType opToken,
@NotNull Type leftType, @NotNull Type leftType,
@NotNull Type rightType, @NotNull Type rightType,
@Nullable final StackValue pregeneratedLeft @Nullable StackValue pregeneratedLeft
) { ) {
assert (opToken == KtTokens.EQEQ || opToken == KtTokens.EXCLEQ) : "Optoken should be '==' or '!=', but: " + opToken; assert (opToken == KtTokens.EQEQ || opToken == KtTokens.EXCLEQ) : "Optoken should be '==' or '!=', but: " + opToken;
final TypeAndNullability left754Type = calcTypeForIEEE754ArithmeticIfNeeded(left); TypeAndNullability left754Type = calcTypeForIEEE754ArithmeticIfNeeded(left);
final TypeAndNullability right754Type = calcTypeForIEEE754ArithmeticIfNeeded(right); TypeAndNullability right754Type = calcTypeForIEEE754ArithmeticIfNeeded(right);
if (left754Type != null && right754Type != null && left754Type.type.equals(right754Type.type)) { if (left754Type != null && right754Type != null && left754Type.type.equals(right754Type.type)) {
//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) {
@@ -3849,17 +3849,16 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
return StackValue.compareWithNull(gen(exp), (KtTokens.EQEQ == opToken || KtTokens.EQEQEQ == opToken) ? IFNONNULL : IFNULL); return StackValue.compareWithNull(gen(exp), (KtTokens.EQEQ == opToken || KtTokens.EQEQEQ == opToken) ? IFNONNULL : IFNULL);
} }
private StackValue generateElvis(@NotNull final KtBinaryExpression expression) { private StackValue generateElvis(@NotNull KtBinaryExpression expression) {
KtExpression left = expression.getLeft(); KtExpression left = expression.getLeft();
final Type exprType = expressionType(expression); Type exprType = expressionType(expression);
final Type leftType = expressionType(left); Type leftType = expressionType(left);
final Label ifNull = new Label();
Label ifNull = new Label();
assert left != null : "left expression in elvis should be not null: " + expression.getText(); assert left != null : "left expression in elvis should be not null: " + expression.getText();
final StackValue value = generateExpressionWithNullFallback(left, ifNull); StackValue value = generateExpressionWithNullFallback(left, ifNull);
if (isPrimitive(leftType)) { if (isPrimitive(leftType)) {
return value; return value;
@@ -3918,7 +3917,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
return CodegenUtilKt.calcTypeForIEEE754ArithmeticIfNeeded(expression, bindingContext, context.getFunctionDescriptor()); return CodegenUtilKt.calcTypeForIEEE754ArithmeticIfNeeded(expression, bindingContext, context.getFunctionDescriptor());
} }
private StackValue generateAssignmentExpression(final KtBinaryExpression expression) { private StackValue generateAssignmentExpression(KtBinaryExpression expression) {
return StackValue.operation(Type.VOID_TYPE, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(Type.VOID_TYPE, new Function1<InstructionAdapter, Unit>() {
@Override @Override
public Unit invoke(InstructionAdapter adapter) { public Unit invoke(InstructionAdapter adapter) {
@@ -3932,7 +3931,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
}); });
} }
private StackValue generateAugmentedAssignment(final KtBinaryExpression expression) { private StackValue generateAugmentedAssignment(KtBinaryExpression expression) {
return StackValue.operation(Type.VOID_TYPE, new Function1<InstructionAdapter, Unit>() { return StackValue.operation(Type.VOID_TYPE, new Function1<InstructionAdapter, Unit>() {
@Override @Override
public Unit invoke(InstructionAdapter adapter) { public Unit invoke(InstructionAdapter adapter) {
@@ -4039,9 +4038,9 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
} }
@Override @Override
public StackValue visitPostfixExpression(@NotNull final KtPostfixExpression expression, StackValue receiver) { public StackValue visitPostfixExpression(@NotNull KtPostfixExpression expression, StackValue receiver) {
if (expression.getOperationReference().getReferencedNameElementType() == KtTokens.EXCLEXCL) { if (expression.getOperationReference().getReferencedNameElementType() == KtTokens.EXCLEXCL) {
final 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 { } else {
@@ -4062,19 +4061,19 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
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;
final ResolvedCall<?> resolvedCall = CallUtilKt.getResolvedCallWithAssert(expression, bindingContext); ResolvedCall<?> resolvedCall = CallUtilKt.getResolvedCallWithAssert(expression, bindingContext);
DeclarationDescriptor op = resolvedCall.getResultingDescriptor(); DeclarationDescriptor op = resolvedCall.getResultingDescriptor();
if (!(op instanceof FunctionDescriptor) || originalOperation == null) { if (!(op instanceof FunctionDescriptor) || originalOperation == null) {
throw new UnsupportedOperationException("Don't know how to generate this postfix expression: " + originalOperationName + " " + op); throw new UnsupportedOperationException("Don't know how to generate this postfix expression: " + originalOperationName + " " + op);
} }
final Type asmResultType = expressionType(expression); Type asmResultType = expressionType(expression);
final Type asmBaseType = expressionType(expression.getBaseExpression()); Type asmBaseType = expressionType(expression.getBaseExpression());
DeclarationDescriptor cls = op.getContainingDeclaration(); DeclarationDescriptor cls = op.getContainingDeclaration();
final int increment; int increment;
if (originalOperationName.equals("inc")) { if (originalOperationName.equals("inc")) {
increment = 1; increment = 1;
} }
@@ -4085,7 +4084,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
throw new UnsupportedOperationException("Unsupported postfix operation: " + originalOperationName + " " + op); throw new UnsupportedOperationException("Unsupported postfix operation: " + originalOperationName + " " + op);
} }
final boolean isPrimitiveNumberClassDescriptor = isPrimitiveNumberClassDescriptor(cls); boolean isPrimitiveNumberClassDescriptor = isPrimitiveNumberClassDescriptor(cls);
if (isPrimitiveNumberClassDescriptor && AsmUtil.isPrimitive(asmBaseType)) { if (isPrimitiveNumberClassDescriptor && AsmUtil.isPrimitive(asmBaseType)) {
KtExpression operand = expression.getBaseExpression(); KtExpression operand = expression.getBaseExpression();
// Optimization for j = i++, when j and i are Int without any smart cast: we just work with primitive int // Optimization for j = i++, when j and i are Int without any smart cast: we just work with primitive int
@@ -4255,7 +4254,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
@NotNull @NotNull
private Type generateProvideDelegateCallForLocalVariable( private Type generateProvideDelegateCallForLocalVariable(
@NotNull StackValue initializer, @NotNull StackValue initializer,
final StackValue metadataValue, StackValue metadataValue,
ResolvedCall<FunctionDescriptor> provideDelegateResolvedCall ResolvedCall<FunctionDescriptor> provideDelegateResolvedCall
) { ) {
StackValue provideDelegateReceiver = StackValue.onStack(initializer.type); StackValue provideDelegateReceiver = StackValue.onStack(initializer.type);
@@ -4340,7 +4339,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
} }
@NotNull @NotNull
public StackValue generateConstructorCall(@NotNull final ResolvedCall<?> resolvedCall, @NotNull final Type objectType) { public StackValue generateConstructorCall(@NotNull ResolvedCall<?> resolvedCall, @NotNull Type objectType) {
return StackValue.functionCall(objectType, new Function1<InstructionAdapter, Unit>() { return StackValue.functionCall(objectType, new Function1<InstructionAdapter, Unit>() {
@Override @Override
public Unit invoke(InstructionAdapter v) { public Unit invoke(InstructionAdapter v) {
@@ -4374,13 +4373,13 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
} }
public StackValue generateNewArray( public StackValue generateNewArray(
@NotNull KtCallExpression expression, @NotNull final KotlinType arrayType, @NotNull ResolvedCall<?> resolvedCall @NotNull KtCallExpression expression, @NotNull KotlinType arrayType, @NotNull ResolvedCall<?> resolvedCall
) { ) {
List<KtValueArgument> args = expression.getValueArguments(); List<KtValueArgument> args = expression.getValueArguments();
assert args.size() == 1 || args.size() == 2 : "Unknown constructor called: " + args.size() + " arguments"; assert args.size() == 1 || args.size() == 2 : "Unknown constructor called: " + args.size() + " arguments";
if (args.size() == 1) { if (args.size() == 1) {
final 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), new Function1<InstructionAdapter, Unit>() {
@Override @Override
public Unit invoke(InstructionAdapter v) { public Unit invoke(InstructionAdapter v) {
@@ -4481,7 +4480,7 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
} }
@Override @Override
public StackValue visitThrowExpression(@NotNull final 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, new Function1<InstructionAdapter, Unit>() {
@Override @Override
public Unit invoke(InstructionAdapter adapter) { public Unit invoke(InstructionAdapter adapter) {
@@ -4510,13 +4509,13 @@ public class ExpressionCodegen extends KtVisitor<StackValue, StackValue> impleme
return generateTryExpression(expression, false); return generateTryExpression(expression, false);
} }
public StackValue generateTryExpression(final KtTryExpression expression, final boolean isStatement) { public StackValue generateTryExpression(KtTryExpression expression, boolean isStatement) {
/* /*
The "returned" value of try expression with no finally is either the last expression in the try block or the last expression in the catch block The "returned" value of try expression with no finally is either the last expression in the try block or the last expression in the catch block
(or blocks). (or blocks).
*/ */
final 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, new Function1<InstructionAdapter, Unit>() {
@Override @Override
@@ -4662,12 +4661,12 @@ The "returned" value of try expression with no finally is either the last expres
@Override @Override
public StackValue visitBinaryWithTypeRHSExpression(@NotNull KtBinaryExpressionWithTypeRHS expression, StackValue receiver) { public StackValue visitBinaryWithTypeRHSExpression(@NotNull KtBinaryExpressionWithTypeRHS expression, StackValue receiver) {
KtExpression left = expression.getLeft(); KtExpression left = expression.getLeft();
final IElementType opToken = expression.getOperationReference().getReferencedNameElementType(); IElementType opToken = expression.getOperationReference().getReferencedNameElementType();
final KotlinType rightType = bindingContext.get(TYPE, expression.getRight()); KotlinType rightType = bindingContext.get(TYPE, expression.getRight());
assert rightType != null; assert rightType != null;
final 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)), new Function1<InstructionAdapter, Unit>() {
@Override @Override
@@ -4732,7 +4731,7 @@ The "returned" value of try expression with no finally is either the last expres
return negated ? StackValue.not(value) : value; return negated ? StackValue.not(value) : value;
} }
private StackValue generateIsCheck(final StackValue expressionToGen, final KotlinType kotlinType, final 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, new Function1<InstructionAdapter, Unit>() {
@Override @Override
public Unit invoke(InstructionAdapter v) { public Unit invoke(InstructionAdapter v) {
@@ -4788,11 +4787,11 @@ The "returned" value of try expression with no finally is either the last expres
return generateWhenExpression(expression, false); return generateWhenExpression(expression, false);
} }
public StackValue generateWhenExpression(final KtWhenExpression expression, final boolean isStatement) { public StackValue generateWhenExpression(KtWhenExpression expression, boolean isStatement) {
final KtExpression expr = expression.getSubjectExpression(); KtExpression expr = expression.getSubjectExpression();
final Type subjectType = expressionType(expr); Type subjectType = expressionType(expr);
final 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, new Function1<InstructionAdapter, Unit>() {
@Override @Override
@@ -268,7 +268,7 @@ public class FunctionCodegen {
} }
private void generateDelegateForDefaultImpl( private void generateDelegateForDefaultImpl(
@NotNull final FunctionDescriptor functionDescriptor, @NotNull FunctionDescriptor functionDescriptor,
@Nullable PsiElement element @Nullable PsiElement element
) { ) {
Method defaultImplMethod = typeMapper.mapAsmMethod(functionDescriptor, OwnerKind.DEFAULT_IMPLS); Method defaultImplMethod = typeMapper.mapAsmMethod(functionDescriptor, OwnerKind.DEFAULT_IMPLS);
@@ -825,7 +825,7 @@ public class FunctionCodegen {
} }
@NotNull @NotNull
private static Function1<FunctionDescriptor, Method> getSignatureMapper(final @NotNull KotlinTypeMapper typeMapper) { private static Function1<FunctionDescriptor, Method> getSignatureMapper(@NotNull KotlinTypeMapper typeMapper) {
return new Function1<FunctionDescriptor, Method>() { return new Function1<FunctionDescriptor, Method>() {
@Override @Override
public Method invoke(FunctionDescriptor descriptor) { public Method invoke(FunctionDescriptor descriptor) {
@@ -847,7 +847,7 @@ public class FunctionCodegen {
} }
@NotNull @NotNull
public static String[] getThrownExceptions(@NotNull FunctionDescriptor function, @NotNull final KotlinTypeMapper mapper) { public static String[] getThrownExceptions(@NotNull FunctionDescriptor function, @NotNull KotlinTypeMapper mapper) {
AnnotationDescriptor annotation = function.getAnnotations().findAnnotation(new FqName("kotlin.throws")); AnnotationDescriptor annotation = function.getAnnotations().findAnnotation(new FqName("kotlin.throws"));
if (annotation == null) { if (annotation == null) {
annotation = function.getAnnotations().findAnnotation(new FqName("kotlin.jvm.Throws")); annotation = function.getAnnotations().findAnnotation(new FqName("kotlin.jvm.Throws"));
@@ -1234,11 +1234,11 @@ public class FunctionCodegen {
} }
private void genDelegate( private void genDelegate(
@NotNull final FunctionDescriptor delegateFunction, @NotNull FunctionDescriptor delegateFunction,
final FunctionDescriptor delegatedTo, FunctionDescriptor delegatedTo,
@NotNull JvmDeclarationOrigin declarationOrigin, @NotNull JvmDeclarationOrigin declarationOrigin,
final ClassDescriptor toClass, ClassDescriptor toClass,
final StackValue field StackValue field
) { ) {
generateMethod( generateMethod(
declarationOrigin, delegateFunction, declarationOrigin, delegateFunction,
@@ -78,10 +78,10 @@ public class FunctionReferenceGenerationStrategy extends FunctionGenerationStrat
*/ */
KtCallExpression fakeExpression = CodegenUtil.constructFakeFunctionCall(state.getProject(), referencedFunction); KtCallExpression fakeExpression = CodegenUtil.constructFakeFunctionCall(state.getProject(), referencedFunction);
final List<? extends ValueArgument> fakeArguments = fakeExpression.getValueArguments(); List<? extends ValueArgument> fakeArguments = fakeExpression.getValueArguments();
final ReceiverValue dispatchReceiver = computeAndSaveReceiver(signature, codegen, referencedFunction.getDispatchReceiverParameter()); ReceiverValue dispatchReceiver = computeAndSaveReceiver(signature, codegen, referencedFunction.getDispatchReceiverParameter());
final ReceiverValue extensionReceiver = computeAndSaveReceiver(signature, codegen, referencedFunction.getExtensionReceiverParameter()); ReceiverValue extensionReceiver = computeAndSaveReceiver(signature, codegen, referencedFunction.getExtensionReceiverParameter());
computeAndSaveArguments(fakeArguments, codegen); computeAndSaveArguments(fakeArguments, codegen);
ResolvedCall<CallableDescriptor> fakeResolvedCall = new DelegatingResolvedCall<CallableDescriptor>(resolvedCall) { ResolvedCall<CallableDescriptor> fakeResolvedCall = new DelegatingResolvedCall<CallableDescriptor>(resolvedCall) {
@@ -395,7 +395,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
private void generateToArray() { private void generateToArray() {
if (descriptor.getKind() == ClassKind.INTERFACE) return; if (descriptor.getKind() == ClassKind.INTERFACE) return;
final 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), new Function1<ClassDescriptor, Boolean>() {
@@ -637,7 +637,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
} }
@Override @Override
public void generateComponentFunction(@NotNull FunctionDescriptor function, @NotNull final ValueParameterDescriptor parameter) { public void generateComponentFunction(@NotNull FunctionDescriptor function, @NotNull ValueParameterDescriptor parameter) {
PsiElement originalElement = DescriptorToSourceUtils.descriptorToDeclaration(parameter); PsiElement originalElement = DescriptorToSourceUtils.descriptorToDeclaration(parameter);
functionCodegen.generateMethod(JvmDeclarationOriginKt.OtherOrigin(originalElement, function), function, new FunctionGenerationStrategy() { functionCodegen.generateMethod(JvmDeclarationOriginKt.OtherOrigin(originalElement, function), function, new FunctionGenerationStrategy() {
@Override @Override
@@ -665,10 +665,10 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
@Override @Override
public void generateCopyFunction( public void generateCopyFunction(
@NotNull final FunctionDescriptor function, @NotNull FunctionDescriptor function,
@NotNull List<? extends KtParameter> constructorParameters @NotNull List<? extends KtParameter> constructorParameters
) { ) {
final Type thisDescriptorType = typeMapper.mapType(descriptor); Type thisDescriptorType = typeMapper.mapType(descriptor);
functionCodegen.generateMethod(JvmDeclarationOriginKt.OtherOrigin(myClass, function), function, new FunctionGenerationStrategy() { functionCodegen.generateMethod(JvmDeclarationOriginKt.OtherOrigin(myClass, function), function, new FunctionGenerationStrategy() {
@Override @Override
@@ -896,15 +896,15 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
StackValue.singleton(companionObject, typeMapper).store(instance, codegen.v, true); StackValue.singleton(companionObject, typeMapper).store(instance, codegen.v, true);
} }
private void generatePrimaryConstructor(final DelegationFieldsInfo delegationFieldsInfo) { private void generatePrimaryConstructor(DelegationFieldsInfo delegationFieldsInfo) {
if (isInterface(descriptor) || isAnnotationClass(descriptor)) return; if (isInterface(descriptor) || isAnnotationClass(descriptor)) return;
final ClassConstructorDescriptor constructorDescriptor = descriptor.getUnsubstitutedPrimaryConstructor(); ClassConstructorDescriptor constructorDescriptor = descriptor.getUnsubstitutedPrimaryConstructor();
if (constructorDescriptor == null) return; if (constructorDescriptor == null) return;
ConstructorContext constructorContext = context.intoConstructor(constructorDescriptor); ConstructorContext constructorContext = context.intoConstructor(constructorDescriptor);
final KtPrimaryConstructor primaryConstructor = myClass.getPrimaryConstructor(); KtPrimaryConstructor primaryConstructor = myClass.getPrimaryConstructor();
JvmDeclarationOrigin origin = JvmDeclarationOriginKt JvmDeclarationOrigin origin = JvmDeclarationOriginKt
.OtherOrigin(primaryConstructor != null ? primaryConstructor : myClass.getPsiOrParent(), constructorDescriptor); .OtherOrigin(primaryConstructor != null ? primaryConstructor : myClass.getPsiOrParent(), constructorDescriptor);
functionCodegen.generateMethod(origin, constructorDescriptor, constructorContext, functionCodegen.generateMethod(origin, constructorDescriptor, constructorContext,
@@ -922,7 +922,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
new DefaultParameterValueSubstitutor(state).generatePrimaryConstructorOverloadsIfNeeded(constructorDescriptor, v, this, kind, myClass); new DefaultParameterValueSubstitutor(state).generatePrimaryConstructorOverloadsIfNeeded(constructorDescriptor, v, this, kind, myClass);
} }
private void generateSecondaryConstructor(@NotNull final ClassConstructorDescriptor constructorDescriptor) { private void generateSecondaryConstructor(@NotNull ClassConstructorDescriptor constructorDescriptor) {
if (!canHaveDeclaredConstructors(descriptor)) return; if (!canHaveDeclaredConstructors(descriptor)) return;
ConstructorContext constructorContext = context.intoConstructor(constructorDescriptor); ConstructorContext constructorContext = context.intoConstructor(constructorDescriptor);
@@ -994,7 +994,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
} }
if (JvmAbi.isCompanionObjectWithBackingFieldsInOuter(descriptor)) { if (JvmAbi.isCompanionObjectWithBackingFieldsInOuter(descriptor)) {
final ImplementationBodyCodegen parentCodegen = (ImplementationBodyCodegen) getParentCodegen(); ImplementationBodyCodegen parentCodegen = (ImplementationBodyCodegen) getParentCodegen();
generateInitializers(new Function0<ExpressionCodegen>() { generateInitializers(new Function0<ExpressionCodegen>() {
@Override @Override
public ExpressionCodegen invoke() { public ExpressionCodegen invoke() {
@@ -1063,7 +1063,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
} }
} }
private void generateInitializers(@NotNull final ExpressionCodegen codegen) { private void generateInitializers(@NotNull ExpressionCodegen codegen) {
generateInitializers(new Function0<ExpressionCodegen>() { generateInitializers(new Function0<ExpressionCodegen>() {
@Override @Override
public ExpressionCodegen invoke() { public ExpressionCodegen invoke() {
@@ -1306,7 +1306,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
CodegenUtilKt.reportTarget6InheritanceErrorIfNeeded(descriptor, myClass.getPsiOrParent(), restrictedInheritance, state); CodegenUtilKt.reportTarget6InheritanceErrorIfNeeded(descriptor, myClass.getPsiOrParent(), restrictedInheritance, state);
} }
private void generateDelegationToDefaultImpl(@NotNull final FunctionDescriptor traitFun, @NotNull final FunctionDescriptor inheritedFun) { private void generateDelegationToDefaultImpl(@NotNull FunctionDescriptor traitFun, @NotNull FunctionDescriptor inheritedFun) {
functionCodegen.generateMethod( functionCodegen.generateMethod(
JvmDeclarationOriginKt.DelegationToDefaultImpls(descriptorToDeclaration(traitFun), traitFun), JvmDeclarationOriginKt.DelegationToDefaultImpls(descriptorToDeclaration(traitFun), traitFun),
inheritedFun, inheritedFun,
@@ -691,8 +691,8 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
private void generateSyntheticAccessor(@NotNull AccessorForCallableDescriptor<?> accessorForCallableDescriptor) { private void generateSyntheticAccessor(@NotNull AccessorForCallableDescriptor<?> accessorForCallableDescriptor) {
if (accessorForCallableDescriptor instanceof FunctionDescriptor) { if (accessorForCallableDescriptor instanceof FunctionDescriptor) {
final FunctionDescriptor accessor = (FunctionDescriptor) accessorForCallableDescriptor; FunctionDescriptor accessor = (FunctionDescriptor) accessorForCallableDescriptor;
final FunctionDescriptor original = (FunctionDescriptor) accessorForCallableDescriptor.getCalleeDescriptor(); FunctionDescriptor original = (FunctionDescriptor) accessorForCallableDescriptor.getCalleeDescriptor();
functionCodegen.generateMethod( functionCodegen.generateMethod(
Synthetic(null, original), accessor, Synthetic(null, original), accessor,
new FunctionGenerationStrategy.CodegenBased(state) { new FunctionGenerationStrategy.CodegenBased(state) {
@@ -708,8 +708,8 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
); );
} }
else if (accessorForCallableDescriptor instanceof AccessorForPropertyDescriptor) { else if (accessorForCallableDescriptor instanceof AccessorForPropertyDescriptor) {
final AccessorForPropertyDescriptor accessor = (AccessorForPropertyDescriptor) accessorForCallableDescriptor; AccessorForPropertyDescriptor accessor = (AccessorForPropertyDescriptor) accessorForCallableDescriptor;
final PropertyDescriptor original = accessor.getCalleeDescriptor(); PropertyDescriptor original = accessor.getCalleeDescriptor();
class PropertyAccessorStrategy extends FunctionGenerationStrategy.CodegenBased { class PropertyAccessorStrategy extends FunctionGenerationStrategy.CodegenBased {
private final PropertyAccessorDescriptor callableDescriptor; private final PropertyAccessorDescriptor callableDescriptor;
@@ -815,10 +815,10 @@ public abstract class MemberCodegen<T extends KtPureElement/* TODO: & KtDeclarat
} }
protected void generateKotlinClassMetadataAnnotation(@NotNull ClassDescriptor descriptor, boolean isScript) { protected void generateKotlinClassMetadataAnnotation(@NotNull ClassDescriptor descriptor, boolean isScript) {
final DescriptorSerializer serializer = DescriptorSerializer serializer =
DescriptorSerializer.create(descriptor, new JvmSerializerExtension(v.getSerializationBindings(), state)); DescriptorSerializer.create(descriptor, new JvmSerializerExtension(v.getSerializationBindings(), state));
final ProtoBuf.Class classProto = serializer.classProto(descriptor).build(); ProtoBuf.Class classProto = serializer.classProto(descriptor).build();
int flags = isScript ? JvmAnnotationNames.METADATA_SCRIPT_FLAG : 0; int flags = isScript ? JvmAnnotationNames.METADATA_SCRIPT_FLAG : 0;
@@ -127,9 +127,9 @@ public class PackagePartCodegen extends MemberCodegen<KtFile> {
} }
} }
final DescriptorSerializer serializer = DescriptorSerializer serializer =
DescriptorSerializer.createTopLevel(new JvmSerializerExtension(v.getSerializationBindings(), state)); DescriptorSerializer.createTopLevel(new JvmSerializerExtension(v.getSerializationBindings(), state));
final 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, new Function1<AnnotationVisitor, Unit>() {
@Override @Override
@@ -537,7 +537,7 @@ public class PropertyCodegen {
@NotNull ExpressionCodegen codegen, @NotNull ExpressionCodegen codegen,
@NotNull KotlinTypeMapper typeMapper, @NotNull KotlinTypeMapper typeMapper,
@NotNull ResolvedCall<FunctionDescriptor> resolvedCall, @NotNull ResolvedCall<FunctionDescriptor> resolvedCall,
final int indexInPropertyMetadataArray, int indexInPropertyMetadataArray,
int propertyMetadataArgumentIndex int propertyMetadataArgumentIndex
) { ) {
StackValue.Property receiver = codegen.intermediateValueForProperty(propertyDescriptor, true, null, StackValue.LOCAL_0); StackValue.Property receiver = codegen.intermediateValueForProperty(propertyDescriptor, true, null, StackValue.LOCAL_0);
@@ -551,14 +551,14 @@ public class PropertyCodegen {
@NotNull ExpressionCodegen codegen, @NotNull ExpressionCodegen codegen,
@NotNull KotlinTypeMapper typeMapper, @NotNull KotlinTypeMapper typeMapper,
@NotNull ResolvedCall<FunctionDescriptor> resolvedCall, @NotNull ResolvedCall<FunctionDescriptor> resolvedCall,
final int indexInPropertyMetadataArray, int indexInPropertyMetadataArray,
int propertyMetadataArgumentIndex, int propertyMetadataArgumentIndex,
@Nullable StackValue receiver, @Nullable StackValue receiver,
@NotNull PropertyDescriptor propertyDescriptor @NotNull PropertyDescriptor propertyDescriptor
) { ) {
final Type owner = JvmAbi.isPropertyWithBackingFieldInOuterClass(propertyDescriptor) ? Type owner = JvmAbi.isPropertyWithBackingFieldInOuterClass(propertyDescriptor) ?
codegen.getState().getTypeMapper().mapOwner(propertyDescriptor) : codegen.getState().getTypeMapper().mapOwner(propertyDescriptor) :
getDelegatedPropertyMetadataOwner(codegen, typeMapper); getDelegatedPropertyMetadataOwner(codegen, typeMapper);
codegen.tempVariables.put( codegen.tempVariables.put(
resolvedCall.getCall().getValueArguments().get(propertyMetadataArgumentIndex).asElement(), resolvedCall.getCall().getValueArguments().get(propertyMetadataArgumentIndex).asElement(),
@@ -200,7 +200,7 @@ public class ScriptCodegen extends MemberCodegen<KtScript> {
iv.putfield(classType.getInternalName(), context.getScriptFieldName(earlierScript), earlierClassType.getDescriptor()); iv.putfield(classType.getInternalName(), context.getScriptFieldName(earlierScript), earlierClassType.getDescriptor());
} }
final 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(new Function0<ExpressionCodegen>() {
@Override @Override
@@ -59,9 +59,9 @@ public class AnonymousObjectTransformer extends ObjectTransformer<AnonymousObjec
@Override @Override
@NotNull @NotNull
public InlineResult doTransform(@NotNull FieldRemapper parentRemapper) { public InlineResult doTransform(@NotNull FieldRemapper parentRemapper) {
final List<InnerClassNode> innerClassNodes = new ArrayList<InnerClassNode>(); List<InnerClassNode> innerClassNodes = new ArrayList<InnerClassNode>();
final ClassBuilder classBuilder = createRemappingClassBuilderViaFactory(inliningContext); ClassBuilder classBuilder = createRemappingClassBuilderViaFactory(inliningContext);
final List<MethodNode> methodsToTransform = new ArrayList<MethodNode>(); List<MethodNode> methodsToTransform = new ArrayList<MethodNode>();
createClassReader().accept(new ClassVisitor(InlineCodegenUtil.API, classBuilder.getVisitor()) { createClassReader().accept(new ClassVisitor(InlineCodegenUtil.API, classBuilder.getVisitor()) {
@Override @Override
@@ -273,7 +273,7 @@ public class AnonymousObjectTransformer extends ObjectTransformer<AnonymousObjec
NO_ORIGIN, constructor.access, "<init>", constructorDescriptor, null, ArrayUtil.EMPTY_STRING_ARRAY NO_ORIGIN, constructor.access, "<init>", constructorDescriptor, null, ArrayUtil.EMPTY_STRING_ARRAY
); );
final Label newBodyStartLabel = new Label(); Label newBodyStartLabel = new Label();
constructorVisitor.visitLabel(newBodyStartLabel); constructorVisitor.visitLabel(newBodyStartLabel);
//initialize captured fields //initialize captured fields
List<NewJavaField> newFieldsWithSkipped = TransformationUtilsKt.getNewFieldsToGenerate(allCapturedBuilder.listCaptured()); List<NewJavaField> newFieldsWithSkipped = TransformationUtilsKt.getNewFieldsToGenerate(allCapturedBuilder.listCaptured());
@@ -316,7 +316,7 @@ public class AnonymousObjectTransformer extends ObjectTransformer<AnonymousObjec
InlineCodegenUtil.removeFinallyMarkers(intermediateMethodNode); InlineCodegenUtil.removeFinallyMarkers(intermediateMethodNode);
AbstractInsnNode first = intermediateMethodNode.instructions.getFirst(); AbstractInsnNode first = intermediateMethodNode.instructions.getFirst();
final Label oldStartLabel = first instanceof LabelNode ? ((LabelNode) first).getLabel() : null; Label oldStartLabel = first instanceof LabelNode ? ((LabelNode) first).getLabel() : null;
intermediateMethodNode.accept(new MethodBodyVisitor(capturedFieldInitializer) { intermediateMethodNode.accept(new MethodBodyVisitor(capturedFieldInitializer) {
@Override @Override
public void visitLocalVariable( public void visitLocalVariable(
@@ -344,7 +344,7 @@ public class AnonymousObjectTransformer extends ObjectTransformer<AnonymousObjec
} }
@NotNull @NotNull
private static DeferredMethodVisitor newMethod(@NotNull final ClassBuilder builder, @NotNull final MethodNode original) { private static DeferredMethodVisitor newMethod(@NotNull ClassBuilder builder, @NotNull MethodNode original) {
return new DeferredMethodVisitor( return new DeferredMethodVisitor(
new MethodNode( new MethodNode(
original.access, original.name, original.desc, original.signature, original.access, original.name, original.desc, original.signature,
@@ -229,7 +229,7 @@ public class InlineCodegen extends CallGenerator {
@NotNull @NotNull
static SMAPAndMethodNode createMethodNode( static SMAPAndMethodNode createMethodNode(
@NotNull final FunctionDescriptor functionDescriptor, @NotNull FunctionDescriptor functionDescriptor,
@NotNull JvmMethodSignature jvmSignature, @NotNull JvmMethodSignature jvmSignature,
@NotNull ExpressionCodegen codegen, @NotNull ExpressionCodegen codegen,
@NotNull CodegenContext context, @NotNull CodegenContext context,
@@ -259,14 +259,14 @@ public class InlineCodegen extends CallGenerator {
); );
} }
final GenerationState state = codegen.getState(); GenerationState state = codegen.getState();
final Method asmMethod = Method asmMethod =
callDefault callDefault
? state.getTypeMapper().mapDefaultMethod(functionDescriptor, context.getContextKind()) ? state.getTypeMapper().mapDefaultMethod(functionDescriptor, context.getContextKind())
: jvmSignature.getAsmMethod(); : jvmSignature.getAsmMethod();
MethodId methodId = new MethodId(DescriptorUtils.getFqNameSafe(functionDescriptor.getContainingDeclaration()), asmMethod); MethodId methodId = new MethodId(DescriptorUtils.getFqNameSafe(functionDescriptor.getContainingDeclaration()), asmMethod);
final CallableMemberDescriptor directMember = getDirectMemberAndCallableFromObject(functionDescriptor); CallableMemberDescriptor directMember = getDirectMemberAndCallableFromObject(functionDescriptor);
if (!isBuiltInArrayIntrinsic(functionDescriptor) && !(directMember instanceof DeserializedCallableMemberDescriptor)) { if (!isBuiltInArrayIntrinsic(functionDescriptor) && !(directMember instanceof DeserializedCallableMemberDescriptor)) {
return doCreateMethodNodeFromSource(functionDescriptor, jvmSignature, codegen, context, callDefault, state, asmMethod); return doCreateMethodNodeFromSource(functionDescriptor, jvmSignature, codegen, context, callDefault, state, asmMethod);
} }
@@ -310,7 +310,7 @@ public class InlineCodegen extends CallGenerator {
@Nullable @Nullable
private static SMAPAndMethodNode doCreateMethodNodeFromCompiled( private static SMAPAndMethodNode doCreateMethodNodeFromCompiled(
@NotNull CallableMemberDescriptor callableDescriptor, @NotNull CallableMemberDescriptor callableDescriptor,
@NotNull final GenerationState state, @NotNull GenerationState state,
@NotNull Method asmMethod @NotNull Method asmMethod
) { ) {
if (isBuiltInArrayIntrinsic(callableDescriptor)) { if (isBuiltInArrayIntrinsic(callableDescriptor)) {
@@ -330,7 +330,7 @@ public class InlineCodegen extends CallGenerator {
KotlinTypeMapper.ContainingClassesInfo containingClasses = KotlinTypeMapper.ContainingClassesInfo containingClasses =
state.getTypeMapper().getContainingClassesForDeserializedCallable((DeserializedCallableMemberDescriptor) callableDescriptor); state.getTypeMapper().getContainingClassesForDeserializedCallable((DeserializedCallableMemberDescriptor) callableDescriptor);
final 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, new Function0<byte[]>() {
@Override @Override
@@ -454,7 +454,7 @@ public class InlineCodegen extends CallGenerator {
result.getReifiedTypeParametersUsages().mergeAll(reificationResult); result.getReifiedTypeParametersUsages().mergeAll(reificationResult);
CallableMemberDescriptor descriptor = getLabelOwnerDescriptor(codegen.getContext()); CallableMemberDescriptor descriptor = getLabelOwnerDescriptor(codegen.getContext());
final Set<String> labels = getDeclarationLabels(DescriptorToSourceUtils.descriptorToDeclaration(descriptor), descriptor); Set<String> labels = getDeclarationLabels(DescriptorToSourceUtils.descriptorToDeclaration(descriptor), descriptor);
LabelOwner labelOwner = new LabelOwner() { LabelOwner labelOwner = new LabelOwner() {
@Override @Override
public boolean isMyLabel(@NotNull String name) { public boolean isMyLabel(@NotNull String name) {
@@ -747,8 +747,8 @@ public class InlineCodegen extends CallGenerator {
return true; return true;
} }
private Runnable recordParameterValueInLocalVal(boolean delayedWritingToLocals, @NotNull final ParameterInfo... infos) { private Runnable recordParameterValueInLocalVal(boolean delayedWritingToLocals, @NotNull ParameterInfo... infos) {
final int[] index = new int[infos.length]; int[] index = new int[infos.length];
for (int i = 0; i < infos.length; i++) { for (int i = 0; i < infos.length; i++) {
ParameterInfo info = infos[i]; ParameterInfo info = infos[i];
if (!info.isSkippedOrRemapped()) { if (!info.isSkippedOrRemapped()) {
@@ -91,14 +91,14 @@ public class InlineCodegenUtil {
@Nullable @Nullable
public static SMAPAndMethodNode getMethodNode( public static SMAPAndMethodNode getMethodNode(
byte[] classData, byte[] classData,
final String methodName, String methodName,
final String methodDescriptor, String methodDescriptor,
ClassId classId ClassId classId
) { ) {
ClassReader cr = new ClassReader(classData); ClassReader cr = new ClassReader(classData);
final MethodNode[] node = new MethodNode[1]; MethodNode[] node = new MethodNode[1];
final String[] debugInfo = new String[2]; String[] debugInfo = new String[2];
final int[] lines = new int[2]; int[] lines = new int[2];
lines[0] = Integer.MAX_VALUE; lines[0] = Integer.MAX_VALUE;
lines[1] = Integer.MIN_VALUE; lines[1] = Integer.MIN_VALUE;
//noinspection PointlessBitwiseExpression //noinspection PointlessBitwiseExpression
@@ -429,7 +429,7 @@ public class MaxStackFrameSizeAndLocalsCalculator extends MaxLocalsCalculator {
// Utility methods // Utility methods
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
private LabelWrapper getLabelWrapper(final Label label) { private LabelWrapper getLabelWrapper(Label label) {
return ContainerUtil.getOrCreate(labelWrappersMap, label, new Factory<LabelWrapper>() { return ContainerUtil.getOrCreate(labelWrappersMap, label, new Factory<LabelWrapper>() {
@Override @Override
public LabelWrapper create() { public LabelWrapper create() {
@@ -126,7 +126,7 @@ public class RedundantBoxingMethodTransformer extends MethodTransformer {
return needToRepeat; return needToRepeat;
} }
private static boolean isUnsafeToRemoveBoxingForConnectedValues(List<BasicValue> usedValues, final Type unboxedType) { private static boolean isUnsafeToRemoveBoxingForConnectedValues(List<BasicValue> usedValues, Type unboxedType) {
return CollectionsKt.any(usedValues, new Function1<BasicValue, Boolean>() { return CollectionsKt.any(usedValues, new Function1<BasicValue, Boolean>() {
@Override @Override
public Boolean invoke(BasicValue input) { public Boolean invoke(BasicValue input) {
@@ -464,7 +464,7 @@ public class KotlinTypeMapper {
@NotNull @NotNull
public Type mapType( public Type mapType(
@NotNull KotlinType kotlinType, @NotNull KotlinType kotlinType,
@Nullable final JvmSignatureWriter signatureVisitor, @Nullable JvmSignatureWriter signatureVisitor,
@NotNull TypeMappingMode mode @NotNull TypeMappingMode mode
) { ) {
return TypeSignatureMappingKt.mapType( return TypeSignatureMappingKt.mapType(
@@ -480,7 +480,7 @@ public class Args {
* @param methodName the name of the one arg method taking a String as parameter that will be used to built a new value * @param methodName the name of the one arg method taking a String as parameter that will be used to built a new value
* @return null if the object could not be created, the value otherwise * @return null if the object could not be created, the value otherwise
*/ */
public static ValueCreator byStaticMethodInvocation(final Class<?> compatibleType, final String methodName) { public static ValueCreator byStaticMethodInvocation(Class<?> compatibleType, String methodName) {
return new ValueCreator() { return new ValueCreator() {
public Object createValue(Class<?> type, String value) { public Object createValue(Class<?> type, String value) {
Object v = null; Object v = null;
@@ -94,7 +94,7 @@ public class K2JSCompiler extends CLICompiler<K2JSCompilerArguments> {
protected ExitCode doExecute( protected ExitCode doExecute(
@NotNull K2JSCompilerArguments arguments, @NotNull CompilerConfiguration configuration, @NotNull Disposable rootDisposable @NotNull K2JSCompilerArguments arguments, @NotNull CompilerConfiguration configuration, @NotNull Disposable rootDisposable
) { ) {
final MessageCollector messageCollector = configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY); MessageCollector messageCollector = configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY);
if (arguments.freeArgs.isEmpty()) { if (arguments.freeArgs.isEmpty()) {
if (arguments.version) { if (arguments.version) {
@@ -242,7 +242,7 @@ public class K2JSCompiler extends CLICompiler<K2JSCompilerArguments> {
} }
private static AnalyzerWithCompilerReport analyzeAndReportErrors( private static AnalyzerWithCompilerReport analyzeAndReportErrors(
@NotNull MessageCollector messageCollector, @NotNull final List<KtFile> sources, @NotNull final JsConfig config @NotNull MessageCollector messageCollector, @NotNull List<KtFile> sources, @NotNull JsConfig config
) { ) {
AnalyzerWithCompilerReport analyzerWithCompilerReport = new AnalyzerWithCompilerReport(messageCollector); AnalyzerWithCompilerReport analyzerWithCompilerReport = new AnalyzerWithCompilerReport(messageCollector);
analyzerWithCompilerReport.analyzeAndReport(sources, new AnalyzerWithCompilerReport.Analyzer() { analyzerWithCompilerReport.analyzeAndReport(sources, new AnalyzerWithCompilerReport.Analyzer() {
@@ -148,17 +148,17 @@ public class CompileEnvironmentUtil {
@NotNull @NotNull
public static List<KtFile> getKtFiles( public static List<KtFile> getKtFiles(
@NotNull final Project project, @NotNull Project project,
@NotNull Collection<String> sourceRoots, @NotNull Collection<String> sourceRoots,
@NotNull CompilerConfiguration configuration, @NotNull CompilerConfiguration configuration,
@NotNull Function1<String, Unit> reportError @NotNull Function1<String, Unit> reportError
) throws IOException { ) throws IOException {
final VirtualFileSystem localFileSystem = VirtualFileManager.getInstance().getFileSystem(StandardFileSystems.FILE_PROTOCOL); VirtualFileSystem localFileSystem = VirtualFileManager.getInstance().getFileSystem(StandardFileSystems.FILE_PROTOCOL);
final Set<VirtualFile> processedFiles = Sets.newHashSet(); Set<VirtualFile> processedFiles = Sets.newHashSet();
final List<KtFile> result = Lists.newArrayList(); List<KtFile> result = Lists.newArrayList();
final PreprocessedFileCreator virtualFileCreator = new PreprocessedFileCreator(project); PreprocessedFileCreator virtualFileCreator = new PreprocessedFileCreator(project);
for (String sourceRootPath : sourceRoots) { for (String sourceRootPath : sourceRoots) {
if (sourceRootPath == null) { if (sourceRootPath == null) {
@@ -229,8 +229,8 @@ public class SingleAbstractMethodUtils {
} }
@NotNull @NotNull
public static SamAdapterDescriptor<JavaMethodDescriptor> createSamAdapterFunction(@NotNull final JavaMethodDescriptor original) { public static SamAdapterDescriptor<JavaMethodDescriptor> createSamAdapterFunction(@NotNull JavaMethodDescriptor original) {
final SamAdapterFunctionDescriptor result = new SamAdapterFunctionDescriptor(original); SamAdapterFunctionDescriptor result = new SamAdapterFunctionDescriptor(original);
return initSamAdapter(original, result, new FunctionInitializer() { return initSamAdapter(original, result, new FunctionInitializer() {
@Override @Override
public void initialize( public void initialize(
@@ -252,8 +252,8 @@ public class SingleAbstractMethodUtils {
} }
@NotNull @NotNull
public static SamAdapterDescriptor<JavaClassConstructorDescriptor> createSamAdapterConstructor(@NotNull final JavaClassConstructorDescriptor original) { public static SamAdapterDescriptor<JavaClassConstructorDescriptor> createSamAdapterConstructor(@NotNull JavaClassConstructorDescriptor original) {
final SamAdapterClassConstructorDescriptor result = new SamAdapterClassConstructorDescriptor(original); SamAdapterClassConstructorDescriptor result = new SamAdapterClassConstructorDescriptor(original);
return initSamAdapter(original, result, new FunctionInitializer() { return initSamAdapter(original, result, new FunctionInitializer() {
@Override @Override
public void initialize( public void initialize(
@@ -89,10 +89,10 @@ public abstract class FileBasedKotlinClass implements KotlinJvmBinaryClass {
@NotNull byte[] fileContents, @NotNull byte[] fileContents,
@NotNull Function4<ClassId, Integer, KotlinClassHeader, InnerClassesInfo, T> factory @NotNull Function4<ClassId, Integer, KotlinClassHeader, InnerClassesInfo, T> factory
) { ) {
final ReadKotlinClassHeaderAnnotationVisitor readHeaderVisitor = new ReadKotlinClassHeaderAnnotationVisitor(); ReadKotlinClassHeaderAnnotationVisitor readHeaderVisitor = new ReadKotlinClassHeaderAnnotationVisitor();
final Ref<String> classNameRef = Ref.create(); Ref<String> classNameRef = Ref.create();
final Ref<Integer> classVersion = Ref.create(); Ref<Integer> classVersion = Ref.create();
final InnerClassesInfo innerClasses = new InnerClassesInfo(); InnerClassesInfo innerClasses = new InnerClassesInfo();
new ClassReader(fileContents).accept(new ClassVisitor(ASM5) { new ClassReader(fileContents).accept(new ClassVisitor(ASM5) {
@Override @Override
public void visit(int version, int access, @NotNull String name, String signature, String superName, String[] interfaces) { public void visit(int version, int access, @NotNull String name, String signature, String superName, String[] interfaces) {
@@ -143,7 +143,7 @@ public abstract class FileBasedKotlinClass implements KotlinJvmBinaryClass {
} }
@Override @Override
public void loadClassAnnotations(@NotNull final AnnotationVisitor annotationVisitor, @Nullable byte[] cachedContents) { public void loadClassAnnotations(@NotNull AnnotationVisitor annotationVisitor, @Nullable byte[] cachedContents) {
byte[] fileContents = cachedContents != null ? cachedContents : getFileContents(); byte[] fileContents = cachedContents != null ? cachedContents : getFileContents();
new ClassReader(fileContents).accept(new ClassVisitor(ASM5) { new ClassReader(fileContents).accept(new ClassVisitor(ASM5) {
@Override @Override
@@ -168,7 +168,7 @@ public abstract class FileBasedKotlinClass implements KotlinJvmBinaryClass {
@NotNull @NotNull
private static org.jetbrains.org.objectweb.asm.AnnotationVisitor convertAnnotationVisitor( private static org.jetbrains.org.objectweb.asm.AnnotationVisitor convertAnnotationVisitor(
@NotNull final AnnotationArgumentVisitor v, @NotNull final InnerClassesInfo innerClasses @NotNull AnnotationArgumentVisitor v, @NotNull InnerClassesInfo innerClasses
) { ) {
return new org.jetbrains.org.objectweb.asm.AnnotationVisitor(ASM5) { return new org.jetbrains.org.objectweb.asm.AnnotationVisitor(ASM5) {
@Override @Override
@@ -178,7 +178,7 @@ public abstract class FileBasedKotlinClass implements KotlinJvmBinaryClass {
@Override @Override
public org.jetbrains.org.objectweb.asm.AnnotationVisitor visitArray(String name) { public org.jetbrains.org.objectweb.asm.AnnotationVisitor visitArray(String name) {
final AnnotationArrayArgumentVisitor arv = v.visitArray(Name.identifier(name)); AnnotationArrayArgumentVisitor arv = v.visitArray(Name.identifier(name));
return arv == null ? null : new org.jetbrains.org.objectweb.asm.AnnotationVisitor(ASM5) { return arv == null ? null : new org.jetbrains.org.objectweb.asm.AnnotationVisitor(ASM5) {
@Override @Override
public void visit(String name, @NotNull Object value) { public void visit(String name, @NotNull Object value) {
@@ -216,12 +216,12 @@ public abstract class FileBasedKotlinClass implements KotlinJvmBinaryClass {
} }
@Override @Override
public void visitMembers(@NotNull final MemberVisitor memberVisitor, @Nullable byte[] cachedContents) { public void visitMembers(@NotNull MemberVisitor memberVisitor, @Nullable byte[] cachedContents) {
byte[] fileContents = cachedContents != null ? cachedContents : getFileContents(); byte[] fileContents = cachedContents != null ? cachedContents : getFileContents();
new ClassReader(fileContents).accept(new ClassVisitor(ASM5) { new ClassReader(fileContents).accept(new ClassVisitor(ASM5) {
@Override @Override
public FieldVisitor visitField(int access, @NotNull String name, @NotNull String desc, String signature, Object value) { public FieldVisitor visitField(int access, @NotNull String name, @NotNull String desc, String signature, Object value) {
final AnnotationVisitor v = memberVisitor.visitField(Name.identifier(name), desc, value); AnnotationVisitor v = memberVisitor.visitField(Name.identifier(name), desc, value);
if (v == null) return null; if (v == null) return null;
return new FieldVisitor(ASM5) { return new FieldVisitor(ASM5) {
@@ -239,7 +239,7 @@ public abstract class FileBasedKotlinClass implements KotlinJvmBinaryClass {
@Override @Override
public MethodVisitor visitMethod(int access, @NotNull String name, @NotNull String desc, String signature, String[] exceptions) { public MethodVisitor visitMethod(int access, @NotNull String name, @NotNull String desc, String signature, String[] exceptions) {
final MethodAnnotationVisitor v = memberVisitor.visitMethod(Name.identifier(name), desc); MethodAnnotationVisitor v = memberVisitor.visitMethod(Name.identifier(name), desc);
if (v == null) return null; if (v == null) return null;
return new MethodVisitor(ASM5) { return new MethodVisitor(ASM5) {
@@ -76,7 +76,7 @@ public class KotlinJavaPsiFacade {
emptyModifierList = new LightModifierList(PsiManager.getInstance(project), KotlinLanguage.INSTANCE); emptyModifierList = new LightModifierList(PsiManager.getInstance(project), KotlinLanguage.INSTANCE);
final PsiModificationTracker modificationTracker = PsiManager.getInstance(project).getModificationTracker(); PsiModificationTracker modificationTracker = PsiManager.getInstance(project).getModificationTracker();
MessageBus bus = project.getMessageBus(); MessageBus bus = project.getMessageBus();
bus.connect().subscribe(PsiModificationTracker.TOPIC, new PsiModificationTracker.Listener() { bus.connect().subscribe(PsiModificationTracker.TOPIC, new PsiModificationTracker.Listener() {
@@ -415,7 +415,7 @@ public class KotlinJavaPsiFacade {
return false; return false;
} }
private static boolean hasDirectoriesInScope(Query<VirtualFile> dirs, final GlobalSearchScope scope) { private static boolean hasDirectoriesInScope(Query<VirtualFile> dirs, GlobalSearchScope scope) {
CommonProcessors.FindProcessor<VirtualFile> findProcessor = new CommonProcessors.FindProcessor<VirtualFile>() { CommonProcessors.FindProcessor<VirtualFile> findProcessor = new CommonProcessors.FindProcessor<VirtualFile>() {
@Override @Override
protected boolean accept(VirtualFile file) { protected boolean accept(VirtualFile file) {
@@ -128,8 +128,8 @@ public class SignaturesPropagationData {
boolean shouldBeExtension = checkIfShouldBeExtension(); boolean shouldBeExtension = checkIfShouldBeExtension();
for (final ValueParameterDescriptor originalParam : parameters) { for (ValueParameterDescriptor originalParam : parameters) {
final int originalIndex = originalParam.getIndex(); int originalIndex = originalParam.getIndex();
List<TypeAndName> typesFromSuperMethods = ContainerUtil.map(superFunctions, List<TypeAndName> typesFromSuperMethods = ContainerUtil.map(superFunctions,
new Function<FunctionDescriptor, TypeAndName>() { new Function<FunctionDescriptor, TypeAndName>() {
@Override @Override
@@ -42,7 +42,7 @@ import static org.jetbrains.kotlin.resolve.BindingContextUtils.variableDescripto
public class PseudocodeUtil { public class PseudocodeUtil {
@NotNull @NotNull
public static Pseudocode generatePseudocode(@NotNull KtDeclaration declaration, @NotNull final BindingContext bindingContext) { public static Pseudocode generatePseudocode(@NotNull KtDeclaration declaration, @NotNull BindingContext bindingContext) {
BindingTrace mockTrace = new BindingTrace() { BindingTrace mockTrace = new BindingTrace() {
@NotNull @NotNull
@Override @Override
@@ -153,11 +153,11 @@ public class CheckerTestUtil {
private static List<ActualDiagnostic> getDebugInfoDiagnostics( private static List<ActualDiagnostic> getDebugInfoDiagnostics(
@NotNull PsiElement root, @NotNull PsiElement root,
@NotNull BindingContext bindingContext, @NotNull BindingContext bindingContext,
final boolean markDynamicCalls, boolean markDynamicCalls,
@Nullable final List<DeclarationDescriptor> dynamicCallDescriptors, @Nullable List<DeclarationDescriptor> dynamicCallDescriptors,
@Nullable final String platform @Nullable String platform
) { ) {
final List<ActualDiagnostic> debugAnnotations = new ArrayList<ActualDiagnostic>(); List<ActualDiagnostic> debugAnnotations = new ArrayList<ActualDiagnostic>();
DebugInfoUtil.markDebugAnnotations(root, bindingContext, new DebugInfoUtil.DebugInfoReporter() { DebugInfoUtil.markDebugAnnotations(root, bindingContext, new DebugInfoUtil.DebugInfoReporter() {
@Override @Override
@@ -297,7 +297,7 @@ public class CheckerTestUtil {
Map<ActualDiagnostic, TextDiagnostic> actualDiagnostics = currentActual.getTextDiagnosticsMap(); Map<ActualDiagnostic, TextDiagnostic> actualDiagnostics = currentActual.getTextDiagnosticsMap();
List<TextDiagnostic> expectedDiagnostics = currentExpected.getDiagnostics(); List<TextDiagnostic> expectedDiagnostics = currentExpected.getDiagnostics();
for (final 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(), new Function1<Map.Entry<ActualDiagnostic, TextDiagnostic>, Boolean>() {
@Override @Override
@@ -69,10 +69,10 @@ public class DebugInfoUtil {
public static void markDebugAnnotations( public static void markDebugAnnotations(
@NotNull PsiElement root, @NotNull PsiElement root,
@NotNull final BindingContext bindingContext, @NotNull BindingContext bindingContext,
@NotNull final DebugInfoReporter debugInfoReporter @NotNull DebugInfoReporter debugInfoReporter
) { ) {
final Map<KtReferenceExpression, DiagnosticFactory<?>> markedWithErrorElements = Maps.newHashMap(); Map<KtReferenceExpression, DiagnosticFactory<?>> markedWithErrorElements = Maps.newHashMap();
for (Diagnostic diagnostic : bindingContext.getDiagnostics()) { for (Diagnostic diagnostic : bindingContext.getDiagnostics()) {
DiagnosticFactory<?> factory = diagnostic.getFactory(); DiagnosticFactory<?> factory = diagnostic.getFactory();
if (Errors.UNRESOLVED_REFERENCE_DIAGNOSTICS.contains(diagnostic.getFactory())) { if (Errors.UNRESOLVED_REFERENCE_DIAGNOSTICS.contains(diagnostic.getFactory())) {
@@ -19,7 +19,7 @@ package org.jetbrains.kotlin.parsing;
public abstract class AbstractTokenStreamPredicate implements TokenStreamPredicate { public abstract class AbstractTokenStreamPredicate implements TokenStreamPredicate {
@Override @Override
public TokenStreamPredicate or(final TokenStreamPredicate other) { public TokenStreamPredicate or(TokenStreamPredicate other) {
return new AbstractTokenStreamPredicate() { return new AbstractTokenStreamPredicate() {
@Override @Override
public boolean matching(boolean topLevel) { public boolean matching(boolean topLevel) {
@@ -64,7 +64,7 @@ public class KotlinParsing extends AbstractKotlinParsing {
} }
private static KotlinParsing createForByClause(SemanticWhitespaceAwarePsiBuilder builder) { private static KotlinParsing createForByClause(SemanticWhitespaceAwarePsiBuilder builder) {
final SemanticWhitespaceAwarePsiBuilderForByClause builderForByClause = new SemanticWhitespaceAwarePsiBuilderForByClause(builder); SemanticWhitespaceAwarePsiBuilderForByClause builderForByClause = new SemanticWhitespaceAwarePsiBuilderForByClause(builder);
KotlinParsing kotlinParsing = new KotlinParsing(builderForByClause); KotlinParsing kotlinParsing = new KotlinParsing(builderForByClause);
kotlinParsing.myExpressionParsing = new KotlinExpressionParsing(builderForByClause, kotlinParsing) { kotlinParsing.myExpressionParsing = new KotlinExpressionParsing(builderForByClause, kotlinParsing) {
@Override @Override
@@ -109,7 +109,7 @@ public class KtPsiUtil {
@NotNull @NotNull
public static Set<KtElement> findRootExpressions(@NotNull Collection<KtElement> unreachableElements) { public static Set<KtElement> findRootExpressions(@NotNull Collection<KtElement> unreachableElements) {
Set<KtElement> rootElements = new HashSet<KtElement>(); Set<KtElement> rootElements = new HashSet<KtElement>();
final Set<KtElement> shadowedElements = new HashSet<KtElement>(); Set<KtElement> shadowedElements = new HashSet<KtElement>();
KtVisitorVoid shadowAllChildren = new KtVisitorVoid() { KtVisitorVoid shadowAllChildren = new KtVisitorVoid() {
@Override @Override
public void visitKtElement(@NotNull KtElement element) { public void visitKtElement(@NotNull KtElement element) {
@@ -47,7 +47,7 @@ public abstract class KtStubElementType<StubT extends StubElement, PsiT extends
@NotNull @NotNull
private final ArrayFactory<PsiT> arrayFactory; private final ArrayFactory<PsiT> arrayFactory;
public KtStubElementType(@NotNull @NonNls String debugName, @NotNull final Class<PsiT> psiClass, @NotNull Class<?> stubClass) { public KtStubElementType(@NotNull @NonNls String debugName, @NotNull Class<PsiT> psiClass, @NotNull Class<?> stubClass) {
super(debugName, KotlinLanguage.INSTANCE); super(debugName, KotlinLanguage.INSTANCE);
try { try {
byNodeConstructor = psiClass.getConstructor(ASTNode.class); byNodeConstructor = psiClass.getConstructor(ASTNode.class);
@@ -51,7 +51,7 @@ public class AnalyzingUtils {
} }
public static List<PsiErrorElement> getSyntaxErrorRanges(@NotNull PsiElement root) { public static List<PsiErrorElement> getSyntaxErrorRanges(@NotNull PsiElement root) {
final List<PsiErrorElement> r = new ArrayList<PsiErrorElement>(); List<PsiErrorElement> r = new ArrayList<PsiErrorElement>();
root.acceptChildren(new PsiErrorElementVisitor() { root.acceptChildren(new PsiErrorElementVisitor() {
@Override @Override
public void visitErrorElement(@NotNull PsiErrorElement element) { public void visitErrorElement(@NotNull PsiErrorElement element) {
@@ -230,7 +230,7 @@ public class BindingContextUtils {
} }
static void addOwnDataTo( static void addOwnDataTo(
@NotNull final BindingTrace trace, @Nullable final 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(new Function3<WritableSlice, Object, Object, Void>() {
@@ -140,10 +140,10 @@ public class BodyResolver {
} }
public void resolveSecondaryConstructorBody( public void resolveSecondaryConstructorBody(
@NotNull final DataFlowInfo outerDataFlowInfo, @NotNull DataFlowInfo outerDataFlowInfo,
@NotNull final BindingTrace trace, @NotNull BindingTrace trace,
@NotNull final KtSecondaryConstructor constructor, @NotNull KtSecondaryConstructor constructor,
@NotNull final ClassConstructorDescriptor descriptor, @NotNull ClassConstructorDescriptor descriptor,
@NotNull LexicalScope declaringScope @NotNull LexicalScope declaringScope
) { ) {
ForceResolveUtil.forceResolveAllContents(descriptor.getAnnotations()); ForceResolveUtil.forceResolveAllContents(descriptor.getAnnotations());
@@ -266,21 +266,21 @@ public class BodyResolver {
} }
public void resolveSuperTypeEntryList( public void resolveSuperTypeEntryList(
@NotNull final DataFlowInfo outerDataFlowInfo, @NotNull DataFlowInfo outerDataFlowInfo,
@NotNull KtClassOrObject ktClass, @NotNull KtClassOrObject ktClass,
@NotNull final ClassDescriptor descriptor, @NotNull ClassDescriptor descriptor,
@Nullable final ConstructorDescriptor primaryConstructor, @Nullable ConstructorDescriptor primaryConstructor,
@NotNull LexicalScope scopeForConstructorResolution, @NotNull LexicalScope scopeForConstructorResolution,
@NotNull final LexicalScope scopeForMemberResolution @NotNull LexicalScope scopeForMemberResolution
) { ) {
final LexicalScope scopeForConstructor = LexicalScope scopeForConstructor =
primaryConstructor == null primaryConstructor == null
? null ? null
: FunctionDescriptorUtil.getFunctionInnerScope(scopeForConstructorResolution, primaryConstructor, trace, overloadChecker); : FunctionDescriptorUtil.getFunctionInnerScope(scopeForConstructorResolution, primaryConstructor, trace, overloadChecker);
final ExpressionTypingServices typeInferrer = expressionTypingServices; // TODO : flow ExpressionTypingServices typeInferrer = expressionTypingServices; // TODO : flow
final Map<KtTypeReference, KotlinType> supertypes = Maps.newLinkedHashMap(); Map<KtTypeReference, KotlinType> supertypes = Maps.newLinkedHashMap();
final ResolvedCall<?>[] primaryConstructorDelegationCall = new ResolvedCall[1]; ResolvedCall<?>[] primaryConstructorDelegationCall = new ResolvedCall[1];
KtVisitorVoid visitor = new KtVisitorVoid() { KtVisitorVoid visitor = new KtVisitorVoid() {
private void recordSupertype(KtTypeReference typeReference, KotlinType supertype) { private void recordSupertype(KtTypeReference typeReference, KotlinType supertype) {
if (supertype == null) return; if (supertype == null) return;
@@ -633,7 +633,7 @@ public class BodyResolver {
private static LexicalScope getPrimaryConstructorParametersScope( private static LexicalScope getPrimaryConstructorParametersScope(
LexicalScope originalScope, LexicalScope originalScope,
final ConstructorDescriptor unsubstitutedPrimaryConstructor ConstructorDescriptor unsubstitutedPrimaryConstructor
) { ) {
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,
@@ -736,7 +736,7 @@ public class BodyResolver {
} }
} }
private ObservableBindingTrace createFieldTrackingTrace(final 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>() { new ObservableBindingTrace.RecordHandler<KtReferenceExpression, DeclarationDescriptor>() {
@@ -847,7 +847,7 @@ public class BodyResolver {
if (functionDescriptor instanceof PropertyAccessorDescriptor && functionDescriptor.getExtensionReceiverParameter() == null) { if (functionDescriptor instanceof PropertyAccessorDescriptor && functionDescriptor.getExtensionReceiverParameter() == null) {
PropertyAccessorDescriptor accessorDescriptor = (PropertyAccessorDescriptor) functionDescriptor; PropertyAccessorDescriptor accessorDescriptor = (PropertyAccessorDescriptor) functionDescriptor;
KtProperty property = (KtProperty) function.getParent(); KtProperty property = (KtProperty) function.getParent();
final 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, new Function1<LexicalScopeImpl.InitializeHandler, Unit>() {
@@ -913,7 +913,7 @@ public class BodyResolver {
return; return;
} }
// +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
final 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, new ObservableBindingTrace.RecordHandler<Box<DeferredType>, Boolean>() {
@Override @Override
public void handleRecord( public void handleRecord(
@@ -295,9 +295,12 @@ public class DescriptorResolver {
@NotNull @NotNull
public ValueParameterDescriptorImpl resolveValueParameterDescriptor( public ValueParameterDescriptorImpl resolveValueParameterDescriptor(
@NotNull final LexicalScope scope, @NotNull final FunctionDescriptor owner, @NotNull LexicalScope scope,
@NotNull KtParameter valueParameter, int index, @NotNull FunctionDescriptor owner,
@NotNull final KotlinType type, @NotNull final BindingTrace trace @NotNull KtParameter valueParameter,
int index,
@NotNull KotlinType type,
@NotNull BindingTrace trace
) { ) {
KotlinType varargElementType = null; KotlinType varargElementType = null;
KotlinType variableType = type; KotlinType variableType = type;
@@ -323,7 +326,7 @@ public class DescriptorResolver {
} }
} }
final KtDestructuringDeclaration destructuringDeclaration = valueParameter.getDestructuringDeclaration(); KtDestructuringDeclaration destructuringDeclaration = valueParameter.getDestructuringDeclaration();
Function0<List<VariableDescriptor>> destructuringVariables; Function0<List<VariableDescriptor>> destructuringVariables;
if (destructuringDeclaration != null) { if (destructuringDeclaration != null) {
@@ -436,11 +439,11 @@ public class DescriptorResolver {
} }
private TypeParameterDescriptorImpl resolveTypeParameterForDescriptor( private TypeParameterDescriptorImpl resolveTypeParameterForDescriptor(
final DeclarationDescriptor containingDescriptor, DeclarationDescriptor containingDescriptor,
LexicalScope scopeForAnnotationsResolve, LexicalScope scopeForAnnotationsResolve,
final KtTypeParameter typeParameter, KtTypeParameter typeParameter,
int index, int index,
final BindingTrace trace BindingTrace trace
) { ) {
if (typeParameter.getVariance() != Variance.INVARIANT) { if (typeParameter.getVariance() != Variance.INVARIANT) {
trace.report(VARIANCE_ON_TYPE_PARAMETER_NOT_ALLOWED.on(typeParameter)); trace.report(VARIANCE_ON_TYPE_PARAMETER_NOT_ALLOWED.on(typeParameter));
@@ -701,7 +704,7 @@ public class DescriptorResolver {
@NotNull DeclarationDescriptor containingDeclaration, @NotNull DeclarationDescriptor containingDeclaration,
@NotNull LexicalScope scope, @NotNull LexicalScope scope,
@NotNull KtTypeAlias typeAlias, @NotNull KtTypeAlias typeAlias,
@NotNull final BindingTrace trace @NotNull BindingTrace trace
) { ) {
if (!(containingDeclaration instanceof PackageFragmentDescriptor)) { if (!(containingDeclaration instanceof PackageFragmentDescriptor)) {
trace.report(TOPLEVEL_TYPEALIASES_ONLY.on(typeAlias)); trace.report(TOPLEVEL_TYPEALIASES_ONLY.on(typeAlias));
@@ -711,13 +714,13 @@ public class DescriptorResolver {
Visibility visibility = resolveVisibilityFromModifiers(typeAlias, getDefaultVisibility(typeAlias, containingDeclaration)); Visibility visibility = resolveVisibilityFromModifiers(typeAlias, getDefaultVisibility(typeAlias, containingDeclaration));
Annotations allAnnotations = annotationResolver.resolveAnnotationsWithArguments(scope, modifierList, trace); Annotations allAnnotations = annotationResolver.resolveAnnotationsWithArguments(scope, modifierList, trace);
final Name name = KtPsiUtil.safeName(typeAlias.getName()); Name name = KtPsiUtil.safeName(typeAlias.getName());
SourceElement sourceElement = KotlinSourceElementKt.toSourceElement(typeAlias); SourceElement sourceElement = KotlinSourceElementKt.toSourceElement(typeAlias);
final LazyTypeAliasDescriptor typeAliasDescriptor = LazyTypeAliasDescriptor.create( LazyTypeAliasDescriptor typeAliasDescriptor = LazyTypeAliasDescriptor.create(
storageManager, trace, containingDeclaration, allAnnotations, name, sourceElement, visibility); storageManager, trace, containingDeclaration, allAnnotations, name, sourceElement, visibility);
List<TypeParameterDescriptorImpl> typeParameterDescriptors; List<TypeParameterDescriptorImpl> typeParameterDescriptors;
final LexicalScope scopeWithTypeParameters; LexicalScope scopeWithTypeParameters;
{ {
List<KtTypeParameter> typeParameters = typeAlias.getTypeParameters(); List<KtTypeParameter> typeParameters = typeAlias.getTypeParameters();
if (typeParameters.isEmpty()) { if (typeParameters.isEmpty()) {
@@ -737,7 +740,7 @@ public class DescriptorResolver {
} }
} }
final KtTypeReference typeReference = typeAlias.getTypeReference(); KtTypeReference typeReference = typeAlias.getTypeReference();
if (typeReference == null) { if (typeReference == null) {
typeAliasDescriptor.initialize( typeAliasDescriptor.initialize(
typeParameterDescriptors, typeParameterDescriptors,
@@ -797,7 +800,7 @@ public class DescriptorResolver {
@NotNull LexicalScope scopeForDeclarationResolution, @NotNull LexicalScope scopeForDeclarationResolution,
@NotNull LexicalScope scopeForInitializerResolution, @NotNull LexicalScope scopeForInitializerResolution,
@NotNull KtProperty property, @NotNull KtProperty property,
@NotNull final BindingTrace trace, @NotNull BindingTrace trace,
@NotNull DataFlowInfo dataFlowInfo @NotNull DataFlowInfo dataFlowInfo
) { ) {
KtModifierList modifierList = property.getModifierList(); KtModifierList modifierList = property.getModifierList();
@@ -810,7 +813,7 @@ public class DescriptorResolver {
trace.getBindingContext(), containingDeclaration) trace.getBindingContext(), containingDeclaration)
: Modality.FINAL; : Modality.FINAL;
final AnnotationSplitter.PropertyWrapper wrapper = new AnnotationSplitter.PropertyWrapper(property); AnnotationSplitter.PropertyWrapper wrapper = new AnnotationSplitter.PropertyWrapper(property);
Annotations allAnnotations = annotationResolver.resolveAnnotationsWithoutArguments(scopeForDeclarationResolution, modifierList, trace); Annotations allAnnotations = annotationResolver.resolveAnnotationsWithoutArguments(scopeForDeclarationResolution, modifierList, trace);
AnnotationSplitter annotationSplitter = AnnotationSplitter annotationSplitter =
@@ -1108,11 +1111,11 @@ public class DescriptorResolver {
@NotNull @NotNull
/*package*/ KotlinType inferReturnTypeFromExpressionBody( /*package*/ KotlinType inferReturnTypeFromExpressionBody(
@NotNull final BindingTrace trace, @NotNull BindingTrace trace,
@NotNull final LexicalScope scope, @NotNull LexicalScope scope,
@NotNull final DataFlowInfo dataFlowInfo, @NotNull DataFlowInfo dataFlowInfo,
@NotNull final KtDeclarationWithBody function, @NotNull KtDeclarationWithBody function,
@NotNull final FunctionDescriptor functionDescriptor @NotNull FunctionDescriptor functionDescriptor
) { ) {
return wrappedTypeFactory.createRecursionIntolerantDeferredType(trace, new Function0<KotlinType>() { return wrappedTypeFactory.createRecursionIntolerantDeferredType(trace, new Function0<KotlinType>() {
@Override @Override
@@ -1132,7 +1135,8 @@ public class DescriptorResolver {
@NotNull ClassDescriptor classDescriptor, @NotNull ClassDescriptor classDescriptor,
@NotNull ValueParameterDescriptor valueParameter, @NotNull ValueParameterDescriptor valueParameter,
@NotNull LexicalScope scope, @NotNull LexicalScope scope,
@NotNull KtParameter parameter, final BindingTrace trace @NotNull KtParameter parameter,
BindingTrace trace
) { ) {
KotlinType type = resolveParameterType(scope, parameter, trace); KotlinType type = resolveParameterType(scope, parameter, trace);
Name name = parameter.getNameAsSafeName(); Name name = parameter.getNameAsSafeName();
@@ -1145,7 +1149,7 @@ public class DescriptorResolver {
} }
} }
final 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, new Function0<Set<AnnotationUseSiteTarget>>() {
@@ -63,7 +63,7 @@ public class FunctionDescriptorUtil {
@NotNull @NotNull
public static LexicalScope getFunctionInnerScope( public static LexicalScope getFunctionInnerScope(
@NotNull LexicalScope outerScope, @NotNull LexicalScope outerScope,
@NotNull final FunctionDescriptor descriptor, @NotNull FunctionDescriptor descriptor,
@NotNull LocalRedeclarationChecker redeclarationChecker @NotNull LocalRedeclarationChecker redeclarationChecker
) { ) {
ReceiverParameterDescriptor receiver = descriptor.getExtensionReceiverParameter(); ReceiverParameterDescriptor receiver = descriptor.getExtensionReceiverParameter();
@@ -176,10 +176,10 @@ public class CallResolver {
@NotNull @NotNull
private <D extends CallableDescriptor> OverloadResolutionResults<D> computeTasksAndResolveCall( private <D extends CallableDescriptor> OverloadResolutionResults<D> computeTasksAndResolveCall(
@NotNull final BasicCallResolutionContext context, @NotNull BasicCallResolutionContext context,
@NotNull final Name name, @NotNull Name name,
@NotNull final TracingStrategy tracing, @NotNull TracingStrategy tracing,
@NotNull final NewResolutionOldInference.ResolutionKind<D> kind @NotNull NewResolutionOldInference.ResolutionKind<D> kind
) { ) {
return callResolvePerfCounter.time(new Function0<OverloadResolutionResults<D>>() { return callResolvePerfCounter.time(new Function0<OverloadResolutionResults<D>>() {
@Override @Override
@@ -204,9 +204,9 @@ public class CallResolver {
@NotNull @NotNull
private <D extends CallableDescriptor> OverloadResolutionResults<D> computeTasksFromCandidatesAndResolvedCall( private <D extends CallableDescriptor> OverloadResolutionResults<D> computeTasksFromCandidatesAndResolvedCall(
@NotNull final BasicCallResolutionContext context, @NotNull BasicCallResolutionContext context,
@NotNull final Collection<ResolutionCandidate<D>> candidates, @NotNull Collection<ResolutionCandidate<D>> candidates,
@NotNull final TracingStrategy tracing @NotNull TracingStrategy tracing
) { ) {
return callResolvePerfCounter.time(new Function0<OverloadResolutionResults<D>>() { return callResolvePerfCounter.time(new Function0<OverloadResolutionResults<D>>() {
@Override @Override
@@ -492,11 +492,11 @@ public class CallResolver {
} }
public OverloadResolutionResults<FunctionDescriptor> resolveCallWithKnownCandidate( public OverloadResolutionResults<FunctionDescriptor> resolveCallWithKnownCandidate(
@NotNull final Call call, @NotNull Call call,
@NotNull final TracingStrategy tracing, @NotNull TracingStrategy tracing,
@NotNull final ResolutionContext<?> context, @NotNull ResolutionContext<?> context,
@NotNull final ResolutionCandidate<FunctionDescriptor> candidate, @NotNull ResolutionCandidate<FunctionDescriptor> candidate,
@Nullable final MutableDataFlowInfoForArguments dataFlowInfoForArguments @Nullable MutableDataFlowInfoForArguments dataFlowInfoForArguments
) { ) {
return callResolvePerfCounter.time(new Function0<OverloadResolutionResults<FunctionDescriptor>>() { return callResolvePerfCounter.time(new Function0<OverloadResolutionResults<FunctionDescriptor>>() {
@Override @Override
@@ -299,7 +299,7 @@ public class CallMaker {
} }
@NotNull @NotNull
public static Call makeConstructorCallForEnumEntryWithoutInitializer(@NotNull final KtSuperTypeCallEntry callElement) { public static Call makeConstructorCallForEnumEntryWithoutInitializer(@NotNull KtSuperTypeCallEntry callElement) {
return new Call() { return new Call() {
@Nullable @Nullable
@Override @Override
@@ -370,7 +370,7 @@ public class CallMaker {
} }
@NotNull @NotNull
public static Call makeCall(@Nullable final Receiver explicitReceiver, @Nullable final ASTNode callOperationNode, @NotNull final KtCallElement callElement) { public static Call makeCall(@Nullable Receiver explicitReceiver, @Nullable ASTNode callOperationNode, @NotNull KtCallElement callElement) {
return new Call() { return new Call() {
@Override @Override
public ASTNode getCallOperationNode() { public ASTNode getCallOperationNode() {
@@ -114,7 +114,7 @@ public class LazyDeclarationResolver {
} }
@NotNull @NotNull
private DeclarationDescriptor resolveToDescriptor(@NotNull KtDeclaration declaration, final boolean track) { private DeclarationDescriptor resolveToDescriptor(@NotNull KtDeclaration declaration, boolean track) {
DeclarationDescriptor result = declaration.accept(new KtVisitor<DeclarationDescriptor, Void>() { DeclarationDescriptor result = declaration.accept(new KtVisitor<DeclarationDescriptor, Void>() {
@NotNull @NotNull
private LookupLocation lookupLocationFor(@NotNull KtDeclaration declaration, boolean isTopLevel) { private LookupLocation lookupLocationFor(@NotNull KtDeclaration declaration, boolean isTopLevel) {
@@ -261,7 +261,7 @@ public class ResolveSession implements KotlinCodeAnalyzer, LazyClassContext {
@Override @Override
@NotNull @NotNull
@ReadOnly @ReadOnly
public Collection<ClassifierDescriptor> getTopLevelClassifierDescriptors(@NotNull FqName fqName, @NotNull final LookupLocation location) { public Collection<ClassifierDescriptor> getTopLevelClassifierDescriptors(@NotNull FqName fqName, @NotNull LookupLocation location) {
if (fqName.isRoot()) return Collections.emptyList(); if (fqName.isRoot()) return Collections.emptyList();
PackageMemberDeclarationProvider provider = declarationProviderFactory.getPackageMemberDeclarationProvider(fqName.parent()); PackageMemberDeclarationProvider provider = declarationProviderFactory.getPackageMemberDeclarationProvider(fqName.parent());
@@ -42,7 +42,7 @@ public class FileBasedDeclarationProviderFactory extends AbstractDeclarationProv
private final StorageManager storageManager; private final StorageManager storageManager;
private final NotNullLazyValue<Index> index; private final NotNullLazyValue<Index> index;
public FileBasedDeclarationProviderFactory(@NotNull StorageManager storageManager, @NotNull final 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(new Function0<Index>() {
@@ -110,10 +110,10 @@ public class LazyClassDescriptor extends ClassDescriptorBase implements ClassDes
private final NotNullLazyValue<Collection<ClassDescriptor>> sealedSubclasses; private final NotNullLazyValue<Collection<ClassDescriptor>> sealedSubclasses;
public LazyClassDescriptor( public LazyClassDescriptor(
@NotNull final LazyClassContext c, @NotNull LazyClassContext c,
@NotNull DeclarationDescriptor containingDeclaration, @NotNull DeclarationDescriptor containingDeclaration,
@NotNull Name name, @NotNull Name name,
@NotNull final KtClassLikeInfo classLikeInfo, @NotNull KtClassLikeInfo classLikeInfo,
boolean isExternal boolean isExternal
) { ) {
super(c.getStorageManager(), containingDeclaration, name, super(c.getStorageManager(), containingDeclaration, name,
@@ -140,7 +140,7 @@ public class LazyClassDescriptor extends ClassDescriptorBase implements ClassDes
this.isCompanionObject = classLikeInfo instanceof KtObjectInfo && ((KtObjectInfo) classLikeInfo).isCompanionObject(); this.isCompanionObject = classLikeInfo instanceof KtObjectInfo && ((KtObjectInfo) classLikeInfo).isCompanionObject();
final 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(new Function0<Modality>() {
@Override @Override
@@ -150,7 +150,7 @@ public class LazyClassDescriptor extends ClassDescriptorBase implements ClassDes
}); });
} }
else { else {
final 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(new Function0<Modality>() {
@Override @Override
public Modality invoke() { public Modality invoke() {
@@ -431,7 +431,7 @@ public class LazyClassDescriptor extends ClassDescriptorBase implements ClassDes
@NotNull @NotNull
@ReadOnly @ReadOnly
public List<ClassDescriptor> getDescriptorsForExtraCompanionObjects() { public List<ClassDescriptor> getDescriptorsForExtraCompanionObjects() {
final KtObjectDeclaration allowedCompanionObject = getCompanionObjectIfAllowed(); KtObjectDeclaration allowedCompanionObject = getCompanionObjectIfAllowed();
return CollectionsKt.map( return CollectionsKt.map(
CollectionsKt.filter( CollectionsKt.filter(
@@ -75,7 +75,7 @@ public class BoundsSubstitutor {
} }
@NotNull @NotNull
private static List<TypeParameterDescriptor> topologicallySortTypeParameters(@NotNull final List<TypeParameterDescriptor> typeParameters) { private static List<TypeParameterDescriptor> topologicallySortTypeParameters(@NotNull List<TypeParameterDescriptor> typeParameters) {
// 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(
@@ -98,7 +98,7 @@ public class BoundsSubstitutor {
@NotNull @NotNull
private static List<TypeParameterDescriptor> getTypeParametersFromUpperBounds( private static List<TypeParameterDescriptor> getTypeParametersFromUpperBounds(
@NotNull TypeParameterDescriptor current, @NotNull TypeParameterDescriptor current,
@NotNull final List<TypeParameterDescriptor> typeParameters @NotNull List<TypeParameterDescriptor> typeParameters
) { ) {
return DFS.dfs( return DFS.dfs(
current.getUpperBounds(), current.getUpperBounds(),
@@ -67,7 +67,7 @@ public class CommonSupertypes {
return max; return max;
} }
private static int depth(@NotNull final 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(), new Function1<TypeProjection, KotlinType>() {
@Override @Override
public KotlinType invoke(TypeProjection projection) { public KotlinType invoke(TypeProjection projection) {
@@ -331,8 +331,8 @@ public class CommonSupertypes {
@NotNull @NotNull
public static List<TypeConstructor> topologicallySortSuperclassesAndRecordAllInstances( public static List<TypeConstructor> topologicallySortSuperclassesAndRecordAllInstances(
@NotNull SimpleType type, @NotNull SimpleType type,
@NotNull final Map<TypeConstructor, Set<SimpleType>> constructorToAllInstances, @NotNull Map<TypeConstructor, Set<SimpleType>> constructorToAllInstances,
@NotNull final Set<TypeConstructor> visited @NotNull Set<TypeConstructor> visited
) { ) {
return DFS.dfs( return DFS.dfs(
Collections.singletonList(type), Collections.singletonList(type),
@@ -173,7 +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
final 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 = new Function1<TypeParameterUsage, Unit>() {
@Override @Override
public Unit invoke(TypeParameterUsage parameterUsage) { public Unit invoke(TypeParameterUsage parameterUsage) {
@@ -714,10 +714,10 @@ public class BasicExpressionTypingVisitor extends ExpressionTypingVisitor {
@Override @Override
public KotlinTypeInfo visitObjectLiteralExpression( public KotlinTypeInfo visitObjectLiteralExpression(
@NotNull final KtObjectLiteralExpression expression, @NotNull KtObjectLiteralExpression expression,
final ExpressionTypingContext context ExpressionTypingContext context
) { ) {
final 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.RecordHandler<PsiElement, ClassDescriptor> handler =
@@ -727,7 +727,7 @@ public class BasicExpressionTypingVisitor extends ExpressionTypingVisitor {
public void handleRecord( public void handleRecord(
WritableSlice<PsiElement, ClassDescriptor> slice, WritableSlice<PsiElement, ClassDescriptor> slice,
PsiElement declaration, PsiElement declaration,
final ClassDescriptor descriptor ClassDescriptor descriptor
) { ) {
if (slice == CLASS && declaration == expression.getObjectDeclaration()) { if (slice == CLASS && declaration == expression.getObjectDeclaration()) {
KotlinType defaultType = components.wrappedTypeFactory.createRecursionIntolerantDeferredType( KotlinType defaultType = components.wrappedTypeFactory.createRecursionIntolerantDeferredType(
@@ -1160,8 +1160,8 @@ public class BasicExpressionTypingVisitor extends ExpressionTypingVisitor {
KtBinaryExpression expression, KtBinaryExpression expression,
ExpressionTypingContext context, ExpressionTypingContext context,
KtSimpleNameExpression operationSign, KtSimpleNameExpression operationSign,
final KtExpression left, KtExpression left,
final KtExpression right KtExpression right
) { ) {
if (right == null || left == null) { if (right == null || left == null) {
ExpressionTypingUtils.getTypeInfoOrNullType(right, context, facade); ExpressionTypingUtils.getTypeInfoOrNullType(right, context, facade);
@@ -1445,7 +1445,7 @@ public class BasicExpressionTypingVisitor extends ExpressionTypingVisitor {
return true; return true;
} }
private void ensureNonemptyIntersectionOfOperandTypes(KtBinaryExpression expression, final ExpressionTypingContext context) { private void ensureNonemptyIntersectionOfOperandTypes(KtBinaryExpression expression, ExpressionTypingContext context) {
KtExpression left = expression.getLeft(); KtExpression left = expression.getLeft();
if (left == null) return; if (left == null) return;
@@ -1580,8 +1580,9 @@ public class BasicExpressionTypingVisitor extends ExpressionTypingVisitor {
@NotNull KtStringTemplateExpression expression, @NotNull KtStringTemplateExpression expression,
ExpressionTypingContext contextWithExpectedType ExpressionTypingContext contextWithExpectedType
) { ) {
final ExpressionTypingContext context = contextWithExpectedType.replaceExpectedType(NO_EXPECTED_TYPE) ExpressionTypingContext context = contextWithExpectedType
.replaceContextDependency(INDEPENDENT); .replaceExpectedType(NO_EXPECTED_TYPE)
.replaceContextDependency(INDEPENDENT);
checkLiteralPrefixAndSuffix(expression, context); checkLiteralPrefixAndSuffix(expression, context);
@@ -191,7 +191,7 @@ public class ControlStructureTypingUtils {
private static MutableDataFlowInfoForArguments createIndependentDataFlowInfoForArgumentsForCall( private static MutableDataFlowInfoForArguments createIndependentDataFlowInfoForArgumentsForCall(
@NotNull DataFlowInfo initialDataFlowInfo, @NotNull DataFlowInfo initialDataFlowInfo,
final Map<ValueArgument, DataFlowInfo> dataFlowInfoForArgumentsMap Map<ValueArgument, DataFlowInfo> dataFlowInfoForArgumentsMap
) { ) {
return new MutableDataFlowInfoForArguments(initialDataFlowInfo) { return new MutableDataFlowInfoForArguments(initialDataFlowInfo) {
@@ -235,11 +235,11 @@ public class ControlStructureTypingUtils {
} }
/*package*/ static Call createCallForSpecialConstruction( /*package*/ static Call createCallForSpecialConstruction(
@NotNull final KtExpression expression, @NotNull KtExpression expression,
@NotNull final KtExpression calleeExpression, @NotNull KtExpression calleeExpression,
@NotNull List<? extends KtExpression> arguments @NotNull List<? extends KtExpression> arguments
) { ) {
final List<ValueArgument> valueArguments = Lists.newArrayList(); List<ValueArgument> valueArguments = Lists.newArrayList();
for (KtExpression argument : arguments) { for (KtExpression argument : arguments) {
valueArguments.add(CallMaker.makeValueArgument(argument)); valueArguments.add(CallMaker.makeValueArgument(argument));
} }
@@ -314,9 +314,9 @@ public class ControlStructureTypingUtils {
@NotNull @NotNull
private TracingStrategy createTracingForSpecialConstruction( private TracingStrategy createTracingForSpecialConstruction(
final @NotNull Call call, @NotNull Call call,
@NotNull String constructionName, @NotNull String constructionName,
final @NotNull ExpressionTypingContext context @NotNull ExpressionTypingContext context
) { ) {
class CheckTypeContext { class CheckTypeContext {
public BindingTrace trace; public BindingTrace trace;
@@ -333,8 +333,7 @@ public class ControlStructureTypingUtils {
} }
} }
final KtVisitor<Boolean, CheckTypeContext> checkTypeVisitor = new KtVisitor<Boolean, CheckTypeContext>() { KtVisitor<Boolean, CheckTypeContext> checkTypeVisitor = new KtVisitor<Boolean, CheckTypeContext>() {
private boolean checkExpressionType(@NotNull KtExpression expression, CheckTypeContext c) { private boolean checkExpressionType(@NotNull KtExpression expression, CheckTypeContext c) {
KotlinTypeInfo typeInfo = BindingContextUtils.getRecordedTypeInfo(expression, c.trace.getBindingContext()); KotlinTypeInfo typeInfo = BindingContextUtils.getRecordedTypeInfo(expression, c.trace.getBindingContext());
if (typeInfo == null) return false; if (typeInfo == null) return false;
@@ -269,8 +269,8 @@ public class ControlStructureTypingVisitor extends ExpressionTypingVisitor {
.replaceDataFlowInfo(dataFlowInfo); .replaceDataFlowInfo(dataFlowInfo);
} }
private boolean containsJumpOutOfLoop(@NotNull final KtExpression expression, final ExpressionTypingContext context) { private boolean containsJumpOutOfLoop(@NotNull KtExpression expression, ExpressionTypingContext context) {
final boolean[] result = new boolean[1]; boolean[] result = new boolean[1];
result[0] = false; result[0] = false;
//todo breaks in inline function literals //todo breaks in inline function literals
expression.accept(new KtTreeVisitor<List<KtLoopExpression>>() { expression.accept(new KtTreeVisitor<List<KtLoopExpression>>() {
@@ -119,12 +119,12 @@ public class DataFlowAnalyzer {
@NotNull @NotNull
public DataFlowInfo extractDataFlowInfoFromCondition( public DataFlowInfo extractDataFlowInfoFromCondition(
@Nullable final KtExpression condition, @Nullable KtExpression condition,
final boolean conditionValue, boolean conditionValue,
final ExpressionTypingContext context ExpressionTypingContext context
) { ) {
if (condition == null) return context.dataFlowInfo; if (condition == null) return context.dataFlowInfo;
final Ref<DataFlowInfo> result = new Ref<DataFlowInfo>(null); Ref<DataFlowInfo> result = new Ref<DataFlowInfo>(null);
condition.accept(new KtVisitorVoid() { condition.accept(new KtVisitorVoid() {
@Override @Override
public void visitIsExpression(@NotNull KtIsExpression expression) { public void visitIsExpression(@NotNull KtIsExpression expression) {
@@ -99,12 +99,12 @@ public class ExpressionTypingServices {
@NotNull @NotNull
public KotlinTypeInfo getTypeInfo( public KotlinTypeInfo getTypeInfo(
@NotNull LexicalScope scope, @NotNull LexicalScope scope,
@NotNull final KtExpression expression, @NotNull KtExpression expression,
@NotNull KotlinType expectedType, @NotNull KotlinType expectedType,
@NotNull DataFlowInfo dataFlowInfo, @NotNull DataFlowInfo dataFlowInfo,
@NotNull BindingTrace trace, @NotNull BindingTrace trace,
boolean isStatement, boolean isStatement,
@NotNull final KtExpression contextExpression, @NotNull KtExpression contextExpression,
@NotNull ContextDependency contextDependency @NotNull ContextDependency contextDependency
) { ) {
ExpressionTypingContext context = ExpressionTypingContext.newContext( ExpressionTypingContext context = ExpressionTypingContext.newContext(
@@ -125,8 +125,8 @@ public class ExpressionTypingUtils {
public static ObservableBindingTrace makeTraceInterceptingTypeMismatch( public static ObservableBindingTrace makeTraceInterceptingTypeMismatch(
@NotNull BindingTrace trace, @NotNull BindingTrace trace,
@NotNull final KtElement expressionToWatch, @NotNull KtElement expressionToWatch,
@NotNull final boolean[] mismatchFound @NotNull boolean[] mismatchFound
) { ) {
return new ObservableBindingTrace(trace) { return new ObservableBindingTrace(trace) {
@@ -168,7 +168,7 @@ public abstract class ExpressionTypingVisitorDispatcher extends KtVisitor<Kotlin
} }
@NotNull @NotNull
private KotlinTypeInfo getTypeInfo(@NotNull final KtExpression expression, final ExpressionTypingContext context, final 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(new Function0<KotlinTypeInfo>() {
@Override @Override
public KotlinTypeInfo invoke() { public KotlinTypeInfo invoke() {
@@ -53,7 +53,7 @@ public class TrackingSlicedMap extends SlicedMapImpl {
} }
@Override @Override
public void forEach(@NotNull final 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(new Function3<WritableSlice, Object, Object, Void>() {
@Override @Override
public Void invoke(WritableSlice slice, Object key, Object value) { public Void invoke(WritableSlice slice, Object key, Object value) {
@@ -39,7 +39,7 @@ public class ClsWrapperStubPsiFactory extends StubPsiFactory {
@Override @Override
public PsiClass createClass(@NotNull PsiClassStub stub) { public PsiClass createClass(@NotNull PsiClassStub stub) {
final PsiElement origin = getOriginalElement(stub); PsiElement origin = getOriginalElement(stub);
return new ClsClassImpl(stub) { return new ClsClassImpl(stub) {
@NotNull @NotNull
@Override @Override
@@ -80,7 +80,7 @@ public class ClsWrapperStubPsiFactory extends StubPsiFactory {
@Override @Override
public PsiField createField(PsiFieldStub stub) { public PsiField createField(PsiFieldStub stub) {
final PsiElement origin = getOriginalElement(stub); PsiElement origin = getOriginalElement(stub);
if (origin == null) return delegate.createField(stub); if (origin == null) return delegate.createField(stub);
if (stub.isEnumConstant()) { if (stub.isEnumConstant()) {
return new ClsEnumConstantImpl(stub) { return new ClsEnumConstantImpl(stub) {
@@ -46,7 +46,7 @@ public class KtLightParameter extends LightParameter implements KtLightDeclarati
private final KtLightMethod method; private final KtLightMethod method;
private KtLightIdentifier lightIdentifier = null; private KtLightIdentifier lightIdentifier = null;
public KtLightParameter(final PsiParameter delegate, int index, KtLightMethod method) { public KtLightParameter(PsiParameter delegate, int index, KtLightMethod method) {
super(getName(delegate, index), delegate.getType(), method, KotlinLanguage.INSTANCE); super(getName(delegate, index), delegate.getType(), method, KotlinLanguage.INSTANCE);
this.delegate = delegate; this.delegate = delegate;
@@ -174,7 +174,7 @@ public class JavaElementFinder extends PsiElementFinder implements KotlinFinderM
@NotNull @NotNull
@Override @Override
public PsiPackage[] getSubPackages(@NotNull PsiPackage psiPackage, @NotNull final GlobalSearchScope scope) { public PsiPackage[] getSubPackages(@NotNull PsiPackage psiPackage, @NotNull GlobalSearchScope scope) {
FqName packageFQN = new FqName(psiPackage.getQualifiedName()); FqName packageFQN = new FqName(psiPackage.getQualifiedName());
Collection<FqName> subpackages = lightClassGenerationSupport.getSubPackages(packageFQN, scope); Collection<FqName> subpackages = lightClassGenerationSupport.getSubPackages(packageFQN, scope);
@@ -218,7 +218,7 @@ public class JavaElementFinder extends PsiElementFinder implements KotlinFinderM
@Override @Override
@Nullable @Nullable
public Condition<PsiFile> getPackageFilesFilter(@NotNull final PsiPackage psiPackage, @NotNull GlobalSearchScope scope) { public Condition<PsiFile> getPackageFilesFilter(@NotNull PsiPackage psiPackage, @NotNull GlobalSearchScope scope) {
return new Condition<PsiFile>() { return new Condition<PsiFile>() {
@Override @Override
public boolean value(PsiFile input) { public boolean value(PsiFile input) {
@@ -231,7 +231,7 @@ public class JavaElementFinder extends PsiElementFinder implements KotlinFinderM
} }
@NotNull @NotNull
public static Comparator<PsiElement> byClasspathComparator(@NotNull final GlobalSearchScope searchScope) { public static Comparator<PsiElement> byClasspathComparator(@NotNull GlobalSearchScope searchScope) {
return new Comparator<PsiElement>() { return new Comparator<PsiElement>() {
@Override @Override
public int compare(@NotNull PsiElement o1, @NotNull PsiElement o2) { public int compare(@NotNull PsiElement o1, @NotNull PsiElement o2) {
@@ -54,7 +54,7 @@ public class InterceptionInstrumenter {
} }
private void addHandlerClass(Class<?> handlerClass) { private void addHandlerClass(Class<?> handlerClass) {
for (final Field field : handlerClass.getFields()) { for (Field field : handlerClass.getFields()) {
MethodInterceptor annotation = field.getAnnotation(MethodInterceptor.class); MethodInterceptor annotation = field.getAnnotation(MethodInterceptor.class);
if (annotation == null) continue; if (annotation == null) continue;
@@ -71,7 +71,7 @@ public class InterceptionInstrumenter {
throw new IllegalArgumentException("Interceptor is null: " + field); throw new IllegalArgumentException("Interceptor is null: " + field);
} }
final Class<?> interceptorClass = interceptor.getClass(); Class<?> interceptorClass = interceptor.getClass();
FieldData fieldData = getFieldData(field, interceptorClass); FieldData fieldData = getFieldData(field, interceptorClass);
@@ -214,7 +214,7 @@ public class InterceptionInstrumenter {
allArgsParameterIndex); allArgsParameterIndex);
} }
private void addDumpTask(final Object interceptor, final Method method, final MethodInstrumenter instrumenter) { private void addDumpTask(Object interceptor, Method method, MethodInstrumenter instrumenter) {
dumpTasks.add(new DumpAction() { dumpTasks.add(new DumpAction() {
@Override @Override
public void dump(PrintStream out) { public void dump(PrintStream out) {
@@ -272,17 +272,17 @@ public class InterceptionInstrumenter {
return name.substring(0, name.length() - suffix.length()); return name.substring(0, name.length() - suffix.length());
} }
private byte[] instrument(byte[] classData, final List<MethodInstrumenter> instrumenters) { private byte[] instrument(byte[] classData, List<MethodInstrumenter> instrumenters) {
final ClassReader cr = new ClassReader(classData); ClassReader cr = new ClassReader(classData);
ClassWriter cw = new ClassWriter(cr, 0); ClassWriter cw = new ClassWriter(cr, 0);
cr.accept(new ClassVisitor(ASM5, cw) { cr.accept(new ClassVisitor(ASM5, cw) {
private final Map<MethodInstrumenter, String> matchedMethods = new HashMap<MethodInstrumenter, String>(); private final Map<MethodInstrumenter, String> matchedMethods = new HashMap<MethodInstrumenter, String>();
@Override @Override
public MethodVisitor visitMethod( public MethodVisitor visitMethod(
final int access, int access,
final String name, String name,
final String desc, String desc,
String signature, String signature,
String[] exceptions String[] exceptions
) { ) {
@@ -304,9 +304,9 @@ public class InterceptionInstrumenter {
if (applicableInstrumenters.isEmpty()) return mv; if (applicableInstrumenters.isEmpty()) return mv;
boolean dumpByteCode = false; boolean dumpByteCode = false;
final List<MethodData> normalReturnData = new ArrayList<MethodData>(); List<MethodData> normalReturnData = new ArrayList<MethodData>();
final List<MethodData> enterData = new ArrayList<MethodData>(); List<MethodData> enterData = new ArrayList<MethodData>();
final List<MethodData> exceptionData = new ArrayList<MethodData>(); List<MethodData> exceptionData = new ArrayList<MethodData>();
for (MethodInstrumenter instrumenter : applicableInstrumenters) { for (MethodInstrumenter instrumenter : applicableInstrumenters) {
enterData.addAll(instrumenter.getEnterData()); enterData.addAll(instrumenter.getEnterData());
@@ -323,8 +323,8 @@ public class InterceptionInstrumenter {
mv = getDumpingVisitorWrapper(mv, name, desc); mv = getDumpingVisitorWrapper(mv, name, desc);
} }
final int maxStackDepth = getMaxStackDepth(name, desc, normalReturnData, enterData, exceptionData); int maxStackDepth = getMaxStackDepth(name, desc, normalReturnData, enterData, exceptionData);
final boolean isConstructor = "<init>".equals(name); boolean isConstructor = "<init>".equals(name);
return new MethodVisitor(ASM5, mv) { return new MethodVisitor(ASM5, mv) {
@@ -430,7 +430,7 @@ public class InterceptionInstrumenter {
} }
} }
private TraceMethodVisitor getDumpingVisitorWrapper(MethodVisitor mv, final String methodName, final String methodDesc) { private TraceMethodVisitor getDumpingVisitorWrapper(MethodVisitor mv, String methodName, String methodDesc) {
return new TraceMethodVisitor(mv, new Textifier(ASM5) { return new TraceMethodVisitor(mv, new Textifier(ASM5) {
@Override @Override
public void visitMethodEnd() { public void visitMethodEnd() {
@@ -43,13 +43,13 @@ public class Preloader {
} }
private static void run(String[] args) throws Exception { private static void run(String[] args) throws Exception {
final long startTime = System.nanoTime(); long startTime = System.nanoTime();
final Options options = parseOptions(args); Options options = parseOptions(args);
ClassLoader classLoader = createClassLoader(options); ClassLoader classLoader = createClassLoader(options);
final Handler handler = getHandler(options, classLoader); Handler handler = getHandler(options, classLoader);
ClassLoader preloaded = ClassPreloadingUtils.preloadClasses(options.classpath, options.estimate, classLoader, null, handler); ClassLoader preloaded = ClassPreloadingUtils.preloadClasses(options.classpath, options.estimate, classLoader, null, handler);
Class<?> mainClass = preloaded.loadClass(options.mainClass); Class<?> mainClass = preloaded.loadClass(options.mainClass);
@@ -147,10 +147,10 @@ public class Preloader {
private static Handler getHandler(Options options, ClassLoader withInstrumenter) { private static Handler getHandler(Options options, ClassLoader withInstrumenter) {
if (!options.measure) return new Handler(); if (!options.measure) return new Handler();
final Instrumenter instrumenter = options.instrumenters.isEmpty() ? Instrumenter.DO_NOTHING : loadInstrumenter(withInstrumenter); Instrumenter instrumenter = options.instrumenters.isEmpty() ? Instrumenter.DO_NOTHING : loadInstrumenter(withInstrumenter);
final int[] counter = new int[1]; int[] counter = new int[1];
final int[] size = new int[1]; int[] size = new int[1];
return new Handler() { return new Handler() {
@Override @Override
public void beforeDefineClass(String name, int sizeInBytes) { public void beforeDefineClass(String name, int sizeInBytes) {
@@ -30,7 +30,7 @@ public final class ScopeUtils {
public static LexicalScope makeScopeForPropertyHeader( public static LexicalScope makeScopeForPropertyHeader(
@NotNull LexicalScope parent, @NotNull LexicalScope parent,
@NotNull final PropertyDescriptor propertyDescriptor @NotNull PropertyDescriptor propertyDescriptor
) { ) {
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()
@@ -106,7 +106,7 @@ public abstract class KotlinMultiFileTestWithJava<M, F> extends KotlinTestWithEn
String expectedText = KotlinTestUtils.doLoadFile(file); String expectedText = KotlinTestUtils.doLoadFile(file);
final Map<String, ModuleAndDependencies> modules = new HashMap<String, ModuleAndDependencies>(); Map<String, ModuleAndDependencies> modules = new HashMap<String, ModuleAndDependencies>();
List<F> testFiles = List<F> testFiles =
KotlinTestUtils.createTestFiles(file.getName(), expectedText, new KotlinTestUtils.TestFileFactory<M, F>() { KotlinTestUtils.createTestFiles(file.getName(), expectedText, new KotlinTestUtils.TestFileFactory<M, F>() {
@@ -80,7 +80,7 @@ public abstract class AbstractBlackBoxCodegenTest extends CodegenTestCase {
@NotNull @NotNull
protected static List<String> findJavaSourcesInDirectory(@NotNull File directory) { protected static List<String> findJavaSourcesInDirectory(@NotNull File directory) {
final List<String> javaFilePaths = new ArrayList<String>(1); List<String> javaFilePaths = new ArrayList<String>(1);
FileUtil.processFilesRecursively(directory, new Processor<File>() { FileUtil.processFilesRecursively(directory, new Processor<File>() {
@Override @Override
@@ -73,7 +73,7 @@ public abstract class AbstractCheckLocalVariablesTableTest extends TestCaseWithT
String classAndMethod = parseClassAndMethodSignature(); String classAndMethod = parseClassAndMethodSignature();
String[] split = classAndMethod.split("\\."); String[] split = classAndMethod.split("\\.");
assert split.length == 2 : "Exactly one dot is expected: " + classAndMethod; assert split.length == 2 : "Exactly one dot is expected: " + classAndMethod;
final 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(), new Condition<OutputFile>() {
@@ -144,7 +144,7 @@ public abstract class AbstractCheckLocalVariablesTableTest extends TestCaseWithT
} }
@NotNull @NotNull
private static List<LocalVariable> readLocalVariable(ClassReader cr, final String methodName) throws Exception { private static List<LocalVariable> readLocalVariable(ClassReader cr, String methodName) throws Exception {
class Visitor extends ClassVisitor { class Visitor extends ClassVisitor {
List<LocalVariable> readVariables = new ArrayList<LocalVariable>(); List<LocalVariable> readVariables = new ArrayList<LocalVariable>();
@@ -167,8 +167,8 @@ public abstract class AbstractLineNumberTest extends TestCaseWithTmpdir {
@NotNull @NotNull
private static List<String> readTestFunLineNumbers(@NotNull ClassReader cr) { private static List<String> readTestFunLineNumbers(@NotNull ClassReader cr) {
final List<Label> labels = Lists.newArrayList(); List<Label> labels = Lists.newArrayList();
final Map<Label, String> labels2LineNumbers = Maps.newHashMap(); Map<Label, String> labels2LineNumbers = Maps.newHashMap();
ClassVisitor visitor = new ClassVisitor(Opcodes.ASM5) { ClassVisitor visitor = new ClassVisitor(Opcodes.ASM5) {
@Override @Override
@@ -212,8 +212,8 @@ public abstract class AbstractLineNumberTest extends TestCaseWithTmpdir {
@NotNull @NotNull
private static List<String> readAllLineNumbers(@NotNull ClassReader reader) { private static List<String> readAllLineNumbers(@NotNull ClassReader reader) {
final List<String> result = new ArrayList<String>(); List<String> result = new ArrayList<String>();
final Set<String> visitedLabels = new HashSet<String>(); Set<String> visitedLabels = new HashSet<String>();
reader.accept(new ClassVisitor(Opcodes.ASM5) { reader.accept(new ClassVisitor(Opcodes.ASM5) {
@Override @Override
@@ -40,7 +40,7 @@ public abstract class AbstractTopLevelMembersInvocationTest extends AbstractByte
@Override @Override
public void doTest(@NotNull String filename) throws Exception { public void doTest(@NotNull String filename) throws Exception {
File root = new File(filename); File root = new File(filename);
final List<String> sourceFiles = new ArrayList<String>(2); List<String> sourceFiles = new ArrayList<String>(2);
FileUtil.processFilesRecursively(root, new Processor<File>() { FileUtil.processFilesRecursively(root, new Processor<File>() {
@Override @Override
@@ -579,7 +579,7 @@ public abstract class CodegenTestCase extends KtUsefulTestCase {
} }
@NotNull @NotNull
private static List<TestFile> createTestFiles(File file, String expectedText, final Ref<File> javaFilesDir) { private static List<TestFile> createTestFiles(File file, String expectedText, Ref<File> javaFilesDir) {
return KotlinTestUtils.createTestFiles(file.getName(), expectedText, new KotlinTestUtils.TestFileFactoryNoModules<TestFile>() { return KotlinTestUtils.createTestFiles(file.getName(), expectedText, new KotlinTestUtils.TestFileFactoryNoModules<TestFile>() {
@NotNull @NotNull
@Override @Override
@@ -154,7 +154,7 @@ public abstract class AbstractLoadJavaTest extends TestCaseWithTmpdir {
JvmContentRootsKt.addJavaSourceRoot(configuration, new File("compiler/testData/loadJava/include")); JvmContentRootsKt.addJavaSourceRoot(configuration, new File("compiler/testData/loadJava/include"));
JvmContentRootsKt.addJavaSourceRoot(configuration, tmpdir); JvmContentRootsKt.addJavaSourceRoot(configuration, tmpdir);
final KotlinCoreEnvironment environment = KotlinCoreEnvironment environment =
KotlinCoreEnvironment.createForTests(getTestRootDisposable(), configuration, EnvironmentConfigFiles.JVM_CONFIG_FILES); KotlinCoreEnvironment.createForTests(getTestRootDisposable(), configuration, EnvironmentConfigFiles.JVM_CONFIG_FILES);
AnalysisResult result = TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration( AnalysisResult result = TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(
@@ -227,7 +227,7 @@ public abstract class AbstractLoadJavaTest extends TestCaseWithTmpdir {
} }
private void doTestCompiledJava(@NotNull String javaFileName, Configuration configuration) throws Exception { private void doTestCompiledJava(@NotNull String javaFileName, Configuration configuration) throws Exception {
final File srcDir = new File(tmpdir, "src"); File srcDir = new File(tmpdir, "src");
File compiledDir = new File(tmpdir, "compiled"); File compiledDir = new File(tmpdir, "compiled");
assertTrue(srcDir.mkdir()); assertTrue(srcDir.mkdir());
assertTrue(compiledDir.mkdir()); assertTrue(compiledDir.mkdir());
@@ -55,7 +55,7 @@ public class ExpectedLoadErrorsUtil {
} }
private static Map<SourceElement, List<String>> getExpectedLoadErrors(@NotNull PackageViewDescriptor packageFromJava) { private static Map<SourceElement, List<String>> getExpectedLoadErrors(@NotNull PackageViewDescriptor packageFromJava) {
final Map<SourceElement, List<String>> map = new HashMap<SourceElement, List<String>>(); Map<SourceElement, List<String>> map = new HashMap<SourceElement, List<String>>();
packageFromJava.acceptVoid(new DeclarationDescriptorVisitorEmptyBodies<Void, Void>() { packageFromJava.acceptVoid(new DeclarationDescriptorVisitorEmptyBodies<Void, Void>() {
@Override @Override
@@ -106,7 +106,7 @@ public class LoadDescriptorUtil {
} }
@NotNull @NotNull
private static List<KtFile> createKtFiles(@NotNull List<File> kotlinFiles, @NotNull final 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, new Function1<File, KtFile>() {
@Override @Override
public KtFile invoke(File kotlinFile) { public KtFile invoke(File kotlinFile) {
@@ -365,7 +365,7 @@ public abstract class AbstractAnnotationDescriptorResolveTest extends KotlinTest
return KotlinTestUtils.doLoadFile(file).replaceAll("ANNOTATION", annotationText); return KotlinTestUtils.doLoadFile(file).replaceAll("ANNOTATION", annotationText);
} }
private static String renderAnnotations(Annotations annotations, @Nullable final 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(), new Function<AnnotationWithTarget, String>() {
@Override @Override
public String fun(AnnotationWithTarget annotationWithTarget) { public String fun(AnnotationWithTarget annotationWithTarget) {
@@ -403,7 +403,7 @@ public class KotlinTestUtils {
} }
@NotNull @NotNull
public static KtFile createFile(@NotNull @NonNls final String name, @NotNull String text, @NotNull Project project) { public static KtFile createFile(@NotNull @NonNls String name, @NotNull String text, @NotNull Project project) {
String shortName = name.substring(name.lastIndexOf('/') + 1); String shortName = name.substring(name.lastIndexOf('/') + 1);
shortName = shortName.substring(shortName.lastIndexOf('\\') + 1); shortName = shortName.substring(shortName.lastIndexOf('\\') + 1);
LightVirtualFile virtualFile = new LightVirtualFile(shortName, KotlinLanguage.INSTANCE, text) { LightVirtualFile virtualFile = new LightVirtualFile(shortName, KotlinLanguage.INSTANCE, text) {
@@ -909,12 +909,12 @@ public class KotlinTestUtils {
public static void assertAllTestsPresentInSingleGeneratedClass( public static void assertAllTestsPresentInSingleGeneratedClass(
@NotNull Class<?> testCaseClass, @NotNull Class<?> testCaseClass,
@NotNull File testDataDir, @NotNull File testDataDir,
@NotNull final Pattern filenamePattern, @NotNull Pattern filenamePattern,
@NotNull final TargetBackend targetBackend @NotNull TargetBackend targetBackend
) { ) {
final File rootFile = new File(getTestsRoot(testCaseClass)); File rootFile = new File(getTestsRoot(testCaseClass));
final Set<String> filePaths = collectPathsMetadata(testCaseClass); Set<String> filePaths = collectPathsMetadata(testCaseClass);
FileUtil.processFilesRecursively(testDataDir, new Processor<File>() { FileUtil.processFilesRecursively(testDataDir, new Processor<File>() {
@Override @Override
@@ -208,7 +208,7 @@ public abstract class KtUsefulTestCase extends TestCase {
@Override @Override
protected void runTest() throws Throwable { protected void runTest() throws Throwable {
final Throwable[] throwables = new Throwable[1]; Throwable[] throwables = new Throwable[1];
Runnable runnable = new Runnable() { Runnable runnable = new Runnable() {
@Override @Override
@@ -34,7 +34,7 @@ public abstract class AbstractControlFlowTest extends AbstractPseudocodeTest {
@NotNull StringBuilder out, @NotNull StringBuilder out,
@NotNull BindingContext bindingContext @NotNull BindingContext bindingContext
) { ) {
final int nextInstructionsColumnWidth = countNextInstructionsColumnWidth(pseudocode.getInstructionsIncludingDeadCode()); int nextInstructionsColumnWidth = countNextInstructionsColumnWidth(pseudocode.getInstructionsIncludingDeadCode());
dumpInstructions(pseudocode, out, new Function3<Instruction, Instruction, Instruction, String>() { dumpInstructions(pseudocode, out, new Function3<Instruction, Instruction, Instruction, String>() {
@Override @Override
@@ -39,13 +39,13 @@ public abstract class AbstractDataFlowTest extends AbstractPseudocodeTest {
@NotNull BindingContext bindingContext @NotNull BindingContext bindingContext
) { ) {
PseudocodeVariablesData pseudocodeVariablesData = new PseudocodeVariablesData(pseudocode.getRootPseudocode(), bindingContext); PseudocodeVariablesData pseudocodeVariablesData = new PseudocodeVariablesData(pseudocode.getRootPseudocode(), bindingContext);
final Map<Instruction, Edges<InitControlFlowInfo>> variableInitializers = Map<Instruction, Edges<InitControlFlowInfo>> variableInitializers =
pseudocodeVariablesData.getVariableInitializers(); pseudocodeVariablesData.getVariableInitializers();
final Map<Instruction, Edges<UseControlFlowInfo>> useStatusData = Map<Instruction, Edges<UseControlFlowInfo>> useStatusData =
pseudocodeVariablesData.getVariableUseStatusData(); pseudocodeVariablesData.getVariableUseStatusData();
final String initPrefix = " INIT:"; String initPrefix = " INIT:";
final String usePrefix = " USE:"; String usePrefix = " USE:";
final 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, new Function3<Instruction, Instruction, Instruction, String>() {
@Override @Override
@@ -74,7 +74,7 @@ public class CFGraphToDotFilePrinter {
out.close(); out.close();
} }
private static void dumpEdges(List<Instruction> instructions, final PrintStream out, final int[] count, final Map<Instruction, String> nodeToName) { private static void dumpEdges(List<Instruction> instructions, PrintStream out, int[] count, Map<Instruction, String> nodeToName) {
for (Instruction fromInst : instructions) { for (Instruction fromInst : instructions) {
fromInst.accept(new InstructionVisitor() { fromInst.accept(new InstructionVisitor() {
@Override @Override
@@ -59,7 +59,7 @@ public class CheckerTestUtilTest extends KotlinTestWithEnvironment {
} }
public void testMissing() throws Exception { public void testMissing() throws Exception {
final DiagnosticData typeMismatch1 = diagnostics.get(1); DiagnosticData typeMismatch1 = diagnostics.get(1);
doTest(new TheTest(missing(typeMismatch1)) { doTest(new TheTest(missing(typeMismatch1)) {
@Override @Override
protected void makeTestData(List<ActualDiagnostic> diagnostics, List<DiagnosedRange> diagnosedRanges) { protected void makeTestData(List<ActualDiagnostic> diagnostics, List<DiagnosedRange> diagnosedRanges) {
@@ -69,7 +69,7 @@ public class CheckerTestUtilTest extends KotlinTestWithEnvironment {
} }
public void testUnexpected() throws Exception { public void testUnexpected() throws Exception {
final DiagnosticData typeMismatch1 = diagnostics.get(1); DiagnosticData typeMismatch1 = diagnostics.get(1);
doTest(new TheTest(unexpected(typeMismatch1)) { doTest(new TheTest(unexpected(typeMismatch1)) {
@Override @Override
protected void makeTestData(List<ActualDiagnostic> diagnostics, List<DiagnosedRange> diagnosedRanges) { protected void makeTestData(List<ActualDiagnostic> diagnostics, List<DiagnosedRange> diagnosedRanges) {
@@ -79,8 +79,8 @@ public class CheckerTestUtilTest extends KotlinTestWithEnvironment {
} }
public void testBoth() throws Exception { public void testBoth() throws Exception {
final DiagnosticData typeMismatch1 = diagnostics.get(1); DiagnosticData typeMismatch1 = diagnostics.get(1);
final DiagnosticData unresolvedReference = diagnostics.get(6); DiagnosticData unresolvedReference = diagnostics.get(6);
doTest(new TheTest(unexpected(typeMismatch1), missing(unresolvedReference)) { doTest(new TheTest(unexpected(typeMismatch1), missing(unresolvedReference)) {
@Override @Override
protected void makeTestData(List<ActualDiagnostic> diagnostics, List<DiagnosedRange> diagnosedRanges) { protected void makeTestData(List<ActualDiagnostic> diagnostics, List<DiagnosedRange> diagnosedRanges) {
@@ -91,8 +91,8 @@ public class CheckerTestUtilTest extends KotlinTestWithEnvironment {
} }
public void testMissingInTheMiddle() throws Exception { public void testMissingInTheMiddle() throws Exception {
final DiagnosticData noneApplicable = diagnostics.get(4); DiagnosticData noneApplicable = diagnostics.get(4);
final DiagnosticData typeMismatch3 = diagnostics.get(5); DiagnosticData typeMismatch3 = diagnostics.get(5);
doTest(new TheTest(unexpected(noneApplicable), missing(typeMismatch3)) { doTest(new TheTest(unexpected(noneApplicable), missing(typeMismatch3)) {
@Override @Override
protected void makeTestData(List<ActualDiagnostic> diagnostics, List<DiagnosedRange> diagnosedRanges) { protected void makeTestData(List<ActualDiagnostic> diagnostics, List<DiagnosedRange> diagnosedRanges) {
@@ -103,9 +103,9 @@ public class CheckerTestUtilTest extends KotlinTestWithEnvironment {
} }
public void testWrongParameters() throws Exception { public void testWrongParameters() throws Exception {
final DiagnosticData unused = diagnostics.get(2); DiagnosticData unused = diagnostics.get(2);
String unusedDiagnostic = asTextDiagnostic(unused, "i"); String unusedDiagnostic = asTextDiagnostic(unused, "i");
final DiagnosedRange range = asDiagnosticRange(unused, unusedDiagnostic); DiagnosedRange range = asDiagnosticRange(unused, unusedDiagnostic);
doTest(new TheTest(wrongParameters(unusedDiagnostic, "UNUSED_VARIABLE(a)", unused.startOffset, unused.endOffset)) { doTest(new TheTest(wrongParameters(unusedDiagnostic, "UNUSED_VARIABLE(a)", unused.startOffset, unused.endOffset)) {
@Override @Override
protected void makeTestData(List<ActualDiagnostic> diagnostics, List<DiagnosedRange> diagnosedRanges) { protected void makeTestData(List<ActualDiagnostic> diagnostics, List<DiagnosedRange> diagnosedRanges) {
@@ -115,10 +115,10 @@ public class CheckerTestUtilTest extends KotlinTestWithEnvironment {
} }
public void testWrongParameterInMultiRange() throws Exception { public void testWrongParameterInMultiRange() throws Exception {
final DiagnosticData unresolvedReference = diagnostics.get(6); DiagnosticData unresolvedReference = diagnostics.get(6);
String unusedDiagnostic = asTextDiagnostic(unresolvedReference, "i"); String unusedDiagnostic = asTextDiagnostic(unresolvedReference, "i");
String toManyArguments = asTextDiagnostic(diagnostics.get(7)); String toManyArguments = asTextDiagnostic(diagnostics.get(7));
final DiagnosedRange range = asDiagnosticRange(unresolvedReference, unusedDiagnostic, toManyArguments); DiagnosedRange range = asDiagnosticRange(unresolvedReference, unusedDiagnostic, toManyArguments);
doTest(new TheTest(wrongParameters(unusedDiagnostic, "UNRESOLVED_REFERENCE(xx)", unresolvedReference.startOffset, unresolvedReference.endOffset)) { doTest(new TheTest(wrongParameters(unusedDiagnostic, "UNRESOLVED_REFERENCE(xx)", unresolvedReference.startOffset, unresolvedReference.endOffset)) {
@Override @Override
protected void makeTestData(List<ActualDiagnostic> diagnostics, List<DiagnosedRange> diagnosedRanges) { protected void makeTestData(List<ActualDiagnostic> diagnostics, List<DiagnosedRange> diagnosedRanges) {
@@ -160,7 +160,7 @@ public class CheckerTestUtilTest extends KotlinTestWithEnvironment {
makeTestData(actualDiagnostics, diagnosedRanges); makeTestData(actualDiagnostics, diagnosedRanges);
List<String> expectedMessages = Lists.newArrayList(expected); List<String> expectedMessages = Lists.newArrayList(expected);
final List<String> actualMessages = Lists.newArrayList(); List<String> actualMessages = Lists.newArrayList();
CheckerTestUtil.diagnosticsDiff(diagnosedRanges, actualDiagnostics, new CheckerTestUtil.DiagnosticDiffCallbacks() { CheckerTestUtil.diagnosticsDiff(diagnosedRanges, actualDiagnostics, new CheckerTestUtil.DiagnosticDiffCallbacks() {
@Override @Override
@@ -127,7 +127,7 @@ public abstract class AbstractCliTest extends TestCaseWithTmpdir {
} }
@NotNull @NotNull
static List<String> readArgs(@NotNull final String argsFilePath, @NotNull final 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, new Function1<String, String>() {
@@ -233,7 +233,7 @@ public class GenerateNotNullAssertionsTest extends CodegenTestCase {
reader.accept(new ClassVisitor(Opcodes.ASM5) { reader.accept(new ClassVisitor(Opcodes.ASM5) {
@Override @Override
public MethodVisitor visitMethod( public MethodVisitor visitMethod(
int access, @NotNull final String callerName, @NotNull final String callerDesc, String signature, String[] exceptions int access, @NotNull String callerName, @NotNull String callerDesc, String signature, String[] exceptions
) { ) {
return new MethodVisitor(Opcodes.ASM5) { return new MethodVisitor(Opcodes.ASM5) {
@Override @Override
@@ -119,7 +119,7 @@ public class InnerClassInfoGenTest extends CodegenTestCase {
private void checkAccess(@NotNull String outerName, @NotNull final 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),
new Function1<InnerClassAttribute, Boolean>() { new Function1<InnerClassAttribute, Boolean>() {
@@ -145,7 +145,7 @@ public class InnerClassInfoGenTest extends CodegenTestCase {
assertNotNull(outputFile); assertNotNull(outputFile);
byte[] bytes = outputFile.asByteArray(); byte[] bytes = outputFile.asByteArray();
ClassReader reader = new ClassReader(bytes); ClassReader reader = new ClassReader(bytes);
final List<InnerClassAttribute> result = new ArrayList<InnerClassAttribute>(); List<InnerClassAttribute> result = new ArrayList<InnerClassAttribute>();
reader.accept(new ClassVisitor(ASM5) { reader.accept(new ClassVisitor(ASM5) {
@Override @Override
@@ -218,7 +218,7 @@ public class OuterClassGenTest extends CodegenTestCase {
@Nullable @Nullable
private static OuterClassInfo readOuterClassInfo(@NotNull ClassReader reader) { private static OuterClassInfo readOuterClassInfo(@NotNull ClassReader reader) {
final Ref<OuterClassInfo> info = Ref.create(); Ref<OuterClassInfo> info = Ref.create();
reader.accept(new ClassVisitor(Opcodes.ASM5) { reader.accept(new ClassVisitor(Opcodes.ASM5) {
@Override @Override
public void visitOuterClass(@NotNull String owner, @Nullable String name, @Nullable String desc) { public void visitOuterClass(@NotNull String owner, @Nullable String name, @Nullable String desc) {
@@ -43,7 +43,7 @@ public class SourceInfoGenTest extends CodegenTestCase {
ClassReader classReader = new ClassReader(file.asByteArray()); ClassReader classReader = new ClassReader(file.asByteArray());
final String [] producer = new String[1]; String[] producer = new String[1];
classReader.accept(new ClassVisitor(Opcodes.ASM5) { classReader.accept(new ClassVisitor(Opcodes.ASM5) {
@Override @Override
@@ -288,10 +288,10 @@ public class CompileKotlinAgainstCustomBinariesTest extends TestCaseWithTmpdir {
private void doTestKotlinLibraryWithWrongMetadataVersion( private void doTestKotlinLibraryWithWrongMetadataVersion(
@NotNull String libraryName, @NotNull String libraryName,
@Nullable final Function2<String, Object, Object> additionalTransformation, @Nullable Function2<String, Object, Object> additionalTransformation,
@NotNull String... additionalOptions @NotNull String... additionalOptions
) throws Exception { ) throws Exception {
final 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(compileLibrary(libraryName), new Function2<String, byte[], byte[]>() {
@Override @Override
public byte[] invoke(String name, byte[] bytes) { public byte[] invoke(String name, byte[] bytes) {
@@ -570,7 +570,7 @@ public class CompileKotlinAgainstCustomBinariesTest extends TestCaseWithTmpdir {
compileKotlin("source.kt", tmpdir, tmpdir); compileKotlin("source.kt", tmpdir, tmpdir);
final Ref<String> debugInfo = new Ref<String>(); Ref<String> debugInfo = new Ref<String>();
File resultFile = new File(tmpdir.getAbsolutePath(), "test/B.class"); File resultFile = new File(tmpdir.getAbsolutePath(), "test/B.class");
new ClassReader(FilesKt.readBytes(resultFile)).accept(new ClassVisitor(Opcodes.ASM5) { new ClassReader(FilesKt.readBytes(resultFile)).accept(new ClassVisitor(Opcodes.ASM5) {
@Override @Override
@@ -644,8 +644,8 @@ public class CompileKotlinAgainstCustomBinariesTest extends TestCaseWithTmpdir {
} }
public void testInnerClassPackageConflict2() throws Exception { public void testInnerClassPackageConflict2() throws Exception {
final File library1 = compileJava("library1"); File library1 = compileJava("library1");
final 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, new Processor<File>() {
@@ -297,7 +297,7 @@ public class StorageManagerTest extends TestCase {
} }
public void testRecursionToleranceAndPostCompute() throws Exception { public void testRecursionToleranceAndPostCompute() throws Exception {
final CounterImpl counter = new CounterImpl(); CounterImpl counter = new CounterImpl();
class C { class C {
NotNullLazyValue<String> rec = m.createLazyValueWithPostCompute( NotNullLazyValue<String> rec = m.createLazyValueWithPostCompute(
new Function0<String>() { new Function0<String>() {
@@ -330,7 +330,7 @@ public class StorageManagerTest extends TestCase {
} }
public void testPostComputeNoRecursion() throws Exception { public void testPostComputeNoRecursion() throws Exception {
final CounterImpl counter = new CounterImpl(); CounterImpl counter = new CounterImpl();
NotNullLazyValue<Collection<String>> v = m.createLazyValueWithPostCompute( NotNullLazyValue<Collection<String>> v = m.createLazyValueWithPostCompute(
new Function0<Collection<String>>() { new Function0<Collection<String>>() {
@Override @Override
@@ -357,7 +357,7 @@ public class StorageManagerTest extends TestCase {
} }
public void testNullablePostComputeNoRecursion() throws Exception { public void testNullablePostComputeNoRecursion() throws Exception {
final CounterImpl counter = new CounterImpl(); CounterImpl counter = new CounterImpl();
NullableLazyValue<Collection<String>> v = m.createNullableLazyValueWithPostCompute( NullableLazyValue<Collection<String>> v = m.createNullableLazyValueWithPostCompute(
new Function0<Collection<String>>() { new Function0<Collection<String>>() {
@Override @Override
@@ -424,7 +424,7 @@ public class StorageManagerTest extends TestCase {
} }
public void testFallThrough() throws Exception { public void testFallThrough() throws Exception {
final CounterImpl c = new CounterImpl(); CounterImpl c = new CounterImpl();
class C { class C {
NotNullLazyValue<Integer> rec = LockBasedStorageManager.NO_LOCKS.createLazyValue(new Function0<Integer>() { NotNullLazyValue<Integer> rec = LockBasedStorageManager.NO_LOCKS.createLazyValue(new Function0<Integer>() {
@Override @Override
@@ -500,7 +500,7 @@ public class StorageManagerTest extends TestCase {
// Utilities // Utilities
private static <K, V> Function0<V> apply(final Function1<K, V> f, final K x) { private static <K, V> Function0<V> apply(Function1<K, V> f, K x) {
return new Function0<V>() { return new Function0<V>() {
@Override @Override
public V invoke() { public V invoke() {
@@ -77,7 +77,7 @@ public class RecursiveDescriptorProcessorTest extends KotlinTestWithEnvironment
} }
private static List<String> recursivelyCollectDescriptors(PackageViewDescriptor testPackage) { private static List<String> recursivelyCollectDescriptors(PackageViewDescriptor testPackage) {
final List<String> lines = Lists.newArrayList(); List<String> lines = Lists.newArrayList();
RecursiveDescriptorProcessor.process(testPackage, null, new DeclarationDescriptorVisitor<Boolean, Void>() { RecursiveDescriptorProcessor.process(testPackage, null, new DeclarationDescriptorVisitor<Boolean, Void>() {
private void add(DeclarationDescriptor descriptor) { private void add(DeclarationDescriptor descriptor) {
@@ -90,7 +90,7 @@ 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());
final DeclarationDescriptor classDescriptor = bindingContext.getBindingContext().get(BindingContext.DECLARATION_TO_DESCRIPTOR, aClass); DeclarationDescriptor classDescriptor = bindingContext.getBindingContext().get(BindingContext.DECLARATION_TO_DESCRIPTOR, aClass);
return new LexicalScopeImpl(ScopeUtilsKt.memberScopeAsImportingScope(libraryScope), root, false, null, 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>() { new Function1<LexicalScopeImpl.InitializeHandler, Unit>() {
@@ -88,7 +88,7 @@ public class TypeSubstitutorTest extends KotlinTestWithEnvironment {
ModuleDescriptor module = analysisResult.getModuleDescriptor(); ModuleDescriptor module = analysisResult.getModuleDescriptor();
LexicalScope topLevelScope = analysisResult.getBindingContext().get(BindingContext.LEXICAL_SCOPE, ktFile); LexicalScope topLevelScope = analysisResult.getBindingContext().get(BindingContext.LEXICAL_SCOPE, ktFile);
final ClassifierDescriptor contextClass = ClassifierDescriptor contextClass =
ScopeUtilsKt.findClassifier(topLevelScope, Name.identifier("___Context"), NoLookupLocation.FROM_TEST); ScopeUtilsKt.findClassifier(topLevelScope, Name.identifier("___Context"), NoLookupLocation.FROM_TEST);
assert contextClass instanceof ClassDescriptor; assert contextClass instanceof ClassDescriptor;
LocalRedeclarationChecker redeclarationChecker = LocalRedeclarationChecker redeclarationChecker =
@@ -76,7 +76,7 @@ public class SingleClassTestModel implements TestClassModel {
@Override @Override
public Collection<MethodModel> getMethods() { public Collection<MethodModel> getMethods() {
if (methods == null) { if (methods == null) {
final List<TestMethodModel> result = Lists.newArrayList(); List<TestMethodModel> result = Lists.newArrayList();
result.add(new TestAllFilesPresentMethodModel()); result.add(new TestAllFilesPresentMethodModel());
@@ -121,7 +121,7 @@ public final class PatternBuilder {
@NotNull @NotNull
private static DescriptorPredicate pattern(@NotNull List<NamePredicate> checkers, @Nullable List<NamePredicate> arguments) { private static DescriptorPredicate pattern(@NotNull List<NamePredicate> checkers, @Nullable List<NamePredicate> arguments) {
assert !checkers.isEmpty(); assert !checkers.isEmpty();
final List<NamePredicate> checkersWithPrefixChecker = Lists.newArrayList(); List<NamePredicate> checkersWithPrefixChecker = Lists.newArrayList();
if (!checkers.get(0).test(KOTLIN_NAME)) { if (!checkers.get(0).test(KOTLIN_NAME)) {
checkersWithPrefixChecker.add(KOTLIN_NAME_PREDICATE); checkersWithPrefixChecker.add(KOTLIN_NAME_PREDICATE);
} }
@@ -130,7 +130,7 @@ public final class PatternBuilder {
assert checkersWithPrefixChecker.size() > 1; assert checkersWithPrefixChecker.size() > 1;
final List<NamePredicate> argumentCheckers = arguments != null ? Lists.newArrayList(arguments) : null; List<NamePredicate> argumentCheckers = arguments != null ? Lists.newArrayList(arguments) : null;
return new DescriptorPredicate() { return new DescriptorPredicate() {
@Override @Override
@@ -56,9 +56,9 @@ public abstract class TranslatorTestCaseBuilder {
} }
public static void appendTestsInDirectory(String dataPath, boolean recursive, public static void appendTestsInDirectory(String dataPath, boolean recursive,
final FilenameFilter filter, NamedTestFactory factory, TestSuite suite) { FilenameFilter filter, NamedTestFactory factory, TestSuite suite) {
final String extensionKt = ".kt"; String extensionKt = ".kt";
final FilenameFilter extensionFilter = new FilenameFilter() { FilenameFilter extensionFilter = new FilenameFilter() {
@Override @Override
public boolean accept(@NotNull File dir, @NotNull String name) { public boolean accept(@NotNull File dir, @NotNull String name) {
return name.endsWith(extensionKt); return name.endsWith(extensionKt);
@@ -194,7 +194,7 @@ public class DirectiveTestUtils {
private static final DirectiveHandler NOT_REFERENCED = new DirectiveHandler("CHECK_NOT_REFERENCED") { private static final DirectiveHandler NOT_REFERENCED = new DirectiveHandler("CHECK_NOT_REFERENCED") {
@Override @Override
void processEntry(@NotNull JsNode ast, @NotNull ArgumentsHelper arguments) throws Exception { void processEntry(@NotNull JsNode ast, @NotNull ArgumentsHelper arguments) throws Exception {
final String reference = arguments.getPositionalArgument(0); String reference = arguments.getPositionalArgument(0);
JsVisitor visitor = new RecursiveJsVisitor() { JsVisitor visitor = new RecursiveJsVisitor() {
@Override @Override
@@ -58,7 +58,7 @@ public abstract class MainCallParameters {
} }
@NotNull @NotNull
public static MainCallParameters mainWithArguments(@NotNull final List<String> parameters) { public static MainCallParameters mainWithArguments(@NotNull List<String> parameters) {
return new MainCallParameters() { return new MainCallParameters() {
@NotNull @NotNull
@@ -431,7 +431,7 @@ public final class StaticContext {
} }
@NotNull @NotNull
private JsName getNameForPackage(@NotNull final FqName packageFqName) { private JsName getNameForPackage(@NotNull FqName packageFqName) {
return ContainerUtil.getOrCreate(packageNames, packageFqName, new Factory<JsName>() { return ContainerUtil.getOrCreate(packageNames, packageFqName, new Factory<JsName>() {
@Override @Override
public JsName create() { public JsName create() {
@@ -281,7 +281,7 @@ public enum PrimitiveUnaryOperationFIF implements FunctionIntrinsicFactory {
jsOperator = OperatorTable.getUnaryOperator(jetToken); jsOperator = OperatorTable.getUnaryOperator(jetToken);
} }
final JsUnaryOperator finalJsOperator = jsOperator; JsUnaryOperator finalJsOperator = jsOperator;
return new FunctionIntrinsicWithReceiverComputed() { return new FunctionIntrinsicWithReceiverComputed() {
@NotNull @NotNull
@Override @Override