diff --git a/.idea/runConfigurations/Generate_Compiler_Tests.xml b/.idea/runConfigurations/Generate_Compiler_Tests.xml
index 44a573c3fb5..621873a8928 100644
--- a/.idea/runConfigurations/Generate_Compiler_Tests.xml
+++ b/.idea/runConfigurations/Generate_Compiler_Tests.xml
@@ -10,12 +10,11 @@
diff --git a/build.gradle.kts b/build.gradle.kts
index af636074a10..9409019b664 100644
--- a/build.gradle.kts
+++ b/build.gradle.kts
@@ -293,6 +293,7 @@ extra["compilerModules"] = arrayOf(
":compiler:fir:checkers",
":compiler:fir:entrypoint",
":compiler:fir:analysis-tests",
+ ":compiler:fir:analysis-tests:legacy-fir-tests",
":wasm:wasm.ir"
)
@@ -667,6 +668,7 @@ tasks {
dependsOn(":compiler:fir:raw-fir:psi2fir:test")
dependsOn(":compiler:fir:raw-fir:light-tree2fir:test")
dependsOn(":compiler:fir:analysis-tests:test")
+ dependsOn(":compiler:fir:analysis-tests:legacy-fir-tests:test")
dependsOn(":compiler:fir:fir2ir:test")
}
@@ -676,6 +678,7 @@ tasks {
":compiler:fir:raw-fir:psi2fir:test",
":compiler:fir:raw-fir:light-tree2fir:test",
":compiler:fir:analysis-tests:test",
+ ":compiler:fir:analysis-tests:legacy-fir-tests:test",
":compiler:fir:fir2ir:test",
":plugins:fir:fir-plugin-prototype:test"
)
@@ -711,7 +714,6 @@ tasks {
}
register("miscCompilerTest") {
- dependsOn("wasmCompilerTest")
dependsOn("nativeCompilerTest")
dependsOn("firCompilerTest")
diff --git a/buildSrc/src/main/kotlin/pluginMarkers.kt b/buildSrc/src/main/kotlin/pluginMarkers.kt
index 8509609ec01..41bf7e5477e 100644
--- a/buildSrc/src/main/kotlin/pluginMarkers.kt
+++ b/buildSrc/src/main/kotlin/pluginMarkers.kt
@@ -20,6 +20,10 @@ internal const val PLUGIN_MARKER_SUFFIX = ".gradle.plugin"
@OptIn(ExperimentalStdlibApi::class)
fun Project.publishPluginMarkers(withEmptyJars: Boolean = true) {
+
+ fun Project.isSonatypePublish(): Boolean =
+ hasProperty("isSonatypePublish") && property("isSonatypePublish") as Boolean
+
val pluginDevelopment = extensions.getByType()
val publishingExtension = extensions.getByType()
val mainPublication = publishingExtension.publications[KotlinBuildPublishingPlugin.PUBLICATION_NAME] as MavenPublication
@@ -32,7 +36,12 @@ fun Project.publishPluginMarkers(withEmptyJars: Boolean = true) {
tasks.named(
"publish${markerPublication.name.capitalize(Locale.ROOT)}PublicationTo${KotlinBuildPublishingPlugin.REPOSITORY_NAME}Repository"
- ).configureRepository()
+ ).apply {
+ configureRepository()
+ configure {
+ onlyIf { !isSonatypePublish() }
+ }
+ }
}
}
diff --git a/compiler/backend.common.jvm/src/org/jetbrains/kotlin/codegen/VersionIndependentOpcodes.kt b/compiler/backend.common.jvm/src/org/jetbrains/kotlin/codegen/VersionIndependentOpcodes.kt
new file mode 100644
index 00000000000..8c4d80e2a62
--- /dev/null
+++ b/compiler/backend.common.jvm/src/org/jetbrains/kotlin/codegen/VersionIndependentOpcodes.kt
@@ -0,0 +1,13 @@
+/*
+ * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
+ * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
+ */
+
+package org.jetbrains.kotlin.codegen
+
+import org.jetbrains.org.objectweb.asm.Opcodes
+
+// This object should help compiling against different ASM versions in different bunch versions
+object VersionIndependentOpcodes {
+ const val ACC_RECORD = Opcodes.ACC_RECORD
+}
diff --git a/compiler/backend.common.jvm/src/org/jetbrains/kotlin/codegen/VersionIndependentOpcodes.kt.201 b/compiler/backend.common.jvm/src/org/jetbrains/kotlin/codegen/VersionIndependentOpcodes.kt.201
new file mode 100644
index 00000000000..2b2b7422592
--- /dev/null
+++ b/compiler/backend.common.jvm/src/org/jetbrains/kotlin/codegen/VersionIndependentOpcodes.kt.201
@@ -0,0 +1,13 @@
+/*
+ * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
+ * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
+ */
+
+package org.jetbrains.kotlin.codegen
+
+import org.jetbrains.org.objectweb.asm.Opcodes
+
+// This object should help compiling against different ASM versions from different bunch versions
+object VersionIndependentOpcodes {
+ const val ACC_RECORD = 0
+}
diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/ClassBuilderRecord.kt b/compiler/backend/src/org/jetbrains/kotlin/codegen/ClassBuilderRecord.kt
new file mode 100644
index 00000000000..eaf3adc8077
--- /dev/null
+++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/ClassBuilderRecord.kt
@@ -0,0 +1,10 @@
+/*
+ * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
+ * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
+ */
+
+package org.jetbrains.kotlin.codegen
+
+fun ClassBuilder.addRecordComponent(name: String, desc: String, signature: String?) {
+ newRecordComponent(name, desc, signature)
+}
diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/ClassBuilderRecord.kt.201 b/compiler/backend/src/org/jetbrains/kotlin/codegen/ClassBuilderRecord.kt.201
new file mode 100644
index 00000000000..72d66859291
--- /dev/null
+++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/ClassBuilderRecord.kt.201
@@ -0,0 +1,10 @@
+/*
+ * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
+ * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
+ */
+
+package org.jetbrains.kotlin.codegen
+
+fun ClassBuilder.addRecordComponent(name: String, desc: String, signature: String?) {
+ // newRecordComponent(name, desc, signature)
+}
diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/ImplementationBodyCodegen.java b/compiler/backend/src/org/jetbrains/kotlin/codegen/ImplementationBodyCodegen.java
index caa9fedb583..a7063ee9de6 100644
--- a/compiler/backend/src/org/jetbrains/kotlin/codegen/ImplementationBodyCodegen.java
+++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/ImplementationBodyCodegen.java
@@ -223,7 +223,7 @@ public class ImplementationBodyCodegen extends ClassBodyCodegen {
}
if (JvmAnnotationUtilKt.isJvmRecord(descriptor)) {
- access |= ACC_RECORD;
+ access |= VersionIndependentOpcodes.ACC_RECORD;
}
v.defineClass(
diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/ImplementationBodyCodegen.java.201 b/compiler/backend/src/org/jetbrains/kotlin/codegen/ImplementationBodyCodegen.java.201
deleted file mode 100644
index f2c8aa9d96d..00000000000
--- a/compiler/backend/src/org/jetbrains/kotlin/codegen/ImplementationBodyCodegen.java.201
+++ /dev/null
@@ -1,1248 +0,0 @@
-/*
- * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
- * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
- */
-
-package org.jetbrains.kotlin.codegen;
-
-import com.intellij.openapi.progress.ProcessCanceledException;
-import com.intellij.psi.PsiElement;
-import com.intellij.util.ArrayUtil;
-import kotlin.Unit;
-import kotlin.collections.CollectionsKt;
-import kotlin.jvm.functions.Function2;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-import org.jetbrains.kotlin.backend.common.DataClassMethodGenerator;
-import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
-import org.jetbrains.kotlin.builtins.jvm.JavaToKotlinClassMap;
-import org.jetbrains.kotlin.builtins.jvm.JavaToKotlinClassMap.PlatformMutabilityMapping;
-import org.jetbrains.kotlin.codegen.binding.CodegenBinding;
-import org.jetbrains.kotlin.codegen.binding.MutableClosure;
-import org.jetbrains.kotlin.codegen.context.*;
-import org.jetbrains.kotlin.codegen.extensions.ExpressionCodegenExtension;
-import org.jetbrains.kotlin.codegen.serialization.JvmSerializerExtension;
-import org.jetbrains.kotlin.codegen.signature.BothSignatureWriter;
-import org.jetbrains.kotlin.codegen.signature.JvmSignatureWriter;
-import org.jetbrains.kotlin.codegen.state.GenerationState;
-import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper;
-import org.jetbrains.kotlin.config.LanguageFeature;
-import org.jetbrains.kotlin.descriptors.*;
-import org.jetbrains.kotlin.incremental.components.NoLookupLocation;
-import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor;
-import org.jetbrains.kotlin.load.kotlin.TypeMappingMode;
-import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader;
-import org.jetbrains.kotlin.metadata.ProtoBuf;
-import org.jetbrains.kotlin.name.ClassId;
-import org.jetbrains.kotlin.name.FqName;
-import org.jetbrains.kotlin.name.Name;
-import org.jetbrains.kotlin.psi.*;
-import org.jetbrains.kotlin.psi.synthetics.SyntheticClassOrObjectDescriptor;
-import org.jetbrains.kotlin.resolve.*;
-import org.jetbrains.kotlin.resolve.calls.callUtil.CallUtilKt;
-import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall;
-import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall;
-import org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilsKt;
-import org.jetbrains.kotlin.resolve.jvm.annotations.JvmAnnotationUtilKt;
-import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin;
-import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOriginKt;
-import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmClassSignature;
-import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature;
-import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter;
-import org.jetbrains.kotlin.resolve.scopes.MemberScope;
-import org.jetbrains.kotlin.resolve.scopes.receivers.ExtensionReceiver;
-import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver;
-import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue;
-import org.jetbrains.kotlin.serialization.DescriptorSerializer;
-import org.jetbrains.kotlin.types.KotlinType;
-import org.jetbrains.org.objectweb.asm.FieldVisitor;
-import org.jetbrains.org.objectweb.asm.MethodVisitor;
-import org.jetbrains.org.objectweb.asm.Type;
-import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
-import org.jetbrains.org.objectweb.asm.commons.Method;
-
-import java.util.*;
-
-import static org.jetbrains.kotlin.builtins.StandardNames.ENUM_VALUES;
-import static org.jetbrains.kotlin.builtins.StandardNames.ENUM_VALUE_OF;
-import static org.jetbrains.kotlin.codegen.AsmUtil.CAPTURED_THIS_FIELD;
-import static org.jetbrains.kotlin.codegen.CodegenUtilKt.isGenericToArray;
-import static org.jetbrains.kotlin.codegen.CodegenUtilKt.isNonGenericToArray;
-import static org.jetbrains.kotlin.codegen.DescriptorAsmUtil.*;
-import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.*;
-import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.enumEntryNeedSubclass;
-import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.getDelegatedLocalVariableMetadata;
-import static org.jetbrains.kotlin.load.java.DescriptorsJvmAbiUtil.*;
-import static org.jetbrains.kotlin.load.java.JvmAbi.HIDDEN_INSTANCE_FIELD;
-import static org.jetbrains.kotlin.load.java.JvmAbi.INSTANCE_FIELD;
-import static org.jetbrains.kotlin.resolve.BindingContext.INDEXED_LVALUE_GET;
-import static org.jetbrains.kotlin.resolve.BindingContext.INDEXED_LVALUE_SET;
-import static org.jetbrains.kotlin.resolve.BindingContextUtils.getNotNull;
-import static org.jetbrains.kotlin.resolve.DescriptorToSourceUtils.descriptorToDeclaration;
-import static org.jetbrains.kotlin.resolve.DescriptorUtils.*;
-import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.OBJECT_TYPE;
-import static org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin.NO_ORIGIN;
-import static org.jetbrains.kotlin.types.Variance.INVARIANT;
-import static org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils.isLocalFunction;
-import static org.jetbrains.org.objectweb.asm.Opcodes.*;
-import static org.jetbrains.org.objectweb.asm.Type.getObjectType;
-
-public class ImplementationBodyCodegen extends ClassBodyCodegen {
- public static final String ENUM_VALUES_FIELD_NAME = "$VALUES";
- private Type superClassAsmType;
- @NotNull
- private SuperClassInfo superClassInfo;
- private final Type classAsmType;
- private final boolean isLocal;
-
- private List companionObjectPropertiesToCopy;
-
- private final DelegationFieldsInfo delegationFieldsInfo;
-
- private final List> additionalTasks = new ArrayList<>();
-
- private final DescriptorSerializer serializer;
-
- private final ConstructorCodegen constructorCodegen;
-
- public ImplementationBodyCodegen(
- @NotNull KtPureClassOrObject aClass,
- @NotNull ClassContext context,
- @NotNull ClassBuilder v,
- @NotNull GenerationState state,
- @Nullable MemberCodegen> parentCodegen,
- boolean isLocal
- ) {
- super(aClass, context, v, state, parentCodegen);
- this.classAsmType = getObjectType(typeMapper.classInternalName(descriptor));
- this.isLocal = isLocal;
-
- this.delegationFieldsInfo =
- new DelegationFieldsInfo(classAsmType, descriptor, state, bindingContext)
- .getDelegationFieldsInfo(myClass.getSuperTypeListEntries());
-
- JvmSerializerExtension extension = new JvmSerializerExtension(v.getSerializationBindings(), state);
- this.serializer = DescriptorSerializer.create(
- descriptor, extension,
- parentCodegen instanceof ImplementationBodyCodegen
- ? ((ImplementationBodyCodegen) parentCodegen).serializer
- : DescriptorSerializer.createTopLevel(extension),
- state.getProject()
- );
-
- this.constructorCodegen = new ConstructorCodegen(
- descriptor, context, functionCodegen, this,
- this, state, kind, v, classAsmType, myClass, bindingContext
- );
- }
-
- @Override
- protected void generateDeclaration() {
- superClassInfo = SuperClassInfo.getSuperClassInfo(descriptor, typeMapper);
- superClassAsmType = superClassInfo.getType();
-
- JvmClassSignature signature = signature();
-
- boolean isAbstract = false;
- boolean isInterface = false;
- boolean isFinal = false;
- boolean isAnnotation = false;
- boolean isEnum = false;
-
- ClassKind kind = descriptor.getKind();
-
- Modality modality = descriptor.getModality();
-
- if (modality == Modality.ABSTRACT || modality == Modality.SEALED) {
- isAbstract = true;
- }
-
- if (kind == ClassKind.INTERFACE) {
- isAbstract = true;
- isInterface = true;
- }
- else if (kind == ClassKind.ANNOTATION_CLASS) {
- isAbstract = true;
- isInterface = true;
- isAnnotation = true;
- }
- else if (kind == ClassKind.ENUM_CLASS) {
- isAbstract = hasAbstractMembers(descriptor);
- isEnum = true;
- }
-
- if (modality != Modality.OPEN && !isAbstract) {
- isFinal = kind == ClassKind.OBJECT ||
- // Light-class mode: Do not make enum classes final since PsiClass corresponding to enum is expected to be inheritable from
- !(kind == ClassKind.ENUM_CLASS && !state.getClassBuilderMode().generateBodies);
- }
-
- int access = 0;
-
- if (state.getClassBuilderMode() == ClassBuilderMode.LIGHT_CLASSES && !DescriptorUtils.isTopLevelDeclaration(descriptor)) {
- // !ClassBuilderMode.generateBodies means we are generating light classes & looking at a nested or inner class
- // Light class generation is implemented so that Cls-classes only read bare code of classes,
- // without knowing whether these classes are inner or not (see ClassStubBuilder.EMPTY_STRATEGY)
- // Thus we must write full accessibility flags on inner classes in this mode
- access |= getVisibilityAccessFlag(descriptor);
- // Same for STATIC
- if (!descriptor.isInner()) {
- access |= ACC_STATIC;
- }
- }
- else {
- access |= getVisibilityAccessFlagForClass(descriptor);
- }
- if (isAbstract) {
- access |= ACC_ABSTRACT;
- }
- if (isInterface) {
- access |= ACC_INTERFACE; // ACC_SUPER
- }
- else {
- access |= ACC_SUPER;
- }
- if (isFinal) {
- access |= ACC_FINAL;
- }
- if (isAnnotation) {
- access |= ACC_ANNOTATION;
- }
- if (KotlinBuiltIns.isDeprecated(descriptor)) {
- access |= ACC_DEPRECATED;
- }
- if (isEnum) {
- for (KtDeclaration declaration : myClass.getDeclarations()) {
- if (declaration instanceof KtEnumEntry) {
- if (enumEntryNeedSubclass(bindingContext, (KtEnumEntry) declaration)) {
- access &= ~ACC_FINAL;
- }
- }
- }
- access |= ACC_ENUM;
- }
-
- v.defineClass(
- myClass.getPsiOrParent(),
- state.getClassFileVersion(),
- access,
- signature.getName(),
- signature.getJavaGenericSignature(),
- signature.getSuperclassName(),
- ArrayUtil.toStringArray(signature.getInterfaces())
- );
-
- v.visitSource(myClass.getContainingKtFile().getName(), null);
-
- initDefaultSourceMappingIfNeeded();
-
- writeEnclosingMethod();
-
- AnnotationCodegen.forClass(v.getVisitor(), this, state).genAnnotations(descriptor, null, null);
-
- generateEnumEntries();
- }
-
- @Override
- protected void generateDefaultImplsIfNeeded() {
- if (isInterface(descriptor) && !isLocal) {
- Type defaultImplsType = state.getTypeMapper().mapDefaultImpls(descriptor);
- ClassBuilder defaultImplsBuilder =
- state.getFactory().newVisitor(JvmDeclarationOriginKt.DefaultImpls(myClass.getPsiOrParent(), descriptor), defaultImplsType, myClass.getContainingKtFile());
-
- CodegenContext parentContext = context.getParentContext();
- assert parentContext != null : "Parent context of interface declaration should not be null";
-
- ClassContext defaultImplsContext = parentContext.intoDefaultImplsClass(descriptor, (ClassContext) context, state);
- new InterfaceImplBodyCodegen(myClass, defaultImplsContext, defaultImplsBuilder, state, this).generate();
- }
- }
-
- @Override
- protected void generateErasedInlineClassIfNeeded() {
- if (!(myClass instanceof KtClass)) return;
- if (!InlineClassesUtilsKt.isInlineClass(descriptor)) return;
-
- ClassContext erasedInlineClassContext = context.intoWrapperForErasedInlineClass(descriptor, state);
- new ErasedInlineClassBodyCodegen((KtClass) myClass, erasedInlineClassContext, v, state, this).generate();
- }
-
- @Override
- protected void generateUnboxMethodForInlineClass() {
- if (!(myClass instanceof KtClass)) return;
- if (!InlineClassesUtilsKt.isInlineClass(descriptor)) return;
-
- Type ownerType = typeMapper.mapClass(descriptor);
- ValueParameterDescriptor inlinedValue = InlineClassesUtilsKt.underlyingRepresentation(this.descriptor);
- if (inlinedValue == null) return;
-
- Type valueType = typeMapper.mapType(inlinedValue.getType());
- SimpleFunctionDescriptor functionDescriptor = InlineClassDescriptorResolver.createUnboxFunctionDescriptor(this.descriptor);
- assert functionDescriptor != null : "FunctionDescriptor for unbox method should be not null during codegen";
-
- functionCodegen.generateMethod(
- JvmDeclarationOriginKt.UnboxMethodOfInlineClass(functionDescriptor), functionDescriptor,
- new FunctionGenerationStrategy.CodegenBased(state) {
- @Override
- public void doGenerateBody(
- @NotNull ExpressionCodegen codegen, @NotNull JvmMethodSignature signature
- ) {
- InstructionAdapter iv = codegen.v;
- iv.load(0, OBJECT_TYPE);
- iv.getfield(ownerType.getInternalName(), inlinedValue.getName().asString(), valueType.getDescriptor());
- iv.areturn(valueType);
- }
- }
- );
- }
-
- @Override
- protected void generateKotlinMetadataAnnotation() {
- ProtoBuf.Class classProto = serializer.classProto(descriptor).build();
-
- WriteAnnotationUtilKt.writeKotlinMetadata(v, state, KotlinClassHeader.Kind.CLASS, 0, av -> {
- writeAnnotationData(av, serializer, classProto);
- return Unit.INSTANCE;
- });
- }
-
- private void writeEnclosingMethod() {
- // Do not emit enclosing method in "light-classes mode" since currently we generate local light classes as if they're top level
- if (!state.getClassBuilderMode().generateBodies) {
- return;
- }
-
- //JVMS7: A class must have an EnclosingMethod attribute if and only if it is a local class or an anonymous class.
- if (isAnonymousObject(descriptor) || !(descriptor.getContainingDeclaration() instanceof ClassOrPackageFragmentDescriptor)) {
- writeOuterClassAndEnclosingMethod();
- }
- }
-
- private static final Map KOTLIN_MARKER_INTERFACES = new HashMap<>();
-
- static {
- for (PlatformMutabilityMapping platformMutabilityMapping : JavaToKotlinClassMap.INSTANCE.getMutabilityMappings()) {
- KOTLIN_MARKER_INTERFACES.put(
- platformMutabilityMapping.getKotlinReadOnly().asSingleFqName(),
- "kotlin/jvm/internal/markers/KMappedMarker");
-
- ClassId mutableClassId = platformMutabilityMapping.getKotlinMutable();
- KOTLIN_MARKER_INTERFACES.put(
- mutableClassId.asSingleFqName(),
- "kotlin/jvm/internal/markers/K" + mutableClassId.getRelativeClassName().asString()
- .replace("MutableEntry", "Entry") // kotlin.jvm.internal.markers.KMutableMap.Entry for some reason
- .replace(".", "$")
- );
- }
- }
-
- @NotNull
- private JvmClassSignature signature() {
- return signature(descriptor, classAsmType, superClassInfo, typeMapper);
- }
-
- @NotNull
- public static JvmClassSignature signature(
- @NotNull ClassDescriptor descriptor,
- @NotNull Type classAsmType,
- @NotNull SuperClassInfo superClassInfo,
- @NotNull KotlinTypeMapper typeMapper
- ) {
- JvmSignatureWriter sw = new BothSignatureWriter(BothSignatureWriter.Mode.CLASS);
-
- typeMapper.writeFormalTypeParameters(descriptor.getDeclaredTypeParameters(), sw);
-
- sw.writeSuperclass();
- if (superClassInfo.getKotlinType() == null) {
- sw.writeClassBegin(superClassInfo.getType());
- sw.writeClassEnd();
- }
- else {
- typeMapper.mapSupertype(superClassInfo.getKotlinType(), sw);
- }
- sw.writeSuperclassEnd();
-
- LinkedHashSet superInterfaces = new LinkedHashSet<>();
- Set kotlinMarkerInterfaces = new LinkedHashSet<>();
-
- for (KotlinType supertype : descriptor.getTypeConstructor().getSupertypes()) {
- if (isJvmInterface(supertype.getConstructor().getDeclarationDescriptor())) {
- FqName kotlinInterfaceName = DescriptorUtils.getFqName(supertype.getConstructor().getDeclarationDescriptor()).toSafe();
-
- sw.writeInterface();
- Type jvmInterfaceType = typeMapper.mapSupertype(supertype, sw);
- sw.writeInterfaceEnd();
- String jvmInterfaceInternalName = jvmInterfaceType.getInternalName();
-
- superInterfaces.add(jvmInterfaceInternalName);
-
- String kotlinMarkerInterfaceInternalName = KOTLIN_MARKER_INTERFACES.get(kotlinInterfaceName);
- if (kotlinMarkerInterfaceInternalName != null) {
- if (typeMapper.getClassBuilderMode() == ClassBuilderMode.LIGHT_CLASSES) {
- sw.writeInterface();
- Type kotlinCollectionType = typeMapper.mapType(supertype, sw, TypeMappingMode.SUPER_TYPE_KOTLIN_COLLECTIONS_AS_IS);
- sw.writeInterfaceEnd();
- superInterfaces.add(kotlinCollectionType.getInternalName());
- }
-
- kotlinMarkerInterfaces.add(kotlinMarkerInterfaceInternalName);
- }
- }
- }
-
- for (String kotlinMarkerInterface : kotlinMarkerInterfaces) {
- sw.writeInterface();
- sw.writeAsmType(getObjectType(kotlinMarkerInterface));
- sw.writeInterfaceEnd();
- }
-
- superInterfaces.addAll(kotlinMarkerInterfaces);
-
- return new JvmClassSignature(classAsmType.getInternalName(), superClassInfo.getType().getInternalName(),
- new ArrayList<>(superInterfaces), sw.makeJavaGenericSignature());
- }
-
- @Override
- protected void generateSyntheticPartsBeforeBody() {
- generatePropertyMetadataArrayFieldIfNeeded(classAsmType);
- }
-
- @Override
- protected void generateSyntheticPartsAfterBody() {
- generateFieldForSingleton();
-
- initializeObjects();
-
- generateCompanionObjectBackingFieldCopies();
-
- generateDelegatesToDefaultImpl();
-
- generateDelegates(delegationFieldsInfo);
-
- generateSyntheticAccessors();
-
- generateEnumMethods();
-
- generateFunctionsForDataClasses();
-
- generateFunctionsFromAnyForInlineClasses();
-
- if (state.getClassBuilderMode() != ClassBuilderMode.LIGHT_CLASSES) {
- new CollectionStubMethodGenerator(typeMapper, descriptor).generate(functionCodegen, v);
-
- generateToArray();
- }
-
-
- if (context.closure != null)
- genClosureFields(context.closure, v, typeMapper, state.getLanguageVersionSettings());
-
- for (ExpressionCodegenExtension extension : ExpressionCodegenExtension.Companion.getInstances(state.getProject())) {
- if (state.getClassBuilderMode() != ClassBuilderMode.LIGHT_CLASSES
- || extension.getShouldGenerateClassSyntheticPartsInLightClassesMode()
- ) {
- extension.generateClassSyntheticParts(this);
- }
- }
- }
-
- @Override
- protected void generateConstructors() {
- try {
- lookupConstructorExpressionsInClosureIfPresent();
- constructorCodegen.generatePrimaryConstructor(delegationFieldsInfo, superClassAsmType);
- if (!InlineClassesUtilsKt.isInlineClass(descriptor) && !(descriptor instanceof SyntheticClassOrObjectDescriptor)) {
- // Synthetic classes does not have declarations for secondary constructors
- for (ClassConstructorDescriptor secondaryConstructor : DescriptorUtilsKt.getSecondaryConstructors(descriptor)) {
- constructorCodegen.generateSecondaryConstructor(secondaryConstructor, superClassAsmType);
- }
- }
- }
- catch (CompilationException | ProcessCanceledException e) {
- throw e;
- }
- catch (RuntimeException e) {
- throw new RuntimeException("Error generating constructors of class " + myClass.getName() + " with kind " + kind, e);
- }
- }
-
- private void generateToArray() {
- if (descriptor.getKind() == ClassKind.INTERFACE) return;
-
- KotlinBuiltIns builtIns = DescriptorUtilsKt.getBuiltIns(descriptor);
- if (!isSubclass(descriptor, builtIns.getCollection())) return;
-
- if (CollectionsKt.any(DescriptorUtilsKt.getAllSuperclassesWithoutAny(descriptor),
- classDescriptor -> !(classDescriptor instanceof JavaClassDescriptor) &&
- isSubclass(classDescriptor, builtIns.getCollection()))) {
- return;
- }
-
- Collection extends SimpleFunctionDescriptor> functions = descriptor.getDefaultType().getMemberScope().getContributedFunctions(
- Name.identifier("toArray"), NoLookupLocation.FROM_BACKEND
- );
- boolean hasGenericToArray = false;
- boolean hasNonGenericToArray = false;
- for (FunctionDescriptor function : functions) {
- hasGenericToArray |= isGenericToArray(function);
- hasNonGenericToArray |= isNonGenericToArray(function);
- }
-
- if (!hasNonGenericToArray) {
- MethodVisitor mv = v.newMethod(NO_ORIGIN, ACC_PUBLIC, "toArray", "()[Ljava/lang/Object;", null, null);
-
- InstructionAdapter iv = new InstructionAdapter(mv);
- mv.visitCode();
-
- iv.load(0, classAsmType);
- iv.invokestatic("kotlin/jvm/internal/CollectionToArray", "toArray", "(Ljava/util/Collection;)[Ljava/lang/Object;", false);
- iv.areturn(Type.getType("[Ljava/lang/Object;"));
-
- FunctionCodegen.endVisit(mv, "toArray", myClass);
- }
-
- if (!hasGenericToArray) {
- MethodVisitor mv = v.newMethod(
- NO_ORIGIN, ACC_PUBLIC, "toArray", "([Ljava/lang/Object;)[Ljava/lang/Object;", "([TT;)[TT;", null);
-
- InstructionAdapter iv = new InstructionAdapter(mv);
- mv.visitCode();
-
- iv.load(0, classAsmType);
- iv.load(1, Type.getType("[Ljava/lang/Object;"));
-
- iv.invokestatic("kotlin/jvm/internal/CollectionToArray", "toArray",
- "(Ljava/util/Collection;[Ljava/lang/Object;)[Ljava/lang/Object;", false);
- iv.areturn(Type.getType("[Ljava/lang/Object;"));
-
- FunctionCodegen.endVisit(mv, "toArray", myClass);
- }
- }
-
- public static JvmKotlinType genPropertyOnStack(
- InstructionAdapter iv,
- MethodContext context,
- @NotNull PropertyDescriptor propertyDescriptor,
- Type classAsmType,
- int index,
- GenerationState state
- ) {
- iv.load(index, classAsmType);
- if (couldUseDirectAccessToProperty(propertyDescriptor, /* forGetter = */ true,
- /* isDelegated = */ false, context, state.getShouldInlineConstVals())) {
- KotlinType kotlinType = propertyDescriptor.getType();
- Type type = state.getTypeMapper().mapType(kotlinType);
- String fieldName = ((FieldOwnerContext) context.getParentContext()).getFieldName(propertyDescriptor, false);
- iv.getfield(classAsmType.getInternalName(), fieldName, type.getDescriptor());
- return new JvmKotlinType(type, kotlinType);
- }
- else {
- PropertyGetterDescriptor getter = propertyDescriptor.getGetter();
-
- //noinspection ConstantConditions
- Method method = state.getTypeMapper().mapAsmMethod(getter);
- iv.invokevirtual(classAsmType.getInternalName(), method.getName(), method.getDescriptor(), false);
- return new JvmKotlinType(method.getReturnType(), getter.getReturnType());
- }
- }
-
- private void generateFunctionsForDataClasses() {
- if (!descriptor.isData()) return;
- if (!(myClass instanceof KtClassOrObject)) return;
- new DataClassMethodGeneratorImpl((KtClassOrObject)myClass, bindingContext).generate();
- }
-
- private void generateFunctionsFromAnyForInlineClasses() {
- if (!InlineClassesUtilsKt.isInlineClass(descriptor)) return;
- if (!(myClass instanceof KtClassOrObject)) return;
- new FunctionsFromAnyGeneratorImpl(
- (KtClassOrObject) myClass, bindingContext, descriptor, classAsmType, context, v, state
- ).generate();
- }
-
- private class DataClassMethodGeneratorImpl extends DataClassMethodGenerator {
- private final FunctionsFromAnyGeneratorImpl functionsFromAnyGenerator;
-
- DataClassMethodGeneratorImpl(
- KtClassOrObject klass,
- BindingContext bindingContext
- ) {
- super(klass, bindingContext);
- this.functionsFromAnyGenerator = new FunctionsFromAnyGeneratorImpl(
- klass, bindingContext, descriptor, classAsmType, ImplementationBodyCodegen.this.context, v, state
- );
- }
-
- @Override
- public void generateEqualsMethod(@NotNull FunctionDescriptor function, @NotNull List extends PropertyDescriptor> properties) {
- functionsFromAnyGenerator.generateEqualsMethod(function, properties);
- }
-
- @Override
- public void generateHashCodeMethod(@NotNull FunctionDescriptor function, @NotNull List extends PropertyDescriptor> properties) {
- functionsFromAnyGenerator.generateHashCodeMethod(function, properties);
- }
-
- @Override
- public void generateToStringMethod(@NotNull FunctionDescriptor function, @NotNull List extends PropertyDescriptor> properties) {
- functionsFromAnyGenerator.generateToStringMethod(function, properties);
- }
-
- @Override
- public void generateComponentFunction(@NotNull FunctionDescriptor function, @NotNull ValueParameterDescriptor parameter) {
- PsiElement originalElement = DescriptorToSourceUtils.descriptorToDeclaration(parameter);
- functionCodegen.generateMethod(JvmDeclarationOriginKt.OtherOrigin(originalElement, function), function, new FunctionGenerationStrategy() {
- @Override
- public void generateBody(
- @NotNull MethodVisitor mv,
- @NotNull FrameMap frameMap,
- @NotNull JvmMethodSignature signature,
- @NotNull MethodContext context,
- @NotNull MemberCodegen> parentCodegen
- ) {
- Type componentType = signature.getReturnType();
- InstructionAdapter iv = new InstructionAdapter(mv);
- if (!componentType.equals(Type.VOID_TYPE)) {
- PropertyDescriptor property =
- bindingContext.get(BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, descriptorToDeclaration(parameter));
- assert property != null : "Property descriptor is not found for primary constructor parameter: " + parameter;
-
- JvmKotlinType propertyType = genPropertyOnStack(
- iv, context, property, ImplementationBodyCodegen.this.classAsmType, 0, state
- );
- StackValue.coerce(propertyType.getType(), componentType, iv);
- }
- iv.areturn(componentType);
- }
-
- @Override
- public boolean skipNotNullAssertionsForParameters() {
- return false;
- }
- });
- }
-
- @Override
- public void generateCopyFunction(
- @NotNull FunctionDescriptor function,
- @NotNull List extends KtParameter> constructorParameters
- ) {
- Type thisDescriptorType = typeMapper.mapType(descriptor);
-
- functionCodegen.generateMethod(JvmDeclarationOriginKt.OtherOriginFromPure(myClass, function), function, new FunctionGenerationStrategy() {
- @Override
- public void generateBody(
- @NotNull MethodVisitor mv,
- @NotNull FrameMap frameMap,
- @NotNull JvmMethodSignature signature,
- @NotNull MethodContext context,
- @NotNull MemberCodegen> parentCodegen
- ) {
- InstructionAdapter iv = new InstructionAdapter(mv);
-
- iv.anew(thisDescriptorType);
- iv.dup();
-
- ConstructorDescriptor constructor = getPrimaryConstructorOfDataClass(descriptor);
- assert function.getValueParameters().size() == constructor.getValueParameters().size() :
- "Number of parameters of copy function and constructor are different. " +
- "Copy: " + function.getValueParameters().size() + ", " +
- "constructor: " + constructor.getValueParameters().size();
-
- MutableClosure closure = ImplementationBodyCodegen.this.context.closure;
- if (closure != null) {
- pushCapturedFieldsOnStack(iv, closure);
- }
-
- int parameterIndex = 1; // localVariable 0 = this
- for (ValueParameterDescriptor parameterDescriptor : function.getValueParameters()) {
- Type type = typeMapper.mapType(parameterDescriptor.getType());
- iv.load(parameterIndex, type);
- parameterIndex += type.getSize();
- }
-
- Method constructorAsmMethod = typeMapper.mapAsmMethod(constructor);
- iv.invokespecial(thisDescriptorType.getInternalName(), "", constructorAsmMethod.getDescriptor(), false);
-
- iv.areturn(thisDescriptorType);
- }
-
- @Override
- public boolean skipNotNullAssertionsForParameters() {
- return false;
- }
-
- private void pushCapturedFieldsOnStack(InstructionAdapter iv, MutableClosure closure) {
- ClassDescriptor captureThis = closure.getCapturedOuterClassDescriptor();
- if (captureThis != null) {
- iv.load(0, classAsmType);
- Type type = typeMapper.mapType(captureThis);
- iv.getfield(classAsmType.getInternalName(), CAPTURED_THIS_FIELD, type.getDescriptor());
- }
-
- KotlinType captureReceiver = closure.getCapturedReceiverFromOuterContext();
- if (captureReceiver != null) {
- iv.load(0, classAsmType);
- Type type = typeMapper.mapType(captureReceiver);
- String fieldName = closure.getCapturedReceiverFieldName(bindingContext, state.getLanguageVersionSettings());
- iv.getfield(classAsmType.getInternalName(), fieldName, type.getDescriptor());
- }
-
- for (Map.Entry entry : closure.getCaptureVariables().entrySet()) {
- DeclarationDescriptor declarationDescriptor = entry.getKey();
- EnclosedValueDescriptor enclosedValueDescriptor = entry.getValue();
- StackValue capturedValue = enclosedValueDescriptor.getInstanceValue();
- Type sharedVarType = typeMapper.getSharedVarType(declarationDescriptor);
- if (sharedVarType == null) {
- sharedVarType = typeMapper.mapType((VariableDescriptor) declarationDescriptor);
- }
- capturedValue.put(sharedVarType, iv);
- }
- }
- });
-
- functionCodegen.generateDefaultIfNeeded(
- context.intoFunction(function), function, OwnerKind.IMPLEMENTATION,
- (valueParameter, codegen) -> {
- assert ((ClassDescriptor) function.getContainingDeclaration()).isData()
- : "Function container must have [data] modifier: " + function;
- PropertyDescriptor property = bindingContext.get(BindingContext.VALUE_PARAMETER_AS_PROPERTY, valueParameter);
- assert property != null : "Copy function doesn't correspond to any property: " + function;
- return codegen.intermediateValueForProperty(property, false, null, StackValue.LOCAL_0);
- },
- null
- );
- }
- }
-
- @NotNull
- private static ConstructorDescriptor getPrimaryConstructorOfDataClass(@NotNull ClassDescriptor classDescriptor) {
- ConstructorDescriptor constructor = classDescriptor.getUnsubstitutedPrimaryConstructor();
- assert constructor != null : "Data class must have primary constructor: " + classDescriptor;
- return constructor;
- }
-
- private void generateEnumMethods() {
- if (isEnumClass(descriptor)) {
- generateEnumValuesMethod();
- generateEnumValueOfMethod();
- }
- }
-
- private void generateEnumValuesMethod() {
- Type type = typeMapper.mapType(DescriptorUtilsKt.getBuiltIns(descriptor).getArrayType(INVARIANT, descriptor.getDefaultType()));
-
- FunctionDescriptor valuesFunction =
- CollectionsKt.single(descriptor.getStaticScope().getContributedFunctions(ENUM_VALUES, NoLookupLocation.FROM_BACKEND));
- MethodVisitor mv = v.newMethod(
- JvmDeclarationOriginKt.OtherOriginFromPure(myClass, valuesFunction), ACC_PUBLIC | ACC_STATIC, ENUM_VALUES.asString(),
- "()" + type.getDescriptor(), null, null
- );
- if (!state.getClassBuilderMode().generateBodies) return;
-
- mv.visitCode();
- mv.visitFieldInsn(GETSTATIC, classAsmType.getInternalName(), ENUM_VALUES_FIELD_NAME, type.getDescriptor());
- mv.visitMethodInsn(INVOKEVIRTUAL, type.getInternalName(), "clone", "()Ljava/lang/Object;", false);
- mv.visitTypeInsn(CHECKCAST, type.getInternalName());
- mv.visitInsn(ARETURN);
- FunctionCodegen.endVisit(mv, "values()", myClass);
- }
-
- private void generateEnumValueOfMethod() {
- FunctionDescriptor valueOfFunction =
- CollectionsKt.single(descriptor.getStaticScope().getContributedFunctions(ENUM_VALUE_OF, NoLookupLocation.FROM_BACKEND),
- DescriptorUtilsKt::isEnumValueOfMethod);
- MethodVisitor mv =
- v.newMethod(JvmDeclarationOriginKt.OtherOriginFromPure(myClass, valueOfFunction), ACC_PUBLIC | ACC_STATIC, ENUM_VALUE_OF.asString(),
- "(Ljava/lang/String;)" + classAsmType.getDescriptor(), null, null);
- if (!state.getClassBuilderMode().generateBodies) return;
-
- mv.visitCode();
- mv.visitLdcInsn(classAsmType);
- mv.visitVarInsn(ALOAD, 0);
- mv.visitMethodInsn(INVOKESTATIC, "java/lang/Enum", "valueOf", "(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;", false);
- mv.visitTypeInsn(CHECKCAST, classAsmType.getInternalName());
- mv.visitInsn(ARETURN);
- FunctionCodegen.endVisit(mv, "valueOf()", myClass);
- }
-
- private void generateFieldForSingleton() {
- if (isCompanionObjectInInterfaceNotIntrinsic(descriptor)) {
- StackValue.Field field = StackValue.createSingletonViaInstance(descriptor, typeMapper, HIDDEN_INSTANCE_FIELD);
- //hidden instance in interface companion
- v.newField(JvmDeclarationOriginKt.OtherOrigin(descriptor),
- ACC_SYNTHETIC | ACC_STATIC | ACC_FINAL, field.name, field.type.getDescriptor(), null, null);
- }
-
- if (isEnumEntry(descriptor) || isCompanionObject(descriptor)) return;
-
- if (isNonCompanionObject(descriptor)) {
- StackValue.Field field = StackValue.createSingletonViaInstance(descriptor, typeMapper, INSTANCE_FIELD);
- FieldVisitor fv = v.newField(
- JvmDeclarationOriginKt.OtherOriginFromPure(myClass),
- ACC_PUBLIC | ACC_STATIC | ACC_FINAL,
- field.name, field.type.getDescriptor(), null, null
- );
- AnnotationCodegen.forField(fv, this, state).visitAnnotation(Type.getDescriptor(NotNull.class), false).visitEnd();
- return;
- }
-
- ClassDescriptor companionObjectDescriptor = descriptor.getCompanionObjectDescriptor();
- if (companionObjectDescriptor == null) {
- return;
- }
-
- @Nullable KtObjectDeclaration companionObject = CollectionsKt.firstOrNull(myClass.getCompanionObjects());
-
- int properFieldVisibilityFlag = getVisibilityAccessFlag(companionObjectDescriptor);
- boolean deprecatedFieldForInvisibleCompanionObject =
- state.getLanguageVersionSettings().supportsFeature(LanguageFeature.DeprecatedFieldForInvisibleCompanionObject);
- boolean properVisibilityForCompanionObjectInstanceField =
- state.getLanguageVersionSettings().supportsFeature(LanguageFeature.ProperVisibilityForCompanionObjectInstanceField);
- boolean hasPrivateOrProtectedProperVisibility = (properFieldVisibilityFlag & (ACC_PRIVATE | ACC_PROTECTED)) != 0;
- boolean hasPackagePrivateProperVisibility = (properFieldVisibilityFlag & (ACC_PUBLIC | ACC_PRIVATE | ACC_PROTECTED)) == 0;
- boolean fieldShouldBeDeprecated =
- deprecatedFieldForInvisibleCompanionObject &&
- !properVisibilityForCompanionObjectInstanceField &&
- (hasPrivateOrProtectedProperVisibility || hasPackagePrivateProperVisibility ||
- isNonIntrinsicPrivateCompanionObjectInInterface(companionObjectDescriptor));
- boolean fieldIsForcedToBePublic =
- JvmCodegenUtil.isJvmInterface(descriptor) ||
- !properVisibilityForCompanionObjectInstanceField;
- int fieldAccessFlags = ACC_STATIC | ACC_FINAL;
- if (fieldIsForcedToBePublic) {
- fieldAccessFlags |= ACC_PUBLIC;
- }
- else {
- fieldAccessFlags |= properFieldVisibilityFlag;
- }
- if (fieldShouldBeDeprecated) {
- fieldAccessFlags |= ACC_DEPRECATED;
- }
- if (properVisibilityForCompanionObjectInstanceField &&
- JvmCodegenUtil.isCompanionObjectInInterfaceNotIntrinsic(companionObjectDescriptor) &&
- DescriptorVisibilities.isPrivate(companionObjectDescriptor.getVisibility())) {
- fieldAccessFlags |= ACC_SYNTHETIC;
- }
- StackValue.Field field = StackValue.singleton(companionObjectDescriptor, typeMapper);
- FieldVisitor fv = v.newField(
- JvmDeclarationOriginKt.OtherOrigin(companionObject == null ? myClass.getPsiOrParent() : companionObject),
- fieldAccessFlags, field.name, field.type.getDescriptor(), null, null
- );
- AnnotationCodegen.forField(fv, this, state).visitAnnotation(Type.getDescriptor(NotNull.class), false).visitEnd();
- if (fieldShouldBeDeprecated) {
- AnnotationCodegen.forField(fv, this, state).visitAnnotation(Type.getDescriptor(Deprecated.class), true).visitEnd();
- }
- }
-
- private void initializeObjects() {
- if (!DescriptorUtils.isObject(descriptor)) return;
- if (!state.getClassBuilderMode().generateBodies) return;
-
- boolean isNonCompanionObject = isNonCompanionObject(descriptor);
- boolean isInterfaceCompanion = isCompanionObjectInInterfaceNotIntrinsic(descriptor);
- boolean isInterfaceCompanionWithBackingFieldsInOuter = isInterfaceCompanionWithBackingFieldsInOuter(descriptor);
- boolean isMappedIntrinsicCompanionObject = isMappedIntrinsicCompanionObject(descriptor);
- boolean isClassCompanionWithBackingFieldsInOuter = isClassCompanionObjectWithBackingFieldsInOuter(descriptor);
- if (isNonCompanionObject ||
- (isInterfaceCompanion && !isInterfaceCompanionWithBackingFieldsInOuter) ||
- isMappedIntrinsicCompanionObject
- ) {
- ExpressionCodegen clInitCodegen = createOrGetClInitCodegen();
- InstructionAdapter v = clInitCodegen.v;
- markLineNumberForElement(element.getPsiOrParent(), v);
- v.anew(classAsmType);
- v.dup();
- v.invokespecial(classAsmType.getInternalName(), "", "()V", false);
-
- //local0 emulates this in object constructor
- int local0Index = clInitCodegen.getFrameMap().enterTemp(classAsmType);
- assert local0Index == 0 : "Local variable with index 0 in clInit should be used only for singleton instance keeping";
- StackValue.Local local0 = StackValue.local(0, classAsmType);
- local0.store(StackValue.onStack(classAsmType), clInitCodegen.v);
- StackValue.Field singleton =
- StackValue.createSingletonViaInstance(
- descriptor, typeMapper, isInterfaceCompanion ? HIDDEN_INSTANCE_FIELD : INSTANCE_FIELD
- );
- singleton.store(local0, clInitCodegen.v);
-
- generateInitializers(clInitCodegen);
-
- if (isInterfaceCompanion) {
- //initialize singleton instance in outer by hidden instance
- StackValue.singleton(descriptor, typeMapper).store(
- singleton, getParentCodegen().createOrGetClInitCodegen().v, true
- );
- }
- }
- else if (isClassCompanionWithBackingFieldsInOuter || isInterfaceCompanionWithBackingFieldsInOuter) {
- ImplementationBodyCodegen parentCodegen = (ImplementationBodyCodegen) getParentCodegen();
- ExpressionCodegen parentClInitCodegen = parentCodegen.createOrGetClInitCodegen();
- InstructionAdapter parentVisitor = parentClInitCodegen.v;
-
- FunctionDescriptor constructor = (FunctionDescriptor) parentCodegen.context.accessibleDescriptor(
- CollectionsKt.single(descriptor.getConstructors()), /* superCallExpression = */ null
- );
- parentCodegen.generateMethodCallTo(constructor, null, parentVisitor);
- StackValue instance = StackValue.onStack(parentCodegen.typeMapper.mapClass(descriptor));
- StackValue.singleton(descriptor, parentCodegen.typeMapper).store(instance, parentVisitor, true);
-
- generateInitializers(parentClInitCodegen);
- }
- else {
- assert false : "Unknown object type: " + descriptor;
- }
- }
-
- private static boolean isInterfaceCompanionWithBackingFieldsInOuter(@NotNull DeclarationDescriptor declarationDescriptor) {
- DeclarationDescriptor interfaceClass = declarationDescriptor.getContainingDeclaration();
- if (!isCompanionObject(declarationDescriptor) || !isJvmInterface(interfaceClass)) return false;
-
- Collection descriptors = ((ClassDescriptor) declarationDescriptor).getUnsubstitutedMemberScope()
- .getContributedDescriptors(DescriptorKindFilter.ALL, MemberScope.Companion.getALL_NAME_FILTER());
- return CollectionsKt.any(descriptors, d -> d instanceof PropertyDescriptor && hasJvmFieldAnnotation((PropertyDescriptor) d));
- }
-
- private void generateCompanionObjectBackingFieldCopies() {
- if (companionObjectPropertiesToCopy == null || companionObjectPropertiesToCopy.isEmpty()) return;
-
- boolean isPrivateCompanion =
- DescriptorVisibilities.isPrivate(
- ((ClassDescriptor) companionObjectPropertiesToCopy.get(0).descriptor.getContainingDeclaration()).getVisibility());
-
- int modifiers = ACC_STATIC | ACC_FINAL | ACC_PUBLIC | (isPrivateCompanion ? ACC_DEPRECATED : 0);
- List additionalVisibleAnnotations =
- isPrivateCompanion ? Collections.singletonList(CodegenUtilKt.JAVA_LANG_DEPRECATED) : Collections.emptyList();
- for (PropertyAndDefaultValue info : companionObjectPropertiesToCopy) {
- PropertyDescriptor property = info.descriptor;
-
- Type type = typeMapper.mapType(property);
-
- FieldVisitor fv = v.newField(JvmDeclarationOriginKt.Synthetic(DescriptorToSourceUtils.descriptorToDeclaration(property), property),
- modifiers, context.getFieldName(property, false),
- type.getDescriptor(), typeMapper.mapFieldSignature(property.getType(), property),
- info.defaultValue);
-
- AnnotationCodegen.forField(fv, this, state).genAnnotations(property, type, null, null, additionalVisibleAnnotations);
-
- //This field are always static and final so if it has constant initializer don't do anything in clinit,
- //field would be initialized via default value in v.newField(...) - see JVM SPEC Ch.4
- // TODO: test this code
- if (state.getClassBuilderMode().generateBodies && info.defaultValue == null) {
- ExpressionCodegen codegen = createOrGetClInitCodegen();
- int companionObjectIndex = putCompanionObjectInLocalVar(codegen);
- StackValue.local(companionObjectIndex, OBJECT_TYPE).put(codegen.v);
- copyFieldFromCompanionObject(property);
- }
- }
- }
-
- private int putCompanionObjectInLocalVar(ExpressionCodegen codegen) {
- FrameMap frameMap = codegen.myFrameMap;
- ClassDescriptor companionObjectDescriptor = descriptor.getCompanionObjectDescriptor();
- int companionObjectIndex = frameMap.getIndex(companionObjectDescriptor);
- if (companionObjectIndex == -1) {
- companionObjectIndex = frameMap.enter(companionObjectDescriptor, OBJECT_TYPE);
- StackValue companionObject = StackValue.singleton(companionObjectDescriptor, typeMapper);
- StackValue.local(companionObjectIndex, companionObject.type).store(companionObject, codegen.v);
- }
- return companionObjectIndex;
- }
-
- private void copyFieldFromCompanionObject(PropertyDescriptor propertyDescriptor) {
- ExpressionCodegen codegen = createOrGetClInitCodegen();
- StackValue property = codegen.intermediateValueForProperty(propertyDescriptor, false, null, StackValue.none());
- StackValue.Field field = StackValue.field(
- property.type, property.kotlinType, classAsmType, propertyDescriptor.getName().asString(),
- true, StackValue.none(), propertyDescriptor
- );
- field.store(property, codegen.v);
- }
-
- public void generateInitializers(@NotNull ExpressionCodegen codegen) {
- generateInitializers(() -> codegen);
- }
-
- private void lookupConstructorExpressionsInClosureIfPresent() {
- if (!state.getClassBuilderMode().generateBodies || descriptor.getConstructors().isEmpty()) return;
-
- KtVisitorVoid visitor = new KtVisitorVoid() {
- @Override
- public void visitKtElement(@NotNull KtElement e) {
- e.acceptChildren(this);
- }
-
- @Override
- public void visitSimpleNameExpression(@NotNull KtSimpleNameExpression expr) {
- DeclarationDescriptor descriptor = bindingContext.get(BindingContext.REFERENCE_TARGET, expr);
-
- if (isLocalFunction(descriptor)) {
- lookupInContext(descriptor);
- }
- else if (descriptor instanceof CallableMemberDescriptor) {
- ResolvedCall extends CallableDescriptor> call = CallUtilKt.getResolvedCall(expr, bindingContext);
- if (call != null) {
- lookupReceivers(call);
- }
- if (call instanceof VariableAsFunctionResolvedCall) {
- lookupReceivers(((VariableAsFunctionResolvedCall) call).getVariableCall());
- }
- }
- else if (descriptor instanceof VariableDescriptor) {
- DeclarationDescriptor containingDeclaration = descriptor.getContainingDeclaration();
- if (containingDeclaration instanceof ConstructorDescriptor) {
- ClassDescriptor classDescriptor = ((ConstructorDescriptor) containingDeclaration).getConstructedClass();
- if (classDescriptor == ImplementationBodyCodegen.this.descriptor) return;
- }
- if (lookupInContext(descriptor)) {
- if (isDelegatedLocalVariable(descriptor)) {
- VariableDescriptor metadata = getDelegatedLocalVariableMetadata((VariableDescriptor) descriptor, bindingContext);
- lookupInContext(metadata);
- }
- }
- }
- }
-
- private void lookupReceivers(@NotNull ResolvedCall extends CallableDescriptor> call) {
- lookupReceiver(call.getDispatchReceiver());
- lookupReceiver(call.getExtensionReceiver());
- }
-
- private void lookupReceiver(@Nullable ReceiverValue value) {
- if (value instanceof ImplicitReceiver) {
- if (value instanceof ExtensionReceiver) {
- ReceiverParameterDescriptor parameter =
- ((ExtensionReceiver) value).getDeclarationDescriptor().getExtensionReceiverParameter();
- assert parameter != null : "Extension receiver should exist: " + ((ExtensionReceiver) value).getDeclarationDescriptor();
- lookupInContext(parameter);
- }
- else {
- lookupInContext(((ImplicitReceiver) value).getDeclarationDescriptor());
- }
- }
- }
-
- private boolean lookupInContext(@NotNull DeclarationDescriptor toLookup) {
- return context.lookupInContext(toLookup, StackValue.LOCAL_0, state, true) != null;
- }
-
- @Override
- public void visitThisExpression(@NotNull KtThisExpression expression) {
- DeclarationDescriptor descriptor = bindingContext.get(BindingContext.REFERENCE_TARGET, expression.getInstanceReference());
- assert descriptor instanceof CallableDescriptor ||
- descriptor instanceof ClassDescriptor : "'This' reference target should be class or callable descriptor but was " + descriptor;
- if (descriptor instanceof ClassDescriptor) {
- lookupInContext(descriptor);
- }
-
- if (descriptor instanceof CallableDescriptor) {
- ReceiverParameterDescriptor parameter = ((CallableDescriptor) descriptor).getExtensionReceiverParameter();
- if (parameter != null) {
- lookupInContext(parameter);
- }
- }
- }
-
- @Override
- public void visitSuperExpression(@NotNull KtSuperExpression expression) {
- lookupInContext(ExpressionCodegen.getSuperCallLabelTarget(context, expression));
- }
-
- @Override
- public void visitArrayAccessExpression(@NotNull KtArrayAccessExpression expression) {
- ResolvedCall resolvedGetCall = bindingContext.get(INDEXED_LVALUE_GET, expression);
- if (resolvedGetCall != null) {
- ReceiverValue receiver = resolvedGetCall.getDispatchReceiver();
- lookupReceiver(receiver);
- }
-
- ResolvedCall resolvedSetCall = bindingContext.get(INDEXED_LVALUE_SET, expression);
- if (resolvedSetCall != null) {
- ReceiverValue receiver = resolvedSetCall.getDispatchReceiver();
- lookupReceiver(receiver);
- }
- super.visitArrayAccessExpression(expression);
- }
- };
-
- for (KtDeclaration declaration : myClass.getDeclarations()) {
- if (declaration instanceof KtProperty) {
- KtProperty property = (KtProperty) declaration;
- KtExpression initializer = property.getDelegateExpressionOrInitializer();
- if (initializer != null) {
- initializer.accept(visitor);
- }
- }
- else if (declaration instanceof KtAnonymousInitializer) {
- KtAnonymousInitializer initializer = (KtAnonymousInitializer) declaration;
- initializer.accept(visitor);
- }
- else if (declaration instanceof KtSecondaryConstructor) {
- KtSecondaryConstructor constructor = (KtSecondaryConstructor) declaration;
- constructor.accept(visitor);
- }
- }
-
- for (KtSuperTypeListEntry specifier : myClass.getSuperTypeListEntries()) {
- if (specifier instanceof KtDelegatedSuperTypeEntry) {
- KtExpression delegateExpression = ((KtDelegatedSuperTypeEntry) specifier).getDelegateExpression();
- assert delegateExpression != null;
- delegateExpression.accept(visitor);
- }
- else if (specifier instanceof KtSuperTypeCallEntry) {
- specifier.accept(visitor);
- }
- }
- }
-
- private void generateEnumEntries() {
- if (descriptor.getKind() != ClassKind.ENUM_CLASS) return;
-
- List enumEntries = CollectionsKt.filterIsInstance(element.getDeclarations(), KtEnumEntry.class);
-
- for (KtEnumEntry enumEntry : enumEntries) {
- ClassDescriptor descriptor = getNotNull(bindingContext, BindingContext.CLASS, enumEntry);
- int isDeprecated = KotlinBuiltIns.isDeprecated(descriptor) ? ACC_DEPRECATED : 0;
- FieldVisitor fv = v.newField(JvmDeclarationOriginKt.OtherOrigin(enumEntry, descriptor), ACC_PUBLIC | ACC_ENUM | ACC_STATIC | ACC_FINAL | isDeprecated,
- descriptor.getName().asString(), classAsmType.getDescriptor(), null, null);
- AnnotationCodegen.forField(fv, this, state).genAnnotations(descriptor, null, null);
- }
-
- initializeEnumConstants(enumEntries);
- }
-
- private void initializeEnumConstants(@NotNull List enumEntries) {
- if (!state.getClassBuilderMode().generateBodies) return;
-
- ExpressionCodegen codegen = createOrGetClInitCodegen();
- InstructionAdapter iv = codegen.v;
-
- Type arrayAsmType = typeMapper.mapType(DescriptorUtilsKt.getBuiltIns(descriptor).getArrayType(INVARIANT, descriptor.getDefaultType()));
- v.newField(JvmDeclarationOriginKt.OtherOriginFromPure(myClass), ACC_PRIVATE | ACC_STATIC | ACC_FINAL | ACC_SYNTHETIC, ENUM_VALUES_FIELD_NAME,
- arrayAsmType.getDescriptor(), null, null);
-
- iv.iconst(enumEntries.size());
- iv.newarray(classAsmType);
-
- if (!enumEntries.isEmpty()) {
- iv.dup();
- for (int ordinal = 0, size = enumEntries.size(); ordinal < size; ordinal++) {
- initializeEnumConstant(enumEntries, ordinal);
- }
- }
-
- iv.putstatic(classAsmType.getInternalName(), ENUM_VALUES_FIELD_NAME, arrayAsmType.getDescriptor());
- }
-
- private void initializeEnumConstant(@NotNull List enumEntries, int ordinal) {
- ExpressionCodegen codegen = createOrGetClInitCodegen();
- InstructionAdapter iv = codegen.v;
- KtEnumEntry enumEntry = enumEntries.get(ordinal);
-
- iv.dup();
- iv.iconst(ordinal);
-
- ClassDescriptor classDescriptor = getNotNull(bindingContext, BindingContext.CLASS, enumEntry);
- Type implClass = typeMapper.mapClass(classDescriptor);
-
- iv.anew(implClass);
- iv.dup();
-
- iv.aconst(enumEntry.getName());
- iv.iconst(ordinal);
-
- List delegationSpecifiers = enumEntry.getSuperTypeListEntries();
- ResolvedCall> defaultArgumentsConstructorCall = CallUtilKt.getResolvedCall(enumEntry, bindingContext);
- boolean enumEntryHasSubclass = CodegenBinding.enumEntryNeedSubclass(bindingContext, classDescriptor);
- if (delegationSpecifiers.size() == 1 && !enumEntryNeedSubclass(bindingContext, enumEntry)) {
- ResolvedCall> resolvedCall = CallUtilKt.getResolvedCallWithAssert(delegationSpecifiers.get(0), bindingContext);
-
- CallableMethod method = typeMapper.mapToCallableMethod((ConstructorDescriptor) resolvedCall.getResultingDescriptor(), false);
-
- codegen.invokeMethodWithArguments(method, resolvedCall, StackValue.none());
- }
- else if (defaultArgumentsConstructorCall != null && !enumEntryHasSubclass) {
- codegen.invokeFunction(defaultArgumentsConstructorCall, StackValue.none()).put(Type.VOID_TYPE, iv);
- }
- else {
- iv.invokespecial(implClass.getInternalName(), "", "(Ljava/lang/String;I)V", false);
- }
-
- iv.dup();
- iv.putstatic(classAsmType.getInternalName(), enumEntry.getName(), classAsmType.getDescriptor());
- iv.astore(OBJECT_TYPE);
- }
-
- private void generateDelegates(DelegationFieldsInfo delegationFieldsInfo) {
- for (KtSuperTypeListEntry specifier : myClass.getSuperTypeListEntries()) {
- if (specifier instanceof KtDelegatedSuperTypeEntry) {
- DelegationFieldsInfo.Field field = delegationFieldsInfo.getInfo((KtDelegatedSuperTypeEntry) specifier);
- if (field == null) continue;
-
- generateDelegateField(field);
- KtExpression delegateExpression = ((KtDelegatedSuperTypeEntry) specifier).getDelegateExpression();
- KotlinType delegateExpressionType = delegateExpression != null ? bindingContext.getType(delegateExpression) : null;
- ClassDescriptor superClass = JvmCodegenUtil.getSuperClass(specifier, state, bindingContext);
- if (superClass == null) continue;
-
- generateDelegates(superClass, delegateExpressionType, field);
- }
- }
- }
-
- private void generateDelegateField(DelegationFieldsInfo.Field fieldInfo) {
- if (!fieldInfo.generateField) return;
-
- v.newField(JvmDeclarationOrigin.NO_ORIGIN, ACC_PRIVATE | ACC_FINAL | ACC_SYNTHETIC,
- fieldInfo.name, fieldInfo.type.getDescriptor(), fieldInfo.genericSignature, null);
- }
-
- private void generateDelegates(
- @NotNull ClassDescriptor toInterface,
- @Nullable KotlinType delegateExpressionType,
- @NotNull DelegationFieldsInfo.Field field
- ) {
- for (Map.Entry entry : DelegationResolver.Companion.getDelegates(
- descriptor, toInterface, delegateExpressionType).entrySet()
- ) {
- CallableMemberDescriptor member = entry.getKey();
- CallableMemberDescriptor delegateTo = entry.getValue();
- if (member instanceof PropertyDescriptor) {
- propertyCodegen.genDelegate((PropertyDescriptor) member, (PropertyDescriptor) delegateTo, field.getStackValue());
- }
- else if (member instanceof FunctionDescriptor) {
- functionCodegen.genDelegate((FunctionDescriptor) member, (FunctionDescriptor) delegateTo, field.getStackValue());
- }
- }
- }
-
- public void addCompanionObjectPropertyToCopy(@NotNull PropertyDescriptor descriptor, Object defaultValue) {
- if (companionObjectPropertiesToCopy == null) {
- companionObjectPropertiesToCopy = new ArrayList<>();
- }
- companionObjectPropertiesToCopy.add(new PropertyAndDefaultValue(descriptor, defaultValue));
- }
-
- @Override
- protected void done() {
- for (Function2 task : additionalTasks) {
- task.invoke(this, v);
- }
-
- super.done();
- }
-
- private static class PropertyAndDefaultValue {
- public final PropertyDescriptor descriptor;
- public final Object defaultValue;
-
- public PropertyAndDefaultValue(@NotNull PropertyDescriptor descriptor, Object defaultValue) {
- this.descriptor = descriptor;
- this.defaultValue = defaultValue;
- }
- }
-
- public void addAdditionalTask(Function2 additionalTask) {
- additionalTasks.add(additionalTask);
- }
-}
diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/MemberCodegen.java b/compiler/backend/src/org/jetbrains/kotlin/codegen/MemberCodegen.java
index 7c45a18cef8..46270c55de0 100644
--- a/compiler/backend/src/org/jetbrains/kotlin/codegen/MemberCodegen.java
+++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/MemberCodegen.java
@@ -19,6 +19,7 @@ import org.jetbrains.kotlin.codegen.inline.SourceMapper;
import org.jetbrains.kotlin.codegen.state.GenerationState;
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper;
import org.jetbrains.kotlin.codegen.state.TypeMapperUtilsKt;
+import org.jetbrains.kotlin.config.JvmDefaultMode;
import org.jetbrains.kotlin.config.LanguageFeature;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.annotations.AnnotatedImpl;
@@ -83,7 +84,9 @@ public abstract class MemberCodegen parentCodegen;
private final ReifiedTypeParametersUsages reifiedTypeParametersUsages = new ReifiedTypeParametersUsages();
+
private final Collection innerClasses = new LinkedHashSet<>();
+ private final Collection syntheticInnerClasses = new LinkedHashSet<>();
private ExpressionCodegen clInit;
private NameGenerator inlineNameGenerator;
@@ -316,6 +319,10 @@ public abstract class MemberCodegen innerClasses) {
@@ -376,18 +386,12 @@ public abstract class MemberCodegen context = getNonInlineOuterContext(this.context.getParentContext());
assert context != null : "Outermost context can't be null: " + this.context;
- Type enclosingAsmType = computeOuterClass(context);
+ Type enclosingAsmType = computeOuterClass(typeMapper, state.getJvmDefaultMode(), element, context);
if (enclosingAsmType != null) {
- Method method = computeEnclosingMethod(context);
+ Method method = computeEnclosingMethod(typeMapper, context);
v.visitOuterClass(
enclosingAsmType.getInternalName(),
@@ -397,15 +401,31 @@ public abstract class MemberCodegen getNonInlineOuterContext(CodegenContext> parentContext) {
+ CodegenContext> context = parentContext;
+ while (context instanceof InlineLambdaContext) {
+ // If this is a lambda which will be inlined, skip its MethodContext and enclosing ClosureContext
+ //noinspection ConstantConditions
+ context = context.getParentContext().getParentContext();
+ }
+ return context;
+ }
+
@Nullable
- private Type computeOuterClass(@NotNull CodegenContext> context) {
+ public static Type computeOuterClass(
+ @NotNull KotlinTypeMapper typeMapper,
+ @NotNull JvmDefaultMode jvmDefaultMode,
+ @NotNull KtPureElement element,
+ @NotNull CodegenContext> context
+ ) {
CodegenContext extends ClassOrPackageFragmentDescriptor> outermost = context.getClassOrPackageParentContext();
if (outermost instanceof ClassContext) {
ClassDescriptor classDescriptor = ((ClassContext) outermost).getContextDescriptor();
if (context instanceof MethodContext) {
FunctionDescriptor functionDescriptor = ((MethodContext) context).getFunctionDescriptor();
- if (isInterface(functionDescriptor.getContainingDeclaration()) && !JvmAnnotationUtilKt
- .isCompiledToJvmDefault(functionDescriptor, state.getJvmDefaultMode())) {
+ if (isInterface(functionDescriptor.getContainingDeclaration()) &&
+ !JvmAnnotationUtilKt.isCompiledToJvmDefault(functionDescriptor, jvmDefaultMode)
+ ) {
return typeMapper.mapDefaultImpls(classDescriptor);
}
}
@@ -425,7 +445,7 @@ public abstract class MemberCodegen".equals(functionDescriptor.getName().asString())) {
diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/PropertyCodegen.java b/compiler/backend/src/org/jetbrains/kotlin/codegen/PropertyCodegen.java
index 449fb9a82d3..cc3c0046a4b 100644
--- a/compiler/backend/src/org/jetbrains/kotlin/codegen/PropertyCodegen.java
+++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/PropertyCodegen.java
@@ -454,7 +454,7 @@ public class PropertyCodegen {
}
if (propertyDescriptor.getContainingDeclaration() instanceof ClassDescriptor && JvmAnnotationUtilKt.isJvmRecord((ClassDescriptor) propertyDescriptor.getContainingDeclaration())) {
- builder.newRecordComponent(name, type.getDescriptor(), signature);
+ ClassBuilderRecordKt.addRecordComponent(builder, name, type.getDescriptor(), signature);
}
}
}
diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/PropertyCodegen.java.201 b/compiler/backend/src/org/jetbrains/kotlin/codegen/PropertyCodegen.java.201
deleted file mode 100644
index 25b7285eb81..00000000000
--- a/compiler/backend/src/org/jetbrains/kotlin/codegen/PropertyCodegen.java.201
+++ /dev/null
@@ -1,680 +0,0 @@
-/*
- * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
- * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
- */
-
-package org.jetbrains.kotlin.codegen;
-
-import com.intellij.psi.PsiElement;
-import kotlin.Pair;
-import kotlin.collections.CollectionsKt;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-import org.jetbrains.kotlin.codegen.context.CodegenContextUtil;
-import org.jetbrains.kotlin.codegen.context.FieldOwnerContext;
-import org.jetbrains.kotlin.codegen.context.MultifileClassFacadeContext;
-import org.jetbrains.kotlin.codegen.context.MultifileClassPartContext;
-import org.jetbrains.kotlin.codegen.state.GenerationState;
-import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper;
-import org.jetbrains.kotlin.config.LanguageFeature;
-import org.jetbrains.kotlin.descriptors.*;
-import org.jetbrains.kotlin.descriptors.annotations.Annotations;
-import org.jetbrains.kotlin.load.java.DescriptorsJvmAbiUtil;
-import org.jetbrains.kotlin.load.java.JvmAbi;
-import org.jetbrains.kotlin.psi.*;
-import org.jetbrains.kotlin.resolve.BindingContext;
-import org.jetbrains.kotlin.resolve.DescriptorFactory;
-import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils;
-import org.jetbrains.kotlin.resolve.InlineClassesUtilsKt;
-import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall;
-import org.jetbrains.kotlin.resolve.calls.util.UnderscoreUtilKt;
-import org.jetbrains.kotlin.resolve.constants.ConstantValue;
-import org.jetbrains.kotlin.resolve.jvm.annotations.JvmAnnotationUtilKt;
-import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOriginKt;
-import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodGenericSignature;
-import org.jetbrains.kotlin.resolve.jvm.jvmSignature.JvmMethodSignature;
-import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedPropertyDescriptor;
-import org.jetbrains.kotlin.types.ErrorUtils;
-import org.jetbrains.kotlin.types.KotlinType;
-import org.jetbrains.org.objectweb.asm.FieldVisitor;
-import org.jetbrains.org.objectweb.asm.MethodVisitor;
-import org.jetbrains.org.objectweb.asm.Opcodes;
-import org.jetbrains.org.objectweb.asm.Type;
-import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
-import org.jetbrains.org.objectweb.asm.commons.Method;
-
-import java.util.Collections;
-import java.util.List;
-
-import static org.jetbrains.kotlin.codegen.DescriptorAsmUtil.getDeprecatedAccessFlag;
-import static org.jetbrains.kotlin.codegen.DescriptorAsmUtil.getVisibilityForBackingField;
-import static org.jetbrains.kotlin.codegen.FunctionCodegen.processInterfaceMethod;
-import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isConstOrHasJvmFieldAnnotation;
-import static org.jetbrains.kotlin.codegen.JvmCodegenUtil.isJvmInterface;
-import static org.jetbrains.kotlin.codegen.binding.CodegenBinding.*;
-import static org.jetbrains.kotlin.codegen.serialization.JvmSerializationBindings.*;
-import static org.jetbrains.kotlin.diagnostics.Errors.EXPECTED_FUNCTION_SOURCE_WITH_DEFAULT_ARGUMENTS_NOT_FOUND;
-import static org.jetbrains.kotlin.fileClasses.JvmFileClassUtilKt.isTopLevelInJvmMultifileClass;
-import static org.jetbrains.kotlin.resolve.DescriptorUtils.isCompanionObject;
-import static org.jetbrains.kotlin.resolve.DescriptorUtils.isInterface;
-import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.K_PROPERTY_TYPE;
-import static org.jetbrains.kotlin.resolve.jvm.annotations.JvmAnnotationUtilKt.hasJvmFieldAnnotation;
-import static org.jetbrains.kotlin.resolve.jvm.annotations.JvmAnnotationUtilKt.hasJvmSyntheticAnnotation;
-import static org.jetbrains.org.objectweb.asm.Opcodes.*;
-
-public class PropertyCodegen {
- private final GenerationState state;
- private final ClassBuilder v;
- private final FunctionCodegen functionCodegen;
- private final KotlinTypeMapper typeMapper;
- private final BindingContext bindingContext;
- private final FieldOwnerContext context;
- private final MemberCodegen> memberCodegen;
- private final OwnerKind kind;
-
- public PropertyCodegen(
- @NotNull FieldOwnerContext context,
- @NotNull ClassBuilder v,
- @NotNull FunctionCodegen functionCodegen,
- @NotNull MemberCodegen> memberCodegen
- ) {
- this.state = functionCodegen.state;
- this.v = v;
- this.functionCodegen = functionCodegen;
- this.typeMapper = state.getTypeMapper();
- this.bindingContext = state.getBindingContext();
- this.context = context;
- this.memberCodegen = memberCodegen;
- this.kind = context.getContextKind();
- }
-
- public void gen(@NotNull KtProperty property) {
- VariableDescriptor variableDescriptor = bindingContext.get(BindingContext.VARIABLE, property);
- if (!(variableDescriptor instanceof PropertyDescriptor)) {
- throw ExceptionLogger.logDescriptorNotFound(
- "Property " + property.getName() + " should have a property descriptor: " + variableDescriptor, property
- );
- }
-
- PropertyDescriptor propertyDescriptor = (PropertyDescriptor) variableDescriptor;
- gen(property, propertyDescriptor, property.getGetter(), property.getSetter());
- }
-
- public void genDestructuringDeclaration(@NotNull KtDestructuringDeclarationEntry entry) {
- VariableDescriptor variableDescriptor = bindingContext.get(BindingContext.VARIABLE, entry);
- if (!(variableDescriptor instanceof PropertyDescriptor)) {
- throw ExceptionLogger.logDescriptorNotFound(
- "Destructuring declaration entry" + entry.getName() + " should have a property descriptor: " + variableDescriptor, entry
- );
- }
-
- if (!UnderscoreUtilKt.isSingleUnderscore(entry)) {
- genDestructuringDeclaration((PropertyDescriptor) variableDescriptor);
- }
- }
-
- public void generateInPackageFacade(@NotNull DeserializedPropertyDescriptor deserializedProperty) {
- assert context instanceof MultifileClassFacadeContext : "should be called only for generating facade: " + context;
-
- genBackingFieldAndAnnotations(deserializedProperty);
-
- if (!isConstOrHasJvmFieldAnnotation(deserializedProperty)) {
- generateGetter(deserializedProperty, null);
- generateSetter(deserializedProperty, null);
- }
- }
-
- private void gen(
- @NotNull KtProperty declaration,
- @NotNull PropertyDescriptor descriptor,
- @Nullable KtPropertyAccessor getter,
- @Nullable KtPropertyAccessor setter
- ) {
- assert kind == OwnerKind.PACKAGE || kind == OwnerKind.IMPLEMENTATION ||
- kind == OwnerKind.DEFAULT_IMPLS || kind == OwnerKind.ERASED_INLINE_CLASS
- : "Generating property with a wrong kind (" + kind + "): " + descriptor;
-
- genBackingFieldAndAnnotations(descriptor);
-
- boolean isDefaultGetterAndSetter = isDefaultAccessor(getter) && isDefaultAccessor(setter);
-
- if (isAccessorNeeded(descriptor, getter, isDefaultGetterAndSetter)) {
- generateGetter(descriptor, getter);
- }
- if (isAccessorNeeded(descriptor, setter, isDefaultGetterAndSetter)) {
- generateSetter(descriptor, setter);
- }
- }
-
- private static boolean isDefaultAccessor(@Nullable KtPropertyAccessor accessor) {
- return accessor == null || !accessor.hasBody();
- }
-
- private void genDestructuringDeclaration(@NotNull PropertyDescriptor descriptor) {
- assert kind == OwnerKind.PACKAGE || kind == OwnerKind.IMPLEMENTATION || kind == OwnerKind.DEFAULT_IMPLS
- : "Generating property with a wrong kind (" + kind + "): " + descriptor;
-
- genBackingFieldAndAnnotations(descriptor);
-
- generateGetter(descriptor, null);
- generateSetter(descriptor, null);
- }
-
- private void genBackingFieldAndAnnotations(@NotNull PropertyDescriptor descriptor) {
- // Fields and '$annotations' methods for non-private const properties are generated in the multi-file facade
- boolean isBackingFieldOwner = descriptor.isConst() && !DescriptorVisibilities.isPrivate(descriptor.getVisibility())
- ? !(context instanceof MultifileClassPartContext)
- : CodegenContextUtil.isImplementationOwner(context, descriptor);
-
- generateBackingField(descriptor, isBackingFieldOwner);
- generateSyntheticMethodIfNeeded(descriptor, isBackingFieldOwner);
- }
-
- private boolean isAccessorNeeded(
- @NotNull PropertyDescriptor descriptor,
- @Nullable KtPropertyAccessor accessor,
- boolean isDefaultGetterAndSetter
- ) {
- return isAccessorNeeded(descriptor, accessor, isDefaultGetterAndSetter, kind);
- }
-
- public static boolean isReferenceablePropertyWithGetter(@NotNull PropertyDescriptor descriptor) {
- PsiElement psiElement = DescriptorToSourceUtils.descriptorToDeclaration(descriptor);
- KtDeclaration ktDeclaration = psiElement instanceof KtDeclaration ? (KtDeclaration) psiElement : null;
- if (ktDeclaration instanceof KtProperty) {
- KtProperty ktProperty = (KtProperty) ktDeclaration;
- boolean isDefaultGetterAndSetter =
- isDefaultAccessor(ktProperty.getGetter()) && isDefaultAccessor(ktProperty.getSetter());
- return isAccessorNeeded(descriptor, ktProperty.getGetter(), isDefaultGetterAndSetter, OwnerKind.IMPLEMENTATION);
- } else if (ktDeclaration instanceof KtParameter) {
- return isAccessorNeeded(descriptor, null, true, OwnerKind.IMPLEMENTATION);
- } else {
- return isAccessorNeeded(descriptor, null, false, OwnerKind.IMPLEMENTATION);
- }
- }
-
- /**
- * Determines if it's necessary to generate an accessor to the property, i.e. if this property can be referenced via getter/setter
- * for any reason
- *
- * @see JvmCodegenUtil#couldUseDirectAccessToProperty
- */
- private static boolean isAccessorNeeded(
- @NotNull PropertyDescriptor descriptor,
- @Nullable KtPropertyAccessor accessor,
- boolean isDefaultGetterAndSetter,
- OwnerKind kind
- ) {
- if (isConstOrHasJvmFieldAnnotation(descriptor)) return false;
-
- boolean isDefaultAccessor = isDefaultAccessor(accessor);
-
- // Don't generate accessors for interface properties with default accessors in DefaultImpls
- if (kind == OwnerKind.DEFAULT_IMPLS && isDefaultAccessor) return false;
-
- // Delegated or extension properties can only be referenced via accessors
- if (descriptor.isDelegated() || descriptor.getExtensionReceiverParameter() != null) return true;
-
- // Companion object properties should have accessors for non-private properties because these properties can be referenced
- // via getter/setter. But these accessors getter/setter are not required for private properties that have a default getter
- // and setter, in this case, the property can always be accessed through the accessor 'access$cp' and avoid some
- // useless indirection by using others accessors.
- if (isCompanionObject(descriptor.getContainingDeclaration())) {
- if (DescriptorVisibilities.isPrivate(descriptor.getVisibility()) && isDefaultGetterAndSetter) {
- return false;
- }
- return true;
- }
-
- // Non-const properties from multifile classes have accessors regardless of visibility
- if (isTopLevelInJvmMultifileClass(descriptor)) return true;
-
- // Private class properties have accessors only in cases when those accessors are non-trivial
- if (DescriptorVisibilities.isPrivate(descriptor.getVisibility())) {
- return !isDefaultAccessor;
- }
-
- // Non-private properties with private setter should not be generated for trivial properties
- // as the class will use direct field access instead
- //noinspection ConstantConditions
- if (accessor != null && accessor.isSetter() && DescriptorVisibilities.isPrivate(descriptor.getSetter().getVisibility())) {
- return !isDefaultAccessor;
- }
-
- // Non-public API (private and internal) primary vals of inline classes don't have getter
- if (InlineClassesUtilsKt.isUnderlyingPropertyOfInlineClass(descriptor) && !descriptor.getVisibility().isPublicAPI()) {
- return false;
- }
-
- return true;
- }
-
- private static boolean areAccessorsNeededForPrimaryConstructorProperty(
- @NotNull PropertyDescriptor descriptor,
- @NotNull OwnerKind kind
- ) {
- if (hasJvmFieldAnnotation(descriptor)) return false;
- if (kind == OwnerKind.ERASED_INLINE_CLASS) return false;
-
- DescriptorVisibility visibility = descriptor.getVisibility();
- if (InlineClassesUtilsKt.isInlineClass(descriptor.getContainingDeclaration())) {
- return visibility.isPublicAPI();
- }
- else {
- return !DescriptorVisibilities.isPrivate(visibility);
- }
- }
-
- public void generatePrimaryConstructorProperty(@NotNull PropertyDescriptor descriptor) {
- genBackingFieldAndAnnotations(descriptor);
-
- if (areAccessorsNeededForPrimaryConstructorProperty(descriptor, context.getContextKind())) {
- generateGetter(descriptor, null);
- generateSetter(descriptor, null);
- }
- }
-
- public void generateConstructorPropertyAsMethodForAnnotationClass(
- @NotNull KtParameter parameter,
- @NotNull PropertyDescriptor descriptor,
- @Nullable FunctionDescriptor expectedAnnotationConstructor
- ) {
- JvmMethodGenericSignature signature = typeMapper.mapAnnotationParameterSignature(descriptor);
- Method asmMethod = signature.getAsmMethod();
- MethodVisitor mv = v.newMethod(
- JvmDeclarationOriginKt.OtherOrigin(parameter, descriptor),
- ACC_PUBLIC | ACC_ABSTRACT,
- asmMethod.getName(),
- asmMethod.getDescriptor(),
- signature.getGenericsSignature(),
- null
- );
-
- PropertyGetterDescriptor getter = descriptor.getGetter();
- assert getter != null : "Annotation property should have a getter: " + descriptor;
- v.getSerializationBindings().put(METHOD_FOR_FUNCTION, getter, asmMethod);
- AnnotationCodegen.forMethod(mv, memberCodegen, state).genAnnotations(getter, asmMethod.getReturnType(), null);
-
- KtExpression defaultValue = loadAnnotationArgumentDefaultValue(parameter, descriptor, expectedAnnotationConstructor);
- if (defaultValue != null) {
- ConstantValue> constant = ExpressionCodegen.getCompileTimeConstant(
- defaultValue, bindingContext, true, state.getShouldInlineConstVals());
- assert !state.getClassBuilderMode().generateBodies || constant != null
- : "Default value for annotation parameter should be compile time value: " + defaultValue.getText();
- if (constant != null) {
- AnnotationCodegen annotationCodegen = AnnotationCodegen.forAnnotationDefaultValue(mv, memberCodegen, state);
- annotationCodegen.generateAnnotationDefaultValue(constant, descriptor.getType());
- }
- }
-
- mv.visitEnd();
- }
-
- private KtExpression loadAnnotationArgumentDefaultValue(
- @NotNull KtParameter ktParameter,
- @NotNull PropertyDescriptor descriptor,
- @Nullable FunctionDescriptor expectedAnnotationConstructor
- ) {
- KtExpression value = ktParameter.getDefaultValue();
- if (value != null) return value;
-
- if (expectedAnnotationConstructor != null) {
- ValueParameterDescriptor expectedParameter = CollectionsKt.single(
- expectedAnnotationConstructor.getValueParameters(), parameter -> parameter.getName().equals(descriptor.getName())
- );
- PsiElement element = DescriptorToSourceUtils.descriptorToDeclaration(expectedParameter);
- if (!(element instanceof KtParameter)) {
- state.getDiagnostics().report(EXPECTED_FUNCTION_SOURCE_WITH_DEFAULT_ARGUMENTS_NOT_FOUND.on(ktParameter));
- return null;
- }
- return ((KtParameter) element).getDefaultValue();
- }
-
- return null;
- }
-
- private void generateBackingField(@NotNull PropertyDescriptor descriptor, boolean isBackingFieldOwner) {
- if (isJvmInterface(descriptor.getContainingDeclaration()) || kind == OwnerKind.DEFAULT_IMPLS ||
- kind == OwnerKind.ERASED_INLINE_CLASS) {
- return;
- }
-
- Object defaultValue;
- if (descriptor.isDelegated()) {
- defaultValue = null;
- }
- else if (Boolean.TRUE.equals(bindingContext.get(BindingContext.BACKING_FIELD_REQUIRED, descriptor))) {
- if (shouldWriteFieldInitializer(descriptor)) {
- ConstantValue> initializer = descriptor.getCompileTimeInitializer();
- defaultValue = initializer == null ? null : initializer.getValue();
- }
- else {
- defaultValue = null;
- }
- }
- else {
- return;
- }
-
- generateBackingField(descriptor, descriptor.isDelegated(), defaultValue, isBackingFieldOwner);
- }
-
- // Annotations on properties are stored in bytecode on an empty synthetic method. This way they're still
- // accessible via reflection, and 'deprecated' and 'synthetic' flags prevent this method from being called accidentally
- private void generateSyntheticMethodIfNeeded(@NotNull PropertyDescriptor descriptor, boolean isBackingFieldOwner) {
- Annotations annotations = descriptor.getAnnotations();
- if (annotations.isEmpty()) return;
-
- Method signature = typeMapper.mapSyntheticMethodForPropertyAnnotations(descriptor);
- if (kind != OwnerKind.DEFAULT_IMPLS && CodegenContextUtil.isImplementationOwner(context, descriptor)) {
- v.getSerializationBindings().put(SYNTHETIC_METHOD_FOR_PROPERTY, descriptor, signature);
- }
-
- if (isBackingFieldOwner) {
- if (!isInterface(context.getContextDescriptor()) ||
- processInterfaceMethod(descriptor, kind, false, true, state.getJvmDefaultMode())) {
- memberCodegen.generateSyntheticAnnotationsMethod(descriptor, signature, annotations);
- }
- }
- }
-
- private void generateBackingField(
- @NotNull PropertyDescriptor propertyDescriptor,
- boolean isDelegate,
- @Nullable Object defaultValue,
- boolean isBackingFieldOwner
- ) {
- FieldDescriptor annotatedField = isDelegate ? propertyDescriptor.getDelegateField() : propertyDescriptor.getBackingField();
-
- int modifiers = getDeprecatedAccessFlag(propertyDescriptor);
-
- for (AnnotationCodegen.JvmFlagAnnotation flagAnnotation : AnnotationCodegen.FIELD_FLAGS) {
- modifiers |= flagAnnotation.getJvmFlag(annotatedField);
- }
-
- if (kind == OwnerKind.PACKAGE) {
- modifiers |= ACC_STATIC;
- }
-
- if (!propertyDescriptor.isLateInit() && (!propertyDescriptor.isVar() || isDelegate)) {
- modifiers |= ACC_FINAL;
- }
-
- if (hasJvmSyntheticAnnotation(propertyDescriptor)) {
- modifiers |= ACC_SYNTHETIC;
- }
-
- KotlinType kotlinType = isDelegate ? getDelegateTypeForProperty(propertyDescriptor, bindingContext) : propertyDescriptor.getType();
- Type type = typeMapper.mapType(kotlinType);
-
- ClassBuilder builder = v;
-
- FieldOwnerContext backingFieldContext = context;
- List additionalVisibleAnnotations = Collections.emptyList();
- if (DescriptorAsmUtil.isInstancePropertyWithStaticBackingField(propertyDescriptor) ) {
- modifiers |= ACC_STATIC;
-
- if (DescriptorsJvmAbiUtil.isPropertyWithBackingFieldInOuterClass(propertyDescriptor)) {
- ImplementationBodyCodegen codegen = (ImplementationBodyCodegen) memberCodegen.getParentCodegen();
- builder = codegen.v;
- backingFieldContext = codegen.context;
- if (DescriptorVisibilities.isPrivate(((ClassDescriptor) propertyDescriptor.getContainingDeclaration()).getVisibility())) {
- modifiers |= ACC_DEPRECATED;
- additionalVisibleAnnotations = Collections.singletonList(CodegenUtilKt.JAVA_LANG_DEPRECATED);
- }
- }
- }
- modifiers |= getVisibilityForBackingField(propertyDescriptor, isDelegate);
-
- if (DescriptorAsmUtil.isPropertyWithBackingFieldCopyInOuterClass(propertyDescriptor)) {
- ImplementationBodyCodegen parentBodyCodegen = (ImplementationBodyCodegen) memberCodegen.getParentCodegen();
- parentBodyCodegen.addCompanionObjectPropertyToCopy(propertyDescriptor, defaultValue);
- }
-
- String name = backingFieldContext.getFieldName(propertyDescriptor, isDelegate);
-
- v.getSerializationBindings().put(FIELD_FOR_PROPERTY, propertyDescriptor, new Pair<>(type, name));
-
- if (isBackingFieldOwner) {
- String signature = isDelegate ? null : typeMapper.mapFieldSignature(kotlinType, propertyDescriptor);
- FieldVisitor fv = builder.newField(
- JvmDeclarationOriginKt.OtherOrigin(propertyDescriptor), modifiers, name, type.getDescriptor(),
- signature, defaultValue
- );
-
- if (annotatedField != null) {
- // Don't emit nullability annotations for backing field if:
- // - backing field is synthetic;
- // - property is lateinit (since corresponding field is actually nullable).
- boolean skipNullabilityAnnotations =
- (modifiers & ACC_SYNTHETIC) != 0 ||
- propertyDescriptor.isLateInit();
- AnnotationCodegen.forField(fv, memberCodegen, state, skipNullabilityAnnotations)
- .genAnnotations(annotatedField, type, propertyDescriptor.getType(), null, additionalVisibleAnnotations);
- }
-
- if (propertyDescriptor.getContainingDeclaration() instanceof ClassDescriptor && JvmAnnotationUtilKt.isJvmRecord((ClassDescriptor) propertyDescriptor.getContainingDeclaration())) {
- // builder.newRecordComponent(name, type.getDescriptor(), signature);
- }
- }
- }
-
- @NotNull
- public static KotlinType getDelegateTypeForProperty(
- @NotNull PropertyDescriptor propertyDescriptor,
- @NotNull BindingContext bindingContext
- ) {
- ResolvedCall provideDelegateResolvedCall =
- bindingContext.get(BindingContext.PROVIDE_DELEGATE_RESOLVED_CALL, propertyDescriptor);
-
- KtProperty property = (KtProperty) DescriptorToSourceUtils.descriptorToDeclaration(propertyDescriptor);
- KtExpression delegateExpression = property != null ? property.getDelegateExpression() : null;
-
- KotlinType delegateType;
- if (provideDelegateResolvedCall != null) {
- delegateType = provideDelegateResolvedCall.getResultingDescriptor().getReturnType();
- }
- else if (delegateExpression != null) {
- delegateType = bindingContext.getType(delegateExpression);
- }
- else {
- delegateType = null;
- }
-
- if (delegateType == null) {
- // Delegation convention is unresolved
- delegateType = ErrorUtils.createErrorType("Delegate type");
- }
- return delegateType;
- }
-
- private boolean shouldWriteFieldInitializer(@NotNull PropertyDescriptor descriptor) {
- if (!descriptor.isConst() &&
- state.getLanguageVersionSettings().supportsFeature(LanguageFeature.NoConstantValueAttributeForNonConstVals)) {
- return false;
- }
-
- //final field of primitive or String type
- if (!descriptor.isVar()) {
- Type type = typeMapper.mapType(descriptor);
- return AsmUtil.isPrimitive(type) || "java.lang.String".equals(type.getClassName());
- }
- return false;
- }
-
- private void generateGetter(@NotNull PropertyDescriptor descriptor, @Nullable KtPropertyAccessor getter) {
- generateAccessor(
- getter,
- descriptor.getGetter() != null ? descriptor.getGetter() : DescriptorFactory.createDefaultGetter(
- descriptor, Annotations.Companion.getEMPTY()
- )
- );
- }
-
- private void generateSetter(@NotNull PropertyDescriptor descriptor, @Nullable KtPropertyAccessor setter) {
- if (!descriptor.isVar()) return;
-
- generateAccessor(
- setter,
- descriptor.getSetter() != null ? descriptor.getSetter() : DescriptorFactory.createDefaultSetter(
- descriptor, Annotations.Companion.getEMPTY(), Annotations.Companion.getEMPTY()
- )
- );
- }
-
- private void generateAccessor(@Nullable KtPropertyAccessor accessor, @NotNull PropertyAccessorDescriptor descriptor) {
- if (context instanceof MultifileClassFacadeContext &&
- (DescriptorVisibilities.isPrivate(descriptor.getVisibility()) ||
- DescriptorAsmUtil.getVisibilityAccessFlag(descriptor) == Opcodes.ACC_PRIVATE)) {
- return;
- }
-
- FunctionGenerationStrategy strategy;
- if (accessor == null || !accessor.hasBody()) {
- if (descriptor.getCorrespondingProperty().isDelegated()) {
- strategy = new DelegatedPropertyAccessorStrategy(state, descriptor);
- }
- else {
- strategy = new DefaultPropertyAccessorStrategy(state, descriptor);
- }
- }
- else {
- strategy = new FunctionGenerationStrategy.FunctionDefault(state, accessor);
- }
-
- functionCodegen.generateMethod(JvmDeclarationOriginKt.OtherOrigin(descriptor), descriptor, strategy);
- }
-
- private static class DefaultPropertyAccessorStrategy extends FunctionGenerationStrategy.CodegenBased {
- private final PropertyAccessorDescriptor propertyAccessorDescriptor;
-
- public DefaultPropertyAccessorStrategy(@NotNull GenerationState state, @NotNull PropertyAccessorDescriptor descriptor) {
- super(state);
- propertyAccessorDescriptor = descriptor;
- }
-
- @Override
- public void doGenerateBody(@NotNull ExpressionCodegen codegen, @NotNull JvmMethodSignature signature) {
- InstructionAdapter v = codegen.v;
- PropertyDescriptor propertyDescriptor = propertyAccessorDescriptor.getCorrespondingProperty();
- StackValue property = codegen.intermediateValueForProperty(propertyDescriptor, true, null, StackValue.LOCAL_0);
-
- PsiElement jetProperty = DescriptorToSourceUtils.descriptorToDeclaration(propertyDescriptor);
- if (jetProperty instanceof KtProperty || jetProperty instanceof KtParameter) {
- codegen.markLineNumber((KtElement) jetProperty, false);
- }
-
- if (propertyAccessorDescriptor instanceof PropertyGetterDescriptor) {
- Type type = signature.getReturnType();
- property.put(type, v);
- v.areturn(type);
- }
- else if (propertyAccessorDescriptor instanceof PropertySetterDescriptor) {
- List valueParameters = propertyAccessorDescriptor.getValueParameters();
- assert valueParameters.size() == 1 : "Property setter should have only one value parameter but has " + propertyAccessorDescriptor;
- int parameterIndex = codegen.lookupLocalIndex(valueParameters.get(0));
- assert parameterIndex >= 0 : "Local index for setter parameter should be positive or zero: " + propertyAccessorDescriptor;
- Type type = codegen.typeMapper.mapType(propertyDescriptor);
- property.store(StackValue.local(parameterIndex, type), codegen.v);
- v.visitInsn(RETURN);
- }
- else {
- throw new IllegalStateException("Unknown property accessor: " + propertyAccessorDescriptor);
- }
- }
- }
-
- public static StackValue invokeDelegatedPropertyConventionMethod(
- @NotNull ExpressionCodegen codegen,
- @NotNull ResolvedCall resolvedCall,
- @NotNull StackValue receiver,
- @NotNull PropertyDescriptor propertyDescriptor
- ) {
- codegen.tempVariables.put(
- resolvedCall.getCall().getValueArguments().get(1).asElement(),
- getDelegatedPropertyMetadata(propertyDescriptor, codegen.getBindingContext())
- );
-
- return codegen.invokeFunction(resolvedCall, receiver);
- }
-
- public static boolean isDelegatedPropertyWithOptimizedMetadata(
- @NotNull VariableDescriptorWithAccessors descriptor,
- @NotNull BindingContext bindingContext
- ) {
- return Boolean.TRUE == bindingContext.get(DELEGATED_PROPERTY_WITH_OPTIMIZED_METADATA, descriptor);
- }
-
- public static @NotNull StackValue getOptimizedDelegatedPropertyMetadataValue() {
- return StackValue.constant(null, K_PROPERTY_TYPE);
- }
-
- @NotNull
- public static StackValue getDelegatedPropertyMetadata(
- @NotNull VariableDescriptorWithAccessors descriptor,
- @NotNull BindingContext bindingContext
- ) {
- if (isDelegatedPropertyWithOptimizedMetadata(descriptor, bindingContext)) {
- return getOptimizedDelegatedPropertyMetadataValue();
- }
-
- Type owner = bindingContext.get(DELEGATED_PROPERTY_METADATA_OWNER, descriptor);
- assert owner != null : "Delegated property owner not found: " + descriptor;
-
- List allDelegatedProperties = bindingContext.get(DELEGATED_PROPERTIES_WITH_METADATA, owner);
- int index = allDelegatedProperties == null ? -1 : allDelegatedProperties.indexOf(descriptor);
- if (index < 0) {
- throw new AssertionError("Delegated property not found in " + owner + ": " + descriptor);
- }
-
- StackValue.Field array = StackValue.field(
- Type.getType("[" + K_PROPERTY_TYPE), owner, JvmAbi.DELEGATED_PROPERTIES_ARRAY_NAME, true, StackValue.none()
- );
- return StackValue.arrayElement(K_PROPERTY_TYPE, null, array, StackValue.constant(index));
- }
-
- private static class DelegatedPropertyAccessorStrategy extends FunctionGenerationStrategy.CodegenBased {
- private final PropertyAccessorDescriptor propertyAccessorDescriptor;
-
- public DelegatedPropertyAccessorStrategy(@NotNull GenerationState state, @NotNull PropertyAccessorDescriptor descriptor) {
- super(state);
- this.propertyAccessorDescriptor = descriptor;
- }
-
- @Override
- public void doGenerateBody(@NotNull ExpressionCodegen codegen, @NotNull JvmMethodSignature signature) {
- InstructionAdapter v = codegen.v;
-
- BindingContext bindingContext = state.getBindingContext();
- ResolvedCall resolvedCall =
- bindingContext.get(BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, propertyAccessorDescriptor);
- assert resolvedCall != null : "Resolve call should be recorded for delegate call " + signature.toString();
-
- PropertyDescriptor propertyDescriptor = propertyAccessorDescriptor.getCorrespondingProperty();
- StackValue.Property property = codegen.intermediateValueForProperty(propertyDescriptor, true, null, StackValue.LOCAL_0);
- StackValue.Property delegate = property.getDelegateOrNull();
- assert delegate != null : "No delegate for delegated property: " + propertyDescriptor;
- StackValue lastValue = invokeDelegatedPropertyConventionMethod(codegen, resolvedCall, delegate, propertyDescriptor);
- Type asmType = signature.getReturnType();
- KotlinType kotlinReturnType = propertyAccessorDescriptor.getOriginal().getReturnType();
- lastValue.put(asmType, kotlinReturnType, v);
- v.areturn(asmType);
- }
- }
-
- public void genDelegate(@NotNull PropertyDescriptor delegate, @NotNull PropertyDescriptor delegateTo, @NotNull StackValue field) {
- ClassDescriptor toClass = (ClassDescriptor) delegateTo.getContainingDeclaration();
-
- PropertyGetterDescriptor getter = delegate.getGetter();
- if (getter != null) {
- //noinspection ConstantConditions
- functionCodegen.genDelegate(getter, delegateTo.getGetter().getOriginal(), toClass, field);
- }
-
- PropertySetterDescriptor setter = delegate.getSetter();
- if (setter != null) {
- //noinspection ConstantConditions
- functionCodegen.genDelegate(setter, delegateTo.getSetter().getOriginal(), toClass, field);
- }
- }
-}
diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/SamWrapperCodegen.java b/compiler/backend/src/org/jetbrains/kotlin/codegen/SamWrapperCodegen.java
index 5a62089be3f..9c204d64ffb 100644
--- a/compiler/backend/src/org/jetbrains/kotlin/codegen/SamWrapperCodegen.java
+++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/SamWrapperCodegen.java
@@ -20,6 +20,8 @@ import kotlin.text.StringsKt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.backend.common.CodegenUtil;
import org.jetbrains.kotlin.codegen.context.ClassContext;
+import org.jetbrains.kotlin.codegen.context.CodegenContext;
+import org.jetbrains.kotlin.codegen.context.FieldOwnerContext;
import org.jetbrains.kotlin.codegen.state.GenerationState;
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper;
import org.jetbrains.kotlin.descriptors.*;
@@ -62,6 +64,7 @@ public class SamWrapperCodegen {
private final SamType samType;
private final MemberCodegen> parentCodegen;
private final int visibility;
+ private final int classFlags;
public static final String SAM_WRAPPER_SUFFIX = "$0";
public SamWrapperCodegen(
@@ -76,6 +79,7 @@ public class SamWrapperCodegen {
this.samType = samType;
this.parentCodegen = parentCodegen;
visibility = isInsideInline ? ACC_PUBLIC : NO_FLAG_PACKAGE_PRIVATE;
+ classFlags = visibility | ACC_FINAL | ACC_SUPER;
}
@NotNull
@@ -121,7 +125,7 @@ public class SamWrapperCodegen {
cv.defineClass(
file,
state.getClassFileVersion(),
- ACC_FINAL | ACC_SUPER | visibility,
+ classFlags,
asmType.getInternalName(),
null,
OBJECT_TYPE.getInternalName(),
@@ -131,6 +135,8 @@ public class SamWrapperCodegen {
WriteAnnotationUtilKt.writeSyntheticClassMetadata(cv, state);
+ generateInnerClassInformation(file, asmType, cv);
+
// e.g. ASM type for Function2
Type functionAsmType = typeMapper.mapType(functionType);
@@ -160,6 +166,24 @@ public class SamWrapperCodegen {
return asmType;
}
+ private void generateInnerClassInformation(@NotNull KtFile file, Type asmType, ClassBuilder cv) {
+ parentCodegen.addSyntheticAnonymousInnerClass(new SyntheticInnerClassInfo(asmType.getInternalName(), classFlags));
+ FieldOwnerContext> parentContext = parentCodegen.context;
+ CodegenContext> outerContext = MemberCodegen.getNonInlineOuterContext(parentContext);
+ assert outerContext != null :
+ "Outer context for SAM wrapper " + asmType.getInternalName() + " is null, parentContext:" + parentContext;
+ Type outerClassType = MemberCodegen.computeOuterClass(state.getTypeMapper(), state.getJvmDefaultMode(), file, outerContext);
+ assert outerClassType != null :
+ "Outer class for SAM wrapper " + asmType.getInternalName() + " is null, parentContext:" + parentContext;
+ Method enclosingMethod = MemberCodegen.computeEnclosingMethod(state.getTypeMapper(), outerContext);
+ cv.visitOuterClass(
+ outerClassType.getInternalName(),
+ enclosingMethod == null ? null : enclosingMethod.getName(),
+ enclosingMethod == null ? null : enclosingMethod.getDescriptor()
+ );
+ cv.visitInnerClass(asmType.getInternalName(), null, null, classFlags);
+ }
+
private void generateConstructor(Type ownerType, Type functionType, ClassBuilder cv) {
MethodVisitor mv = cv.newMethod(JvmDeclarationOriginKt.OtherOrigin(samType.getClassDescriptor()),
visibility, "", Type.getMethodDescriptor(Type.VOID_TYPE, functionType), null, null);
diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/SyntheticInnerClassInfo.kt b/compiler/backend/src/org/jetbrains/kotlin/codegen/SyntheticInnerClassInfo.kt
new file mode 100644
index 00000000000..c17cb165052
--- /dev/null
+++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/SyntheticInnerClassInfo.kt
@@ -0,0 +1,8 @@
+/*
+ * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
+ * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
+ */
+
+package org.jetbrains.kotlin.codegen
+
+data class SyntheticInnerClassInfo(val internalName: String, val flags: Int)
\ No newline at end of file
diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/coroutines/CoroutineTransformerMethodVisitor.kt b/compiler/backend/src/org/jetbrains/kotlin/codegen/coroutines/CoroutineTransformerMethodVisitor.kt
index 2099d5c044f..eaa421dd181 100644
--- a/compiler/backend/src/org/jetbrains/kotlin/codegen/coroutines/CoroutineTransformerMethodVisitor.kt
+++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/coroutines/CoroutineTransformerMethodVisitor.kt
@@ -1113,7 +1113,7 @@ inline fun withInstructionAdapter(block: InstructionAdapter.() -> Unit): InsnLis
return tmpMethodNode.instructions
}
-internal fun Type.normalize() =
+fun Type.normalize() =
when (sort) {
Type.ARRAY, Type.OBJECT -> AsmTypes.OBJECT_TYPE
else -> this
diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/inline/InlineCodegen.kt b/compiler/backend/src/org/jetbrains/kotlin/codegen/inline/InlineCodegen.kt
index c578ef0058d..7c45a0bfbff 100644
--- a/compiler/backend/src/org/jetbrains/kotlin/codegen/inline/InlineCodegen.kt
+++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/inline/InlineCodegen.kt
@@ -16,6 +16,7 @@ import org.jetbrains.kotlin.codegen.intrinsics.IntrinsicArrayConstructors
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper
import org.jetbrains.kotlin.config.CommonConfigurationKeys
+import org.jetbrains.kotlin.config.JVMConfigurationKeys
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.incremental.components.Position
import org.jetbrains.kotlin.incremental.components.ScopeKind
@@ -522,10 +523,15 @@ abstract class InlineCodegen(
return SMAPAndMethodNode(intrinsic, createDefaultFakeSMAP())
}
- val asmMethod = if (callDefault)
- state.typeMapper.mapDefaultMethod(functionDescriptor, sourceCompiler.contextKind)
- else
- mangleSuspendInlineFunctionAsmMethodIfNeeded(functionDescriptor, jvmSignature.asmMethod)
+ var asmMethod = mapMethod(callDefault)
+ if (asmMethod.name.contains("-") &&
+ !state.configuration.getBoolean(JVMConfigurationKeys.USE_OLD_INLINE_CLASSES_MANGLING_SCHEME) &&
+ classFileContainsMethod(functionDescriptor, state, asmMethod) == false
+ ) {
+ state.typeMapper.useOldManglingRulesForFunctionAcceptingInlineClass = true
+ asmMethod = mapMethod(callDefault)
+ state.typeMapper.useOldManglingRulesForFunctionAcceptingInlineClass = false
+ }
val directMember = getDirectMemberAndCallableFromObject(functionDescriptor)
if (!isBuiltInArrayIntrinsic(functionDescriptor) && !descriptorIsDeserialized(directMember)) {
@@ -537,6 +543,10 @@ abstract class InlineCodegen(
return getCompiledMethodNodeInner(functionDescriptor, directMember, asmMethod, methodOwner, state, jvmSignature)
}
+ private fun mapMethod(callDefault: Boolean): Method =
+ if (callDefault) state.typeMapper.mapDefaultMethod(functionDescriptor, sourceCompiler.contextKind)
+ else mangleSuspendInlineFunctionAsmMethodIfNeeded(functionDescriptor, jvmSignature.asmMethod)
+
companion object {
internal fun createSpecialInlineMethodNodeFromBinaries(functionDescriptor: FunctionDescriptor, state: GenerationState): MethodNode {
diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/state/GenerationState.kt b/compiler/backend/src/org/jetbrains/kotlin/codegen/state/GenerationState.kt
index 1923db861c7..844cfe00604 100644
--- a/compiler/backend/src/org/jetbrains/kotlin/codegen/state/GenerationState.kt
+++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/state/GenerationState.kt
@@ -298,7 +298,7 @@ class GenerationState private constructor(
?: if (languageVersionSettings.languageVersion >= LanguageVersion.LATEST_STABLE) JvmMetadataVersion.INSTANCE
else JvmMetadataVersion(1, 1, 18)
- val isIrWithStableAbi = configuration.getBoolean(JVMConfigurationKeys.IS_IR_WITH_STABLE_ABI)
+ val abiStability = configuration.get(JVMConfigurationKeys.ABI_STABILITY)
val globalSerializationBindings = JvmSerializationBindings()
var mapInlineClass: (ClassDescriptor) -> Type = { descriptor -> typeMapper.mapType(descriptor.defaultType) }
diff --git a/compiler/build.gradle.kts b/compiler/build.gradle.kts
index e01d48d01cf..4afd3561e5e 100644
--- a/compiler/build.gradle.kts
+++ b/compiler/build.gradle.kts
@@ -46,7 +46,7 @@ dependencies {
testCompile(projectTests(":compiler:fir:raw-fir:psi2fir"))
testCompile(projectTests(":compiler:fir:raw-fir:light-tree2fir"))
testCompile(projectTests(":compiler:fir:fir2ir"))
- testCompile(projectTests(":compiler:fir:analysis-tests"))
+ testCompile(projectTests(":compiler:fir:analysis-tests:legacy-fir-tests"))
testCompile(projectTests(":compiler:visualizer"))
testCompile(projectTests(":generators:test-generator"))
testCompile(project(":compiler:ir.ir2cfg"))
@@ -99,8 +99,5 @@ projectTest(parallel = true) {
}
val generateTestData by generator("org.jetbrains.kotlin.generators.tests.GenerateCompilerTestDataKt")
-val generateTests by generator("org.jetbrains.kotlin.generators.tests.GenerateCompilerTestsKt") {
- dependsOn(generateTestData)
-}
testsJar()
diff --git a/compiler/cli/cli-common/src/org/jetbrains/kotlin/cli/common/arguments/K2JVMCompilerArguments.kt b/compiler/cli/cli-common/src/org/jetbrains/kotlin/cli/common/arguments/K2JVMCompilerArguments.kt
index 2137b548ada..25ff966572d 100644
--- a/compiler/cli/cli-common/src/org/jetbrains/kotlin/cli/common/arguments/K2JVMCompilerArguments.kt
+++ b/compiler/cli/cli-common/src/org/jetbrains/kotlin/cli/common/arguments/K2JVMCompilerArguments.kt
@@ -95,18 +95,20 @@ class K2JVMCompilerArguments : CommonCompilerArguments() {
var irCheckLocalNames: Boolean by FreezableVar(false)
@Argument(
- value = "-Xallow-jvm-ir-dependencies",
- description = "When not using the IR backend, do not report errors on those classes in dependencies, " +
- "which were compiled by the IR backend"
+ value = "-Xallow-unstable-dependencies",
+ description = "Do not report errors on classes in dependencies, which were compiled by an unstable version of the Kotlin compiler"
)
- var allowJvmIrDependencies: Boolean by FreezableVar(false)
+ var allowUnstableDependencies: Boolean by FreezableVar(false)
@Argument(
- value = "-Xir-binary-with-stable-abi",
- description = "When using the IR backend, produce binaries which can be read by non-IR backend.\n" +
- "The author is responsible for verifying that the resulting binaries do indeed have the correct ABI"
+ value = "-Xabi-stability",
+ valueDescription = "{stable|unstable}",
+ description = "When using unstable compiler features such as FIR, use 'stable' to mark generated class files as stable\n" +
+ "to prevent diagnostics from stable compilers at the call site.\n" +
+ "When using the JVM IR backend, conversely, use 'unstable' to mark generated class files as unstable\n" +
+ "to force diagnostics to be reported."
)
- var isIrWithStableAbi: Boolean by FreezableVar(false)
+ var abiStability: String? by FreezableVar(null)
@Argument(
value = "-Xir-do-not-clear-binding-context",
@@ -446,7 +448,7 @@ class K2JVMCompilerArguments : CommonCompilerArguments() {
result[JvmAnalysisFlags.suppressMissingBuiltinsError] = suppressMissingBuiltinsError
result[JvmAnalysisFlags.irCheckLocalNames] = irCheckLocalNames
result[JvmAnalysisFlags.enableJvmPreview] = enableJvmPreview
- result[AnalysisFlags.reportErrorsOnIrDependencies] = !useIR && !useFir && !allowJvmIrDependencies
+ result[AnalysisFlags.allowUnstableDependencies] = allowUnstableDependencies || useFir
result[JvmAnalysisFlags.disableUltraLightClasses] = disableUltraLightClasses
return result
}
diff --git a/compiler/cli/src/org/jetbrains/kotlin/cli/common/messages/AnalyzerWithCompilerReport.kt b/compiler/cli/src/org/jetbrains/kotlin/cli/common/messages/AnalyzerWithCompilerReport.kt
index 0c749ba5708..d5e0db6b644 100644
--- a/compiler/cli/src/org/jetbrains/kotlin/cli/common/messages/AnalyzerWithCompilerReport.kt
+++ b/compiler/cli/src/org/jetbrains/kotlin/cli/common/messages/AnalyzerWithCompilerReport.kt
@@ -182,11 +182,19 @@ class AnalyzerWithCompilerReport(
)
}
- if (diagnostics.any { it.factory == Errors.IR_COMPILED_CLASS }) {
+ if (diagnostics.any { it.factory == Errors.IR_WITH_UNSTABLE_ABI_COMPILED_CLASS }) {
messageCollector.report(
ERROR,
- "Classes compiled by a new Kotlin compiler backend were found in dependencies. " +
- "Remove them from the classpath or use '-Xallow-jvm-ir-dependencies' to suppress errors"
+ "Classes compiled by an unstable version of the Kotlin compiler were found in dependencies. " +
+ "Remove them from the classpath or use '-Xallow-unstable-dependencies' to suppress errors"
+ )
+ }
+
+ if (diagnostics.any { it.factory == Errors.FIR_COMPILED_CLASS }) {
+ messageCollector.report(
+ ERROR,
+ "Classes compiled by the new Kotlin compiler frontend were found in dependencies. " +
+ "Remove them from the classpath or use '-Xallow-unstable-dependencies' to suppress errors"
)
}
diff --git a/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/JavaLanguageLevel.kt b/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/JavaLanguageLevel.kt
new file mode 100644
index 00000000000..b14569fb5fc
--- /dev/null
+++ b/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/JavaLanguageLevel.kt
@@ -0,0 +1,14 @@
+/*
+ * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
+ * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
+ */
+
+package org.jetbrains.kotlin.cli.jvm.compiler
+
+import com.intellij.openapi.project.Project
+import com.intellij.openapi.roots.LanguageLevelProjectExtension
+import com.intellij.pom.java.LanguageLevel
+
+fun Project.setupHighestLanguageLevel() {
+ LanguageLevelProjectExtension.getInstance(this).languageLevel = LanguageLevel.JDK_15_PREVIEW
+}
diff --git a/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/JavaLanguageLevel.kt.201 b/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/JavaLanguageLevel.kt.201
new file mode 100644
index 00000000000..423b6b10229
--- /dev/null
+++ b/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/JavaLanguageLevel.kt.201
@@ -0,0 +1,14 @@
+/*
+ * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
+ * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
+ */
+
+package org.jetbrains.kotlin.cli.jvm.compiler
+
+import com.intellij.openapi.project.Project
+import com.intellij.openapi.roots.LanguageLevelProjectExtension
+import com.intellij.pom.java.LanguageLevel
+
+fun Project.setupHighestLanguageLevel() {
+ // LanguageLevelProjectExtension.getInstance(this).languageLevel = LanguageLevel.JDK_15_PREVIEW
+}
diff --git a/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/KotlinCoreEnvironment.kt b/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/KotlinCoreEnvironment.kt
index 47c6ee66a30..dc9270e9345 100644
--- a/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/KotlinCoreEnvironment.kt
+++ b/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/KotlinCoreEnvironment.kt
@@ -253,7 +253,7 @@ class KotlinCoreEnvironment private constructor(
updateClasspath(roots.map { JavaSourceRoot(it, null) })
})
- LanguageLevelProjectExtension.getInstance(project).languageLevel = LanguageLevel.JDK_15_PREVIEW
+ project.setupHighestLanguageLevel()
}
private fun collectAdditionalSources(project: MockProject) {
diff --git a/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/KotlinCoreEnvironment.kt.201 b/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/KotlinCoreEnvironment.kt.201
deleted file mode 100644
index 6120985d6ce..00000000000
--- a/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/KotlinCoreEnvironment.kt.201
+++ /dev/null
@@ -1,703 +0,0 @@
-/*
- * Copyright 2010-2017 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.jetbrains.kotlin.cli.jvm.compiler
-
-import com.intellij.codeInsight.ExternalAnnotationsManager
-import com.intellij.codeInsight.InferredAnnotationsManager
-import com.intellij.core.CoreApplicationEnvironment
-import com.intellij.core.CoreJavaFileManager
-import com.intellij.core.JavaCoreProjectEnvironment
-import com.intellij.ide.highlighter.JavaFileType
-import com.intellij.lang.java.JavaParserDefinition
-import com.intellij.mock.MockProject
-import com.intellij.openapi.Disposable
-import com.intellij.openapi.application.TransactionGuard
-import com.intellij.openapi.application.TransactionGuardImpl
-import com.intellij.openapi.components.ServiceManager
-import com.intellij.openapi.diagnostic.Logger
-import com.intellij.openapi.extensions.Extensions
-import com.intellij.openapi.extensions.ExtensionsArea
-import com.intellij.openapi.fileTypes.PlainTextFileType
-import com.intellij.openapi.project.Project
-import com.intellij.openapi.roots.LanguageLevelProjectExtension
-import com.intellij.openapi.util.Disposer
-import com.intellij.openapi.util.io.FileUtilRt
-import com.intellij.openapi.util.text.StringUtil
-import com.intellij.openapi.vfs.*
-import com.intellij.openapi.vfs.impl.ZipHandler
-import com.intellij.pom.java.LanguageLevel
-import com.intellij.psi.PsiElementFinder
-import com.intellij.psi.PsiManager
-import com.intellij.psi.compiled.ClassFileDecompilers
-import com.intellij.psi.impl.JavaClassSupersImpl
-import com.intellij.psi.impl.PsiElementFinderImpl
-import com.intellij.psi.impl.PsiTreeChangePreprocessor
-import com.intellij.psi.impl.file.impl.JavaFileManager
-import com.intellij.psi.search.GlobalSearchScope
-import com.intellij.psi.util.JavaClassSupers
-import com.intellij.util.io.URLUtil
-import com.intellij.util.lang.UrlClassLoader
-import org.jetbrains.annotations.TestOnly
-import org.jetbrains.kotlin.asJava.KotlinAsJavaSupport
-import org.jetbrains.kotlin.asJava.LightClassGenerationSupport
-import org.jetbrains.kotlin.asJava.classes.FacadeCache
-import org.jetbrains.kotlin.asJava.finder.JavaElementFinder
-import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension
-import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
-import org.jetbrains.kotlin.cli.common.CliModuleVisibilityManagerImpl
-import org.jetbrains.kotlin.cli.common.KOTLIN_COMPILER_ENVIRONMENT_KEEPALIVE_PROPERTY
-import org.jetbrains.kotlin.cli.common.config.ContentRoot
-import org.jetbrains.kotlin.cli.common.config.KotlinSourceRoot
-import org.jetbrains.kotlin.cli.common.config.kotlinSourceRoots
-import org.jetbrains.kotlin.cli.common.extensions.ScriptEvaluationExtension
-import org.jetbrains.kotlin.cli.common.extensions.ShellExtension
-import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
-import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.ERROR
-import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.STRONG_WARNING
-import org.jetbrains.kotlin.cli.common.messages.MessageCollector
-import org.jetbrains.kotlin.cli.common.toBooleanLenient
-import org.jetbrains.kotlin.cli.jvm.JvmRuntimeVersionsConsistencyChecker
-import org.jetbrains.kotlin.cli.jvm.config.*
-import org.jetbrains.kotlin.cli.jvm.index.*
-import org.jetbrains.kotlin.cli.jvm.javac.JavacWrapperRegistrar
-import org.jetbrains.kotlin.cli.jvm.modules.CliJavaModuleFinder
-import org.jetbrains.kotlin.cli.jvm.modules.CliJavaModuleResolver
-import org.jetbrains.kotlin.cli.jvm.modules.CoreJrtFileSystem
-import org.jetbrains.kotlin.codegen.extensions.ClassBuilderInterceptorExtension
-import org.jetbrains.kotlin.codegen.extensions.ExpressionCodegenExtension
-import org.jetbrains.kotlin.compiler.plugin.ComponentRegistrar
-import org.jetbrains.kotlin.config.*
-import org.jetbrains.kotlin.extensions.*
-import org.jetbrains.kotlin.extensions.internal.CandidateInterceptor
-import org.jetbrains.kotlin.extensions.internal.TypeResolutionInterceptor
-import org.jetbrains.kotlin.idea.KotlinFileType
-import org.jetbrains.kotlin.js.translate.extensions.JsSyntheticTranslateExtension
-import org.jetbrains.kotlin.load.kotlin.KotlinBinaryClassCache
-import org.jetbrains.kotlin.load.kotlin.MetadataFinderFactory
-import org.jetbrains.kotlin.load.kotlin.ModuleVisibilityManager
-import org.jetbrains.kotlin.load.kotlin.VirtualFileFinderFactory
-import org.jetbrains.kotlin.parsing.KotlinParserDefinition
-import org.jetbrains.kotlin.psi.KtFile
-import org.jetbrains.kotlin.resolve.CodeAnalyzerInitializer
-import org.jetbrains.kotlin.resolve.ModuleAnnotationsResolver
-import org.jetbrains.kotlin.resolve.extensions.ExtraImportsProviderExtension
-import org.jetbrains.kotlin.resolve.extensions.SyntheticResolveExtension
-import org.jetbrains.kotlin.resolve.jvm.KotlinJavaPsiFacade
-import org.jetbrains.kotlin.resolve.jvm.extensions.AnalysisHandlerExtension
-import org.jetbrains.kotlin.resolve.jvm.extensions.PackageFragmentProviderExtension
-import org.jetbrains.kotlin.resolve.jvm.modules.JavaModuleResolver
-import org.jetbrains.kotlin.resolve.lazy.declarations.CliDeclarationProviderFactoryService
-import org.jetbrains.kotlin.resolve.lazy.declarations.DeclarationProviderFactoryService
-import org.jetbrains.kotlin.serialization.DescriptorSerializerPlugin
-import org.jetbrains.kotlin.utils.PathUtil
-import java.io.File
-import java.nio.file.FileSystems
-import java.util.zip.ZipFile
-
-class KotlinCoreEnvironment private constructor(
- val projectEnvironment: JavaCoreProjectEnvironment,
- private val initialConfiguration: CompilerConfiguration,
- configFiles: EnvironmentConfigFiles
-) {
-
- class ProjectEnvironment(
- disposable: Disposable,
- applicationEnvironment: KotlinCoreApplicationEnvironment
- ) :
- KotlinCoreProjectEnvironment(disposable, applicationEnvironment) {
-
- private var extensionRegistered = false
-
- override fun preregisterServices() {
- registerProjectExtensionPoints(project.extensionArea)
- }
-
- fun registerExtensionsFromPlugins(configuration: CompilerConfiguration) {
- if (!extensionRegistered) {
- registerPluginExtensionPoints(project)
- registerExtensionsFromPlugins(project, configuration)
- extensionRegistered = true
- }
- }
-
- override fun registerJavaPsiFacade() {
- with(project) {
- registerService(
- CoreJavaFileManager::class.java,
- ServiceManager.getService(this, JavaFileManager::class.java) as CoreJavaFileManager
- )
-
- registerKotlinLightClassSupport(project)
-
- registerService(ExternalAnnotationsManager::class.java, MockExternalAnnotationsManager())
- registerService(InferredAnnotationsManager::class.java, MockInferredAnnotationsManager())
- }
-
- super.registerJavaPsiFacade()
- }
- }
-
- private val sourceFiles = mutableListOf()
- private val rootsIndex: JvmDependenciesDynamicCompoundIndex
- private val packagePartProviders = mutableListOf()
-
- private val classpathRootsResolver: ClasspathRootsResolver
- private val initialRoots = ArrayList()
-
- val configuration: CompilerConfiguration = initialConfiguration.apply { setupJdkClasspathRoots(configFiles) }.copy()
-
- init {
- PersistentFSConstants::class.java.getDeclaredField("ourMaxIntellisenseFileSize")
- .apply { isAccessible = true }
- .setInt(null, FileUtilRt.LARGE_FOR_CONTENT_LOADING)
-
- val project = projectEnvironment.project
-
- val messageCollector = configuration.get(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY)
-
- (projectEnvironment as? ProjectEnvironment)?.registerExtensionsFromPlugins(configuration)
- // otherwise consider that project environment is properly configured before passing to the environment
- // TODO: consider some asserts to check important extension points
-
- project.registerService(DeclarationProviderFactoryService::class.java, CliDeclarationProviderFactoryService(sourceFiles))
-
- val isJvm = configFiles == EnvironmentConfigFiles.JVM_CONFIG_FILES
- project.registerService(ModuleVisibilityManager::class.java, CliModuleVisibilityManagerImpl(isJvm))
-
- registerProjectServicesForCLI(projectEnvironment)
-
- registerProjectServices(projectEnvironment.project)
-
- for (extension in CompilerConfigurationExtension.getInstances(project)) {
- extension.updateConfiguration(configuration)
- }
-
- sourceFiles += createKtFiles(project)
-
- collectAdditionalSources(project)
-
- sourceFiles.sortBy { it.virtualFile.path }
-
- val jdkHome = configuration.get(JVMConfigurationKeys.JDK_HOME)
- val jrtFileSystem = VirtualFileManager.getInstance().getFileSystem(StandardFileSystems.JRT_PROTOCOL)
- val javaModuleFinder = CliJavaModuleFinder(jdkHome?.path?.let { path ->
- jrtFileSystem?.findFileByPath(path + URLUtil.JAR_SEPARATOR)
- })
-
- val outputDirectory =
- configuration.get(JVMConfigurationKeys.MODULES)?.singleOrNull()?.getOutputDirectory()
- ?: configuration.get(JVMConfigurationKeys.OUTPUT_DIRECTORY)?.absolutePath
-
- classpathRootsResolver = ClasspathRootsResolver(
- PsiManager.getInstance(project),
- messageCollector,
- configuration.getList(JVMConfigurationKeys.ADDITIONAL_JAVA_MODULES),
- this::contentRootToVirtualFile,
- javaModuleFinder,
- !configuration.getBoolean(CLIConfigurationKeys.ALLOW_KOTLIN_PACKAGE),
- outputDirectory?.let(this::findLocalFile)
- )
-
- val (initialRoots, javaModules) =
- classpathRootsResolver.convertClasspathRoots(configuration.getList(CLIConfigurationKeys.CONTENT_ROOTS))
- this.initialRoots.addAll(initialRoots)
-
- if (!configuration.getBoolean(JVMConfigurationKeys.SKIP_RUNTIME_VERSION_CHECK) && messageCollector != null) {
- JvmRuntimeVersionsConsistencyChecker.checkCompilerClasspathConsistency(
- messageCollector,
- configuration,
- initialRoots.mapNotNull { (file, type) -> if (type == JavaRoot.RootType.BINARY) file else null }
- )
- }
-
- val (roots, singleJavaFileRoots) =
- initialRoots.partition { (file) -> file.isDirectory || file.extension != JavaFileType.DEFAULT_EXTENSION }
-
- // REPL and kapt2 update classpath dynamically
- rootsIndex = JvmDependenciesDynamicCompoundIndex().apply {
- addIndex(JvmDependenciesIndexImpl(roots))
- updateClasspathFromRootsIndex(this)
- }
-
- (ServiceManager.getService(project, CoreJavaFileManager::class.java) as KotlinCliJavaFileManagerImpl).initialize(
- rootsIndex,
- packagePartProviders,
- SingleJavaFileRootsIndex(singleJavaFileRoots),
- configuration.getBoolean(JVMConfigurationKeys.USE_PSI_CLASS_FILES_READING)
- )
-
- project.registerService(
- JavaModuleResolver::class.java,
- CliJavaModuleResolver(classpathRootsResolver.javaModuleGraph, javaModules, javaModuleFinder.systemModules.toList())
- )
-
- val finderFactory = CliVirtualFileFinderFactory(rootsIndex)
- project.registerService(MetadataFinderFactory::class.java, finderFactory)
- project.registerService(VirtualFileFinderFactory::class.java, finderFactory)
-
- project.putUserData(APPEND_JAVA_SOURCE_ROOTS_HANDLER_KEY, fun(roots: List) {
- updateClasspath(roots.map { JavaSourceRoot(it, null) })
- })
- }
-
- private fun collectAdditionalSources(project: MockProject) {
- var unprocessedSources: Collection = sourceFiles
- val processedSources = HashSet()
- val processedSourcesByExtension = HashMap>()
- // repeat feeding extensions with sources while new sources a being added
- var sourceCollectionIterations = 0
- while (unprocessedSources.isNotEmpty()) {
- if (sourceCollectionIterations++ > 10) { // TODO: consider using some appropriate global constant
- throw IllegalStateException("Unable to collect additional sources in reasonable number of iterations")
- }
- processedSources.addAll(unprocessedSources)
- val allNewSources = ArrayList()
- for (extension in CollectAdditionalSourcesExtension.getInstances(project)) {
- // do not feed the extension with the sources it returned on the previous iteration
- val sourcesToProcess = unprocessedSources - (processedSourcesByExtension[extension] ?: emptyList())
- val newSources = extension.collectAdditionalSourcesAndUpdateConfiguration(sourcesToProcess, configuration, project)
- if (newSources.isNotEmpty()) {
- allNewSources.addAll(newSources)
- processedSourcesByExtension[extension] = newSources
- }
- }
- unprocessedSources = allNewSources.filterNot { processedSources.contains(it) }.distinct()
- sourceFiles += unprocessedSources
- }
- }
-
- fun addKotlinSourceRoots(rootDirs: List) {
- val roots = rootDirs.map { KotlinSourceRoot(it.absolutePath, isCommon = false) }
- sourceFiles += createSourceFilesFromSourceRoots(configuration, project, roots)
- }
-
- fun createPackagePartProvider(scope: GlobalSearchScope): JvmPackagePartProvider {
- return JvmPackagePartProvider(configuration.languageVersionSettings, scope).apply {
- addRoots(initialRoots, configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY))
- packagePartProviders += this
- (ModuleAnnotationsResolver.getInstance(project) as CliModuleAnnotationsResolver).addPackagePartProvider(this)
- }
- }
-
- private val VirtualFile.javaFiles: List
- get() = mutableListOf().apply {
- VfsUtilCore.processFilesRecursively(this@javaFiles) { file ->
- if (file.fileType == JavaFileType.INSTANCE) {
- add(file)
- }
- true
- }
- }
-
- private val allJavaFiles: List
- get() = configuration.javaSourceRoots
- .mapNotNull(this::findLocalFile)
- .flatMap { it.javaFiles }
- .map { File(it.canonicalPath) }
-
- fun registerJavac(
- javaFiles: List = allJavaFiles,
- kotlinFiles: List = sourceFiles,
- arguments: Array? = null,
- bootClasspath: List? = null,
- sourcePath: List? = null
- ): Boolean {
- return JavacWrapperRegistrar.registerJavac(
- projectEnvironment.project, configuration, javaFiles, kotlinFiles, arguments, bootClasspath, sourcePath,
- LightClassGenerationSupport.getInstance(project), packagePartProviders
- )
- }
-
- private val applicationEnvironment: CoreApplicationEnvironment
- get() = projectEnvironment.environment
-
- val project: Project
- get() = projectEnvironment.project
-
- internal fun countLinesOfCode(sourceFiles: List): Int =
- sourceFiles.sumBy { sourceFile ->
- val text = sourceFile.text
- StringUtil.getLineBreakCount(text) + (if (StringUtil.endsWithLineBreak(text)) 0 else 1)
- }
-
- private fun updateClasspathFromRootsIndex(index: JvmDependenciesIndex) {
- index.indexedRoots.forEach {
- projectEnvironment.addSourcesToClasspath(it.file)
- }
- }
-
- fun updateClasspath(contentRoots: List): List? {
- // TODO: add new Java modules to CliJavaModuleResolver
- val newRoots = classpathRootsResolver.convertClasspathRoots(contentRoots).roots
-
- if (packagePartProviders.isEmpty()) {
- initialRoots.addAll(newRoots)
- } else {
- for (packagePartProvider in packagePartProviders) {
- packagePartProvider.addRoots(newRoots, configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY))
- }
- }
-
- return rootsIndex.addNewIndexForRoots(newRoots)?.let { newIndex ->
- updateClasspathFromRootsIndex(newIndex)
- newIndex.indexedRoots.mapNotNull { (file) ->
- VfsUtilCore.virtualToIoFile(VfsUtilCore.getVirtualFileForJar(file) ?: file)
- }.toList()
- }.orEmpty()
- }
-
- private fun contentRootToVirtualFile(root: JvmContentRoot): VirtualFile? =
- when (root) {
- is JvmClasspathRoot ->
- if (root.file.isFile) findJarRoot(root.file) else findExistingRoot(root, "Classpath entry")
- is JvmModulePathRoot ->
- if (root.file.isFile) findJarRoot(root.file) else findExistingRoot(root, "Java module root")
- is JavaSourceRoot ->
- findExistingRoot(root, "Java source root")
- else ->
- throw IllegalStateException("Unexpected root: $root")
- }
-
- internal fun findLocalFile(path: String): VirtualFile? =
- applicationEnvironment.localFileSystem.findFileByPath(path)
-
- private fun findExistingRoot(root: JvmContentRoot, rootDescription: String): VirtualFile? {
- return findLocalFile(root.file.absolutePath).also {
- if (it == null) {
- report(STRONG_WARNING, "$rootDescription points to a non-existent location: ${root.file}")
- }
- }
- }
-
- private fun findJarRoot(file: File): VirtualFile? =
- applicationEnvironment.jarFileSystem.findFileByPath("$file${URLUtil.JAR_SEPARATOR}")
-
- private fun getSourceRootsCheckingForDuplicates(): List {
- val uniqueSourceRoots = hashSetOf()
- val result = mutableListOf()
-
- for (root in configuration.kotlinSourceRoots) {
- if (!uniqueSourceRoots.add(root.path)) {
- report(STRONG_WARNING, "Duplicate source root: ${root.path}")
- }
- result.add(root)
- }
-
- return result
- }
-
- fun getSourceFiles(): List = sourceFiles
-
- private fun createKtFiles(project: Project): List =
- createSourceFilesFromSourceRoots(configuration, project, getSourceRootsCheckingForDuplicates())
-
- internal fun report(severity: CompilerMessageSeverity, message: String) = configuration.report(severity, message)
-
- companion object {
- private val LOG = Logger.getInstance(KotlinCoreEnvironment::class.java)
-
- private val APPLICATION_LOCK = Object()
- private var ourApplicationEnvironment: KotlinCoreApplicationEnvironment? = null
- private var ourProjectCount = 0
-
- @JvmStatic
- fun createForProduction(
- parentDisposable: Disposable, configuration: CompilerConfiguration, configFiles: EnvironmentConfigFiles
- ): KotlinCoreEnvironment {
- setupIdeaStandaloneExecution()
- val appEnv = getOrCreateApplicationEnvironmentForProduction(parentDisposable, configuration)
- val projectEnv = ProjectEnvironment(parentDisposable, appEnv)
- val environment = KotlinCoreEnvironment(projectEnv, configuration, configFiles)
-
- synchronized(APPLICATION_LOCK) {
- ourProjectCount++
- }
- return environment
- }
-
- @JvmStatic
- fun createForProduction(
- projectEnvironment: JavaCoreProjectEnvironment, configuration: CompilerConfiguration, configFiles: EnvironmentConfigFiles
- ): KotlinCoreEnvironment {
- val environment = KotlinCoreEnvironment(projectEnvironment, configuration, configFiles)
-
- if (projectEnvironment.environment == applicationEnvironment) {
- // accounting for core environment disposing
- synchronized(APPLICATION_LOCK) {
- ourProjectCount++
- }
- }
- return environment
- }
-
- @TestOnly
- @JvmStatic
- fun createForTests(
- parentDisposable: Disposable, initialConfiguration: CompilerConfiguration, extensionConfigs: EnvironmentConfigFiles
- ): KotlinCoreEnvironment {
- val configuration = initialConfiguration.copy()
- // Tests are supposed to create a single project and dispose it right after use
- val appEnv = createApplicationEnvironment(parentDisposable, configuration, unitTestMode = true)
- val projectEnv = ProjectEnvironment(parentDisposable, appEnv)
- return KotlinCoreEnvironment(projectEnv, configuration, extensionConfigs)
- }
-
- // used in the daemon for jar cache cleanup
- val applicationEnvironment: KotlinCoreApplicationEnvironment? get() = ourApplicationEnvironment
-
- fun getOrCreateApplicationEnvironmentForProduction(
- parentDisposable: Disposable, configuration: CompilerConfiguration
- ): KotlinCoreApplicationEnvironment {
- synchronized(APPLICATION_LOCK) {
- if (ourApplicationEnvironment == null) {
- val disposable = Disposer.newDisposable()
- ourApplicationEnvironment = createApplicationEnvironment(disposable, configuration, unitTestMode = false)
- ourProjectCount = 0
- Disposer.register(disposable, Disposable {
- synchronized(APPLICATION_LOCK) {
- ourApplicationEnvironment = null
- }
- })
- }
- // Disposing of the environment is unsafe in production then parallel builds are enabled, but turning it off universally
- // breaks a lot of tests, therefore it is disabled for production and enabled for tests
- if (System.getProperty(KOTLIN_COMPILER_ENVIRONMENT_KEEPALIVE_PROPERTY).toBooleanLenient() != true) {
- // JPS may run many instances of the compiler in parallel (there's an option for compiling independent modules in parallel in IntelliJ)
- // All projects share the same ApplicationEnvironment, and when the last project is disposed, the ApplicationEnvironment is disposed as well
- @Suppress("ObjectLiteralToLambda") // Disposer tree depends on identity of disposables.
- Disposer.register(parentDisposable, object : Disposable {
- override fun dispose() {
- synchronized(APPLICATION_LOCK) {
- if (--ourProjectCount <= 0) {
- disposeApplicationEnvironment()
- }
- }
- }
- })
- }
-
- return ourApplicationEnvironment!!
- }
- }
-
- /**
- * This method is also used in Gradle after configuration phase finished.
- */
- fun disposeApplicationEnvironment() {
- synchronized(APPLICATION_LOCK) {
- val environment = ourApplicationEnvironment ?: return
- ourApplicationEnvironment = null
- Disposer.dispose(environment.parentDisposable)
- ZipHandler.clearFileAccessorCache()
- }
- }
-
- private fun createApplicationEnvironment(
- parentDisposable: Disposable, configuration: CompilerConfiguration, unitTestMode: Boolean
- ): KotlinCoreApplicationEnvironment {
- val applicationEnvironment = KotlinCoreApplicationEnvironment.create(parentDisposable, unitTestMode)
-
- registerApplicationExtensionPointsAndExtensionsFrom(configuration, "extensions/compiler.xml")
- // FIX ME WHEN BUNCH 202 REMOVED: this code is required to support compiler bundled to both 202 and 203.
- // Please, remove "com.intellij.psi.classFileDecompiler" EP registration once 202 is no longer supported by the compiler
- if (!Extensions.getRootArea().hasExtensionPoint("com.intellij.psi.classFileDecompiler")) {
- registerApplicationExtensionPointsAndExtensionsFrom(configuration, "extensions/core.xml")
- }
-
- registerApplicationServicesForCLI(applicationEnvironment)
- registerApplicationServices(applicationEnvironment)
-
- return applicationEnvironment
- }
-
- private fun registerApplicationExtensionPointsAndExtensionsFrom(configuration: CompilerConfiguration, configFilePath: String) {
- fun File.hasConfigFile(configFile: String): Boolean =
- if (isDirectory) File(this, "META-INF" + File.separator + configFile).exists()
- else try {
- ZipFile(this).use {
- it.getEntry("META-INF/$configFile") != null
- }
- } catch (e: Throwable) {
- false
- }
-
- val pluginRoot: File =
- configuration.get(CLIConfigurationKeys.INTELLIJ_PLUGIN_ROOT)?.let(::File)
- ?: PathUtil.getResourcePathForClass(this::class.java).takeIf { it.hasConfigFile(configFilePath) }
- // hack for load extensions when compiler run directly from project directory (e.g. in tests)
- ?: File("compiler/cli/cli-common/resources").takeIf { it.hasConfigFile(configFilePath) }
- ?: throw IllegalStateException(
- "Unable to find extension point configuration $configFilePath " +
- "(cp:\n ${(Thread.currentThread().contextClassLoader as? UrlClassLoader)?.urls?.joinToString("\n ") { it.file }})"
- )
-
- CoreApplicationEnvironment.registerExtensionPointAndExtensions(
- FileSystems.getDefault().getPath(pluginRoot.path),
- configFilePath,
- Extensions.getRootArea()
- )
- }
-
- @JvmStatic
- @Suppress("MemberVisibilityCanPrivate") // made public for CLI Android Lint
- fun registerPluginExtensionPoints(project: MockProject) {
- ExpressionCodegenExtension.registerExtensionPoint(project)
- SyntheticResolveExtension.registerExtensionPoint(project)
- ClassBuilderInterceptorExtension.registerExtensionPoint(project)
- AnalysisHandlerExtension.registerExtensionPoint(project)
- PackageFragmentProviderExtension.registerExtensionPoint(project)
- StorageComponentContainerContributor.registerExtensionPoint(project)
- DeclarationAttributeAltererExtension.registerExtensionPoint(project)
- PreprocessedVirtualFileFactoryExtension.registerExtensionPoint(project)
- JsSyntheticTranslateExtension.registerExtensionPoint(project)
- CompilerConfigurationExtension.registerExtensionPoint(project)
- CollectAdditionalSourcesExtension.registerExtensionPoint(project)
- ExtraImportsProviderExtension.registerExtensionPoint(project)
- IrGenerationExtension.registerExtensionPoint(project)
- ScriptEvaluationExtension.registerExtensionPoint(project)
- ShellExtension.registerExtensionPoint(project)
- TypeResolutionInterceptor.registerExtensionPoint(project)
- CandidateInterceptor.registerExtensionPoint(project)
- DescriptorSerializerPlugin.registerExtensionPoint(project)
- }
-
- internal fun registerExtensionsFromPlugins(project: MockProject, configuration: CompilerConfiguration) {
- val messageCollector = configuration.get(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY)
- for (registrar in configuration.getList(ComponentRegistrar.PLUGIN_COMPONENT_REGISTRARS)) {
- try {
- registrar.registerProjectComponents(project, configuration)
- } catch (e: AbstractMethodError) {
- val message = "The provided plugin ${registrar.javaClass.name} is not compatible with this version of compiler"
- // Since the scripting plugin is often discovered in the compiler environment, it is often taken from the incompatible
- // location, and in many cases this is not a fatal error, therefore strong warning is generated instead of exception
- if (registrar.javaClass.simpleName == "ScriptingCompilerConfigurationComponentRegistrar") {
- messageCollector?.report(STRONG_WARNING, "Default scripting plugin is disabled: $message")
- } else {
- throw IllegalStateException(message, e)
- }
- }
- }
- }
-
-
- private fun registerApplicationServicesForCLI(applicationEnvironment: KotlinCoreApplicationEnvironment) {
- // ability to get text from annotations xml files
- applicationEnvironment.registerFileType(PlainTextFileType.INSTANCE, "xml")
- applicationEnvironment.registerParserDefinition(JavaParserDefinition())
- }
-
- // made public for Upsource
- @Suppress("MemberVisibilityCanBePrivate")
- @JvmStatic
- fun registerApplicationServices(applicationEnvironment: KotlinCoreApplicationEnvironment) {
- with(applicationEnvironment) {
- registerFileType(KotlinFileType.INSTANCE, "kt")
- registerFileType(KotlinFileType.INSTANCE, KotlinParserDefinition.STD_SCRIPT_SUFFIX)
- registerParserDefinition(KotlinParserDefinition())
- application.registerService(KotlinBinaryClassCache::class.java, KotlinBinaryClassCache())
- application.registerService(JavaClassSupers::class.java, JavaClassSupersImpl::class.java)
- application.registerService(TransactionGuard::class.java, TransactionGuardImpl::class.java)
- }
- }
-
- @JvmStatic
- fun registerProjectExtensionPoints(area: ExtensionsArea) {
- CoreApplicationEnvironment.registerExtensionPoint(
- area, PsiTreeChangePreprocessor.EP.name, PsiTreeChangePreprocessor::class.java
- )
- CoreApplicationEnvironment.registerExtensionPoint(area, PsiElementFinder.EP.name, PsiElementFinder::class.java)
-
- IdeaExtensionPoints.registerVersionSpecificProjectExtensionPoints(area)
- }
-
- // made public for Upsource
- @JvmStatic
- @Deprecated("Use registerProjectServices(project) instead.", ReplaceWith("registerProjectServices(projectEnvironment.project)"))
- fun registerProjectServices(
- projectEnvironment: JavaCoreProjectEnvironment,
- @Suppress("UNUSED_PARAMETER") messageCollector: MessageCollector?
- ) {
- registerProjectServices(projectEnvironment.project)
- }
-
- // made public for Android Lint
- @JvmStatic
- fun registerProjectServices(project: MockProject) {
- with(project) {
- registerService(KotlinJavaPsiFacade::class.java, KotlinJavaPsiFacade(this))
- registerService(FacadeCache::class.java, FacadeCache(this))
- registerService(ModuleAnnotationsResolver::class.java, CliModuleAnnotationsResolver())
- }
- }
-
- private fun registerProjectServicesForCLI(@Suppress("UNUSED_PARAMETER") projectEnvironment: JavaCoreProjectEnvironment) {
- /**
- * Note that Kapt may restart code analysis process, and CLI services should be aware of that.
- * Use PsiManager.getModificationTracker() to ensure that all the data you cached is still valid.
- */
- }
-
- // made public for Android Lint
- @JvmStatic
- fun registerKotlinLightClassSupport(project: MockProject) {
- with(project) {
- val traceHolder = CliTraceHolder()
- val cliLightClassGenerationSupport = CliLightClassGenerationSupport(traceHolder, project)
- val kotlinAsJavaSupport = CliKotlinAsJavaSupport(this, traceHolder)
- registerService(LightClassGenerationSupport::class.java, cliLightClassGenerationSupport)
- registerService(CliLightClassGenerationSupport::class.java, cliLightClassGenerationSupport)
- registerService(KotlinAsJavaSupport::class.java, kotlinAsJavaSupport)
- registerService(CodeAnalyzerInitializer::class.java, traceHolder)
-
- // We don't pass Disposable because in some tests, we manually unregister these extensions, and that leads to LOG.error
- // exception from `ExtensionPointImpl.doRegisterExtension`, because the registered extension can no longer be found
- // when the project is being disposed.
- // For example, see the `unregisterExtension` call in `GenerationUtils.compileFilesUsingFrontendIR`.
- // TODO: refactor this to avoid registering unneeded extensions in the first place, and avoid using deprecated API.
- @Suppress("DEPRECATION")
- PsiElementFinder.EP.getPoint(project).registerExtension(JavaElementFinder(this, kotlinAsJavaSupport))
- @Suppress("DEPRECATION")
- PsiElementFinder.EP.getPoint(project).registerExtension(PsiElementFinderImpl(this))
- }
- }
-
- private fun CompilerConfiguration.setupJdkClasspathRoots(configFiles: EnvironmentConfigFiles) {
- if (getBoolean(JVMConfigurationKeys.NO_JDK)) return
-
- val jvmTarget = configFiles == EnvironmentConfigFiles.JVM_CONFIG_FILES
- if (!jvmTarget) return
-
- val jdkHome = get(JVMConfigurationKeys.JDK_HOME)
- val (javaRoot, classesRoots) = if (jdkHome == null) {
- val javaHome = File(System.getProperty("java.home"))
- put(JVMConfigurationKeys.JDK_HOME, javaHome)
-
- javaHome to PathUtil.getJdkClassesRootsFromCurrentJre()
- } else {
- jdkHome to PathUtil.getJdkClassesRoots(jdkHome)
- }
-
- if (!CoreJrtFileSystem.isModularJdk(javaRoot)) {
- if (classesRoots.isEmpty()) {
- report(ERROR, "No class roots are found in the JDK path: $javaRoot")
- } else {
- addJvmSdkRoots(classesRoots)
- }
- }
- }
- }
-}
diff --git a/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/KotlinToJVMBytecodeCompiler.kt b/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/KotlinToJVMBytecodeCompiler.kt
index 55339968a7a..6087fdd8f86 100644
--- a/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/KotlinToJVMBytecodeCompiler.kt
+++ b/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/compiler/KotlinToJVMBytecodeCompiler.kt
@@ -52,10 +52,10 @@ import org.jetbrains.kotlin.codegen.state.GenerationStateEventCallback
import org.jetbrains.kotlin.config.*
import org.jetbrains.kotlin.container.get
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
-import org.jetbrains.kotlin.diagnostics.*
+import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.fir.analysis.FirAnalyzerFacade
import org.jetbrains.kotlin.fir.backend.jvm.FirJvmBackendClassResolver
-import org.jetbrains.kotlin.fir.backend.jvm.FirMetadataSerializer
+import org.jetbrains.kotlin.fir.backend.jvm.FirJvmBackendExtension
import org.jetbrains.kotlin.fir.checkers.registerExtendedCommonCheckers
import org.jetbrains.kotlin.fir.java.FirProjectSessionProvider
import org.jetbrains.kotlin.fir.session.FirJvmModuleInfo
@@ -389,10 +389,8 @@ object KotlinToJVMBytecodeCompiler {
performanceManager?.notifyIRGenerationStarted()
generationState.beforeCompile()
codegenFactory.generateModuleInFrontendIRMode(
- generationState, moduleFragment, symbolTable, sourceManager, extensions
- ) { context, irClass, _, serializationBindings, parent ->
- FirMetadataSerializer(session, context, irClass, serializationBindings, components, parent)
- }
+ generationState, moduleFragment, symbolTable, sourceManager, extensions, FirJvmBackendExtension(session, components)
+ )
CodegenFactory.doCheckCancelled(generationState)
generationState.factory.done()
@@ -572,8 +570,6 @@ object KotlinToJVMBytecodeCompiler {
sourceFiles: List,
module: Module?
): GenerationState {
- val isIR = (configuration.getBoolean(JVMConfigurationKeys.IR) ||
- configuration.getBoolean(CommonConfigurationKeys.USE_FIR))
val generationState = GenerationState.Builder(
environment.project,
ClassBuilderFactories.BINARIES,
@@ -583,13 +579,12 @@ object KotlinToJVMBytecodeCompiler {
configuration
)
.codegenFactory(
- if (isIR) JvmIrCodegenFactory(
+ if (configuration.getBoolean(JVMConfigurationKeys.IR)) JvmIrCodegenFactory(
configuration.get(CLIConfigurationKeys.PHASE_CONFIG) ?: PhaseConfig(jvmPhases)
) else DefaultCodegenFactory
)
.withModule(module)
.onIndependentPartCompilationEnd(createOutputFilesFlushingCallbackIfPossible(configuration))
- .isIrBackend(isIR)
.build()
ProgressIndicatorAndCompilationCanceledStatus.checkCanceled()
diff --git a/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/jvmArguments.kt b/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/jvmArguments.kt
index 709ba73a6b3..cbb8f6d9f58 100644
--- a/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/jvmArguments.kt
+++ b/compiler/cli/src/org/jetbrains/kotlin/cli/jvm/jvmArguments.kt
@@ -9,6 +9,7 @@ import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.cli.common.getLibraryFromHome
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.*
+import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.jetbrains.kotlin.cli.jvm.config.JvmClasspathRoot
import org.jetbrains.kotlin.cli.jvm.config.JvmModulePathRoot
@@ -19,9 +20,6 @@ import org.jetbrains.kotlin.utils.PathUtil
import java.io.File
fun CompilerConfiguration.setupJvmSpecificArguments(arguments: K2JVMCompilerArguments) {
-
- val messageCollector = getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY)
-
put(JVMConfigurationKeys.INCLUDE_RUNTIME, arguments.includeRuntime)
putIfNotNull(JVMConfigurationKeys.FRIEND_PATHS, arguments.friendPaths?.asList())
@@ -71,9 +69,6 @@ fun CompilerConfiguration.setupJvmSpecificArguments(arguments: K2JVMCompilerArgu
}
fun CompilerConfiguration.configureJdkHome(arguments: K2JVMCompilerArguments): Boolean {
-
- val messageCollector = getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY)
-
if (arguments.noJdk) {
put(JVMConfigurationKeys.NO_JDK, true)
@@ -84,7 +79,7 @@ fun CompilerConfiguration.configureJdkHome(arguments: K2JVMCompilerArguments): B
}
if (arguments.jdkHome != null) {
- val jdkHome = File(arguments.jdkHome)
+ val jdkHome = File(arguments.jdkHome!!)
if (!jdkHome.exists()) {
messageCollector.report(ERROR, "JDK home directory does not exist: $jdkHome")
return false
@@ -114,7 +109,6 @@ fun CompilerConfiguration.configureExplicitContentRoots(arguments: K2JVMCompiler
}
fun CompilerConfiguration.configureStandardLibs(paths: KotlinPaths?, arguments: K2JVMCompilerArguments) {
- val messageCollector = getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY)
val isModularJava = isModularJava()
fun addRoot(moduleName: String, libraryName: String, getLibrary: (KotlinPaths) -> File, noLibraryArgument: String) {
@@ -171,8 +165,23 @@ fun CompilerConfiguration.configureAdvancedJvmOptions(arguments: K2JVMCompilerAr
put(JVMConfigurationKeys.PARAMETERS_METADATA, arguments.javaParameters)
- put(JVMConfigurationKeys.IR, arguments.useIR && !arguments.noUseIR)
- put(JVMConfigurationKeys.IS_IR_WITH_STABLE_ABI, arguments.isIrWithStableAbi)
+ val useIR = (arguments.useIR && !arguments.noUseIR) || arguments.useFir
+ put(JVMConfigurationKeys.IR, useIR)
+
+ val abiStability = JvmAbiStability.fromStringOrNull(arguments.abiStability)
+ if (arguments.abiStability != null) {
+ if (abiStability == null) {
+ messageCollector.report(
+ ERROR,
+ "Unknown ABI stability mode: ${arguments.abiStability}, supported modes: ${JvmAbiStability.values().map { it.description }}"
+ )
+ } else if (!useIR && abiStability == JvmAbiStability.UNSTABLE) {
+ messageCollector.report(ERROR, "-Xabi-stability=unstable is not supported in the old JVM backend")
+ } else {
+ put(JVMConfigurationKeys.ABI_STABILITY, abiStability)
+ }
+ }
+
put(JVMConfigurationKeys.DO_NOT_CLEAR_BINDING_CONTEXT, arguments.doNotClearBindingContext)
put(JVMConfigurationKeys.DISABLE_CALL_ASSERTIONS, arguments.noCallAssertions)
put(JVMConfigurationKeys.DISABLE_RECEIVER_ASSERTIONS, arguments.noReceiverAssertions)
@@ -189,43 +198,34 @@ fun CompilerConfiguration.configureAdvancedJvmOptions(arguments: K2JVMCompilerAr
put(JVMConfigurationKeys.NO_UNIFIED_NULL_CHECKS, arguments.noUnifiedNullChecks)
if (!JVMConstructorCallNormalizationMode.isSupportedValue(arguments.constructorCallNormalizationMode)) {
- getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY).report(
+ messageCollector.report(
ERROR,
"Unknown constructor call normalization mode: ${arguments.constructorCallNormalizationMode}, " +
"supported modes: ${JVMConstructorCallNormalizationMode.values().map { it.description }}"
)
}
- val constructorCallNormalizationMode =
- JVMConstructorCallNormalizationMode.fromStringOrNull(arguments.constructorCallNormalizationMode)
+ val constructorCallNormalizationMode = JVMConstructorCallNormalizationMode.fromStringOrNull(arguments.constructorCallNormalizationMode)
if (constructorCallNormalizationMode != null) {
- put(
- JVMConfigurationKeys.CONSTRUCTOR_CALL_NORMALIZATION_MODE,
- constructorCallNormalizationMode
- )
+ put(JVMConfigurationKeys.CONSTRUCTOR_CALL_NORMALIZATION_MODE, constructorCallNormalizationMode)
}
val assertionsMode =
JVMAssertionsMode.fromStringOrNull(arguments.assertionsMode)
if (assertionsMode == null) {
- getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY).report(
+ messageCollector.report(
ERROR,
- "Unknown assertions mode: ${arguments.assertionsMode}, " +
- "supported modes: ${JVMAssertionsMode.values().map { it.description }}"
+ "Unknown assertions mode: ${arguments.assertionsMode}, supported modes: ${JVMAssertionsMode.values().map { it.description }}"
)
}
- put(
- JVMConfigurationKeys.ASSERTIONS_MODE,
- assertionsMode ?: JVMAssertionsMode.DEFAULT
- )
+ put(JVMConfigurationKeys.ASSERTIONS_MODE, assertionsMode ?: JVMAssertionsMode.DEFAULT)
put(JVMConfigurationKeys.USE_TYPE_TABLE, arguments.useTypeTable)
put(JVMConfigurationKeys.SKIP_RUNTIME_VERSION_CHECK, arguments.skipRuntimeVersionCheck)
put(JVMConfigurationKeys.USE_PSI_CLASS_FILES_READING, arguments.useOldClassFilesReading)
if (arguments.useOldClassFilesReading) {
- getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY)
- .report(INFO, "Using the old java class files reading implementation")
+ messageCollector.report(INFO, "Using the old java class files reading implementation")
}
put(CLIConfigurationKeys.ALLOW_KOTLIN_PACKAGE, arguments.allowKotlinPackage)
@@ -235,8 +235,7 @@ fun CompilerConfiguration.configureAdvancedJvmOptions(arguments: K2JVMCompilerAr
put(JVMConfigurationKeys.ENABLE_JVM_PREVIEW, arguments.enableJvmPreview)
if (arguments.enableJvmPreview) {
- getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY)
- .report(INFO, "Using preview Java language features")
+ messageCollector.report(INFO, "Using preview Java language features")
}
arguments.declarationsOutputPath?.let { put(JVMConfigurationKeys.DECLARATIONS_JSON_PATH, it) }
@@ -249,3 +248,6 @@ fun CompilerConfiguration.configureKlibPaths(arguments: K2JVMCompilerArguments)
?.filterNot { it.isEmpty() }
?.let { put(JVMConfigurationKeys.KLIB_PATHS, it) }
}
+
+private val CompilerConfiguration.messageCollector: MessageCollector
+ get() = getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY)
diff --git a/compiler/config.jvm/src/org/jetbrains/kotlin/config/JVMConfigurationKeys.java b/compiler/config.jvm/src/org/jetbrains/kotlin/config/JVMConfigurationKeys.java
index de4c0f9e015..b8e6870b0a6 100644
--- a/compiler/config.jvm/src/org/jetbrains/kotlin/config/JVMConfigurationKeys.java
+++ b/compiler/config.jvm/src/org/jetbrains/kotlin/config/JVMConfigurationKeys.java
@@ -117,8 +117,8 @@ public class JVMConfigurationKeys {
public static final CompilerConfigurationKey> KLIB_PATHS =
CompilerConfigurationKey.create("Paths to .klib libraries");
- public static final CompilerConfigurationKey IS_IR_WITH_STABLE_ABI =
- CompilerConfigurationKey.create("Is IR with stable ABI");
+ public static final CompilerConfigurationKey ABI_STABILITY =
+ CompilerConfigurationKey.create("ABI stability of class files produced by JVM IR and/or FIR");
public static final CompilerConfigurationKey DO_NOT_CLEAR_BINDING_CONTEXT =
CompilerConfigurationKey.create("When using the IR backend, do not clear BindingContext between psi2ir and lowerings");
diff --git a/compiler/config.jvm/src/org/jetbrains/kotlin/config/JvmAbiStability.kt b/compiler/config.jvm/src/org/jetbrains/kotlin/config/JvmAbiStability.kt
new file mode 100644
index 00000000000..e40ecfae2c6
--- /dev/null
+++ b/compiler/config.jvm/src/org/jetbrains/kotlin/config/JvmAbiStability.kt
@@ -0,0 +1,17 @@
+/*
+ * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
+ * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
+ */
+
+package org.jetbrains.kotlin.config
+
+enum class JvmAbiStability(val description: String) {
+ STABLE("stable"),
+ UNSTABLE("unstable"),
+ ;
+
+ companion object {
+ fun fromStringOrNull(string: String?): JvmAbiStability? =
+ values().find { it.description == string }
+ }
+}
diff --git a/compiler/config/src/org/jetbrains/kotlin/config/AnalysisFlags.kt b/compiler/config/src/org/jetbrains/kotlin/config/AnalysisFlags.kt
index 123e5bad772..3cab8a5ff3a 100644
--- a/compiler/config/src/org/jetbrains/kotlin/config/AnalysisFlags.kt
+++ b/compiler/config/src/org/jetbrains/kotlin/config/AnalysisFlags.kt
@@ -46,7 +46,7 @@ object AnalysisFlags {
val ideMode by AnalysisFlag.Delegates.Boolean
@JvmStatic
- val reportErrorsOnIrDependencies by AnalysisFlag.Delegates.Boolean
+ val allowUnstableDependencies by AnalysisFlag.Delegates.Boolean
@JvmStatic
val libraryToSourceAnalysis by AnalysisFlag.Delegates.Boolean
diff --git a/compiler/fir/analysis-tests/build.gradle.kts b/compiler/fir/analysis-tests/build.gradle.kts
index f615e816581..bcc22c88270 100644
--- a/compiler/fir/analysis-tests/build.gradle.kts
+++ b/compiler/fir/analysis-tests/build.gradle.kts
@@ -14,21 +14,59 @@ dependencies {
compileOnly(intellijCoreDep()) { includeJars("intellij-core", "guava", rootProject = rootProject) }
testApi(intellijDep())
-
- testApi(commonDep("junit:junit"))
- testCompileOnly(project(":kotlin-test:kotlin-test-jvm"))
- testCompileOnly(project(":kotlin-test:kotlin-test-junit"))
- testApi(projectTests(":compiler:tests-common"))
+ testApi(projectTests(":compiler:test-infrastructure"))
+ testApi(projectTests(":compiler:test-infrastructure-utils"))
+ testApi(projectTests(":compiler:tests-compiler-utils"))
+ testApi(projectTests(":compiler:tests-common-new"))
+ testApi(project(":compiler:cli"))
testApi(project(":compiler:fir:checkers"))
testApi(project(":compiler:fir:entrypoint"))
testApi(project(":compiler:frontend"))
- testCompileOnly(project(":kotlin-reflect-api"))
- testRuntime(project(":kotlin-reflect"))
- testRuntime(project(":core:descriptors.runtime"))
+ testApi(platform("org.junit:junit-bom:5.7.0"))
+ testApi("org.junit.jupiter:junit-jupiter")
+ testApi("org.junit.platform:junit-platform-commons:1.7.0")
- testCompileOnly(intellijCoreDep()) { includeJars("intellij-core") }
- testRuntimeOnly(intellijCoreDep()) { includeJars("intellij-core") }
+ testCompileOnly(project(":kotlin-reflect-api"))
+ testRuntimeOnly(project(":kotlin-reflect"))
+ testRuntimeOnly(project(":core:descriptors.runtime"))
+
+ testImplementation(intellijCoreDep()) { includeJars("intellij-core") }
+ testImplementation(intellijDep()) {
+ // This dependency is needed only for FileComparisonFailure
+ includeJars("idea_rt", rootProject = rootProject)
+ isTransitive = false
+ }
+
+ // This is needed only for using FileComparisonFailure, which relies on JUnit 3 classes
+ testRuntimeOnly(commonDep("junit:junit"))
+ testRuntimeOnly(intellijDep()) {
+ includeJars(
+ "jps-model",
+ "extensions",
+ "util",
+ "platform-api",
+ "platform-impl",
+ "idea",
+ "guava",
+ "trove4j",
+ "asm-all",
+ "log4j",
+ "jdom",
+ "streamex",
+ "bootstrap",
+ "jna",
+ rootProject = rootProject
+ )
+ }
+
+ Platform[202] {
+ testRuntimeOnly(intellijDep()) { includeJars("intellij-deps-fastutil-8.3.1-1") }
+ }
+ Platform[203].orHigher {
+ testRuntimeOnly(intellijDep()) { includeJars("intellij-deps-fastutil-8.3.1-3") }
+ }
+ testRuntimeOnly(toolsJar())
}
val generationRoot = projectDir.resolve("tests-gen")
@@ -48,11 +86,13 @@ if (kotlinBuildProperties.isInJpsBuildIdeaSync) {
}
}
-projectTest(parallel = true) {
+projectTest(parallel = true, jUnit5Enabled = true) {
dependsOn(":dist")
workingDir = rootDir
jvmArgs!!.removeIf { it.contains("-Xmx") }
maxHeapSize = "3g"
+
+ useJUnitPlatform()
}
testsJar()
diff --git a/compiler/fir/analysis-tests/ReadMe.md b/compiler/fir/analysis-tests/legacy-fir-tests/ReadMe.md
similarity index 100%
rename from compiler/fir/analysis-tests/ReadMe.md
rename to compiler/fir/analysis-tests/legacy-fir-tests/ReadMe.md
diff --git a/compiler/fir/analysis-tests/legacy-fir-tests/build.gradle.kts b/compiler/fir/analysis-tests/legacy-fir-tests/build.gradle.kts
new file mode 100644
index 00000000000..b20a8328451
--- /dev/null
+++ b/compiler/fir/analysis-tests/legacy-fir-tests/build.gradle.kts
@@ -0,0 +1,58 @@
+import org.jetbrains.kotlin.ideaExt.idea
+
+/*
+ * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
+ * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
+ */
+
+plugins {
+ kotlin("jvm")
+ id("jps-compatible")
+}
+
+dependencies {
+ compileOnly(intellijCoreDep()) { includeJars("intellij-core", "guava", rootProject = rootProject) }
+
+ testApi(intellijDep())
+
+ testApi(commonDep("junit:junit"))
+ testCompileOnly(project(":kotlin-test:kotlin-test-jvm"))
+ testCompileOnly(project(":kotlin-test:kotlin-test-junit"))
+ testApi(projectTests(":compiler:tests-common"))
+ testApi(project(":compiler:fir:checkers"))
+ testApi(project(":compiler:fir:entrypoint"))
+ testApi(project(":compiler:frontend"))
+
+ testCompileOnly(project(":kotlin-reflect-api"))
+ testRuntimeOnly(project(":kotlin-reflect"))
+ testRuntimeOnly(project(":core:descriptors.runtime"))
+
+ testCompileOnly(intellijCoreDep()) { includeJars("intellij-core") }
+ testRuntimeOnly(intellijCoreDep()) { includeJars("intellij-core") }
+}
+
+val generationRoot = projectDir.resolve("tests-gen")
+
+sourceSets {
+ "main" { none() }
+ "test" {
+ projectDefault()
+ this.java.srcDir(generationRoot.name)
+ }
+}
+
+if (kotlinBuildProperties.isInJpsBuildIdeaSync) {
+ apply(plugin = "idea")
+ idea {
+ this.module.generatedSourceDirs.add(generationRoot)
+ }
+}
+
+projectTest(parallel = true) {
+ dependsOn(":dist")
+ workingDir = rootDir
+ jvmArgs!!.removeIf { it.contains("-Xmx") }
+ maxHeapSize = "3g"
+}
+
+testsJar()
diff --git a/compiler/fir/analysis-tests/tests-gen/org/jetbrains/kotlin/fir/FirLoadCompiledKotlinGenerated.java b/compiler/fir/analysis-tests/legacy-fir-tests/tests-gen/org/jetbrains/kotlin/fir/FirLoadCompiledKotlinGenerated.java
similarity index 100%
rename from compiler/fir/analysis-tests/tests-gen/org/jetbrains/kotlin/fir/FirLoadCompiledKotlinGenerated.java
rename to compiler/fir/analysis-tests/legacy-fir-tests/tests-gen/org/jetbrains/kotlin/fir/FirLoadCompiledKotlinGenerated.java
diff --git a/compiler/fir/analysis-tests/tests-gen/org/jetbrains/kotlin/fir/LazyBodyIsNotTouchedTilContractsPhaseTestGenerated.java b/compiler/fir/analysis-tests/legacy-fir-tests/tests-gen/org/jetbrains/kotlin/fir/LazyBodyIsNotTouchedTilContractsPhaseTestGenerated.java
similarity index 85%
rename from compiler/fir/analysis-tests/tests-gen/org/jetbrains/kotlin/fir/LazyBodyIsNotTouchedTilContractsPhaseTestGenerated.java
rename to compiler/fir/analysis-tests/legacy-fir-tests/tests-gen/org/jetbrains/kotlin/fir/LazyBodyIsNotTouchedTilContractsPhaseTestGenerated.java
index c2daeaee160..aecd9bc650b 100644
--- a/compiler/fir/analysis-tests/tests-gen/org/jetbrains/kotlin/fir/LazyBodyIsNotTouchedTilContractsPhaseTestGenerated.java
+++ b/compiler/fir/analysis-tests/legacy-fir-tests/tests-gen/org/jetbrains/kotlin/fir/LazyBodyIsNotTouchedTilContractsPhaseTestGenerated.java
@@ -1685,6 +1685,419 @@ public class LazyBodyIsNotTouchedTilContractsPhaseTestGenerated extends Abstract
}
}
+ @TestMetadata("compiler/fir/analysis-tests/testData/resolve/extendedCheckers")
+ @TestDataPath("$PROJECT_ROOT")
+ @RunWith(JUnit3RunnerWithInners.class)
+ public static class ExtendedCheckers extends AbstractLazyBodyIsNotTouchedTilContractsPhaseTest {
+ private void runTest(String testDataFilePath) throws Exception {
+ KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
+ }
+
+ public void testAllFilesPresentInExtendedCheckers() throws Exception {
+ KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/resolve/extendedCheckers"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
+ }
+
+ @TestMetadata("ArrayEqualityCanBeReplacedWithEquals.kt")
+ public void testArrayEqualityCanBeReplacedWithEquals() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/ArrayEqualityCanBeReplacedWithEquals.kt");
+ }
+
+ @TestMetadata("CanBeValChecker.kt")
+ public void testCanBeValChecker() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/CanBeValChecker.kt");
+ }
+
+ @TestMetadata("RedundantExplicitTypeChecker.kt")
+ public void testRedundantExplicitTypeChecker() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantExplicitTypeChecker.kt");
+ }
+
+ @TestMetadata("RedundantModalityModifierChecker.kt")
+ public void testRedundantModalityModifierChecker() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantModalityModifierChecker.kt");
+ }
+
+ @TestMetadata("RedundantReturnUnitTypeChecker.kt")
+ public void testRedundantReturnUnitTypeChecker() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantReturnUnitTypeChecker.kt");
+ }
+
+ @TestMetadata("RedundantSetterParameterTypeChecker.kt")
+ public void testRedundantSetterParameterTypeChecker() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantSetterParameterTypeChecker.kt");
+ }
+
+ @TestMetadata("RedundantSingleExpressionStringTemplateChecker.kt")
+ public void testRedundantSingleExpressionStringTemplateChecker() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantSingleExpressionStringTemplateChecker.kt");
+ }
+
+ @TestMetadata("RedundantVisibilityModifierChecker.kt")
+ public void testRedundantVisibilityModifierChecker() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantVisibilityModifierChecker.kt");
+ }
+
+ @TestMetadata("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment")
+ @TestDataPath("$PROJECT_ROOT")
+ @RunWith(JUnit3RunnerWithInners.class)
+ public static class CanBeReplacedWithOperatorAssignment extends AbstractLazyBodyIsNotTouchedTilContractsPhaseTest {
+ private void runTest(String testDataFilePath) throws Exception {
+ KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
+ }
+
+ public void testAllFilesPresentInCanBeReplacedWithOperatorAssignment() throws Exception {
+ KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
+ }
+
+ @TestMetadata("BasicTest.kt")
+ public void testBasicTest() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/BasicTest.kt");
+ }
+
+ @TestMetadata("ComplexExpression.kt")
+ public void testComplexExpression() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/ComplexExpression.kt");
+ }
+
+ @TestMetadata("flexibleTypeBug.kt")
+ public void testFlexibleTypeBug() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/flexibleTypeBug.kt");
+ }
+
+ @TestMetadata("illegalMultipleOperators.kt")
+ public void testIllegalMultipleOperators() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/illegalMultipleOperators.kt");
+ }
+
+ @TestMetadata("illegalMultipleOperatorsMiddle.kt")
+ public void testIllegalMultipleOperatorsMiddle() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/illegalMultipleOperatorsMiddle.kt");
+ }
+
+ @TestMetadata("invalidSubtraction.kt")
+ public void testInvalidSubtraction() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/invalidSubtraction.kt");
+ }
+
+ @TestMetadata("list.kt")
+ public void testList() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/list.kt");
+ }
+
+ @TestMetadata("logicOperators.kt")
+ public void testLogicOperators() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/logicOperators.kt");
+ }
+
+ @TestMetadata("multipleOperators.kt")
+ public void testMultipleOperators() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperators.kt");
+ }
+
+ @TestMetadata("multipleOperatorsRightSideRepeat.kt")
+ public void testMultipleOperatorsRightSideRepeat() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperatorsRightSideRepeat.kt");
+ }
+
+ @TestMetadata("mutableList.kt")
+ public void testMutableList() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/mutableList.kt");
+ }
+
+ @TestMetadata("nonCommutativeRepeat.kt")
+ public void testNonCommutativeRepeat() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/nonCommutativeRepeat.kt");
+ }
+
+ @TestMetadata("nonRepeatingAssignment.kt")
+ public void testNonRepeatingAssignment() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/nonRepeatingAssignment.kt");
+ }
+
+ @TestMetadata("OperatorAssignment.kt")
+ public void testOperatorAssignment() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/OperatorAssignment.kt");
+ }
+
+ @TestMetadata("plusAssignConflict.kt")
+ public void testPlusAssignConflict() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/plusAssignConflict.kt");
+ }
+
+ @TestMetadata("rightSideRepeat.kt")
+ public void testRightSideRepeat() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/rightSideRepeat.kt");
+ }
+
+ @TestMetadata("simpleAssign.kt")
+ public void testSimpleAssign() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/simpleAssign.kt");
+ }
+
+ @TestMetadata("validAddition.kt")
+ public void testValidAddition() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/validAddition.kt");
+ }
+
+ @TestMetadata("validSubtraction.kt")
+ public void testValidSubtraction() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/validSubtraction.kt");
+ }
+ }
+
+ @TestMetadata("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/emptyRangeChecker")
+ @TestDataPath("$PROJECT_ROOT")
+ @RunWith(JUnit3RunnerWithInners.class)
+ public static class EmptyRangeChecker extends AbstractLazyBodyIsNotTouchedTilContractsPhaseTest {
+ private void runTest(String testDataFilePath) throws Exception {
+ KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
+ }
+
+ public void testAllFilesPresentInEmptyRangeChecker() throws Exception {
+ KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/emptyRangeChecker"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
+ }
+
+ @TestMetadata("NoWarning.kt")
+ public void testNoWarning() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/emptyRangeChecker/NoWarning.kt");
+ }
+
+ @TestMetadata("Warning.kt")
+ public void testWarning() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/emptyRangeChecker/Warning.kt");
+ }
+ }
+
+ @TestMetadata("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod")
+ @TestDataPath("$PROJECT_ROOT")
+ @RunWith(JUnit3RunnerWithInners.class)
+ public static class RedundantCallOfConversionMethod extends AbstractLazyBodyIsNotTouchedTilContractsPhaseTest {
+ private void runTest(String testDataFilePath) throws Exception {
+ KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
+ }
+
+ public void testAllFilesPresentInRedundantCallOfConversionMethod() throws Exception {
+ KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
+ }
+
+ @TestMetadata("booleanToInt.kt")
+ public void testBooleanToInt() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/booleanToInt.kt");
+ }
+
+ @TestMetadata("byte.kt")
+ public void testByte() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/byte.kt");
+ }
+
+ @TestMetadata("char.kt")
+ public void testChar() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/char.kt");
+ }
+
+ @TestMetadata("double.kt")
+ public void testDouble() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/double.kt");
+ }
+
+ @TestMetadata("float.kt")
+ public void testFloat() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/float.kt");
+ }
+
+ @TestMetadata("int.kt")
+ public void testInt() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/int.kt");
+ }
+
+ @TestMetadata("long.kt")
+ public void testLong() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/long.kt");
+ }
+
+ @TestMetadata("nullable.kt")
+ public void testNullable() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/nullable.kt");
+ }
+
+ @TestMetadata("nullable2.kt")
+ public void testNullable2() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/nullable2.kt");
+ }
+
+ @TestMetadata("safeString.kt")
+ public void testSafeString() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/safeString.kt");
+ }
+
+ @TestMetadata("safeString2.kt")
+ public void testSafeString2() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/safeString2.kt");
+ }
+
+ @TestMetadata("short.kt")
+ public void testShort() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/short.kt");
+ }
+
+ @TestMetadata("string.kt")
+ public void testString() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/string.kt");
+ }
+
+ @TestMetadata("StringTemplate.kt")
+ public void testStringTemplate() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/StringTemplate.kt");
+ }
+
+ @TestMetadata("toOtherType.kt")
+ public void testToOtherType() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/toOtherType.kt");
+ }
+
+ @TestMetadata("uByte.kt")
+ public void testUByte() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uByte.kt");
+ }
+
+ @TestMetadata("uInt.kt")
+ public void testUInt() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uInt.kt");
+ }
+
+ @TestMetadata("uLong.kt")
+ public void testULong() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uLong.kt");
+ }
+
+ @TestMetadata("uShort.kt")
+ public void testUShort() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uShort.kt");
+ }
+
+ @TestMetadata("variable.kt")
+ public void testVariable() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/variable.kt");
+ }
+ }
+
+ @TestMetadata("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused")
+ @TestDataPath("$PROJECT_ROOT")
+ @RunWith(JUnit3RunnerWithInners.class)
+ public static class Unused extends AbstractLazyBodyIsNotTouchedTilContractsPhaseTest {
+ private void runTest(String testDataFilePath) throws Exception {
+ KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
+ }
+
+ public void testAllFilesPresentInUnused() throws Exception {
+ KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
+ }
+
+ @TestMetadata("classProperty.kt")
+ public void testClassProperty() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/classProperty.kt");
+ }
+
+ @TestMetadata("invoke.kt")
+ public void testInvoke() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/invoke.kt");
+ }
+
+ @TestMetadata("lambda.kt")
+ public void testLambda() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/lambda.kt");
+ }
+
+ @TestMetadata("localVariable.kt")
+ public void testLocalVariable() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/localVariable.kt");
+ }
+
+ @TestMetadata("manyLocalVariables.kt")
+ public void testManyLocalVariables() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/manyLocalVariables.kt");
+ }
+
+ @TestMetadata("usedInAnnotationArguments.kt")
+ public void testUsedInAnnotationArguments() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/usedInAnnotationArguments.kt");
+ }
+
+ @TestMetadata("valueIsNeverRead.kt")
+ public void testValueIsNeverRead() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/valueIsNeverRead.kt");
+ }
+ }
+
+ @TestMetadata("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker")
+ @TestDataPath("$PROJECT_ROOT")
+ @RunWith(JUnit3RunnerWithInners.class)
+ public static class UselessCallOnNotNullChecker extends AbstractLazyBodyIsNotTouchedTilContractsPhaseTest {
+ private void runTest(String testDataFilePath) throws Exception {
+ KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
+ }
+
+ public void testAllFilesPresentInUselessCallOnNotNullChecker() throws Exception {
+ KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
+ }
+
+ @TestMetadata("Basic.kt")
+ public void testBasic() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/Basic.kt");
+ }
+
+ @TestMetadata("NotNullType.kt")
+ public void testNotNullType() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NotNullType.kt");
+ }
+
+ @TestMetadata("NotNullTypeChain.kt")
+ public void testNotNullTypeChain() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NotNullTypeChain.kt");
+ }
+
+ @TestMetadata("NullOrBlankSafe.kt")
+ public void testNullOrBlankSafe() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrBlankSafe.kt");
+ }
+
+ @TestMetadata("NullOrEmpty.kt")
+ public void testNullOrEmpty() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmpty.kt");
+ }
+
+ @TestMetadata("NullOrEmptyFake.kt")
+ public void testNullOrEmptyFake() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmptyFake.kt");
+ }
+
+ @TestMetadata("NullOrEmptySafe.kt")
+ public void testNullOrEmptySafe() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmptySafe.kt");
+ }
+
+ @TestMetadata("OrEmptyFake.kt")
+ public void testOrEmptyFake() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/OrEmptyFake.kt");
+ }
+
+ @TestMetadata("SafeCall.kt")
+ public void testSafeCall() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/SafeCall.kt");
+ }
+
+ @TestMetadata("Sequence.kt")
+ public void testSequence() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/Sequence.kt");
+ }
+
+ @TestMetadata("String.kt")
+ public void testString() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/String.kt");
+ }
+ }
+ }
+
@TestMetadata("compiler/fir/analysis-tests/testData/resolve/fromBuilder")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
diff --git a/compiler/fir/analysis-tests/tests-gen/org/jetbrains/kotlin/fir/java/FirOldFrontendLightClassesTestGenerated.java b/compiler/fir/analysis-tests/legacy-fir-tests/tests-gen/org/jetbrains/kotlin/fir/java/FirOldFrontendLightClassesTestGenerated.java
similarity index 100%
rename from compiler/fir/analysis-tests/tests-gen/org/jetbrains/kotlin/fir/java/FirOldFrontendLightClassesTestGenerated.java
rename to compiler/fir/analysis-tests/legacy-fir-tests/tests-gen/org/jetbrains/kotlin/fir/java/FirOldFrontendLightClassesTestGenerated.java
diff --git a/compiler/fir/analysis-tests/tests-gen/org/jetbrains/kotlin/fir/java/FirTypeEnhancementTestGenerated.java b/compiler/fir/analysis-tests/legacy-fir-tests/tests-gen/org/jetbrains/kotlin/fir/java/FirTypeEnhancementTestGenerated.java
similarity index 100%
rename from compiler/fir/analysis-tests/tests-gen/org/jetbrains/kotlin/fir/java/FirTypeEnhancementTestGenerated.java
rename to compiler/fir/analysis-tests/legacy-fir-tests/tests-gen/org/jetbrains/kotlin/fir/java/FirTypeEnhancementTestGenerated.java
diff --git a/compiler/fir/analysis-tests/tests-gen/org/jetbrains/kotlin/fir/java/OwnFirTypeEnhancementTestGenerated.java b/compiler/fir/analysis-tests/legacy-fir-tests/tests-gen/org/jetbrains/kotlin/fir/java/OwnFirTypeEnhancementTestGenerated.java
similarity index 100%
rename from compiler/fir/analysis-tests/tests-gen/org/jetbrains/kotlin/fir/java/OwnFirTypeEnhancementTestGenerated.java
rename to compiler/fir/analysis-tests/legacy-fir-tests/tests-gen/org/jetbrains/kotlin/fir/java/OwnFirTypeEnhancementTestGenerated.java
diff --git a/compiler/fir/analysis-tests/tests/org/jetbrains/kotlin/fir/AbstractFirLoadBinariesTest.kt b/compiler/fir/analysis-tests/legacy-fir-tests/tests/org/jetbrains/kotlin/fir/AbstractFirLoadBinariesTest.kt
similarity index 100%
rename from compiler/fir/analysis-tests/tests/org/jetbrains/kotlin/fir/AbstractFirLoadBinariesTest.kt
rename to compiler/fir/analysis-tests/legacy-fir-tests/tests/org/jetbrains/kotlin/fir/AbstractFirLoadBinariesTest.kt
diff --git a/compiler/fir/analysis-tests/tests/org/jetbrains/kotlin/fir/AbstractFirLoadCompiledKotlin.kt b/compiler/fir/analysis-tests/legacy-fir-tests/tests/org/jetbrains/kotlin/fir/AbstractFirLoadCompiledKotlin.kt
similarity index 100%
rename from compiler/fir/analysis-tests/tests/org/jetbrains/kotlin/fir/AbstractFirLoadCompiledKotlin.kt
rename to compiler/fir/analysis-tests/legacy-fir-tests/tests/org/jetbrains/kotlin/fir/AbstractFirLoadCompiledKotlin.kt
diff --git a/compiler/fir/analysis-tests/tests/org/jetbrains/kotlin/fir/AbstractFirResolveWithSessionTestCase.kt b/compiler/fir/analysis-tests/legacy-fir-tests/tests/org/jetbrains/kotlin/fir/AbstractFirResolveWithSessionTestCase.kt
similarity index 100%
rename from compiler/fir/analysis-tests/tests/org/jetbrains/kotlin/fir/AbstractFirResolveWithSessionTestCase.kt
rename to compiler/fir/analysis-tests/legacy-fir-tests/tests/org/jetbrains/kotlin/fir/AbstractFirResolveWithSessionTestCase.kt
diff --git a/compiler/fir/analysis-tests/tests/org/jetbrains/kotlin/fir/BuiltInsDeserializationForFirTestCase.kt b/compiler/fir/analysis-tests/legacy-fir-tests/tests/org/jetbrains/kotlin/fir/BuiltInsDeserializationForFirTestCase.kt
similarity index 100%
rename from compiler/fir/analysis-tests/tests/org/jetbrains/kotlin/fir/BuiltInsDeserializationForFirTestCase.kt
rename to compiler/fir/analysis-tests/legacy-fir-tests/tests/org/jetbrains/kotlin/fir/BuiltInsDeserializationForFirTestCase.kt
diff --git a/compiler/fir/analysis-tests/tests/org/jetbrains/kotlin/fir/java/AbstractFirOldFrontendLightClassesTest.kt b/compiler/fir/analysis-tests/legacy-fir-tests/tests/org/jetbrains/kotlin/fir/java/AbstractFirOldFrontendLightClassesTest.kt
similarity index 100%
rename from compiler/fir/analysis-tests/tests/org/jetbrains/kotlin/fir/java/AbstractFirOldFrontendLightClassesTest.kt
rename to compiler/fir/analysis-tests/legacy-fir-tests/tests/org/jetbrains/kotlin/fir/java/AbstractFirOldFrontendLightClassesTest.kt
diff --git a/compiler/fir/analysis-tests/tests/org/jetbrains/kotlin/fir/java/AbstractFirTypeEnhancementTest.kt b/compiler/fir/analysis-tests/legacy-fir-tests/tests/org/jetbrains/kotlin/fir/java/AbstractFirTypeEnhancementTest.kt
similarity index 98%
rename from compiler/fir/analysis-tests/tests/org/jetbrains/kotlin/fir/java/AbstractFirTypeEnhancementTest.kt
rename to compiler/fir/analysis-tests/legacy-fir-tests/tests/org/jetbrains/kotlin/fir/java/AbstractFirTypeEnhancementTest.kt
index 5b9505f687d..26f76d172a2 100644
--- a/compiler/fir/analysis-tests/tests/org/jetbrains/kotlin/fir/java/AbstractFirTypeEnhancementTest.kt
+++ b/compiler/fir/analysis-tests/legacy-fir-tests/tests/org/jetbrains/kotlin/fir/java/AbstractFirTypeEnhancementTest.kt
@@ -61,7 +61,7 @@ abstract class AbstractFirTypeEnhancementTest : KtUsefulTestCase() {
}
private fun createJarWithForeignAnnotations(): File =
- MockLibraryUtil.compileJavaFilesLibraryToJar(FOREIGN_ANNOTATIONS_SOURCES_PATH, "foreign-annotations")
+ MockLibraryUtilExt.compileJavaFilesLibraryToJar(FOREIGN_ANNOTATIONS_SOURCES_PATH, "foreign-annotations")
private fun createEnvironment(content: String): KotlinCoreEnvironment {
val classpath = mutableListOf(getAnnotationsJar(), ForTestCompileRuntime.runtimeJarForTests())
diff --git a/compiler/fir/analysis-tests/tests/org/jetbrains/kotlin/fir/java/JavaClassRendering.kt b/compiler/fir/analysis-tests/legacy-fir-tests/tests/org/jetbrains/kotlin/fir/java/JavaClassRendering.kt
similarity index 100%
rename from compiler/fir/analysis-tests/tests/org/jetbrains/kotlin/fir/java/JavaClassRendering.kt
rename to compiler/fir/analysis-tests/legacy-fir-tests/tests/org/jetbrains/kotlin/fir/java/JavaClassRendering.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/ArrayEqualityCanBeReplacedWithEquals.kt b/compiler/fir/analysis-tests/testData/extendedCheckers/ArrayEqualityCanBeReplacedWithEquals.kt
deleted file mode 100644
index 43b5af89a04..00000000000
--- a/compiler/fir/analysis-tests/testData/extendedCheckers/ArrayEqualityCanBeReplacedWithEquals.kt
+++ /dev/null
@@ -1,17 +0,0 @@
-// WITH_RUNTIME
-
-fun foo(p: Int) {
- val a = arrayOf(1, 2, 3)
- val b = arrayOf(3, 2, 1)
-
- if (a == b) { }
-}
-
-fun testsFromIdea() {
- val a = arrayOf("a")
- val b = a
- val c: Any? = null
- a == b
- a == c
- a != b
-}
\ No newline at end of file
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/nullable.kt b/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/nullable.kt
deleted file mode 100644
index 97809b57f70..00000000000
--- a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/nullable.kt
+++ /dev/null
@@ -1,5 +0,0 @@
-// WITH_RUNTIME
-// IS_APPLICABLE: false
-fun foo(s: String?) {
- val t: String = s.toString()
-}
\ No newline at end of file
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/safeString2.kt b/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/safeString2.kt
deleted file mode 100644
index c0b5a99987e..00000000000
--- a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/safeString2.kt
+++ /dev/null
@@ -1,6 +0,0 @@
-// WITH_RUNTIME
-data class Foo(val name: String)
-
-fun test(foo: Foo?) {
- val s: String? = foo?.name?.toString()
-}
\ No newline at end of file
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uByte.kt b/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uByte.kt
deleted file mode 100644
index 20444d1549d..00000000000
--- a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uByte.kt
+++ /dev/null
@@ -1,4 +0,0 @@
-// WITH_RUNTIME
-fun test(i: UByte) {
- val foo = i.toUByte()
-}
\ No newline at end of file
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uInt.kt b/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uInt.kt
deleted file mode 100644
index fec6f346b66..00000000000
--- a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uInt.kt
+++ /dev/null
@@ -1,4 +0,0 @@
-// WITH_RUNTIME
-fun test(i: UInt) {
- val foo = i.toUInt()
-}
\ No newline at end of file
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uLong.kt b/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uLong.kt
deleted file mode 100644
index c9fc29d32ca..00000000000
--- a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uLong.kt
+++ /dev/null
@@ -1,4 +0,0 @@
-// WITH_RUNTIME
-fun test(i: ULong) {
- val foo = i.toULong()
-}
\ No newline at end of file
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uShort.kt b/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uShort.kt
deleted file mode 100644
index 98fd40c8c4e..00000000000
--- a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uShort.kt
+++ /dev/null
@@ -1,4 +0,0 @@
-// WITH_RUNTIME
-fun test(i: UShort) {
- val foo = i.toUShort()
-}
\ No newline at end of file
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantExplicitTypeChecker.kt b/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantExplicitTypeChecker.kt
deleted file mode 100644
index d28a4286e91..00000000000
--- a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantExplicitTypeChecker.kt
+++ /dev/null
@@ -1,76 +0,0 @@
-import kotlin.reflect.KClass
-
-@Target(AnnotationTarget.TYPE)
-annotation class A
-
-fun annotated() {
- val x: @A Int /* NOT redundant */ = 1
-}
-
-object SomeObj
-fun fer() {
- val x: Any /* NOT redundant */ = SomeObj
-}
-
-fun f2(y: String?): String {
- val f: KClass<*> = (y ?: return "")::class
- return ""
-}
-
-object Obj {}
-
-interface IA
-interface IB : IA
-
-fun IA.extFun(x: IB) {}
-
-fun testWithExpectedType() {
- val extFun_AB_A: IA.(IB) -> Unit = IA::extFun
-}
-
-interface Point {
- val x: Int
- val y: Int
-}
-
-class PointImpl(override val x: Int, override val y: Int) : Point
-
-fun foo() {
- val s: String = "Hello ${10+1}"
- val str: String? = ""
-
- val o: Obj = Obj
-
- val p: Point = PointImpl(1, 2)
- val a: Boolean = true
- val i: Int = 2 * 2
- val l: Long = 1234567890123L
- val s: String? = null
- val sh: Short = 42
-
- val integer: Int = 42
- val piFloat: Float = 3.14f
- val piDouble: Double = 3.14
- val charZ: Char = 'z'
- var alpha: Int = 0
-}
-
-fun test(boolean: Boolean) {
- val expectedLong: Long = if (boolean) {
- 42
- } else {
- return
- }
-}
-
-class My {
- val x: Int = 1
-}
-
-val ZERO: Int = 0
-
-fun main() {
- val id: Id = 11
-}
-
-typealias Id = Int
\ No newline at end of file
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantModalityModifierChecker.kt b/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantModalityModifierChecker.kt
deleted file mode 100644
index 990762a9590..00000000000
--- a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantModalityModifierChecker.kt
+++ /dev/null
@@ -1,85 +0,0 @@
-object O {
- fun foo() {}
-}
-
-// Interface
-interface Interface {
- // Questionable cuz compiler reports warning here in FE 1.0
- open val gav: Int
- get() = 42
- // Redundant
- abstract fun foo()
- // error
- private final fun bar() {}
-
- open fun goo() {}
- abstract fun tar()
-
- // error
- abstract fun too() {}
-}
-interface B {
- abstract var bar: Unit
- abstract fun foo()
-}
-interface Foo
-
-expect abstract class AbstractClass : Foo {
- abstract override fun foo()
-
- abstract fun bar()
-
- abstract val baz: Int
-}
-
-
-// Abstract
-abstract class Base {
- // Redundant final
- final fun foo() {}
- // Abstract
- abstract fun bar()
- // Open
- open val gav = 42
-}
-
-class FinalDerived : Base() {
- // Redundant final
- override final fun bar() {}
- // Non-final member in final class
- override open val gav = 13
-}
-// Open
-open class OpenDerived : Base() {
- // Final
- override final fun bar() {}
- // Redundant open
- override open val gav = 13
-}
-// Redundant final
-final class Final
-// Derived interface
-interface Derived : Interface {
- // Redundant
- override open fun foo() {}
- // error
- final class Nested
-}
-// Derived abstract class
-abstract class AbstractDerived1(override final val gav: Int) : Interface {
- // Redundant
- override open fun foo() {}
-}
-// Derived abstract class
-abstract class AbstractDerived2 : Interface {
- // Final
- override final fun foo() {}
- // Redundant
- override open val gav = 13
-}
-// Redundant abstract interface
-abstract interface AbstractInterface
-// Redundant final object
-final object FinalObject
-// Open interface
-open interface OpenInterface
\ No newline at end of file
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantVisibilityModifierChecker.kt b/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantVisibilityModifierChecker.kt
deleted file mode 100644
index 00343ba50ed..00000000000
--- a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantVisibilityModifierChecker.kt
+++ /dev/null
@@ -1,86 +0,0 @@
-fun f() {
- public var baz = 0
- class LocalClass {
- internal var foo = 0
- }
- LocalClass().foo = 1
-}
-
-internal inline fun internal() {
- f()
-}
-
-class C {
- internal val z = object {
- fun foo() = 13
- }
-}
-
-class Foo2<
- T1,
- T2: T1,
- > {
- fun foo2() {}
-
- internal inner class B
-}
-
-public class C {
- public val foo: Int = 0
-
- public fun bar() {}
-
-}
-
-open class D {
- protected open fun willRemainProtected() {
- }
-
- protected open fun willBecomePublic() {
- }
-}
-
-class E : D() {
- protected override fun willRemainProtected() {
- }
-
- public override fun willBecomePublic() {
- }
-}
-
-enum class F private constructor(val x: Int) {
- FIRST(42)
-}
-
-sealed class G constructor(val y: Int) {
- private constructor(): this(42)
-
- object H : G()
-}
-
-interface I {
- fun bar()
-}
-
-public var baz = 0
-
-open class J {
- protected val baz = 0
- protected get() = field * 2
- var baf = 0
- public get() = 1
- public set(value) {
- field = value
- }
-
- var buf = 0
- private get() = 42
- protected set(value) {
- field = value
- }
-
- var bar = 0
- get() = 3.1415926535
- set(value) {}
-}
\ No newline at end of file
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/Sequence.kt b/compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/Sequence.kt
deleted file mode 100644
index e4a155284c8..00000000000
--- a/compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/Sequence.kt
+++ /dev/null
@@ -1,5 +0,0 @@
-// WITH_RUNTIME
-
-fun test(s: Sequence) {
- val foo = s.orEmpty()
-}
\ No newline at end of file
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/BasicTest.kt b/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/BasicTest.kt
deleted file mode 100644
index e218c599d57..00000000000
--- a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/BasicTest.kt
+++ /dev/null
@@ -1,7 +0,0 @@
-fun goo() {
- var a = 2
- val b = 4
- a = a + 1 + b
- a = (a + 1)
- a = a * b + 1
-}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperators.kt b/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperators.kt
deleted file mode 100644
index 9d171517e9c..00000000000
--- a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperators.kt
+++ /dev/null
@@ -1,5 +0,0 @@
-fun foo() {
- var x = 0
- var y = 0
- x = x + y + 5
-}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperatorsRightSideRepeat.kt b/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperatorsRightSideRepeat.kt
deleted file mode 100644
index a93064495f9..00000000000
--- a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperatorsRightSideRepeat.kt
+++ /dev/null
@@ -1,5 +0,0 @@
-fun foo() {
- var x = 0
- var y = 0
- x = y + x + 5
-}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/nonCommutativeRepeat.kt b/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/nonCommutativeRepeat.kt
deleted file mode 100644
index 2208ebf69b3..00000000000
--- a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/nonCommutativeRepeat.kt
+++ /dev/null
@@ -1,8 +0,0 @@
-fun foo() {
- var x = 0
- x = x - 1 - 1
-
- x = x / 1
- x = 1 / x
- x = -1 + x
-}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/rightSideRepeat.kt b/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/rightSideRepeat.kt
deleted file mode 100644
index 43f50dd8c40..00000000000
--- a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/rightSideRepeat.kt
+++ /dev/null
@@ -1,4 +0,0 @@
-fun foo() {
- var x = 0
- x = 1 + x
-}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/simpleAssign.kt b/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/simpleAssign.kt
deleted file mode 100644
index ba5108a3cc6..00000000000
--- a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/simpleAssign.kt
+++ /dev/null
@@ -1,5 +0,0 @@
-fun foo() {
- var y = 0
- val x = 0
- y = y + x
-}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/validAddition.kt b/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/validAddition.kt
deleted file mode 100644
index 191b05aebd9..00000000000
--- a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/validAddition.kt
+++ /dev/null
@@ -1,4 +0,0 @@
-fun foo() {
- var x = 0
- x = x + 1
-}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/validSubtraction.kt b/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/validSubtraction.kt
deleted file mode 100644
index 41407233e65..00000000000
--- a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/validSubtraction.kt
+++ /dev/null
@@ -1,4 +0,0 @@
-fun foo() {
- var x = 0
- x = x - 1
-}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/ArrayEqualityCanBeReplacedWithEquals.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/ArrayEqualityCanBeReplacedWithEquals.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/ArrayEqualityCanBeReplacedWithEquals.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/ArrayEqualityCanBeReplacedWithEquals.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/ArrayEqualityCanBeReplacedWithEquals.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/ArrayEqualityCanBeReplacedWithEquals.kt
new file mode 100644
index 00000000000..48ee3140b41
--- /dev/null
+++ b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/ArrayEqualityCanBeReplacedWithEquals.kt
@@ -0,0 +1,17 @@
+// WITH_RUNTIME
+
+fun foo(p: Int) {
+ val a = arrayOf(1, 2, 3)
+ val b = arrayOf(3, 2, 1)
+
+ if (a == b) { }
+}
+
+fun testsFromIdea() {
+ val a = arrayOf("a")
+ val b = a
+ val c: Any? = null
+ a == b
+ a == c
+ a != b
+}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/CanBeValChecker.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/CanBeValChecker.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/CanBeValChecker.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/CanBeValChecker.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/CanBeValChecker.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/CanBeValChecker.kt
similarity index 65%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/CanBeValChecker.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/CanBeValChecker.kt
index 69ad599adbc..5265bf5f52c 100644
--- a/compiler/fir/analysis-tests/testData/extendedCheckers/CanBeValChecker.kt
+++ b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/CanBeValChecker.kt
@@ -4,8 +4,8 @@ import kotlin.reflect.KProperty
import kotlin.properties.Delegates
fun testDelegator() {
- var x: Boolean by LocalFreezableVar(true)
- var y by LocalFreezableVar("")
+ var x: Boolean by LocalFreezableVar(true)
+ var y by LocalFreezableVar("")
}
class LocalFreezableVar(private var value: T) {
@@ -23,7 +23,7 @@ operator fun C.plusAssign(a: Any) {}
fun testOperatorAssignment() {
val c = C()
c += ""
- var c1 = C()
+ var c1 = C()
c1 += ""
var a = 1
@@ -33,7 +33,7 @@ fun testOperatorAssignment() {
fun destructuringDeclaration() {
- var (v1, v2) = getPair()
+ var (v1, v2) = getPair()
print(v1)
var (v3, v4) = getPair()
@@ -49,11 +49,11 @@ fun destructuringDeclaration() {
val (a, b, c) = Triple(1, 1, 1)
- var (x, y, z) = Triple(1, 1, 1)
+ var (x, y, z) = Triple(1, 1, 1)
}
fun stackOverflowBug() {
- var a: Int
+ var a: Int
a = 1
for (i in 1..10)
print(i)
@@ -71,8 +71,8 @@ fun smth(flag: Boolean) {
}
fun withAnnotation(p: List) {
- @Suppress("UNCHECKED_CAST")
- var v = p as List
+ @Suppress("UNCHECKED_CAST")
+ var v = p as List
print(v)
}
@@ -86,9 +86,9 @@ fun getPair(): Pair = Pair(1, "1")
fun listReceiver(p: List) {}
fun withInitializer() {
- var v1 = 1
+ var v1 = 1
var v2 = 2
- var v3 = 3
+ var v3 = 3
v1 = 1
v2++ // todo mark this UNUSED_CHANGED_VALUES
print(v3)
@@ -102,10 +102,10 @@ fun test() {
}
fun foo() {
- var a: Int
+ var a: Int
val bool = true
if (bool) a = 4 else a = 42
- val b: String
+ val b: String
bool = false
}
@@ -116,7 +116,7 @@ fun cycles() {
a--
}
- var b: Int
+ var b: Int
while (a < 10) {
a++
b = a
@@ -124,14 +124,14 @@ fun cycles() {
}
fun assignedTwice(p: Int) {
- var v: Int
+ var v: Int
v = 0
if (p > 0) v = 1
}
fun main(args: Array) {
- var a: String?
- val unused = 0
+ var a: String?
+ val unused = 0
if (args.size == 1) {
a = args[0]
@@ -144,7 +144,7 @@ fun main(args: Array) {
fun run(f: () -> Unit) = f()
fun lambda() {
- var a: Int
+ var a: Int
a = 10
run {
@@ -153,7 +153,7 @@ fun lambda() {
}
fun lambdaInitialization() {
- var a: Int
+ var a: Int
run {
a = 20
@@ -161,7 +161,7 @@ fun lambdaInitialization() {
}
fun notAssignedWhenNotUsed(p: Int) {
- var v: Int
+ var v: Int
if (p > 0) {
v = 1
print(v)
@@ -180,6 +180,6 @@ class C {
}
fun withDelegate() {
- var s: String by Delegates.notNull()
+ var s: String by Delegates.notNull()
s = ""
}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/StringTemplate.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/StringTemplate.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/StringTemplate.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/StringTemplate.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/StringTemplate.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/StringTemplate.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/StringTemplate.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/StringTemplate.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/booleanToInt.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/booleanToInt.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/booleanToInt.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/booleanToInt.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/booleanToInt.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/booleanToInt.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/booleanToInt.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/booleanToInt.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/byte.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/byte.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/byte.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/byte.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/byte.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/byte.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/byte.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/byte.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/char.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/char.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/char.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/char.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/char.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/char.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/char.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/char.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/double.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/double.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/double.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/double.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/double.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/double.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/double.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/double.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/float.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/float.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/float.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/float.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/float.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/float.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/float.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/float.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/int.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/int.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/int.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/int.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/int.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/int.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/int.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/int.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/long.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/long.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/long.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/long.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/long.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/long.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/long.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/long.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/nullable.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/nullable.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/nullable.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/nullable.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/nullable.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/nullable.kt
new file mode 100644
index 00000000000..6d7764f6103
--- /dev/null
+++ b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/nullable.kt
@@ -0,0 +1,5 @@
+// WITH_RUNTIME
+// IS_APPLICABLE: false
+fun foo(s: String?) {
+ val t: String = s.toString()
+}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/nullable2.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/nullable2.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/nullable2.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/nullable2.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/nullable2.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/nullable2.kt
similarity index 51%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/nullable2.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/nullable2.kt
index c828043775a..d20e7f71eeb 100644
--- a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/nullable2.kt
+++ b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/nullable2.kt
@@ -3,5 +3,5 @@
data class Foo(val name: String)
fun nullable2(foo: Foo?) {
- val s: String = foo?.name.toString()
-}
\ No newline at end of file
+ val s: String = foo?.name.toString()
+}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/safeString.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/safeString.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/safeString.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/safeString.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/safeString.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/safeString.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/safeString.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/safeString.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/safeString2.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/safeString2.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/safeString2.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/safeString2.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/safeString2.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/safeString2.kt
new file mode 100644
index 00000000000..d43d4744156
--- /dev/null
+++ b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/safeString2.kt
@@ -0,0 +1,6 @@
+// WITH_RUNTIME
+data class Foo(val name: String)
+
+fun test(foo: Foo?) {
+ val s: String? = foo?.name?.toString()
+}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/short.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/short.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/short.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/short.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/short.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/short.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/short.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/short.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/string.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/string.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/string.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/string.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/string.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/string.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/string.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/string.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/toOtherType.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/toOtherType.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/toOtherType.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/toOtherType.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/toOtherType.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/toOtherType.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/toOtherType.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/toOtherType.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uByte.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uByte.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uByte.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uByte.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uByte.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uByte.kt
new file mode 100644
index 00000000000..b0ff5f59ae8
--- /dev/null
+++ b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uByte.kt
@@ -0,0 +1,4 @@
+// WITH_RUNTIME
+fun test(i: UByte) {
+ val foo = i.toUByte()
+}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uInt.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uInt.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uInt.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uInt.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uInt.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uInt.kt
new file mode 100644
index 00000000000..c82679bd2f9
--- /dev/null
+++ b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uInt.kt
@@ -0,0 +1,4 @@
+// WITH_RUNTIME
+fun test(i: UInt) {
+ val foo = i.toUInt()
+}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uLong.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uLong.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uLong.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uLong.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uLong.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uLong.kt
new file mode 100644
index 00000000000..12885e9713a
--- /dev/null
+++ b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uLong.kt
@@ -0,0 +1,4 @@
+// WITH_RUNTIME
+fun test(i: ULong) {
+ val foo = i.toULong()
+}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uShort.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uShort.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uShort.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uShort.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uShort.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uShort.kt
new file mode 100644
index 00000000000..b847d74e797
--- /dev/null
+++ b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uShort.kt
@@ -0,0 +1,4 @@
+// WITH_RUNTIME
+fun test(i: UShort) {
+ val foo = i.toUShort()
+}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/variable.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/variable.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/variable.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/variable.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/variable.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/variable.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/variable.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/variable.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantExplicitTypeChecker.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantExplicitTypeChecker.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantExplicitTypeChecker.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantExplicitTypeChecker.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantExplicitTypeChecker.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantExplicitTypeChecker.kt
new file mode 100644
index 00000000000..033dc08beeb
--- /dev/null
+++ b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantExplicitTypeChecker.kt
@@ -0,0 +1,76 @@
+import kotlin.reflect.KClass
+
+@Target(AnnotationTarget.TYPE)
+annotation class A
+
+fun annotated() {
+ val x: @A Int /* NOT redundant */ = 1
+}
+
+object SomeObj
+fun fer() {
+ val x: Any /* NOT redundant */ = SomeObj
+}
+
+fun f2(y: String?): String {
+ val f: KClass<*> = (y ?: return "")::class
+ return ""
+}
+
+object Obj {}
+
+interface IA
+interface IB : IA
+
+fun IA.extFun(x: IB) {}
+
+fun testWithExpectedType() {
+ val extFun_AB_A: IA.(IB) -> Unit = IA::extFun
+}
+
+interface Point {
+ val x: Int
+ val y: Int
+}
+
+class PointImpl(override val x: Int, override val y: Int) : Point
+
+fun foo() {
+ val s: String = "Hello ${10+1}"
+ val str: String? = ""
+
+ val o: Obj = Obj
+
+ val p: Point = PointImpl(1, 2)
+ val a: Boolean = true
+ val i: Int = 2 * 2
+ val l: Long = 1234567890123L
+ val s: String? = null
+ val sh: Short = 42
+
+ val integer: Int = 42
+ val piFloat: Float = 3.14f
+ val piDouble: Double = 3.14
+ val charZ: Char = 'z'
+ var alpha: Int = 0
+}
+
+fun test(boolean: Boolean) {
+ val expectedLong: Long = if (boolean) {
+ 42
+ } else {
+ return
+ }
+}
+
+class My {
+ val x: Int = 1
+}
+
+val ZERO: Int = 0
+
+fun main() {
+ val id: Id = 11
+}
+
+typealias Id = Int
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantModalityModifierChecker.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantModalityModifierChecker.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantModalityModifierChecker.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantModalityModifierChecker.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantModalityModifierChecker.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantModalityModifierChecker.kt
new file mode 100644
index 00000000000..6a0140e094a
--- /dev/null
+++ b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantModalityModifierChecker.kt
@@ -0,0 +1,85 @@
+object O {
+ fun foo() {}
+}
+
+// Interface
+interface Interface {
+ // Questionable cuz compiler reports warning here in FE 1.0
+ open val gav: Int
+ get() = 42
+ // Redundant
+ abstract fun foo()
+ // error
+ private final fun bar() {}
+
+ open fun goo() {}
+ abstract fun tar()
+
+ // error
+ abstract fun too() {}
+}
+interface B {
+ abstract var bar: Unit
+ abstract fun foo()
+}
+interface Foo
+
+expect abstract class AbstractClass : Foo {
+ abstract override fun foo()
+
+ abstract fun bar()
+
+ abstract val baz: Int
+}
+
+
+// Abstract
+abstract class Base {
+ // Redundant final
+ final fun foo() {}
+ // Abstract
+ abstract fun bar()
+ // Open
+ open val gav = 42
+}
+
+class FinalDerived : Base() {
+ // Redundant final
+ override final fun bar() {}
+ // Non-final member in final class
+ override open val gav = 13
+}
+// Open
+open class OpenDerived : Base() {
+ // Final
+ override final fun bar() {}
+ // Redundant open
+ override open val gav = 13
+}
+// Redundant final
+final class Final
+// Derived interface
+interface Derived : Interface {
+ // Redundant
+ override open fun foo() {}
+ // error
+ final class Nested
+}
+// Derived abstract class
+abstract class AbstractDerived1(override final val gav: Int) : Interface {
+ // Redundant
+ override open fun foo() {}
+}
+// Derived abstract class
+abstract class AbstractDerived2 : Interface {
+ // Final
+ override final fun foo() {}
+ // Redundant
+ override open val gav = 13
+}
+// Redundant abstract interface
+abstract interface AbstractInterface
+// Redundant final object
+final object FinalObject
+// Open interface
+open interface OpenInterface
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantReturnUnitTypeChecker.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantReturnUnitTypeChecker.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantReturnUnitTypeChecker.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantReturnUnitTypeChecker.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantReturnUnitTypeChecker.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantReturnUnitTypeChecker.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantReturnUnitTypeChecker.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantReturnUnitTypeChecker.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantSetterParameterTypeChecker.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantSetterParameterTypeChecker.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantSetterParameterTypeChecker.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantSetterParameterTypeChecker.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantSetterParameterTypeChecker.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantSetterParameterTypeChecker.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantSetterParameterTypeChecker.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantSetterParameterTypeChecker.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantSingleExpressionStringTemplateChecker.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantSingleExpressionStringTemplateChecker.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantSingleExpressionStringTemplateChecker.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantSingleExpressionStringTemplateChecker.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantSingleExpressionStringTemplateChecker.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantSingleExpressionStringTemplateChecker.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantSingleExpressionStringTemplateChecker.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantSingleExpressionStringTemplateChecker.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/RedundantVisibilityModifierChecker.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantVisibilityModifierChecker.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/RedundantVisibilityModifierChecker.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantVisibilityModifierChecker.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantVisibilityModifierChecker.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantVisibilityModifierChecker.kt
new file mode 100644
index 00000000000..9bd5d5fab2b
--- /dev/null
+++ b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantVisibilityModifierChecker.kt
@@ -0,0 +1,86 @@
+fun f() {
+ public var baz = 0
+ class LocalClass {
+ internal var foo = 0
+ }
+ LocalClass().foo = 1
+}
+
+internal inline fun internal() {
+ f()
+}
+
+class C {
+ internal val z = object {
+ fun foo() = 13
+ }
+}
+
+class Foo2<
+ T1,
+ T2: T1,
+ > {
+ fun foo2() {}
+
+ internal inner class B
+}
+
+public class C {
+ public val foo: Int = 0
+
+ public fun bar() {}
+
+}
+
+open class D {
+ protected open fun willRemainProtected() {
+ }
+
+ protected open fun willBecomePublic() {
+ }
+}
+
+class E : D() {
+ protected override fun willRemainProtected() {
+ }
+
+ public override fun willBecomePublic() {
+ }
+}
+
+enum class F private constructor(val x: Int) {
+ FIRST(42)
+}
+
+sealed class G constructor(val y: Int) {
+ private constructor(): this(42)
+
+ object H : G()
+}
+
+interface I {
+ fun bar()
+}
+
+public var baz = 0
+
+open class J {
+ protected val baz = 0
+ protected get() = field * 2
+ var baf = 0
+ public get() = 1
+ public set(value) {
+ field = value
+ }
+
+ var buf = 0
+ private get() = 42
+ protected set(value) {
+ field = value
+ }
+
+ var bar = 0
+ get() = 3.1415926535
+ set(value) {}
+}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/Basic.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/Basic.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/Basic.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/Basic.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/Basic.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/Basic.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/Basic.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/Basic.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NotNullType.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NotNullType.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NotNullType.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NotNullType.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NotNullType.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NotNullType.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NotNullType.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NotNullType.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NotNullTypeChain.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NotNullTypeChain.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NotNullTypeChain.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NotNullTypeChain.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NotNullTypeChain.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NotNullTypeChain.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NotNullTypeChain.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NotNullTypeChain.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NullOrBlankSafe.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrBlankSafe.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NullOrBlankSafe.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrBlankSafe.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NullOrBlankSafe.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrBlankSafe.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NullOrBlankSafe.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrBlankSafe.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmpty.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmpty.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmpty.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmpty.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmpty.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmpty.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmpty.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmpty.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmptyFake.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmptyFake.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmptyFake.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmptyFake.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmptyFake.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmptyFake.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmptyFake.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmptyFake.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmptySafe.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmptySafe.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmptySafe.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmptySafe.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmptySafe.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmptySafe.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmptySafe.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmptySafe.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/OrEmptyFake.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/OrEmptyFake.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/OrEmptyFake.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/OrEmptyFake.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/OrEmptyFake.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/OrEmptyFake.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/OrEmptyFake.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/OrEmptyFake.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/SafeCall.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/SafeCall.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/SafeCall.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/SafeCall.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/SafeCall.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/SafeCall.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/SafeCall.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/SafeCall.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/Sequence.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/Sequence.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/Sequence.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/Sequence.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/Sequence.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/Sequence.kt
new file mode 100644
index 00000000000..7d42aa11536
--- /dev/null
+++ b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/Sequence.kt
@@ -0,0 +1,5 @@
+// WITH_RUNTIME
+
+fun test(s: Sequence) {
+ val foo = s.orEmpty()
+}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/String.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/String.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/String.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/String.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/String.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/String.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/String.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/String.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/BasicTest.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/BasicTest.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/BasicTest.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/BasicTest.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/BasicTest.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/BasicTest.kt
new file mode 100644
index 00000000000..912b9269c91
--- /dev/null
+++ b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/BasicTest.kt
@@ -0,0 +1,7 @@
+fun goo() {
+ var a = 2
+ val b = 4
+ a = a + 1 + b
+ a = (a + 1)
+ a = a * b + 1
+}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/ComplexExpression.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/ComplexExpression.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/ComplexExpression.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/ComplexExpression.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/ComplexExpression.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/ComplexExpression.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/ComplexExpression.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/ComplexExpression.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/OperatorAssignment.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/OperatorAssignment.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/OperatorAssignment.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/OperatorAssignment.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/OperatorAssignment.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/OperatorAssignment.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/OperatorAssignment.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/OperatorAssignment.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/flexibleTypeBug.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/flexibleTypeBug.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/flexibleTypeBug.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/flexibleTypeBug.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/flexibleTypeBug.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/flexibleTypeBug.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/flexibleTypeBug.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/flexibleTypeBug.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/illegalMultipleOperators.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/illegalMultipleOperators.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/illegalMultipleOperators.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/illegalMultipleOperators.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/illegalMultipleOperators.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/illegalMultipleOperators.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/illegalMultipleOperators.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/illegalMultipleOperators.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/illegalMultipleOperatorsMiddle.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/illegalMultipleOperatorsMiddle.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/illegalMultipleOperatorsMiddle.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/illegalMultipleOperatorsMiddle.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/illegalMultipleOperatorsMiddle.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/illegalMultipleOperatorsMiddle.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/illegalMultipleOperatorsMiddle.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/illegalMultipleOperatorsMiddle.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/invalidSubtraction.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/invalidSubtraction.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/invalidSubtraction.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/invalidSubtraction.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/invalidSubtraction.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/invalidSubtraction.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/invalidSubtraction.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/invalidSubtraction.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/list.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/list.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/list.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/list.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/list.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/list.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/list.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/list.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/logicOperators.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/logicOperators.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/logicOperators.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/logicOperators.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/logicOperators.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/logicOperators.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/logicOperators.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/logicOperators.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperators.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperators.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperators.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperators.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperators.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperators.kt
new file mode 100644
index 00000000000..11f1bca71de
--- /dev/null
+++ b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperators.kt
@@ -0,0 +1,5 @@
+fun foo() {
+ var x = 0
+ var y = 0
+ x = x + y + 5
+}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperatorsRightSideRepeat.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperatorsRightSideRepeat.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperatorsRightSideRepeat.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperatorsRightSideRepeat.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperatorsRightSideRepeat.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperatorsRightSideRepeat.kt
new file mode 100644
index 00000000000..96977f2be0e
--- /dev/null
+++ b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperatorsRightSideRepeat.kt
@@ -0,0 +1,5 @@
+fun foo() {
+ var x = 0
+ var y = 0
+ x = y + x + 5
+}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/mutableList.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/mutableList.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/mutableList.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/mutableList.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/mutableList.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/mutableList.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/mutableList.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/mutableList.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/nonCommutativeRepeat.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/nonCommutativeRepeat.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/nonCommutativeRepeat.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/nonCommutativeRepeat.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/nonCommutativeRepeat.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/nonCommutativeRepeat.kt
new file mode 100644
index 00000000000..dcc6e3c00c3
--- /dev/null
+++ b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/nonCommutativeRepeat.kt
@@ -0,0 +1,8 @@
+fun foo() {
+ var x = 0
+ x = x - 1 - 1
+
+ x = x / 1
+ x = 1 / x
+ x = -1 + x
+}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/nonRepeatingAssignment.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/nonRepeatingAssignment.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/nonRepeatingAssignment.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/nonRepeatingAssignment.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/nonRepeatingAssignment.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/nonRepeatingAssignment.kt
similarity index 54%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/nonRepeatingAssignment.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/nonRepeatingAssignment.kt
index 0b19a7e7ab5..ab87652e702 100644
--- a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/nonRepeatingAssignment.kt
+++ b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/nonRepeatingAssignment.kt
@@ -1,5 +1,5 @@
fun foo() {
- var x = 0
+ var x = 0
val y = 0
val z = 0
x = y + z
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/plusAssignConflict.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/plusAssignConflict.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/plusAssignConflict.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/plusAssignConflict.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/plusAssignConflict.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/plusAssignConflict.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/plusAssignConflict.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/plusAssignConflict.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/rightSideRepeat.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/rightSideRepeat.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/rightSideRepeat.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/rightSideRepeat.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/rightSideRepeat.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/rightSideRepeat.kt
new file mode 100644
index 00000000000..adde06044e7
--- /dev/null
+++ b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/rightSideRepeat.kt
@@ -0,0 +1,4 @@
+fun foo() {
+ var x = 0
+ x = 1 + x
+}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/simpleAssign.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/simpleAssign.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/simpleAssign.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/simpleAssign.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/simpleAssign.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/simpleAssign.kt
new file mode 100644
index 00000000000..cb9f57e7075
--- /dev/null
+++ b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/simpleAssign.kt
@@ -0,0 +1,5 @@
+fun foo() {
+ var y = 0
+ val x = 0
+ y = y + x
+}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/validAddition.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/validAddition.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/validAddition.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/validAddition.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/validAddition.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/validAddition.kt
new file mode 100644
index 00000000000..d77084bd75a
--- /dev/null
+++ b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/validAddition.kt
@@ -0,0 +1,4 @@
+fun foo() {
+ var x = 0
+ x = x + 1
+}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/validSubtraction.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/validSubtraction.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/validSubtraction.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/validSubtraction.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/validSubtraction.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/validSubtraction.kt
new file mode 100644
index 00000000000..a474c593fa1
--- /dev/null
+++ b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/validSubtraction.kt
@@ -0,0 +1,4 @@
+fun foo() {
+ var x = 0
+ x = x - 1
+}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/emptyRangeChecker/NoWarning.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/emptyRangeChecker/NoWarning.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/emptyRangeChecker/NoWarning.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/emptyRangeChecker/NoWarning.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/emptyRangeChecker/NoWarning.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/emptyRangeChecker/NoWarning.kt
similarity index 56%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/emptyRangeChecker/NoWarning.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/emptyRangeChecker/NoWarning.kt
index 209d2c11c89..6e69cac3315 100644
--- a/compiler/fir/analysis-tests/testData/extendedCheckers/emptyRangeChecker/NoWarning.kt
+++ b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/emptyRangeChecker/NoWarning.kt
@@ -3,7 +3,7 @@
fun foo() {
for (i in 1..2) { }
- val a = 3..4
+ val a = 3..4
val v = 1
if (v in 5..6) { }
@@ -13,7 +13,7 @@ fun foo() {
fun backward() {
for (i in 2 downTo 1) { }
- val a = 4 downTo 3
+ val a = 4 downTo 3
val v = 1
if (v in -5 downTo -6) { }
@@ -22,7 +22,7 @@ fun backward() {
fun until() {
for (i in 1 until 2) { }
- val a = 3 until 4
+ val a = 3 until 4
val v = 1
if (v in -5 until -4) { }
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/emptyRangeChecker/Warning.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/emptyRangeChecker/Warning.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/emptyRangeChecker/Warning.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/emptyRangeChecker/Warning.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/emptyRangeChecker/Warning.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/emptyRangeChecker/Warning.kt
similarity index 58%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/emptyRangeChecker/Warning.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/emptyRangeChecker/Warning.kt
index ad813ac13fd..0d5cebd779e 100644
--- a/compiler/fir/analysis-tests/testData/extendedCheckers/emptyRangeChecker/Warning.kt
+++ b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/emptyRangeChecker/Warning.kt
@@ -3,7 +3,7 @@
fun foo() {
for (i in 2..1) { }
- val a = 10..0
+ val a = 10..0
val v = 1
if (v in 10..1) { }
@@ -12,7 +12,7 @@ fun foo() {
fun backward() {
for (i in 1 downTo 2) { }
- val a = -3 downTo 4
+ val a = -3 downTo 4
val v = 1
if (v in 0 downTo 6) { }
@@ -21,7 +21,7 @@ fun backward() {
fun until() {
for (i in 1 until 1) { }
- val a = 4 until 3
+ val a = 4 until 3
val v = 1
if (v in -5 until -5) { }
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/unused/classProperty.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/classProperty.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/unused/classProperty.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/classProperty.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/unused/classProperty.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/classProperty.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/unused/classProperty.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/classProperty.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/unused/invoke.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/invoke.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/unused/invoke.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/invoke.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/unused/invoke.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/invoke.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/unused/invoke.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/invoke.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/unused/lambda.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/lambda.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/unused/lambda.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/lambda.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/unused/lambda.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/lambda.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/unused/lambda.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/lambda.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/unused/localVariable.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/localVariable.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/unused/localVariable.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/localVariable.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/unused/localVariable.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/localVariable.kt
similarity index 58%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/unused/localVariable.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/localVariable.kt
index aa69fc811ae..0d8f0230869 100644
--- a/compiler/fir/analysis-tests/testData/extendedCheckers/unused/localVariable.kt
+++ b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/localVariable.kt
@@ -4,7 +4,7 @@ class Outer {
fun foo() {
class Local {
fun bar() {
- val x = y
+ val x = y
}
}
}
@@ -22,13 +22,13 @@ fun f() {
fun foo(v: Int) {
- val d: Int by Delegate
- val a: Int
- val b = 1
+ val d: Int by Delegate
+ val a: Int
+ val b = 1
val c = 2
- @Anno
- val e: Int
+ @Anno
+ val e: Int
foo(c)
}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/unused/manyLocalVariables.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/manyLocalVariables.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/unused/manyLocalVariables.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/manyLocalVariables.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/unused/manyLocalVariables.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/manyLocalVariables.kt
similarity index 83%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/unused/manyLocalVariables.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/manyLocalVariables.kt
index 7de68571e70..d95d419335f 100644
--- a/compiler/fir/analysis-tests/testData/extendedCheckers/unused/manyLocalVariables.kt
+++ b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/manyLocalVariables.kt
@@ -1,5 +1,5 @@
fun foo() {
- var a = 1
+ var a = 1
var b = 2
var c = 3
@@ -16,4 +16,4 @@ fun foo() {
if (c == a) {
foo()
}
-}
\ No newline at end of file
+}
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/unused/usedInAnnotationArguments.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/usedInAnnotationArguments.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/unused/usedInAnnotationArguments.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/usedInAnnotationArguments.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/unused/usedInAnnotationArguments.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/usedInAnnotationArguments.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/unused/usedInAnnotationArguments.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/usedInAnnotationArguments.kt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/unused/valueIsNeverRead.txt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/valueIsNeverRead.fir.txt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/unused/valueIsNeverRead.txt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/valueIsNeverRead.fir.txt
diff --git a/compiler/fir/analysis-tests/testData/extendedCheckers/unused/valueIsNeverRead.kt b/compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/valueIsNeverRead.kt
similarity index 100%
rename from compiler/fir/analysis-tests/testData/extendedCheckers/unused/valueIsNeverRead.kt
rename to compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/valueIsNeverRead.kt
diff --git a/compiler/fir/analysis-tests/tests-gen/org/jetbrains/kotlin/fir/ExtendedFirDiagnosticsTestGenerated.java b/compiler/fir/analysis-tests/tests-gen/org/jetbrains/kotlin/fir/ExtendedFirDiagnosticsTestGenerated.java
deleted file mode 100644
index d1d2c85606e..00000000000
--- a/compiler/fir/analysis-tests/tests-gen/org/jetbrains/kotlin/fir/ExtendedFirDiagnosticsTestGenerated.java
+++ /dev/null
@@ -1,431 +0,0 @@
-/*
- * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
- * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
- */
-
-package org.jetbrains.kotlin.fir;
-
-import com.intellij.testFramework.TestDataPath;
-import org.jetbrains.kotlin.test.JUnit3RunnerWithInners;
-import org.jetbrains.kotlin.test.KotlinTestUtils;
-import org.jetbrains.kotlin.test.util.KtTestUtil;
-import org.jetbrains.kotlin.test.TestMetadata;
-import org.junit.runner.RunWith;
-
-import java.io.File;
-import java.util.regex.Pattern;
-
-/** This class is generated by {@link org.jetbrains.kotlin.generators.tests.TestsPackage}. DO NOT MODIFY MANUALLY */
-@SuppressWarnings("all")
-@TestMetadata("compiler/fir/analysis-tests/testData/extendedCheckers")
-@TestDataPath("$PROJECT_ROOT")
-@RunWith(JUnit3RunnerWithInners.class)
-public class ExtendedFirDiagnosticsTestGenerated extends AbstractExtendedFirDiagnosticsTest {
- private void runTest(String testDataFilePath) throws Exception {
- KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
- }
-
- public void testAllFilesPresentInExtendedCheckers() throws Exception {
- KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/extendedCheckers"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
- }
-
- @TestMetadata("ArrayEqualityCanBeReplacedWithEquals.kt")
- public void testArrayEqualityCanBeReplacedWithEquals() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/ArrayEqualityCanBeReplacedWithEquals.kt");
- }
-
- @TestMetadata("CanBeValChecker.kt")
- public void testCanBeValChecker() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/CanBeValChecker.kt");
- }
-
- @TestMetadata("RedundantExplicitTypeChecker.kt")
- public void testRedundantExplicitTypeChecker() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantExplicitTypeChecker.kt");
- }
-
- @TestMetadata("RedundantModalityModifierChecker.kt")
- public void testRedundantModalityModifierChecker() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantModalityModifierChecker.kt");
- }
-
- @TestMetadata("RedundantReturnUnitTypeChecker.kt")
- public void testRedundantReturnUnitTypeChecker() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantReturnUnitTypeChecker.kt");
- }
-
- @TestMetadata("RedundantSetterParameterTypeChecker.kt")
- public void testRedundantSetterParameterTypeChecker() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantSetterParameterTypeChecker.kt");
- }
-
- @TestMetadata("RedundantSingleExpressionStringTemplateChecker.kt")
- public void testRedundantSingleExpressionStringTemplateChecker() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantSingleExpressionStringTemplateChecker.kt");
- }
-
- @TestMetadata("RedundantVisibilityModifierChecker.kt")
- public void testRedundantVisibilityModifierChecker() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantVisibilityModifierChecker.kt");
- }
-
- @TestMetadata("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment")
- @TestDataPath("$PROJECT_ROOT")
- @RunWith(JUnit3RunnerWithInners.class)
- public static class CanBeReplacedWithOperatorAssignment extends AbstractExtendedFirDiagnosticsTest {
- private void runTest(String testDataFilePath) throws Exception {
- KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
- }
-
- public void testAllFilesPresentInCanBeReplacedWithOperatorAssignment() throws Exception {
- KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
- }
-
- @TestMetadata("BasicTest.kt")
- public void testBasicTest() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/BasicTest.kt");
- }
-
- @TestMetadata("ComplexExpression.kt")
- public void testComplexExpression() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/ComplexExpression.kt");
- }
-
- @TestMetadata("flexibleTypeBug.kt")
- public void testFlexibleTypeBug() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/flexibleTypeBug.kt");
- }
-
- @TestMetadata("illegalMultipleOperators.kt")
- public void testIllegalMultipleOperators() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/illegalMultipleOperators.kt");
- }
-
- @TestMetadata("illegalMultipleOperatorsMiddle.kt")
- public void testIllegalMultipleOperatorsMiddle() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/illegalMultipleOperatorsMiddle.kt");
- }
-
- @TestMetadata("invalidSubtraction.kt")
- public void testInvalidSubtraction() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/invalidSubtraction.kt");
- }
-
- @TestMetadata("list.kt")
- public void testList() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/list.kt");
- }
-
- @TestMetadata("logicOperators.kt")
- public void testLogicOperators() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/logicOperators.kt");
- }
-
- @TestMetadata("multipleOperators.kt")
- public void testMultipleOperators() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperators.kt");
- }
-
- @TestMetadata("multipleOperatorsRightSideRepeat.kt")
- public void testMultipleOperatorsRightSideRepeat() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperatorsRightSideRepeat.kt");
- }
-
- @TestMetadata("mutableList.kt")
- public void testMutableList() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/mutableList.kt");
- }
-
- @TestMetadata("nonCommutativeRepeat.kt")
- public void testNonCommutativeRepeat() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/nonCommutativeRepeat.kt");
- }
-
- @TestMetadata("nonRepeatingAssignment.kt")
- public void testNonRepeatingAssignment() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/nonRepeatingAssignment.kt");
- }
-
- @TestMetadata("OperatorAssignment.kt")
- public void testOperatorAssignment() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/OperatorAssignment.kt");
- }
-
- @TestMetadata("plusAssignConflict.kt")
- public void testPlusAssignConflict() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/plusAssignConflict.kt");
- }
-
- @TestMetadata("rightSideRepeat.kt")
- public void testRightSideRepeat() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/rightSideRepeat.kt");
- }
-
- @TestMetadata("simpleAssign.kt")
- public void testSimpleAssign() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/simpleAssign.kt");
- }
-
- @TestMetadata("validAddition.kt")
- public void testValidAddition() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/validAddition.kt");
- }
-
- @TestMetadata("validSubtraction.kt")
- public void testValidSubtraction() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/validSubtraction.kt");
- }
- }
-
- @TestMetadata("compiler/fir/analysis-tests/testData/extendedCheckers/emptyRangeChecker")
- @TestDataPath("$PROJECT_ROOT")
- @RunWith(JUnit3RunnerWithInners.class)
- public static class EmptyRangeChecker extends AbstractExtendedFirDiagnosticsTest {
- private void runTest(String testDataFilePath) throws Exception {
- KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
- }
-
- public void testAllFilesPresentInEmptyRangeChecker() throws Exception {
- KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/extendedCheckers/emptyRangeChecker"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
- }
-
- @TestMetadata("NoWarning.kt")
- public void testNoWarning() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/emptyRangeChecker/NoWarning.kt");
- }
-
- @TestMetadata("Warning.kt")
- public void testWarning() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/emptyRangeChecker/Warning.kt");
- }
- }
-
- @TestMetadata("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod")
- @TestDataPath("$PROJECT_ROOT")
- @RunWith(JUnit3RunnerWithInners.class)
- public static class RedundantCallOfConversionMethod extends AbstractExtendedFirDiagnosticsTest {
- private void runTest(String testDataFilePath) throws Exception {
- KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
- }
-
- public void testAllFilesPresentInRedundantCallOfConversionMethod() throws Exception {
- KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
- }
-
- @TestMetadata("booleanToInt.kt")
- public void testBooleanToInt() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/booleanToInt.kt");
- }
-
- @TestMetadata("byte.kt")
- public void testByte() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/byte.kt");
- }
-
- @TestMetadata("char.kt")
- public void testChar() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/char.kt");
- }
-
- @TestMetadata("double.kt")
- public void testDouble() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/double.kt");
- }
-
- @TestMetadata("float.kt")
- public void testFloat() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/float.kt");
- }
-
- @TestMetadata("int.kt")
- public void testInt() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/int.kt");
- }
-
- @TestMetadata("long.kt")
- public void testLong() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/long.kt");
- }
-
- @TestMetadata("nullable.kt")
- public void testNullable() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/nullable.kt");
- }
-
- @TestMetadata("nullable2.kt")
- public void testNullable2() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/nullable2.kt");
- }
-
- @TestMetadata("safeString.kt")
- public void testSafeString() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/safeString.kt");
- }
-
- @TestMetadata("safeString2.kt")
- public void testSafeString2() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/safeString2.kt");
- }
-
- @TestMetadata("short.kt")
- public void testShort() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/short.kt");
- }
-
- @TestMetadata("string.kt")
- public void testString() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/string.kt");
- }
-
- @TestMetadata("StringTemplate.kt")
- public void testStringTemplate() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/StringTemplate.kt");
- }
-
- @TestMetadata("toOtherType.kt")
- public void testToOtherType() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/toOtherType.kt");
- }
-
- @TestMetadata("uByte.kt")
- public void testUByte() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uByte.kt");
- }
-
- @TestMetadata("uInt.kt")
- public void testUInt() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uInt.kt");
- }
-
- @TestMetadata("uLong.kt")
- public void testULong() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uLong.kt");
- }
-
- @TestMetadata("uShort.kt")
- public void testUShort() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uShort.kt");
- }
-
- @TestMetadata("variable.kt")
- public void testVariable() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/variable.kt");
- }
- }
-
- @TestMetadata("compiler/fir/analysis-tests/testData/extendedCheckers/unused")
- @TestDataPath("$PROJECT_ROOT")
- @RunWith(JUnit3RunnerWithInners.class)
- public static class Unused extends AbstractExtendedFirDiagnosticsTest {
- private void runTest(String testDataFilePath) throws Exception {
- KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
- }
-
- public void testAllFilesPresentInUnused() throws Exception {
- KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/extendedCheckers/unused"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
- }
-
- @TestMetadata("classProperty.kt")
- public void testClassProperty() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/unused/classProperty.kt");
- }
-
- @TestMetadata("invoke.kt")
- public void testInvoke() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/unused/invoke.kt");
- }
-
- @TestMetadata("lambda.kt")
- public void testLambda() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/unused/lambda.kt");
- }
-
- @TestMetadata("localVariable.kt")
- public void testLocalVariable() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/unused/localVariable.kt");
- }
-
- @TestMetadata("manyLocalVariables.kt")
- public void testManyLocalVariables() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/unused/manyLocalVariables.kt");
- }
-
- @TestMetadata("usedInAnnotationArguments.kt")
- public void testUsedInAnnotationArguments() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/unused/usedInAnnotationArguments.kt");
- }
-
- @TestMetadata("valueIsNeverRead.kt")
- public void testValueIsNeverRead() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/unused/valueIsNeverRead.kt");
- }
- }
-
- @TestMetadata("compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker")
- @TestDataPath("$PROJECT_ROOT")
- @RunWith(JUnit3RunnerWithInners.class)
- public static class UselessCallOnNotNullChecker extends AbstractExtendedFirDiagnosticsTest {
- private void runTest(String testDataFilePath) throws Exception {
- KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
- }
-
- public void testAllFilesPresentInUselessCallOnNotNullChecker() throws Exception {
- KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
- }
-
- @TestMetadata("Basic.kt")
- public void testBasic() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/Basic.kt");
- }
-
- @TestMetadata("NotNullType.kt")
- public void testNotNullType() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NotNullType.kt");
- }
-
- @TestMetadata("NotNullTypeChain.kt")
- public void testNotNullTypeChain() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NotNullTypeChain.kt");
- }
-
- @TestMetadata("NullOrBlankSafe.kt")
- public void testNullOrBlankSafe() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NullOrBlankSafe.kt");
- }
-
- @TestMetadata("NullOrEmpty.kt")
- public void testNullOrEmpty() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmpty.kt");
- }
-
- @TestMetadata("NullOrEmptyFake.kt")
- public void testNullOrEmptyFake() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmptyFake.kt");
- }
-
- @TestMetadata("NullOrEmptySafe.kt")
- public void testNullOrEmptySafe() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmptySafe.kt");
- }
-
- @TestMetadata("OrEmptyFake.kt")
- public void testOrEmptyFake() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/OrEmptyFake.kt");
- }
-
- @TestMetadata("SafeCall.kt")
- public void testSafeCall() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/SafeCall.kt");
- }
-
- @TestMetadata("Sequence.kt")
- public void testSequence() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/Sequence.kt");
- }
-
- @TestMetadata("String.kt")
- public void testString() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/String.kt");
- }
- }
-}
diff --git a/compiler/fir/analysis-tests/tests-gen/org/jetbrains/kotlin/fir/ExtendedFirWithLightTreeDiagnosticsTestGenerated.java b/compiler/fir/analysis-tests/tests-gen/org/jetbrains/kotlin/fir/ExtendedFirWithLightTreeDiagnosticsTestGenerated.java
deleted file mode 100644
index 09565f356d5..00000000000
--- a/compiler/fir/analysis-tests/tests-gen/org/jetbrains/kotlin/fir/ExtendedFirWithLightTreeDiagnosticsTestGenerated.java
+++ /dev/null
@@ -1,431 +0,0 @@
-/*
- * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
- * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
- */
-
-package org.jetbrains.kotlin.fir;
-
-import com.intellij.testFramework.TestDataPath;
-import org.jetbrains.kotlin.test.JUnit3RunnerWithInners;
-import org.jetbrains.kotlin.test.KotlinTestUtils;
-import org.jetbrains.kotlin.test.util.KtTestUtil;
-import org.jetbrains.kotlin.test.TestMetadata;
-import org.junit.runner.RunWith;
-
-import java.io.File;
-import java.util.regex.Pattern;
-
-/** This class is generated by {@link org.jetbrains.kotlin.generators.tests.TestsPackage}. DO NOT MODIFY MANUALLY */
-@SuppressWarnings("all")
-@TestMetadata("compiler/fir/analysis-tests/testData/extendedCheckers")
-@TestDataPath("$PROJECT_ROOT")
-@RunWith(JUnit3RunnerWithInners.class)
-public class ExtendedFirWithLightTreeDiagnosticsTestGenerated extends AbstractExtendedFirWithLightTreeDiagnosticsTest {
- private void runTest(String testDataFilePath) throws Exception {
- KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
- }
-
- public void testAllFilesPresentInExtendedCheckers() throws Exception {
- KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/extendedCheckers"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
- }
-
- @TestMetadata("ArrayEqualityCanBeReplacedWithEquals.kt")
- public void testArrayEqualityCanBeReplacedWithEquals() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/ArrayEqualityCanBeReplacedWithEquals.kt");
- }
-
- @TestMetadata("CanBeValChecker.kt")
- public void testCanBeValChecker() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/CanBeValChecker.kt");
- }
-
- @TestMetadata("RedundantExplicitTypeChecker.kt")
- public void testRedundantExplicitTypeChecker() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantExplicitTypeChecker.kt");
- }
-
- @TestMetadata("RedundantModalityModifierChecker.kt")
- public void testRedundantModalityModifierChecker() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantModalityModifierChecker.kt");
- }
-
- @TestMetadata("RedundantReturnUnitTypeChecker.kt")
- public void testRedundantReturnUnitTypeChecker() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantReturnUnitTypeChecker.kt");
- }
-
- @TestMetadata("RedundantSetterParameterTypeChecker.kt")
- public void testRedundantSetterParameterTypeChecker() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantSetterParameterTypeChecker.kt");
- }
-
- @TestMetadata("RedundantSingleExpressionStringTemplateChecker.kt")
- public void testRedundantSingleExpressionStringTemplateChecker() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantSingleExpressionStringTemplateChecker.kt");
- }
-
- @TestMetadata("RedundantVisibilityModifierChecker.kt")
- public void testRedundantVisibilityModifierChecker() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantVisibilityModifierChecker.kt");
- }
-
- @TestMetadata("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment")
- @TestDataPath("$PROJECT_ROOT")
- @RunWith(JUnit3RunnerWithInners.class)
- public static class CanBeReplacedWithOperatorAssignment extends AbstractExtendedFirWithLightTreeDiagnosticsTest {
- private void runTest(String testDataFilePath) throws Exception {
- KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
- }
-
- public void testAllFilesPresentInCanBeReplacedWithOperatorAssignment() throws Exception {
- KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
- }
-
- @TestMetadata("BasicTest.kt")
- public void testBasicTest() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/BasicTest.kt");
- }
-
- @TestMetadata("ComplexExpression.kt")
- public void testComplexExpression() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/ComplexExpression.kt");
- }
-
- @TestMetadata("flexibleTypeBug.kt")
- public void testFlexibleTypeBug() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/flexibleTypeBug.kt");
- }
-
- @TestMetadata("illegalMultipleOperators.kt")
- public void testIllegalMultipleOperators() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/illegalMultipleOperators.kt");
- }
-
- @TestMetadata("illegalMultipleOperatorsMiddle.kt")
- public void testIllegalMultipleOperatorsMiddle() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/illegalMultipleOperatorsMiddle.kt");
- }
-
- @TestMetadata("invalidSubtraction.kt")
- public void testInvalidSubtraction() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/invalidSubtraction.kt");
- }
-
- @TestMetadata("list.kt")
- public void testList() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/list.kt");
- }
-
- @TestMetadata("logicOperators.kt")
- public void testLogicOperators() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/logicOperators.kt");
- }
-
- @TestMetadata("multipleOperators.kt")
- public void testMultipleOperators() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperators.kt");
- }
-
- @TestMetadata("multipleOperatorsRightSideRepeat.kt")
- public void testMultipleOperatorsRightSideRepeat() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperatorsRightSideRepeat.kt");
- }
-
- @TestMetadata("mutableList.kt")
- public void testMutableList() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/mutableList.kt");
- }
-
- @TestMetadata("nonCommutativeRepeat.kt")
- public void testNonCommutativeRepeat() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/nonCommutativeRepeat.kt");
- }
-
- @TestMetadata("nonRepeatingAssignment.kt")
- public void testNonRepeatingAssignment() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/nonRepeatingAssignment.kt");
- }
-
- @TestMetadata("OperatorAssignment.kt")
- public void testOperatorAssignment() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/OperatorAssignment.kt");
- }
-
- @TestMetadata("plusAssignConflict.kt")
- public void testPlusAssignConflict() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/plusAssignConflict.kt");
- }
-
- @TestMetadata("rightSideRepeat.kt")
- public void testRightSideRepeat() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/rightSideRepeat.kt");
- }
-
- @TestMetadata("simpleAssign.kt")
- public void testSimpleAssign() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/simpleAssign.kt");
- }
-
- @TestMetadata("validAddition.kt")
- public void testValidAddition() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/validAddition.kt");
- }
-
- @TestMetadata("validSubtraction.kt")
- public void testValidSubtraction() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/canBeReplacedWithOperatorAssignment/validSubtraction.kt");
- }
- }
-
- @TestMetadata("compiler/fir/analysis-tests/testData/extendedCheckers/emptyRangeChecker")
- @TestDataPath("$PROJECT_ROOT")
- @RunWith(JUnit3RunnerWithInners.class)
- public static class EmptyRangeChecker extends AbstractExtendedFirWithLightTreeDiagnosticsTest {
- private void runTest(String testDataFilePath) throws Exception {
- KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
- }
-
- public void testAllFilesPresentInEmptyRangeChecker() throws Exception {
- KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/extendedCheckers/emptyRangeChecker"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
- }
-
- @TestMetadata("NoWarning.kt")
- public void testNoWarning() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/emptyRangeChecker/NoWarning.kt");
- }
-
- @TestMetadata("Warning.kt")
- public void testWarning() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/emptyRangeChecker/Warning.kt");
- }
- }
-
- @TestMetadata("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod")
- @TestDataPath("$PROJECT_ROOT")
- @RunWith(JUnit3RunnerWithInners.class)
- public static class RedundantCallOfConversionMethod extends AbstractExtendedFirWithLightTreeDiagnosticsTest {
- private void runTest(String testDataFilePath) throws Exception {
- KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
- }
-
- public void testAllFilesPresentInRedundantCallOfConversionMethod() throws Exception {
- KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
- }
-
- @TestMetadata("booleanToInt.kt")
- public void testBooleanToInt() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/booleanToInt.kt");
- }
-
- @TestMetadata("byte.kt")
- public void testByte() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/byte.kt");
- }
-
- @TestMetadata("char.kt")
- public void testChar() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/char.kt");
- }
-
- @TestMetadata("double.kt")
- public void testDouble() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/double.kt");
- }
-
- @TestMetadata("float.kt")
- public void testFloat() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/float.kt");
- }
-
- @TestMetadata("int.kt")
- public void testInt() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/int.kt");
- }
-
- @TestMetadata("long.kt")
- public void testLong() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/long.kt");
- }
-
- @TestMetadata("nullable.kt")
- public void testNullable() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/nullable.kt");
- }
-
- @TestMetadata("nullable2.kt")
- public void testNullable2() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/nullable2.kt");
- }
-
- @TestMetadata("safeString.kt")
- public void testSafeString() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/safeString.kt");
- }
-
- @TestMetadata("safeString2.kt")
- public void testSafeString2() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/safeString2.kt");
- }
-
- @TestMetadata("short.kt")
- public void testShort() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/short.kt");
- }
-
- @TestMetadata("string.kt")
- public void testString() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/string.kt");
- }
-
- @TestMetadata("StringTemplate.kt")
- public void testStringTemplate() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/StringTemplate.kt");
- }
-
- @TestMetadata("toOtherType.kt")
- public void testToOtherType() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/toOtherType.kt");
- }
-
- @TestMetadata("uByte.kt")
- public void testUByte() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uByte.kt");
- }
-
- @TestMetadata("uInt.kt")
- public void testUInt() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uInt.kt");
- }
-
- @TestMetadata("uLong.kt")
- public void testULong() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uLong.kt");
- }
-
- @TestMetadata("uShort.kt")
- public void testUShort() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/uShort.kt");
- }
-
- @TestMetadata("variable.kt")
- public void testVariable() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/RedundantCallOfConversionMethod/variable.kt");
- }
- }
-
- @TestMetadata("compiler/fir/analysis-tests/testData/extendedCheckers/unused")
- @TestDataPath("$PROJECT_ROOT")
- @RunWith(JUnit3RunnerWithInners.class)
- public static class Unused extends AbstractExtendedFirWithLightTreeDiagnosticsTest {
- private void runTest(String testDataFilePath) throws Exception {
- KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
- }
-
- public void testAllFilesPresentInUnused() throws Exception {
- KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/extendedCheckers/unused"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
- }
-
- @TestMetadata("classProperty.kt")
- public void testClassProperty() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/unused/classProperty.kt");
- }
-
- @TestMetadata("invoke.kt")
- public void testInvoke() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/unused/invoke.kt");
- }
-
- @TestMetadata("lambda.kt")
- public void testLambda() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/unused/lambda.kt");
- }
-
- @TestMetadata("localVariable.kt")
- public void testLocalVariable() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/unused/localVariable.kt");
- }
-
- @TestMetadata("manyLocalVariables.kt")
- public void testManyLocalVariables() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/unused/manyLocalVariables.kt");
- }
-
- @TestMetadata("usedInAnnotationArguments.kt")
- public void testUsedInAnnotationArguments() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/unused/usedInAnnotationArguments.kt");
- }
-
- @TestMetadata("valueIsNeverRead.kt")
- public void testValueIsNeverRead() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/unused/valueIsNeverRead.kt");
- }
- }
-
- @TestMetadata("compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker")
- @TestDataPath("$PROJECT_ROOT")
- @RunWith(JUnit3RunnerWithInners.class)
- public static class UselessCallOnNotNullChecker extends AbstractExtendedFirWithLightTreeDiagnosticsTest {
- private void runTest(String testDataFilePath) throws Exception {
- KotlinTestUtils.runTest(this::doTest, this, testDataFilePath);
- }
-
- public void testAllFilesPresentInUselessCallOnNotNullChecker() throws Exception {
- KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
- }
-
- @TestMetadata("Basic.kt")
- public void testBasic() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/Basic.kt");
- }
-
- @TestMetadata("NotNullType.kt")
- public void testNotNullType() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NotNullType.kt");
- }
-
- @TestMetadata("NotNullTypeChain.kt")
- public void testNotNullTypeChain() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NotNullTypeChain.kt");
- }
-
- @TestMetadata("NullOrBlankSafe.kt")
- public void testNullOrBlankSafe() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NullOrBlankSafe.kt");
- }
-
- @TestMetadata("NullOrEmpty.kt")
- public void testNullOrEmpty() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmpty.kt");
- }
-
- @TestMetadata("NullOrEmptyFake.kt")
- public void testNullOrEmptyFake() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmptyFake.kt");
- }
-
- @TestMetadata("NullOrEmptySafe.kt")
- public void testNullOrEmptySafe() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmptySafe.kt");
- }
-
- @TestMetadata("OrEmptyFake.kt")
- public void testOrEmptyFake() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/OrEmptyFake.kt");
- }
-
- @TestMetadata("SafeCall.kt")
- public void testSafeCall() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/SafeCall.kt");
- }
-
- @TestMetadata("Sequence.kt")
- public void testSequence() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/Sequence.kt");
- }
-
- @TestMetadata("String.kt")
- public void testString() throws Exception {
- runTest("compiler/fir/analysis-tests/testData/extendedCheckers/UselessCallOnNotNullChecker/String.kt");
- }
- }
-}
diff --git a/compiler/tests-common-new/tests-gen/org/jetbrains/kotlin/test/runners/FirDiagnosticTestGenerated.java b/compiler/fir/analysis-tests/tests-gen/org/jetbrains/kotlin/test/runners/FirDiagnosticTestGenerated.java
similarity index 89%
rename from compiler/tests-common-new/tests-gen/org/jetbrains/kotlin/test/runners/FirDiagnosticTestGenerated.java
rename to compiler/fir/analysis-tests/tests-gen/org/jetbrains/kotlin/test/runners/FirDiagnosticTestGenerated.java
index 0c45772647f..25e4476062f 100644
--- a/compiler/tests-common-new/tests-gen/org/jetbrains/kotlin/test/runners/FirDiagnosticTestGenerated.java
+++ b/compiler/fir/analysis-tests/tests-gen/org/jetbrains/kotlin/test/runners/FirDiagnosticTestGenerated.java
@@ -1946,6 +1946,468 @@ public class FirDiagnosticTestGenerated extends AbstractFirDiagnosticTest {
}
}
+ @Nested
+ @TestMetadata("compiler/fir/analysis-tests/testData/resolve/extendedCheckers")
+ @TestDataPath("$PROJECT_ROOT")
+ public class ExtendedCheckers extends AbstractFirDiagnosticTest {
+ @Test
+ public void testAllFilesPresentInExtendedCheckers() throws Exception {
+ KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/resolve/extendedCheckers"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
+ }
+
+ @Test
+ @TestMetadata("ArrayEqualityCanBeReplacedWithEquals.kt")
+ public void testArrayEqualityCanBeReplacedWithEquals() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/ArrayEqualityCanBeReplacedWithEquals.kt");
+ }
+
+ @Test
+ @TestMetadata("CanBeValChecker.kt")
+ public void testCanBeValChecker() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/CanBeValChecker.kt");
+ }
+
+ @Test
+ @TestMetadata("RedundantExplicitTypeChecker.kt")
+ public void testRedundantExplicitTypeChecker() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantExplicitTypeChecker.kt");
+ }
+
+ @Test
+ @TestMetadata("RedundantModalityModifierChecker.kt")
+ public void testRedundantModalityModifierChecker() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantModalityModifierChecker.kt");
+ }
+
+ @Test
+ @TestMetadata("RedundantReturnUnitTypeChecker.kt")
+ public void testRedundantReturnUnitTypeChecker() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantReturnUnitTypeChecker.kt");
+ }
+
+ @Test
+ @TestMetadata("RedundantSetterParameterTypeChecker.kt")
+ public void testRedundantSetterParameterTypeChecker() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantSetterParameterTypeChecker.kt");
+ }
+
+ @Test
+ @TestMetadata("RedundantSingleExpressionStringTemplateChecker.kt")
+ public void testRedundantSingleExpressionStringTemplateChecker() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantSingleExpressionStringTemplateChecker.kt");
+ }
+
+ @Test
+ @TestMetadata("RedundantVisibilityModifierChecker.kt")
+ public void testRedundantVisibilityModifierChecker() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantVisibilityModifierChecker.kt");
+ }
+
+ @Nested
+ @TestMetadata("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment")
+ @TestDataPath("$PROJECT_ROOT")
+ public class CanBeReplacedWithOperatorAssignment extends AbstractFirDiagnosticTest {
+ @Test
+ public void testAllFilesPresentInCanBeReplacedWithOperatorAssignment() throws Exception {
+ KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
+ }
+
+ @Test
+ @TestMetadata("BasicTest.kt")
+ public void testBasicTest() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/BasicTest.kt");
+ }
+
+ @Test
+ @TestMetadata("ComplexExpression.kt")
+ public void testComplexExpression() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/ComplexExpression.kt");
+ }
+
+ @Test
+ @TestMetadata("flexibleTypeBug.kt")
+ public void testFlexibleTypeBug() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/flexibleTypeBug.kt");
+ }
+
+ @Test
+ @TestMetadata("illegalMultipleOperators.kt")
+ public void testIllegalMultipleOperators() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/illegalMultipleOperators.kt");
+ }
+
+ @Test
+ @TestMetadata("illegalMultipleOperatorsMiddle.kt")
+ public void testIllegalMultipleOperatorsMiddle() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/illegalMultipleOperatorsMiddle.kt");
+ }
+
+ @Test
+ @TestMetadata("invalidSubtraction.kt")
+ public void testInvalidSubtraction() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/invalidSubtraction.kt");
+ }
+
+ @Test
+ @TestMetadata("list.kt")
+ public void testList() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/list.kt");
+ }
+
+ @Test
+ @TestMetadata("logicOperators.kt")
+ public void testLogicOperators() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/logicOperators.kt");
+ }
+
+ @Test
+ @TestMetadata("multipleOperators.kt")
+ public void testMultipleOperators() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperators.kt");
+ }
+
+ @Test
+ @TestMetadata("multipleOperatorsRightSideRepeat.kt")
+ public void testMultipleOperatorsRightSideRepeat() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperatorsRightSideRepeat.kt");
+ }
+
+ @Test
+ @TestMetadata("mutableList.kt")
+ public void testMutableList() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/mutableList.kt");
+ }
+
+ @Test
+ @TestMetadata("nonCommutativeRepeat.kt")
+ public void testNonCommutativeRepeat() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/nonCommutativeRepeat.kt");
+ }
+
+ @Test
+ @TestMetadata("nonRepeatingAssignment.kt")
+ public void testNonRepeatingAssignment() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/nonRepeatingAssignment.kt");
+ }
+
+ @Test
+ @TestMetadata("OperatorAssignment.kt")
+ public void testOperatorAssignment() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/OperatorAssignment.kt");
+ }
+
+ @Test
+ @TestMetadata("plusAssignConflict.kt")
+ public void testPlusAssignConflict() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/plusAssignConflict.kt");
+ }
+
+ @Test
+ @TestMetadata("rightSideRepeat.kt")
+ public void testRightSideRepeat() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/rightSideRepeat.kt");
+ }
+
+ @Test
+ @TestMetadata("simpleAssign.kt")
+ public void testSimpleAssign() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/simpleAssign.kt");
+ }
+
+ @Test
+ @TestMetadata("validAddition.kt")
+ public void testValidAddition() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/validAddition.kt");
+ }
+
+ @Test
+ @TestMetadata("validSubtraction.kt")
+ public void testValidSubtraction() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/validSubtraction.kt");
+ }
+ }
+
+ @Nested
+ @TestMetadata("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/emptyRangeChecker")
+ @TestDataPath("$PROJECT_ROOT")
+ public class EmptyRangeChecker extends AbstractFirDiagnosticTest {
+ @Test
+ public void testAllFilesPresentInEmptyRangeChecker() throws Exception {
+ KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/emptyRangeChecker"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
+ }
+
+ @Test
+ @TestMetadata("NoWarning.kt")
+ public void testNoWarning() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/emptyRangeChecker/NoWarning.kt");
+ }
+
+ @Test
+ @TestMetadata("Warning.kt")
+ public void testWarning() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/emptyRangeChecker/Warning.kt");
+ }
+ }
+
+ @Nested
+ @TestMetadata("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod")
+ @TestDataPath("$PROJECT_ROOT")
+ public class RedundantCallOfConversionMethod extends AbstractFirDiagnosticTest {
+ @Test
+ public void testAllFilesPresentInRedundantCallOfConversionMethod() throws Exception {
+ KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
+ }
+
+ @Test
+ @TestMetadata("booleanToInt.kt")
+ public void testBooleanToInt() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/booleanToInt.kt");
+ }
+
+ @Test
+ @TestMetadata("byte.kt")
+ public void testByte() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/byte.kt");
+ }
+
+ @Test
+ @TestMetadata("char.kt")
+ public void testChar() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/char.kt");
+ }
+
+ @Test
+ @TestMetadata("double.kt")
+ public void testDouble() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/double.kt");
+ }
+
+ @Test
+ @TestMetadata("float.kt")
+ public void testFloat() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/float.kt");
+ }
+
+ @Test
+ @TestMetadata("int.kt")
+ public void testInt() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/int.kt");
+ }
+
+ @Test
+ @TestMetadata("long.kt")
+ public void testLong() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/long.kt");
+ }
+
+ @Test
+ @TestMetadata("nullable.kt")
+ public void testNullable() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/nullable.kt");
+ }
+
+ @Test
+ @TestMetadata("nullable2.kt")
+ public void testNullable2() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/nullable2.kt");
+ }
+
+ @Test
+ @TestMetadata("safeString.kt")
+ public void testSafeString() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/safeString.kt");
+ }
+
+ @Test
+ @TestMetadata("safeString2.kt")
+ public void testSafeString2() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/safeString2.kt");
+ }
+
+ @Test
+ @TestMetadata("short.kt")
+ public void testShort() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/short.kt");
+ }
+
+ @Test
+ @TestMetadata("string.kt")
+ public void testString() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/string.kt");
+ }
+
+ @Test
+ @TestMetadata("StringTemplate.kt")
+ public void testStringTemplate() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/StringTemplate.kt");
+ }
+
+ @Test
+ @TestMetadata("toOtherType.kt")
+ public void testToOtherType() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/toOtherType.kt");
+ }
+
+ @Test
+ @TestMetadata("uByte.kt")
+ public void testUByte() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uByte.kt");
+ }
+
+ @Test
+ @TestMetadata("uInt.kt")
+ public void testUInt() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uInt.kt");
+ }
+
+ @Test
+ @TestMetadata("uLong.kt")
+ public void testULong() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uLong.kt");
+ }
+
+ @Test
+ @TestMetadata("uShort.kt")
+ public void testUShort() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uShort.kt");
+ }
+
+ @Test
+ @TestMetadata("variable.kt")
+ public void testVariable() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/variable.kt");
+ }
+ }
+
+ @Nested
+ @TestMetadata("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused")
+ @TestDataPath("$PROJECT_ROOT")
+ public class Unused extends AbstractFirDiagnosticTest {
+ @Test
+ public void testAllFilesPresentInUnused() throws Exception {
+ KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
+ }
+
+ @Test
+ @TestMetadata("classProperty.kt")
+ public void testClassProperty() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/classProperty.kt");
+ }
+
+ @Test
+ @TestMetadata("invoke.kt")
+ public void testInvoke() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/invoke.kt");
+ }
+
+ @Test
+ @TestMetadata("lambda.kt")
+ public void testLambda() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/lambda.kt");
+ }
+
+ @Test
+ @TestMetadata("localVariable.kt")
+ public void testLocalVariable() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/localVariable.kt");
+ }
+
+ @Test
+ @TestMetadata("manyLocalVariables.kt")
+ public void testManyLocalVariables() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/manyLocalVariables.kt");
+ }
+
+ @Test
+ @TestMetadata("usedInAnnotationArguments.kt")
+ public void testUsedInAnnotationArguments() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/usedInAnnotationArguments.kt");
+ }
+
+ @Test
+ @TestMetadata("valueIsNeverRead.kt")
+ public void testValueIsNeverRead() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/valueIsNeverRead.kt");
+ }
+ }
+
+ @Nested
+ @TestMetadata("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker")
+ @TestDataPath("$PROJECT_ROOT")
+ public class UselessCallOnNotNullChecker extends AbstractFirDiagnosticTest {
+ @Test
+ public void testAllFilesPresentInUselessCallOnNotNullChecker() throws Exception {
+ KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
+ }
+
+ @Test
+ @TestMetadata("Basic.kt")
+ public void testBasic() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/Basic.kt");
+ }
+
+ @Test
+ @TestMetadata("NotNullType.kt")
+ public void testNotNullType() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NotNullType.kt");
+ }
+
+ @Test
+ @TestMetadata("NotNullTypeChain.kt")
+ public void testNotNullTypeChain() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NotNullTypeChain.kt");
+ }
+
+ @Test
+ @TestMetadata("NullOrBlankSafe.kt")
+ public void testNullOrBlankSafe() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrBlankSafe.kt");
+ }
+
+ @Test
+ @TestMetadata("NullOrEmpty.kt")
+ public void testNullOrEmpty() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmpty.kt");
+ }
+
+ @Test
+ @TestMetadata("NullOrEmptyFake.kt")
+ public void testNullOrEmptyFake() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmptyFake.kt");
+ }
+
+ @Test
+ @TestMetadata("NullOrEmptySafe.kt")
+ public void testNullOrEmptySafe() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmptySafe.kt");
+ }
+
+ @Test
+ @TestMetadata("OrEmptyFake.kt")
+ public void testOrEmptyFake() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/OrEmptyFake.kt");
+ }
+
+ @Test
+ @TestMetadata("SafeCall.kt")
+ public void testSafeCall() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/SafeCall.kt");
+ }
+
+ @Test
+ @TestMetadata("Sequence.kt")
+ public void testSequence() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/Sequence.kt");
+ }
+
+ @Test
+ @TestMetadata("String.kt")
+ public void testString() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/String.kt");
+ }
+ }
+ }
+
@Nested
@TestMetadata("compiler/fir/analysis-tests/testData/resolve/fromBuilder")
@TestDataPath("$PROJECT_ROOT")
diff --git a/compiler/tests-common-new/tests-gen/org/jetbrains/kotlin/test/runners/FirDiagnosticsWithLightTreeTestGenerated.java b/compiler/fir/analysis-tests/tests-gen/org/jetbrains/kotlin/test/runners/FirDiagnosticsWithLightTreeTestGenerated.java
similarity index 85%
rename from compiler/tests-common-new/tests-gen/org/jetbrains/kotlin/test/runners/FirDiagnosticsWithLightTreeTestGenerated.java
rename to compiler/fir/analysis-tests/tests-gen/org/jetbrains/kotlin/test/runners/FirDiagnosticsWithLightTreeTestGenerated.java
index 95c5bdf1c1a..aa281345df5 100644
--- a/compiler/tests-common-new/tests-gen/org/jetbrains/kotlin/test/runners/FirDiagnosticsWithLightTreeTestGenerated.java
+++ b/compiler/fir/analysis-tests/tests-gen/org/jetbrains/kotlin/test/runners/FirDiagnosticsWithLightTreeTestGenerated.java
@@ -1944,6 +1944,468 @@ public class FirDiagnosticsWithLightTreeTestGenerated extends AbstractFirDiagnos
}
}
+ @Nested
+ @TestMetadata("compiler/fir/analysis-tests/testData/resolve/extendedCheckers")
+ @TestDataPath("$PROJECT_ROOT")
+ public class ExtendedCheckers extends AbstractFirDiagnosticsWithLightTreeTest {
+ @Test
+ public void testAllFilesPresentInExtendedCheckers() throws Exception {
+ KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/resolve/extendedCheckers"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
+ }
+
+ @Test
+ @TestMetadata("ArrayEqualityCanBeReplacedWithEquals.kt")
+ public void testArrayEqualityCanBeReplacedWithEquals() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/ArrayEqualityCanBeReplacedWithEquals.kt");
+ }
+
+ @Test
+ @TestMetadata("CanBeValChecker.kt")
+ public void testCanBeValChecker() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/CanBeValChecker.kt");
+ }
+
+ @Test
+ @TestMetadata("RedundantExplicitTypeChecker.kt")
+ public void testRedundantExplicitTypeChecker() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantExplicitTypeChecker.kt");
+ }
+
+ @Test
+ @TestMetadata("RedundantModalityModifierChecker.kt")
+ public void testRedundantModalityModifierChecker() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantModalityModifierChecker.kt");
+ }
+
+ @Test
+ @TestMetadata("RedundantReturnUnitTypeChecker.kt")
+ public void testRedundantReturnUnitTypeChecker() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantReturnUnitTypeChecker.kt");
+ }
+
+ @Test
+ @TestMetadata("RedundantSetterParameterTypeChecker.kt")
+ public void testRedundantSetterParameterTypeChecker() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantSetterParameterTypeChecker.kt");
+ }
+
+ @Test
+ @TestMetadata("RedundantSingleExpressionStringTemplateChecker.kt")
+ public void testRedundantSingleExpressionStringTemplateChecker() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantSingleExpressionStringTemplateChecker.kt");
+ }
+
+ @Test
+ @TestMetadata("RedundantVisibilityModifierChecker.kt")
+ public void testRedundantVisibilityModifierChecker() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantVisibilityModifierChecker.kt");
+ }
+
+ @Nested
+ @TestMetadata("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment")
+ @TestDataPath("$PROJECT_ROOT")
+ public class CanBeReplacedWithOperatorAssignment extends AbstractFirDiagnosticsWithLightTreeTest {
+ @Test
+ public void testAllFilesPresentInCanBeReplacedWithOperatorAssignment() throws Exception {
+ KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
+ }
+
+ @Test
+ @TestMetadata("BasicTest.kt")
+ public void testBasicTest() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/BasicTest.kt");
+ }
+
+ @Test
+ @TestMetadata("ComplexExpression.kt")
+ public void testComplexExpression() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/ComplexExpression.kt");
+ }
+
+ @Test
+ @TestMetadata("flexibleTypeBug.kt")
+ public void testFlexibleTypeBug() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/flexibleTypeBug.kt");
+ }
+
+ @Test
+ @TestMetadata("illegalMultipleOperators.kt")
+ public void testIllegalMultipleOperators() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/illegalMultipleOperators.kt");
+ }
+
+ @Test
+ @TestMetadata("illegalMultipleOperatorsMiddle.kt")
+ public void testIllegalMultipleOperatorsMiddle() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/illegalMultipleOperatorsMiddle.kt");
+ }
+
+ @Test
+ @TestMetadata("invalidSubtraction.kt")
+ public void testInvalidSubtraction() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/invalidSubtraction.kt");
+ }
+
+ @Test
+ @TestMetadata("list.kt")
+ public void testList() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/list.kt");
+ }
+
+ @Test
+ @TestMetadata("logicOperators.kt")
+ public void testLogicOperators() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/logicOperators.kt");
+ }
+
+ @Test
+ @TestMetadata("multipleOperators.kt")
+ public void testMultipleOperators() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperators.kt");
+ }
+
+ @Test
+ @TestMetadata("multipleOperatorsRightSideRepeat.kt")
+ public void testMultipleOperatorsRightSideRepeat() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/multipleOperatorsRightSideRepeat.kt");
+ }
+
+ @Test
+ @TestMetadata("mutableList.kt")
+ public void testMutableList() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/mutableList.kt");
+ }
+
+ @Test
+ @TestMetadata("nonCommutativeRepeat.kt")
+ public void testNonCommutativeRepeat() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/nonCommutativeRepeat.kt");
+ }
+
+ @Test
+ @TestMetadata("nonRepeatingAssignment.kt")
+ public void testNonRepeatingAssignment() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/nonRepeatingAssignment.kt");
+ }
+
+ @Test
+ @TestMetadata("OperatorAssignment.kt")
+ public void testOperatorAssignment() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/OperatorAssignment.kt");
+ }
+
+ @Test
+ @TestMetadata("plusAssignConflict.kt")
+ public void testPlusAssignConflict() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/plusAssignConflict.kt");
+ }
+
+ @Test
+ @TestMetadata("rightSideRepeat.kt")
+ public void testRightSideRepeat() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/rightSideRepeat.kt");
+ }
+
+ @Test
+ @TestMetadata("simpleAssign.kt")
+ public void testSimpleAssign() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/simpleAssign.kt");
+ }
+
+ @Test
+ @TestMetadata("validAddition.kt")
+ public void testValidAddition() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/validAddition.kt");
+ }
+
+ @Test
+ @TestMetadata("validSubtraction.kt")
+ public void testValidSubtraction() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/canBeReplacedWithOperatorAssignment/validSubtraction.kt");
+ }
+ }
+
+ @Nested
+ @TestMetadata("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/emptyRangeChecker")
+ @TestDataPath("$PROJECT_ROOT")
+ public class EmptyRangeChecker extends AbstractFirDiagnosticsWithLightTreeTest {
+ @Test
+ public void testAllFilesPresentInEmptyRangeChecker() throws Exception {
+ KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/emptyRangeChecker"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
+ }
+
+ @Test
+ @TestMetadata("NoWarning.kt")
+ public void testNoWarning() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/emptyRangeChecker/NoWarning.kt");
+ }
+
+ @Test
+ @TestMetadata("Warning.kt")
+ public void testWarning() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/emptyRangeChecker/Warning.kt");
+ }
+ }
+
+ @Nested
+ @TestMetadata("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod")
+ @TestDataPath("$PROJECT_ROOT")
+ public class RedundantCallOfConversionMethod extends AbstractFirDiagnosticsWithLightTreeTest {
+ @Test
+ public void testAllFilesPresentInRedundantCallOfConversionMethod() throws Exception {
+ KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
+ }
+
+ @Test
+ @TestMetadata("booleanToInt.kt")
+ public void testBooleanToInt() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/booleanToInt.kt");
+ }
+
+ @Test
+ @TestMetadata("byte.kt")
+ public void testByte() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/byte.kt");
+ }
+
+ @Test
+ @TestMetadata("char.kt")
+ public void testChar() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/char.kt");
+ }
+
+ @Test
+ @TestMetadata("double.kt")
+ public void testDouble() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/double.kt");
+ }
+
+ @Test
+ @TestMetadata("float.kt")
+ public void testFloat() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/float.kt");
+ }
+
+ @Test
+ @TestMetadata("int.kt")
+ public void testInt() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/int.kt");
+ }
+
+ @Test
+ @TestMetadata("long.kt")
+ public void testLong() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/long.kt");
+ }
+
+ @Test
+ @TestMetadata("nullable.kt")
+ public void testNullable() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/nullable.kt");
+ }
+
+ @Test
+ @TestMetadata("nullable2.kt")
+ public void testNullable2() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/nullable2.kt");
+ }
+
+ @Test
+ @TestMetadata("safeString.kt")
+ public void testSafeString() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/safeString.kt");
+ }
+
+ @Test
+ @TestMetadata("safeString2.kt")
+ public void testSafeString2() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/safeString2.kt");
+ }
+
+ @Test
+ @TestMetadata("short.kt")
+ public void testShort() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/short.kt");
+ }
+
+ @Test
+ @TestMetadata("string.kt")
+ public void testString() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/string.kt");
+ }
+
+ @Test
+ @TestMetadata("StringTemplate.kt")
+ public void testStringTemplate() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/StringTemplate.kt");
+ }
+
+ @Test
+ @TestMetadata("toOtherType.kt")
+ public void testToOtherType() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/toOtherType.kt");
+ }
+
+ @Test
+ @TestMetadata("uByte.kt")
+ public void testUByte() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uByte.kt");
+ }
+
+ @Test
+ @TestMetadata("uInt.kt")
+ public void testUInt() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uInt.kt");
+ }
+
+ @Test
+ @TestMetadata("uLong.kt")
+ public void testULong() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uLong.kt");
+ }
+
+ @Test
+ @TestMetadata("uShort.kt")
+ public void testUShort() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/uShort.kt");
+ }
+
+ @Test
+ @TestMetadata("variable.kt")
+ public void testVariable() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/RedundantCallOfConversionMethod/variable.kt");
+ }
+ }
+
+ @Nested
+ @TestMetadata("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused")
+ @TestDataPath("$PROJECT_ROOT")
+ public class Unused extends AbstractFirDiagnosticsWithLightTreeTest {
+ @Test
+ public void testAllFilesPresentInUnused() throws Exception {
+ KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
+ }
+
+ @Test
+ @TestMetadata("classProperty.kt")
+ public void testClassProperty() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/classProperty.kt");
+ }
+
+ @Test
+ @TestMetadata("invoke.kt")
+ public void testInvoke() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/invoke.kt");
+ }
+
+ @Test
+ @TestMetadata("lambda.kt")
+ public void testLambda() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/lambda.kt");
+ }
+
+ @Test
+ @TestMetadata("localVariable.kt")
+ public void testLocalVariable() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/localVariable.kt");
+ }
+
+ @Test
+ @TestMetadata("manyLocalVariables.kt")
+ public void testManyLocalVariables() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/manyLocalVariables.kt");
+ }
+
+ @Test
+ @TestMetadata("usedInAnnotationArguments.kt")
+ public void testUsedInAnnotationArguments() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/usedInAnnotationArguments.kt");
+ }
+
+ @Test
+ @TestMetadata("valueIsNeverRead.kt")
+ public void testValueIsNeverRead() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/unused/valueIsNeverRead.kt");
+ }
+ }
+
+ @Nested
+ @TestMetadata("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker")
+ @TestDataPath("$PROJECT_ROOT")
+ public class UselessCallOnNotNullChecker extends AbstractFirDiagnosticsWithLightTreeTest {
+ @Test
+ public void testAllFilesPresentInUselessCallOnNotNullChecker() throws Exception {
+ KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker"), Pattern.compile("^([^.]+)\\.kt$"), null, true);
+ }
+
+ @Test
+ @TestMetadata("Basic.kt")
+ public void testBasic() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/Basic.kt");
+ }
+
+ @Test
+ @TestMetadata("NotNullType.kt")
+ public void testNotNullType() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NotNullType.kt");
+ }
+
+ @Test
+ @TestMetadata("NotNullTypeChain.kt")
+ public void testNotNullTypeChain() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NotNullTypeChain.kt");
+ }
+
+ @Test
+ @TestMetadata("NullOrBlankSafe.kt")
+ public void testNullOrBlankSafe() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrBlankSafe.kt");
+ }
+
+ @Test
+ @TestMetadata("NullOrEmpty.kt")
+ public void testNullOrEmpty() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmpty.kt");
+ }
+
+ @Test
+ @TestMetadata("NullOrEmptyFake.kt")
+ public void testNullOrEmptyFake() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmptyFake.kt");
+ }
+
+ @Test
+ @TestMetadata("NullOrEmptySafe.kt")
+ public void testNullOrEmptySafe() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/NullOrEmptySafe.kt");
+ }
+
+ @Test
+ @TestMetadata("OrEmptyFake.kt")
+ public void testOrEmptyFake() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/OrEmptyFake.kt");
+ }
+
+ @Test
+ @TestMetadata("SafeCall.kt")
+ public void testSafeCall() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/SafeCall.kt");
+ }
+
+ @Test
+ @TestMetadata("Sequence.kt")
+ public void testSequence() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/Sequence.kt");
+ }
+
+ @Test
+ @TestMetadata("String.kt")
+ public void testString() throws Exception {
+ runTest("compiler/fir/analysis-tests/testData/resolve/extendedCheckers/UselessCallOnNotNullChecker/String.kt");
+ }
+ }
+ }
+
@Nested
@TestMetadata("compiler/fir/analysis-tests/testData/resolve/fromBuilder")
@TestDataPath("$PROJECT_ROOT")
diff --git a/compiler/tests-common-new/tests-gen/org/jetbrains/kotlin/test/runners/FirOldFrontendDiagnosticsTestGenerated.java b/compiler/fir/analysis-tests/tests-gen/org/jetbrains/kotlin/test/runners/FirOldFrontendDiagnosticsTestGenerated.java
similarity index 99%
rename from compiler/tests-common-new/tests-gen/org/jetbrains/kotlin/test/runners/FirOldFrontendDiagnosticsTestGenerated.java
rename to compiler/fir/analysis-tests/tests-gen/org/jetbrains/kotlin/test/runners/FirOldFrontendDiagnosticsTestGenerated.java
index 5e40236383c..6a8aa712660 100644
--- a/compiler/tests-common-new/tests-gen/org/jetbrains/kotlin/test/runners/FirOldFrontendDiagnosticsTestGenerated.java
+++ b/compiler/fir/analysis-tests/tests-gen/org/jetbrains/kotlin/test/runners/FirOldFrontendDiagnosticsTestGenerated.java
@@ -3004,6 +3004,12 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirDiagnosti
runTest("compiler/testData/diagnostics/tests/callableReference/property/memberFromTopLevel.kt");
}
+ @Test
+ @TestMetadata("propertyFromAbstractSuperClass.kt")
+ public void testPropertyFromAbstractSuperClass() throws Exception {
+ runTest("compiler/testData/diagnostics/tests/callableReference/property/propertyFromAbstractSuperClass.kt");
+ }
+
@Test
@TestMetadata("protectedVarFromClass.kt")
public void testProtectedVarFromClass() throws Exception {
@@ -6951,6 +6957,12 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirDiagnosti
runTest("compiler/testData/diagnostics/tests/delegatedProperty/incompleteTypeInference.kt");
}
+ @Test
+ @TestMetadata("kt37796.kt")
+ public void testKt37796() throws Exception {
+ runTest("compiler/testData/diagnostics/tests/delegatedProperty/kt37796.kt");
+ }
+
@Test
@TestMetadata("kt4640.kt")
public void testKt4640() throws Exception {
@@ -9100,6 +9112,22 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirDiagnosti
}
}
+ @Nested
+ @TestMetadata("compiler/testData/diagnostics/tests/exceptions")
+ @TestDataPath("$PROJECT_ROOT")
+ public class Exceptions extends AbstractFirDiagnosticTest {
+ @Test
+ public void testAllFilesPresentInExceptions() throws Exception {
+ KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/testData/diagnostics/tests/exceptions"), Pattern.compile("^(.+)\\.kt$"), Pattern.compile("^(.+)\\.fir\\.kts?$"), true);
+ }
+
+ @Test
+ @TestMetadata("kt24158.kt")
+ public void testKt24158() throws Exception {
+ runTest("compiler/testData/diagnostics/tests/exceptions/kt24158.kt");
+ }
+ }
+
@Nested
@TestMetadata("compiler/testData/diagnostics/tests/exposed")
@TestDataPath("$PROJECT_ROOT")
@@ -12145,6 +12173,12 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirDiagnosti
runTest("compiler/testData/diagnostics/tests/inference/reportAboutUnresolvedReferenceAsUnresolved.kt");
}
+ @Test
+ @TestMetadata("reportNotEnoughTypeInformationErrorsOnBlockExpressions.kt")
+ public void testReportNotEnoughTypeInformationErrorsOnBlockExpressions() throws Exception {
+ runTest("compiler/testData/diagnostics/tests/inference/reportNotEnoughTypeInformationErrorsOnBlockExpressions.kt");
+ }
+
@Test
@TestMetadata("resolveWithUnknownLambdaParameterType.kt")
public void testResolveWithUnknownLambdaParameterType() throws Exception {
@@ -12158,15 +12192,9 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirDiagnosti
}
@Test
- @TestMetadata("simpleLambdaInCallWithAnotherLambdaWithBuilderInference.kt")
- public void testSimpleLambdaInCallWithAnotherLambdaWithBuilderInference() throws Exception {
- runTest("compiler/testData/diagnostics/tests/inference/simpleLambdaInCallWithAnotherLambdaWithBuilderInference.kt");
- }
-
- @Test
- @TestMetadata("skipedUnresolvedInBuilderInferenceWithStubReceiverType.kt")
- public void testSkipedUnresolvedInBuilderInferenceWithStubReceiverType() throws Exception {
- runTest("compiler/testData/diagnostics/tests/inference/skipedUnresolvedInBuilderInferenceWithStubReceiverType.kt");
+ @TestMetadata("specialCallsWithCallableReferences.kt")
+ public void testSpecialCallsWithCallableReferences() throws Exception {
+ runTest("compiler/testData/diagnostics/tests/inference/specialCallsWithCallableReferences.kt");
}
@Test
@@ -12235,6 +12263,64 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirDiagnosti
runTest("compiler/testData/diagnostics/tests/inference/useFunctionLiteralsToInferType.kt");
}
+ @Nested
+ @TestMetadata("compiler/testData/diagnostics/tests/inference/builderInference")
+ @TestDataPath("$PROJECT_ROOT")
+ public class BuilderInference extends AbstractFirDiagnosticTest {
+ @Test
+ public void testAllFilesPresentInBuilderInference() throws Exception {
+ KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/testData/diagnostics/tests/inference/builderInference"), Pattern.compile("^(.+)\\.kt$"), Pattern.compile("^(.+)\\.fir\\.kts?$"), true);
+ }
+
+ @Test
+ @TestMetadata("simpleLambdaInCallWithAnotherLambdaWithBuilderInference.kt")
+ public void testSimpleLambdaInCallWithAnotherLambdaWithBuilderInference() throws Exception {
+ runTest("compiler/testData/diagnostics/tests/inference/builderInference/simpleLambdaInCallWithAnotherLambdaWithBuilderInference.kt");
+ }
+
+ @Test
+ @TestMetadata("skipedUnresolvedInBuilderInferenceWithStubReceiverType.kt")
+ public void testSkipedUnresolvedInBuilderInferenceWithStubReceiverType() throws Exception {
+ runTest("compiler/testData/diagnostics/tests/inference/builderInference/skipedUnresolvedInBuilderInferenceWithStubReceiverType.kt");
+ }
+
+ @Test
+ @TestMetadata("specialCallsWithCallableReferences.kt")
+ public void testSpecialCallsWithCallableReferences() throws Exception {
+ runTest("compiler/testData/diagnostics/tests/inference/builderInference/specialCallsWithCallableReferences.kt");
+ }
+
+ @Test
+ @TestMetadata("specialCallsWithCallableReferencesDontCareTypeInBlockExression.kt")
+ public void testSpecialCallsWithCallableReferencesDontCareTypeInBlockExression() throws Exception {
+ runTest("compiler/testData/diagnostics/tests/inference/builderInference/specialCallsWithCallableReferencesDontCareTypeInBlockExression.kt");
+ }
+
+ @Test
+ @TestMetadata("specialCallsWithCallableReferencesDontRewriteAtSlice.kt")
+ public void testSpecialCallsWithCallableReferencesDontRewriteAtSlice() throws Exception {
+ runTest("compiler/testData/diagnostics/tests/inference/builderInference/specialCallsWithCallableReferencesDontRewriteAtSlice.kt");
+ }
+
+ @Test
+ @TestMetadata("specialCallsWithCallableReferencesErrorType.kt")
+ public void testSpecialCallsWithCallableReferencesErrorType() throws Exception {
+ runTest("compiler/testData/diagnostics/tests/inference/builderInference/specialCallsWithCallableReferencesErrorType.kt");
+ }
+
+ @Test
+ @TestMetadata("specialCallsWithCallableReferencesNonStrictOnlyInputTypes.kt")
+ public void testSpecialCallsWithCallableReferencesNonStrictOnlyInputTypes() throws Exception {
+ runTest("compiler/testData/diagnostics/tests/inference/builderInference/specialCallsWithCallableReferencesNonStrictOnlyInputTypes.kt");
+ }
+
+ @Test
+ @TestMetadata("specialCallsWithLambdas.kt")
+ public void testSpecialCallsWithLambdas() throws Exception {
+ runTest("compiler/testData/diagnostics/tests/inference/builderInference/specialCallsWithLambdas.kt");
+ }
+ }
+
@Nested
@TestMetadata("compiler/testData/diagnostics/tests/inference/capturedTypes")
@TestDataPath("$PROJECT_ROOT")
@@ -28208,6 +28294,96 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirDiagnosti
}
}
+ @Nested
+ @TestMetadata("compiler/testData/diagnostics/tests/testsWithJava15")
+ @TestDataPath("$PROJECT_ROOT")
+ public class TestsWithJava15 extends AbstractFirDiagnosticTest {
+ @Test
+ public void testAllFilesPresentInTestsWithJava15() throws Exception {
+ KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/testData/diagnostics/tests/testsWithJava15"), Pattern.compile("^(.+)\\.kt$"), Pattern.compile("^(.+)\\.fir\\.kts?$"), true);
+ }
+
+ @Nested
+ @TestMetadata("compiler/testData/diagnostics/tests/testsWithJava15/jvmRecord")
+ @TestDataPath("$PROJECT_ROOT")
+ public class JvmRecord extends AbstractFirDiagnosticTest {
+ @Test
+ public void testAllFilesPresentInJvmRecord() throws Exception {
+ KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/testData/diagnostics/tests/testsWithJava15/jvmRecord"), Pattern.compile("^(.+)\\.kt$"), Pattern.compile("^(.+)\\.fir\\.kts?$"), true);
+ }
+
+ @Test
+ @TestMetadata("diagnostics.kt")
+ public void testDiagnostics() throws Exception {
+ runTest("compiler/testData/diagnostics/tests/testsWithJava15/jvmRecord/diagnostics.kt");
+ }
+
+ @Test
+ @TestMetadata("disabledFeature.kt")
+ public void testDisabledFeature() throws Exception {
+ runTest("compiler/testData/diagnostics/tests/testsWithJava15/jvmRecord/disabledFeature.kt");
+ }
+
+ @Test
+ @TestMetadata("irrelevantFields.kt")
+ public void testIrrelevantFields() throws Exception {
+ runTest("compiler/testData/diagnostics/tests/testsWithJava15/jvmRecord/irrelevantFields.kt");
+ }
+
+ @Test
+ @TestMetadata("jvmRecordDescriptorStructure.kt")
+ public void testJvmRecordDescriptorStructure() throws Exception {
+ runTest("compiler/testData/diagnostics/tests/testsWithJava15/jvmRecord/jvmRecordDescriptorStructure.kt");
+ }
+
+ @Test
+ @TestMetadata("simpleRecords.kt")
+ public void testSimpleRecords() throws Exception {
+ runTest("compiler/testData/diagnostics/tests/testsWithJava15/jvmRecord/simpleRecords.kt");
+ }
+
+ @Test
+ @TestMetadata("supertypesCheck.kt")
+ public void testSupertypesCheck() throws Exception {
+ runTest("compiler/testData/diagnostics/tests/testsWithJava15/jvmRecord/supertypesCheck.kt");
+ }
+ }
+
+ @Nested
+ @TestMetadata("compiler/testData/diagnostics/tests/testsWithJava15/sealedClasses")
+ @TestDataPath("$PROJECT_ROOT")
+ public class SealedClasses extends AbstractFirDiagnosticTest {
+ @Test
+ public void testAllFilesPresentInSealedClasses() throws Exception {
+ KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/testData/diagnostics/tests/testsWithJava15/sealedClasses"), Pattern.compile("^(.+)\\.kt$"), Pattern.compile("^(.+)\\.fir\\.kts?$"), true);
+ }
+
+ @Test
+ @TestMetadata("javaSealedClassExhaustiveness.kt")
+ public void testJavaSealedClassExhaustiveness() throws Exception {
+ runTest("compiler/testData/diagnostics/tests/testsWithJava15/sealedClasses/javaSealedClassExhaustiveness.kt");
+ }
+
+ @Test
+ @TestMetadata("javaSealedInterfaceExhaustiveness.kt")
+ public void testJavaSealedInterfaceExhaustiveness() throws Exception {
+ runTest("compiler/testData/diagnostics/tests/testsWithJava15/sealedClasses/javaSealedInterfaceExhaustiveness.kt");
+ }
+
+ @Test
+ @TestMetadata("kotlinInheritsJavaClass.kt")
+ public void testKotlinInheritsJavaClass() throws Exception {
+ runTest("compiler/testData/diagnostics/tests/testsWithJava15/sealedClasses/kotlinInheritsJavaClass.kt");
+ }
+
+ @Test
+ @TestMetadata("kotlinInheritsJavaInterface.kt")
+ public void testKotlinInheritsJavaInterface() throws Exception {
+ runTest("compiler/testData/diagnostics/tests/testsWithJava15/sealedClasses/kotlinInheritsJavaInterface.kt");
+ }
+ }
+ }
+
@Nested
@TestMetadata("compiler/testData/diagnostics/tests/thisAndSuper")
@TestDataPath("$PROJECT_ROOT")
@@ -28557,6 +28733,12 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirDiagnosti
runTest("compiler/testData/diagnostics/tests/typealias/boundsViolationInTypeAliasRHS.kt");
}
+ @Test
+ @TestMetadata("boundsViolationRecursive.kt")
+ public void testBoundsViolationRecursive() throws Exception {
+ runTest("compiler/testData/diagnostics/tests/typealias/boundsViolationRecursive.kt");
+ }
+
@Test
@TestMetadata("capturingTypeParametersFromOuterClass.kt")
public void testCapturingTypeParametersFromOuterClass() throws Exception {
@@ -28731,6 +28913,12 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirDiagnosti
runTest("compiler/testData/diagnostics/tests/typealias/kt14518.kt");
}
+ @Test
+ @TestMetadata("kt14612.kt")
+ public void testKt14612() throws Exception {
+ runTest("compiler/testData/diagnostics/tests/typealias/kt14612.kt");
+ }
+
@Test
@TestMetadata("kt14641.kt")
public void testKt14641() throws Exception {
diff --git a/compiler/fir/analysis-tests/tests/org/jetbrains/kotlin/fir/AbstractFirResolveTestCaseWithStdlib.kt b/compiler/fir/analysis-tests/tests/org/jetbrains/kotlin/fir/AbstractFirResolveTestCaseWithStdlib.kt
deleted file mode 100644
index 7349332a74d..00000000000
--- a/compiler/fir/analysis-tests/tests/org/jetbrains/kotlin/fir/AbstractFirResolveTestCaseWithStdlib.kt
+++ /dev/null
@@ -1,15 +0,0 @@
-/*
- * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
- * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
- */
-
-package org.jetbrains.kotlin.fir
-
-import org.jetbrains.kotlin.test.ConfigurationKind
-
-abstract class AbstractFirDiagnosticsWithStdlibTest : AbstractFirDiagnosticsTest() {
-
- override fun extractConfigurationKind(files: List): ConfigurationKind {
- return ConfigurationKind.ALL
- }
-}
diff --git a/compiler/fir/checkers/src/org/jetbrains/kotlin/fir/analysis/checkers/FirHelpers.kt b/compiler/fir/checkers/src/org/jetbrains/kotlin/fir/analysis/checkers/FirHelpers.kt
index 7ce2f17043d..2b5a7f6f0d4 100644
--- a/compiler/fir/checkers/src/org/jetbrains/kotlin/fir/analysis/checkers/FirHelpers.kt
+++ b/compiler/fir/checkers/src/org/jetbrains/kotlin/fir/analysis/checkers/FirHelpers.kt
@@ -288,12 +288,12 @@ private fun FirDeclaration.hasBody(): Boolean = when (this) {
*/
fun FirClass<*>.findNonInterfaceSupertype(context: CheckerContext): FirTypeRef? {
for (it in superTypeRefs) {
- val classId = it.safeAs()
+ val lookupTag = it.safeAs()
?.type.safeAs()
- ?.lookupTag?.classId
+ ?.lookupTag
?: continue
- val fir = context.session.firSymbolProvider.getClassLikeSymbolByFqName(classId)
+ val fir = lookupTag.toSymbol(context.session)
?.fir.safeAs>()
?: continue
diff --git a/compiler/fir/checkers/src/org/jetbrains/kotlin/fir/analysis/checkers/declaration/FirSealedClassConstructorCallChecker.kt b/compiler/fir/checkers/src/org/jetbrains/kotlin/fir/analysis/checkers/declaration/FirSealedClassConstructorCallChecker.kt
index d6610c355e0..1a014103fec 100644
--- a/compiler/fir/checkers/src/org/jetbrains/kotlin/fir/analysis/checkers/declaration/FirSealedClassConstructorCallChecker.kt
+++ b/compiler/fir/checkers/src/org/jetbrains/kotlin/fir/analysis/checkers/declaration/FirSealedClassConstructorCallChecker.kt
@@ -13,13 +13,11 @@ import org.jetbrains.kotlin.fir.analysis.diagnostics.DiagnosticReporter
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors
import org.jetbrains.kotlin.fir.declarations.FirConstructor
import org.jetbrains.kotlin.fir.declarations.FirRegularClass
-import org.jetbrains.kotlin.fir.declarations.classId
import org.jetbrains.kotlin.fir.expressions.FirQualifiedAccessExpression
import org.jetbrains.kotlin.fir.references.FirResolvedNamedReference
-import org.jetbrains.kotlin.fir.resolve.firSymbolProvider
+import org.jetbrains.kotlin.fir.resolve.toSymbol
import org.jetbrains.kotlin.fir.types.ConeClassLikeType
import org.jetbrains.kotlin.fir.types.FirResolvedTypeRef
-import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
object FirSealedClassConstructorCallChecker : FirQualifiedAccessChecker() {
@@ -29,13 +27,10 @@ object FirSealedClassConstructorCallChecker : FirQualifiedAccessChecker() {
?.fir.safeAs()
?: return
- val typeClassId = constructorFir.returnTypeRef.safeAs()
+ val typeFir = constructorFir.returnTypeRef.safeAs()
?.type.safeAs()
- ?.lookupTag
- ?.classId
- ?: return
-
- val typeFir = typeClassId.toRegularClass(context)
+ ?.lookupTag?.toSymbol(context.session)
+ ?.fir as? FirRegularClass
?: return
if (typeFir.status.modality == Modality.SEALED) {
@@ -43,15 +38,6 @@ object FirSealedClassConstructorCallChecker : FirQualifiedAccessChecker() {
}
}
- private fun ClassId.toRegularClass(context: CheckerContext): FirRegularClass? = if (!isLocal) {
- context.session.firSymbolProvider.getClassLikeSymbolByFqName(this)
- ?.fir.safeAs()
- } else {
- context.containingDeclarations
- .lastOrNull { it.safeAs()?.classId == this }
- .safeAs()
- }
-
private fun DiagnosticReporter.report(source: FirSourceElement?) {
source?.let { report(FirErrors.SEALED_CLASS_CONSTRUCTOR_CALL.on(it)) }
}
diff --git a/compiler/fir/fir2ir/build.gradle.kts b/compiler/fir/fir2ir/build.gradle.kts
index 78323a18eb1..df30ec3e8b2 100644
--- a/compiler/fir/fir2ir/build.gradle.kts
+++ b/compiler/fir/fir2ir/build.gradle.kts
@@ -25,7 +25,7 @@ dependencies {
testCompileOnly(project(":kotlin-test:kotlin-test-jvm"))
testCompileOnly(project(":kotlin-test:kotlin-test-junit"))
testApi(projectTests(":compiler:tests-common"))
- testApi(projectTests(":compiler:fir:analysis-tests"))
+ testApi(projectTests(":compiler:fir:analysis-tests:legacy-fir-tests"))
testApi(project(":compiler:resolution.common"))
testCompileOnly(project(":kotlin-reflect-api"))
diff --git a/compiler/fir/fir2ir/jvm-backend/src/org/jetbrains/kotlin/fir/backend/jvm/FirJvmBackendExtension.kt b/compiler/fir/fir2ir/jvm-backend/src/org/jetbrains/kotlin/fir/backend/jvm/FirJvmBackendExtension.kt
new file mode 100644
index 00000000000..058449161fa
--- /dev/null
+++ b/compiler/fir/fir2ir/jvm-backend/src/org/jetbrains/kotlin/fir/backend/jvm/FirJvmBackendExtension.kt
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
+ * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
+ */
+
+package org.jetbrains.kotlin.fir.backend.jvm
+
+import org.jetbrains.kotlin.backend.jvm.JvmBackendContext
+import org.jetbrains.kotlin.backend.jvm.JvmBackendExtension
+import org.jetbrains.kotlin.backend.jvm.codegen.MetadataSerializer
+import org.jetbrains.kotlin.codegen.serialization.JvmSerializationBindings
+import org.jetbrains.kotlin.config.JvmAbiStability
+import org.jetbrains.kotlin.fir.FirSession
+import org.jetbrains.kotlin.fir.backend.Fir2IrComponents
+import org.jetbrains.kotlin.ir.declarations.IrClass
+import org.jetbrains.kotlin.load.java.JvmAnnotationNames
+import org.jetbrains.org.objectweb.asm.Type
+
+class FirJvmBackendExtension(private val session: FirSession, private val components: Fir2IrComponents) : JvmBackendExtension {
+ override fun createSerializer(
+ context: JvmBackendContext,
+ klass: IrClass,
+ type: Type,
+ bindings: JvmSerializationBindings,
+ parentSerializer: MetadataSerializer?
+ ): MetadataSerializer {
+ return FirMetadataSerializer(session, context, klass, bindings, components, parentSerializer)
+ }
+
+ override fun generateMetadataExtraFlags(abiStability: JvmAbiStability?): Int =
+ JvmAnnotationNames.METADATA_JVM_IR_FLAG or
+ JvmAnnotationNames.METADATA_FIR_FLAG or
+ (if (abiStability == JvmAbiStability.STABLE) JvmAnnotationNames.METADATA_JVM_IR_STABLE_ABI_FLAG else 0)
+}
diff --git a/compiler/fir/fir2ir/jvm-backend/src/org/jetbrains/kotlin/fir/backend/jvm/FirJvmTypeMapper.kt b/compiler/fir/fir2ir/jvm-backend/src/org/jetbrains/kotlin/fir/backend/jvm/FirJvmTypeMapper.kt
index 689fcfc4309..ab8b39b178f 100644
--- a/compiler/fir/fir2ir/jvm-backend/src/org/jetbrains/kotlin/fir/backend/jvm/FirJvmTypeMapper.kt
+++ b/compiler/fir/fir2ir/jvm-backend/src/org/jetbrains/kotlin/fir/backend/jvm/FirJvmTypeMapper.kt
@@ -36,6 +36,7 @@ import org.jetbrains.kotlin.types.model.SimpleTypeMarker
import org.jetbrains.kotlin.types.model.TypeConstructorMarker
import org.jetbrains.kotlin.types.model.TypeParameterMarker
import org.jetbrains.kotlin.utils.addToStdlib.runIf
+import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.org.objectweb.asm.Type
class FirJvmTypeMapper(val session: FirSession) : TypeMappingContext, FirSessionComponent {
@@ -189,7 +190,8 @@ val FirSession.jvmTypeMapper: FirJvmTypeMapper by FirSession.sessionComponentAcc
class ConeTypeSystemCommonBackendContextForTypeMapping(
val context: ConeTypeContext
) : TypeSystemCommonBackendContext by context, TypeSystemCommonBackendContextForTypeMapping {
- private val symbolProvider = context.session.firSymbolProvider
+ private val session = context.session
+ private val symbolProvider = session.firSymbolProvider
override fun TypeConstructorMarker.isTypeParameter(): Boolean {
return this is ConeTypeParameterLookupTag
@@ -200,7 +202,7 @@ class ConeTypeSystemCommonBackendContextForTypeMapping(
return when (this) {
is ConeTypeParameterLookupTag -> ConeTypeParameterTypeImpl(this, isNullable = false)
is ConeClassLikeLookupTag -> {
- val symbol = symbolProvider.getClassLikeSymbolByFqName(classId) as? FirRegularClassSymbol
+ val symbol = toSymbol(session) as? FirRegularClassSymbol
?: error("Class for $this not found")
symbol.fir.defaultType()
}
@@ -210,7 +212,7 @@ class ConeTypeSystemCommonBackendContextForTypeMapping(
override fun SimpleTypeMarker.isSuspendFunction(): Boolean {
require(this is ConeSimpleKotlinType)
- return isSuspendFunctionType(context.session)
+ return isSuspendFunctionType(session)
}
override fun SimpleTypeMarker.isKClass(): Boolean {
@@ -234,8 +236,8 @@ class ConeTypeSystemCommonBackendContextForTypeMapping(
require(this is ConeTypeParameterLookupTag)
val bounds = this.typeParameterSymbol.fir.bounds.map { it.coneType }
return bounds.firstOrNull {
- val classId = it.classId ?: return@firstOrNull false
- val classSymbol = symbolProvider.getClassLikeSymbolByFqName(classId) as? FirRegularClassSymbol ?: return@firstOrNull false
+ val classSymbol = it.safeAs()?.fullyExpandedType(session)
+ ?.lookupTag?.toSymbol(session) as? FirRegularClassSymbol ?: return@firstOrNull false
val kind = classSymbol.fir.classKind
kind != ClassKind.INTERFACE && kind != ClassKind.ANNOTATION_CLASS
} ?: bounds.first()
diff --git a/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/ConversionUtils.kt b/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/ConversionUtils.kt
index d34e472b1b6..6e8e5916690 100644
--- a/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/ConversionUtils.kt
+++ b/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/ConversionUtils.kt
@@ -35,13 +35,13 @@ import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET
import org.jetbrains.kotlin.ir.builders.declarations.UNDEFINED_PARAMETER_INDEX
import org.jetbrains.kotlin.ir.declarations.*
-import org.jetbrains.kotlin.ir.descriptors.WrappedReceiverParameterDescriptor
import org.jetbrains.kotlin.ir.expressions.IrConst
import org.jetbrains.kotlin.ir.expressions.IrConstKind
import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.ir.expressions.IrStatementOrigin
import org.jetbrains.kotlin.ir.expressions.impl.*
import org.jetbrains.kotlin.ir.symbols.*
+import org.jetbrains.kotlin.ir.symbols.impl.IrValueParameterSymbolImpl
import org.jetbrains.kotlin.ir.types.*
import org.jetbrains.kotlin.ir.types.impl.IrErrorTypeImpl
import org.jetbrains.kotlin.ir.util.SymbolTable
@@ -331,22 +331,15 @@ internal fun IrDeclarationParent.declareThisReceiverParameter(
thisOrigin: IrDeclarationOrigin,
startOffset: Int = this.startOffset,
endOffset: Int = this.endOffset
-): IrValueParameter {
- val receiverDescriptor = WrappedReceiverParameterDescriptor()
- return symbolTable.declareValueParameter(
- startOffset, endOffset, thisOrigin, receiverDescriptor, thisType
- ) { symbol ->
- symbolTable.irFactory.createValueParameter(
- startOffset, endOffset, thisOrigin, symbol,
- Name.special(""), UNDEFINED_PARAMETER_INDEX, thisType,
- varargElementType = null, isCrossinline = false, isNoinline = false,
- isHidden = false, isAssignable = false
- ).apply {
- this.parent = this@declareThisReceiverParameter
- receiverDescriptor.bind(this)
- }
+): IrValueParameter =
+ symbolTable.irFactory.createValueParameter(
+ startOffset, endOffset, thisOrigin, IrValueParameterSymbolImpl(),
+ Name.special(""), UNDEFINED_PARAMETER_INDEX, thisType,
+ varargElementType = null, isCrossinline = false, isNoinline = false,
+ isHidden = false, isAssignable = false
+ ).apply {
+ this.parent = this@declareThisReceiverParameter
}
-}
fun FirClass<*>.irOrigin(firProvider: FirProvider): IrDeclarationOrigin = when {
firProvider.getFirClassifierContainerFileIfAny(symbol) != null -> IrDeclarationOrigin.DEFINED
diff --git a/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/ExternalPackageParentPatcher.kt b/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/ExternalPackageParentPatcher.kt
new file mode 100644
index 00000000000..274b3a2069d
--- /dev/null
+++ b/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/ExternalPackageParentPatcher.kt
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
+ * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
+ */
+
+package org.jetbrains.kotlin.fir.backend
+
+import org.jetbrains.kotlin.ir.IrElement
+import org.jetbrains.kotlin.ir.ObsoleteDescriptorBasedAPI
+import org.jetbrains.kotlin.ir.declarations.*
+import org.jetbrains.kotlin.ir.expressions.IrMemberAccessExpression
+import org.jetbrains.kotlin.ir.util.DeclarationStubGenerator
+import org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid
+import org.jetbrains.kotlin.ir.visitors.acceptChildrenVoid
+
+// TODO: could be a lowering
+internal class ExternalPackageParentPatcher(private val stubGenerator: DeclarationStubGenerator) : IrElementVisitorVoid {
+ override fun visitElement(element: IrElement) {
+ element.acceptChildrenVoid(this)
+ }
+
+ override fun visitMemberAccess(expression: IrMemberAccessExpression<*>) {
+ super.visitMemberAccess(expression)
+ val callee = expression.symbol.owner as? IrDeclaration ?: return
+ if (callee.parent is IrExternalPackageFragment) {
+ @OptIn(ObsoleteDescriptorBasedAPI::class)
+ val parentClass = stubGenerator.generateOrGetFacadeClass(callee.descriptor) ?: return
+ callee.parent = parentClass
+ when (callee) {
+ is IrProperty -> handleProperty(callee, parentClass)
+ is IrSimpleFunction -> callee.correspondingPropertySymbol?.owner?.let { handleProperty(it, parentClass) }
+ }
+ }
+ }
+
+ private fun handleProperty(property: IrProperty, newParent: IrClass) {
+ property.parent = newParent
+ property.getter?.parent = newParent
+ property.setter?.parent = newParent
+ property.backingField?.parent = newParent
+ }
+}
\ No newline at end of file
diff --git a/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/Fir2IrClassifierStorage.kt b/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/Fir2IrClassifierStorage.kt
index 02e48d99049..3b8ba3a879a 100644
--- a/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/Fir2IrClassifierStorage.kt
+++ b/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/Fir2IrClassifierStorage.kt
@@ -12,31 +12,28 @@ import org.jetbrains.kotlin.descriptors.Visibility
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.lazy.Fir2IrLazyClass
import org.jetbrains.kotlin.fir.resolve.firProvider
+import org.jetbrains.kotlin.fir.resolve.firSymbolProvider
import org.jetbrains.kotlin.fir.resolve.toSymbol
-import org.jetbrains.kotlin.fir.symbols.Fir2IrClassSymbol
-import org.jetbrains.kotlin.fir.symbols.Fir2IrEnumEntrySymbol
-import org.jetbrains.kotlin.fir.symbols.Fir2IrTypeAliasSymbol
-import org.jetbrains.kotlin.fir.symbols.StandardClassIds
+import org.jetbrains.kotlin.fir.symbols.*
import org.jetbrains.kotlin.fir.symbols.impl.ConeClassLikeLookupTagImpl
import org.jetbrains.kotlin.fir.symbols.impl.FirClassSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirTypeParameterSymbol
import org.jetbrains.kotlin.fir.types.FirTypeRef
import org.jetbrains.kotlin.ir.builders.declarations.UNDEFINED_PARAMETER_INDEX
import org.jetbrains.kotlin.ir.declarations.*
-import org.jetbrains.kotlin.ir.descriptors.WrappedClassDescriptor
-import org.jetbrains.kotlin.ir.descriptors.WrappedEnumEntryDescriptor
-import org.jetbrains.kotlin.ir.descriptors.WrappedTypeAliasDescriptor
-import org.jetbrains.kotlin.ir.descriptors.WrappedTypeParameterDescriptor
import org.jetbrains.kotlin.ir.expressions.impl.IrEnumConstructorCallImpl
import org.jetbrains.kotlin.ir.symbols.IrClassSymbol
import org.jetbrains.kotlin.ir.symbols.IrEnumEntrySymbol
import org.jetbrains.kotlin.ir.symbols.IrTypeAliasSymbol
import org.jetbrains.kotlin.ir.symbols.IrTypeParameterSymbol
+import org.jetbrains.kotlin.ir.symbols.impl.IrClassSymbolImpl
+import org.jetbrains.kotlin.ir.symbols.impl.IrEnumEntrySymbolImpl
+import org.jetbrains.kotlin.ir.symbols.impl.IrTypeAliasSymbolImpl
+import org.jetbrains.kotlin.ir.symbols.impl.IrTypeParameterSymbolImpl
import org.jetbrains.kotlin.ir.types.IrType
import org.jetbrains.kotlin.ir.types.impl.IrSimpleTypeImpl
import org.jetbrains.kotlin.ir.util.IdSignature
import org.jetbrains.kotlin.ir.util.constructors
-import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.Name
class Fir2IrClassifierStorage(
@@ -143,11 +140,8 @@ class Fir2IrClassifierStorage(
}
}
- internal fun getCachedLocalClass(classId: ClassId): IrClass? {
- require(classId.isLocal) {
- "As the function name implies, it ought to be used to look up _local_ classes."
- }
- return localStorage.getLocalClass(classId)
+ internal fun getCachedLocalClass(lookupTag: ConeClassLikeLookupTag): IrClass? {
+ return localStorage.getLocalClass(lookupTag.toSymbol(session)!!.fir as FirClass<*>)
}
private fun FirRegularClass.enumClassModality(): Modality {
@@ -183,13 +177,11 @@ class Fir2IrClassifierStorage(
return irClass
}
- private fun declareIrTypeAlias(signature: IdSignature?, factory: (IrTypeAliasSymbol) -> IrTypeAlias): IrTypeAlias {
- if (signature == null) {
- val descriptor = WrappedTypeAliasDescriptor()
- return symbolTable.declareTypeAlias(descriptor, factory).apply { descriptor.bind(this) }
- }
- return symbolTable.declareTypeAlias(signature, { Fir2IrTypeAliasSymbol(signature) }, factory)
- }
+ private fun declareIrTypeAlias(signature: IdSignature?, factory: (IrTypeAliasSymbol) -> IrTypeAlias): IrTypeAlias =
+ if (signature == null)
+ factory(IrTypeAliasSymbolImpl())
+ else
+ symbolTable.declareTypeAlias(signature, { Fir2IrTypeAliasSymbol(signature) }, factory)
fun registerTypeAlias(
typeAlias: FirTypeAlias,
@@ -217,13 +209,11 @@ class Fir2IrClassifierStorage(
internal fun getCachedTypeAlias(firTypeAlias: FirTypeAlias): IrTypeAlias? = typeAliasCache[firTypeAlias]
- private fun declareIrClass(signature: IdSignature?, factory: (IrClassSymbol) -> IrClass): IrClass {
- if (signature == null) {
- val descriptor = WrappedClassDescriptor()
- return symbolTable.declareClass(descriptor, factory).apply { descriptor.bind(this) }
- }
- return symbolTable.declareClass(signature, { Fir2IrClassSymbol(signature) }, factory)
- }
+ private fun declareIrClass(signature: IdSignature?, factory: (IrClassSymbol) -> IrClass): IrClass =
+ if (signature == null)
+ factory(IrClassSymbolImpl())
+ else
+ symbolTable.declareClass(signature, { Fir2IrClassSymbol(signature) }, factory)
fun registerIrClass(
regularClass: FirRegularClass,
@@ -311,20 +301,15 @@ class Fir2IrClassifierStorage(
typeContext: ConversionTypeContext = ConversionTypeContext.DEFAULT
): IrTypeParameter {
require(index >= 0)
- val descriptor = WrappedTypeParameterDescriptor()
val origin = IrDeclarationOrigin.DEFINED
val irTypeParameter = with(typeParameter) {
convertWithOffsets { startOffset, endOffset ->
- symbolTable.declareGlobalTypeParameter(startOffset, endOffset, origin, descriptor) { symbol ->
- irFactory.createTypeParameter(
- startOffset, endOffset, origin, symbol,
- name, if (index < 0) 0 else index,
- isReified,
- variance
- ).apply {
- descriptor.bind(this)
- }
- }
+ irFactory.createTypeParameter(
+ startOffset, endOffset, origin, IrTypeParameterSymbolImpl(),
+ name, if (index < 0) 0 else index,
+ isReified,
+ variance
+ )
}
}
@@ -381,13 +366,11 @@ class Fir2IrClassifierStorage(
internal fun getCachedIrEnumEntry(enumEntry: FirEnumEntry): IrEnumEntry? = enumEntryCache[enumEntry]
- private fun declareIrEnumEntry(signature: IdSignature?, factory: (IrEnumEntrySymbol) -> IrEnumEntry): IrEnumEntry {
- if (signature == null) {
- val descriptor = WrappedEnumEntryDescriptor()
- return symbolTable.declareEnumEntry(0, 0, IrDeclarationOrigin.DEFINED, descriptor, factory).apply { descriptor.bind(this) }
- }
- return symbolTable.declareEnumEntry(signature, { Fir2IrEnumEntrySymbol(signature) }, factory)
- }
+ private fun declareIrEnumEntry(signature: IdSignature?, factory: (IrEnumEntrySymbol) -> IrEnumEntry): IrEnumEntry =
+ if (signature == null)
+ factory(IrEnumEntrySymbolImpl())
+ else
+ symbolTable.declareEnumEntry(signature, { Fir2IrEnumEntrySymbol(signature) }, factory)
fun createIrEnumEntry(
enumEntry: FirEnumEntry,
@@ -452,7 +435,8 @@ class Fir2IrClassifierStorage(
firClass as FirRegularClass
val classId = firClassSymbol.classId
val parentId = classId.outerClassId
- val irParent = declarationStorage.findIrParent(classId.packageFqName, parentId, firClassSymbol)!!
+ val parentClass = parentId?.let { session.firSymbolProvider.getClassLikeSymbolByFqName(it) }
+ val irParent = declarationStorage.findIrParent(classId.packageFqName, parentClass?.toLookupTag(), firClassSymbol)!!
val symbol = Fir2IrClassSymbol(signature)
val irClass = firClass.convertWithOffsets { startOffset, endOffset ->
symbolTable.declareClass(signature, { symbol }) {
diff --git a/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/Fir2IrConverter.kt b/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/Fir2IrConverter.kt
index 00f385371b7..58134b80893 100644
--- a/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/Fir2IrConverter.kt
+++ b/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/Fir2IrConverter.kt
@@ -22,8 +22,8 @@ import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.declarations.impl.IrFileImpl
import org.jetbrains.kotlin.ir.declarations.impl.IrModuleFragmentImpl
import org.jetbrains.kotlin.ir.descriptors.IrBuiltIns
-import org.jetbrains.kotlin.ir.descriptors.WrappedDeclarationDescriptor
import org.jetbrains.kotlin.ir.util.*
+import org.jetbrains.kotlin.ir.visitors.acceptVoid
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi2ir.PsiSourceManager
@@ -318,14 +318,7 @@ class Fir2IrConverter(
externalDependenciesGenerator.generateUnboundSymbolsAsDependencies()
val stubGenerator = irProviders.filterIsInstance().first()
- for (descriptor in symbolTable.wrappedTopLevelCallableDescriptors()) {
- val parentClass = stubGenerator.generateOrGetFacadeClass(descriptor as WrappedDeclarationDescriptor<*>)
- val owner = descriptor.owner
- owner.parent = parentClass ?: continue
- if (owner is IrProperty) {
- owner.backingField?.parent = parentClass
- }
- }
+ irModuleFragment.acceptVoid(ExternalPackageParentPatcher(stubGenerator))
evaluateConstants(irModuleFragment)
diff --git a/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/Fir2IrDeclarationStorage.kt b/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/Fir2IrDeclarationStorage.kt
index 1b2734c6a2b..f2b35fd9b4c 100644
--- a/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/Fir2IrDeclarationStorage.kt
+++ b/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/Fir2IrDeclarationStorage.kt
@@ -19,15 +19,17 @@ import org.jetbrains.kotlin.fir.descriptors.FirModuleDescriptor
import org.jetbrains.kotlin.fir.descriptors.FirPackageFragmentDescriptor
import org.jetbrains.kotlin.fir.expressions.FirConstExpression
import org.jetbrains.kotlin.fir.expressions.FirExpression
+import org.jetbrains.kotlin.fir.expressions.FirQualifiedAccess
import org.jetbrains.kotlin.fir.expressions.impl.FirExpressionStub
import org.jetbrains.kotlin.fir.lazy.Fir2IrLazyClass
import org.jetbrains.kotlin.fir.lazy.Fir2IrLazyConstructor
import org.jetbrains.kotlin.fir.lazy.Fir2IrLazyProperty
import org.jetbrains.kotlin.fir.lazy.Fir2IrLazySimpleFunction
+import org.jetbrains.kotlin.fir.references.FirResolvedNamedReference
import org.jetbrains.kotlin.fir.resolve.firProvider
-import org.jetbrains.kotlin.fir.resolve.firSymbolProvider
import org.jetbrains.kotlin.fir.resolve.inference.isSuspendFunctionType
import org.jetbrains.kotlin.fir.resolve.isKFunctionInvoke
+import org.jetbrains.kotlin.fir.resolve.toSymbol
import org.jetbrains.kotlin.fir.symbols.*
import org.jetbrains.kotlin.fir.symbols.impl.*
import org.jetbrains.kotlin.fir.types.*
@@ -42,11 +44,11 @@ import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.ir.expressions.IrSyntheticBodyKind
import org.jetbrains.kotlin.ir.expressions.impl.IrErrorExpressionImpl
import org.jetbrains.kotlin.ir.symbols.*
+import org.jetbrains.kotlin.ir.symbols.impl.*
import org.jetbrains.kotlin.ir.types.IrErrorType
import org.jetbrains.kotlin.ir.types.IrSimpleType
import org.jetbrains.kotlin.ir.types.IrType
import org.jetbrains.kotlin.ir.util.*
-import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedContainerSource
@@ -58,8 +60,6 @@ class Fir2IrDeclarationStorage(
private val moduleDescriptor: FirModuleDescriptor
) : Fir2IrComponents by components {
- private val firSymbolProvider = session.firSymbolProvider
-
private val firProvider = session.firProvider
private val fragmentCache = mutableMapOf()
@@ -198,11 +198,11 @@ class Fir2IrDeclarationStorage(
}
}
- private fun findIrClass(classId: ClassId): IrClass? =
- if (classId.isLocal) {
- classifierStorage.getCachedLocalClass(classId)
+ private fun findIrClass(lookupTag: ConeClassLikeLookupTag): IrClass? =
+ if (lookupTag.classId.isLocal) {
+ classifierStorage.getCachedLocalClass(lookupTag)
} else {
- val firSymbol = firSymbolProvider.getClassLikeSymbolByFqName(classId)
+ val firSymbol = lookupTag.toSymbol(session)
if (firSymbol is FirClassSymbol) {
classifierStorage.getIrClassSymbol(firSymbol).owner
} else {
@@ -210,9 +210,13 @@ class Fir2IrDeclarationStorage(
}
}
- internal fun findIrParent(packageFqName: FqName, parentClassId: ClassId?, firBasedSymbol: FirBasedSymbol<*>): IrDeclarationParent? {
- return if (parentClassId != null) {
- findIrClass(parentClassId)
+ internal fun findIrParent(
+ packageFqName: FqName,
+ parentLookupTag: ConeClassLikeLookupTag?,
+ firBasedSymbol: FirBasedSymbol<*>
+ ): IrDeclarationParent? {
+ return if (parentLookupTag != null) {
+ findIrClass(parentLookupTag)
} else {
val containerFile = when (firBasedSymbol) {
is FirCallableSymbol -> firProvider.getFirCallableContainerFile(firBasedSymbol)
@@ -233,7 +237,7 @@ class Fir2IrDeclarationStorage(
internal fun findIrParent(callableDeclaration: FirCallableDeclaration<*>): IrDeclarationParent? {
val firBasedSymbol = callableDeclaration.symbol
val callableId = firBasedSymbol.callableId
- return findIrParent(callableId.packageName, callableDeclaration.containingClass()?.classId, firBasedSymbol)
+ return findIrParent(callableId.packageName, callableDeclaration.containingClass(), firBasedSymbol)
}
private fun IrDeclaration.setAndModifyParent(irParent: IrDeclarationParent?) {
@@ -261,20 +265,14 @@ class Fir2IrDeclarationStorage(
type: IrType,
parent: IrFunction
): IrValueParameter {
- val descriptor = WrappedValueParameterDescriptor()
- return symbolTable.declareValueParameter(
- startOffset, endOffset, origin, descriptor, type
- ) { symbol ->
- irFactory.createValueParameter(
- startOffset, endOffset, IrDeclarationOrigin.DEFINED, symbol,
- Name.special(""), 0, type,
- varargElementType = null,
- isCrossinline = false, isNoinline = false,
- isHidden = false, isAssignable = false
- ).apply {
- this.parent = parent
- descriptor.bind(this)
- }
+ return irFactory.createValueParameter(
+ startOffset, endOffset, IrDeclarationOrigin.DEFINED, IrValueParameterSymbolImpl(),
+ Name.special(""), 0, type,
+ varargElementType = null,
+ isCrossinline = false, isNoinline = false,
+ isHidden = false, isAssignable = false
+ ).apply {
+ this.parent = parent
}
}
@@ -357,9 +355,7 @@ class Fir2IrDeclarationStorage(
isStatic: Boolean,
parentPropertyReceiverType: FirTypeRef? = null
): T {
- if (irParent != null) {
- parent = irParent
- }
+ setAndModifyParent(irParent)
declareParameters(function, thisReceiverOwner, isStatic, parentPropertyReceiverType)
return this
}
@@ -403,13 +399,12 @@ class Fir2IrDeclarationStorage(
signature: IdSignature?,
containerSource: DeserializedContainerSource?,
factory: (IrSimpleFunctionSymbol) -> IrSimpleFunction
- ): IrSimpleFunction {
+ ): IrSimpleFunction =
if (signature == null) {
- val descriptor = WrappedSimpleFunctionDescriptor()
- return symbolTable.declareSimpleFunction(descriptor, factory).apply { descriptor.bind(this) }
+ factory(IrSimpleFunctionSymbolImpl())
+ } else {
+ symbolTable.declareSimpleFunction(signature, { Fir2IrSimpleFunctionSymbol(signature, containerSource) }, factory)
}
- return symbolTable.declareSimpleFunction(signature, { Fir2IrSimpleFunctionSymbol(signature, containerSource) }, factory)
- }
fun getOrCreateIrFunction(
function: FirSimpleFunction,
@@ -515,13 +510,12 @@ class Fir2IrDeclarationStorage(
}
}
- private fun declareIrConstructor(signature: IdSignature?, factory: (IrConstructorSymbol) -> IrConstructor): IrConstructor {
- if (signature == null) {
- val descriptor = WrappedClassConstructorDescriptor()
- return symbolTable.declareConstructor(descriptor, factory).apply { descriptor.bind(this) }
- }
- return symbolTable.declareConstructor(signature, { Fir2IrConstructorSymbol(signature) }, factory)
- }
+ private fun declareIrConstructor(signature: IdSignature?, factory: (IrConstructorSymbol) -> IrConstructor): IrConstructor =
+ if (signature == null)
+ factory(IrConstructorSymbolImpl())
+ else
+ symbolTable.declareConstructor(signature, { Fir2IrConstructorSymbol(signature) }, factory)
+
fun createIrConstructor(
constructor: FirConstructor,
@@ -554,17 +548,12 @@ class Fir2IrDeclarationStorage(
private fun declareIrAccessor(
signature: IdSignature?,
containerSource: DeserializedContainerSource?,
- isGetter: Boolean,
factory: (IrSimpleFunctionSymbol) -> IrSimpleFunction
- ): IrSimpleFunction {
- if (signature == null) {
- val descriptor =
- if (isGetter) WrappedPropertyGetterDescriptor()
- else WrappedPropertySetterDescriptor()
- return symbolTable.declareSimpleFunction(descriptor, factory).apply { descriptor.bind(this) }
- }
- return symbolTable.declareSimpleFunction(signature, { Fir2IrSimpleFunctionSymbol(signature, containerSource) }, factory)
- }
+ ): IrSimpleFunction =
+ if (signature == null)
+ factory(IrSimpleFunctionSymbolImpl())
+ else
+ symbolTable.declareSimpleFunction(signature, { Fir2IrSimpleFunctionSymbol(signature, containerSource) }, factory)
internal fun createIrPropertyAccessor(
propertyAccessor: FirPropertyAccessor?,
@@ -585,8 +574,7 @@ class Fir2IrDeclarationStorage(
val containerSource = (correspondingProperty as? IrProperty)?.containerSource
return declareIrAccessor(
signature,
- containerSource,
- isGetter = !isSetter
+ containerSource
) { symbol ->
val accessorReturnType = if (isSetter) irBuiltIns.unitType else propertyType
val visibility = propertyAccessor?.visibility?.let {
@@ -684,15 +672,11 @@ class Fir2IrDeclarationStorage(
signature: IdSignature?,
containerSource: DeserializedContainerSource?,
factory: (IrPropertySymbol) -> IrProperty
- ): IrProperty {
- if (signature == null) {
- val descriptor = WrappedPropertyDescriptor()
- return symbolTable.declareProperty(0, 0, IrDeclarationOrigin.DEFINED, descriptor, isDelegated = false, factory).apply {
- descriptor.bind(this)
- }
- }
- return symbolTable.declareProperty(signature, { Fir2IrPropertySymbol(signature, containerSource) }, factory)
- }
+ ): IrProperty =
+ if (signature == null)
+ factory(IrPropertySymbolImpl())
+ else
+ symbolTable.declareProperty(signature, { Fir2IrPropertySymbol(signature, containerSource) }, factory)
fun getOrCreateIrProperty(
property: FirProperty,
@@ -739,6 +723,12 @@ class Fir2IrDeclarationStorage(
containingClass: ConeClassLikeLookupTag? = null,
): IrProperty {
classifierStorage.preCacheTypeParameters(property)
+ if (property.delegate != null) {
+ val delegateReference = (property.delegate as? FirQualifiedAccess)?.calleeReference as? FirResolvedNamedReference
+ (delegateReference?.resolvedSymbol?.fir as? FirTypeParameterRefsOwner)?.let {
+ classifierStorage.preCacheTypeParameters(it)
+ }
+ }
val signature = if (isLocal) null else signatureComposer.composeSignature(property, containingClass)
return property.convertWithOffsets { startOffset, endOffset ->
val result = declareIrProperty(signature, property.containerSource) { symbol ->
@@ -852,28 +842,21 @@ class Fir2IrDeclarationStorage(
field: FirField,
origin: IrDeclarationOrigin = IrDeclarationOrigin.IR_EXTERNAL_JAVA_DECLARATION_STUB
): IrField {
- val descriptor = WrappedFieldDescriptor()
val type = field.returnTypeRef.toIrType()
return field.convertWithOffsets { startOffset, endOffset ->
- symbolTable.declareField(
- startOffset, endOffset,
- origin, descriptor, type
- ) { symbol ->
- irFactory.createField(
- startOffset, endOffset, origin, symbol,
- field.name, type, components.visibilityConverter.convertToDescriptorVisibility(field.visibility),
- isFinal = field.modality == Modality.FINAL,
- isExternal = false,
- isStatic = field.isStatic
- ).apply {
- field.initializer?.let {
- val expression = visitor.convertToIrExpression(it)
- expression.type = type
- initializer = irFactory.createExpressionBody(expression)
- }
- descriptor.bind(this)
- fieldCache[field] = this
+ irFactory.createField(
+ startOffset, endOffset, origin, IrFieldSymbolImpl(),
+ field.name, type, components.visibilityConverter.convertToDescriptorVisibility(field.visibility),
+ isFinal = field.modality == Modality.FINAL,
+ isExternal = false,
+ isStatic = field.isStatic
+ ).apply {
+ field.initializer?.let {
+ val expression = visitor.convertToIrExpression(it)
+ expression.type = type
+ initializer = irFactory.createExpressionBody(expression)
}
+ fieldCache[field] = this
}
}
}
@@ -884,33 +867,27 @@ class Fir2IrDeclarationStorage(
useStubForDefaultValueStub: Boolean = true,
typeContext: ConversionTypeContext = ConversionTypeContext.DEFAULT
): IrValueParameter {
- val descriptor = WrappedValueParameterDescriptor()
val origin = IrDeclarationOrigin.DEFINED
val type = valueParameter.returnTypeRef.toIrType()
val irParameter = valueParameter.convertWithOffsets { startOffset, endOffset ->
- symbolTable.declareValueParameter(
- startOffset, endOffset, origin, descriptor, type
- ) { symbol ->
- irFactory.createValueParameter(
- startOffset, endOffset, origin, symbol,
- valueParameter.name, index, type,
- if (!valueParameter.isVararg) null
- else valueParameter.returnTypeRef.coneType.arrayElementType()?.toIrType(typeContext),
- isCrossinline = valueParameter.isCrossinline, isNoinline = valueParameter.isNoinline,
- isHidden = false, isAssignable = false
- ).apply {
- descriptor.bind(this)
- if (valueParameter.defaultValue.let {
- it != null && (useStubForDefaultValueStub || it !is FirExpressionStub)
- }
- ) {
- this.defaultValue = factory.createExpressionBody(
- IrErrorExpressionImpl(
- UNDEFINED_OFFSET, UNDEFINED_OFFSET, type,
- "Stub expression for default value of ${valueParameter.name}"
- )
- )
+ irFactory.createValueParameter(
+ startOffset, endOffset, origin, IrValueParameterSymbolImpl(),
+ valueParameter.name, index, type,
+ if (!valueParameter.isVararg) null
+ else valueParameter.returnTypeRef.coneType.arrayElementType()?.toIrType(typeContext),
+ isCrossinline = valueParameter.isCrossinline, isNoinline = valueParameter.isNoinline,
+ isHidden = false, isAssignable = false
+ ).apply {
+ if (valueParameter.defaultValue.let {
+ it != null && (useStubForDefaultValueStub || it !is FirExpressionStub)
}
+ ) {
+ this.defaultValue = factory.createExpressionBody(
+ IrErrorExpressionImpl(
+ UNDEFINED_OFFSET, UNDEFINED_OFFSET, type,
+ "Stub expression for default value of ${valueParameter.name}"
+ )
+ )
}
}
}
@@ -930,17 +907,11 @@ class Fir2IrDeclarationStorage(
startOffset: Int, endOffset: Int,
origin: IrDeclarationOrigin, name: Name, type: IrType,
isVar: Boolean, isConst: Boolean, isLateinit: Boolean
- ): IrVariable {
- val descriptor = WrappedVariableDescriptor()
- return symbolTable.declareVariable(startOffset, endOffset, origin, descriptor, type) { symbol ->
- IrVariableImpl(
- startOffset, endOffset, origin, symbol, name, type,
- isVar, isConst, isLateinit
- ).apply {
- descriptor.bind(this)
- }
- }
- }
+ ): IrVariable =
+ IrVariableImpl(
+ startOffset, endOffset, origin, IrVariableSymbolImpl(), name, type,
+ isVar, isConst, isLateinit
+ )
fun createIrVariable(variable: FirVariable<*>, irParent: IrDeclarationParent, givenOrigin: IrDeclarationOrigin? = null): IrVariable {
val type = variable.returnTypeRef.toIrType()
@@ -967,12 +938,15 @@ class Fir2IrDeclarationStorage(
val type = property.returnTypeRef.toIrType()
val origin = IrDeclarationOrigin.DEFINED
val irProperty = property.convertWithOffsets { startOffset, endOffset ->
- val descriptor = WrappedVariableDescriptorWithAccessor()
- symbolTable.declareLocalDelegatedProperty(startOffset, endOffset, origin, descriptor, type) {
- irFactory.createLocalDelegatedProperty(startOffset, endOffset, origin, it, property.name, type, property.isVar).apply {
- descriptor.bind(this)
- }
- }
+ irFactory.createLocalDelegatedProperty(
+ startOffset,
+ endOffset,
+ origin,
+ IrLocalDelegatedPropertySymbolImpl(),
+ property.name,
+ type,
+ property.isVar
+ )
}.apply {
parent = irParent
metadata = FirMetadataSource.Property(property)
@@ -1041,9 +1015,7 @@ class Fir2IrDeclarationStorage(
val irParent = findIrParent(fir)
val parentOrigin = (irParent as? IrDeclaration)?.origin ?: IrDeclarationOrigin.DEFINED
val declarationOrigin = computeDeclarationOrigin(firFunctionSymbol, parentOrigin, irParent)
- createIrFunction(fir, irParent, origin = declarationOrigin).apply {
- setAndModifyParent(irParent)
- }.symbol
+ createIrFunction(fir, irParent, origin = declarationOrigin).symbol
}
is FirSimpleFunction -> {
return getIrCallableSymbol(
@@ -1150,7 +1122,7 @@ class Fir2IrDeclarationStorage(
parentOrigin: IrDeclarationOrigin,
irParent: IrDeclarationParent?
): IrDeclarationOrigin {
- return if (irParent.isSourceClass() && symbol.fir.isIntersectionOverride)
+ return if (irParent.isSourceClass() && (symbol.fir.isIntersectionOverride || symbol.fir.isSubstitutionOverride))
IrDeclarationOrigin.FAKE_OVERRIDE
else
parentOrigin
@@ -1160,8 +1132,12 @@ class Fir2IrDeclarationStorage(
fun getIrFieldSymbol(firFieldSymbol: FirFieldSymbol): IrSymbol {
val fir = firFieldSymbol.fir
- val irProperty = fieldCache[fir] ?: createIrField(fir).apply {
- setAndModifyParent(findIrParent(fir))
+ val irProperty = fieldCache[fir] ?: run {
+ // In case of type parameters from the parent as the field's return type, find the parent ahead to cache type parameters.
+ val irParent = findIrParent(fir)
+ createIrField(fir).apply {
+ setAndModifyParent(irParent)
+ }
}
return irProperty.symbol
}
@@ -1195,7 +1171,7 @@ class Fir2IrDeclarationStorage(
is FirEnumEntry -> {
classifierStorage.getCachedIrEnumEntry(firDeclaration)?.let { return it.symbol }
val containingFile = firProvider.getFirCallableContainerFile(firVariableSymbol)
- val irParentClass = firDeclaration.containingClass()?.classId?.let { findIrClass(it) }
+ val irParentClass = firDeclaration.containingClass()?.let { findIrClass(it) }
classifierStorage.createIrEnumEntry(
firDeclaration,
irParent = irParentClass,
@@ -1216,7 +1192,7 @@ class Fir2IrDeclarationStorage(
private fun IrMutableAnnotationContainer.convertAnnotationsFromLibrary(firAnnotationContainer: FirAnnotationContainer) {
if ((firAnnotationContainer as? FirDeclaration)?.isFromLibrary == true) {
- annotationGenerator?.generate(this, firAnnotationContainer)
+ annotationGenerator.generate(this, firAnnotationContainer)
}
}
diff --git a/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/Fir2IrLocalStorage.kt b/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/Fir2IrLocalStorage.kt
index 68039f8c03c..4a3ae5f2515 100644
--- a/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/Fir2IrLocalStorage.kt
+++ b/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/Fir2IrLocalStorage.kt
@@ -39,10 +39,6 @@ class Fir2IrLocalStorage {
return localClassCache[localClass]
}
- fun getLocalClass(classId: ClassId): IrClass? {
- return localClassCache.entries.find { (firClass, _) -> firClass.classId == classId }?.value
- }
-
fun getLocalFunction(localFunction: FirFunction<*>): IrSimpleFunction? =
last { getLocalFunction(localFunction) }
diff --git a/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/generators/AdapterGenerator.kt b/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/generators/AdapterGenerator.kt
index 79e66bca164..4633c6c2675 100644
--- a/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/generators/AdapterGenerator.kt
+++ b/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/generators/AdapterGenerator.kt
@@ -20,8 +20,6 @@ import org.jetbrains.kotlin.fir.types.FirTypeRef
import org.jetbrains.kotlin.fir.types.coneType
import org.jetbrains.kotlin.ir.builders.declarations.UNDEFINED_PARAMETER_INDEX
import org.jetbrains.kotlin.ir.declarations.*
-import org.jetbrains.kotlin.ir.descriptors.WrappedSimpleFunctionDescriptor
-import org.jetbrains.kotlin.ir.descriptors.WrappedValueParameterDescriptor
import org.jetbrains.kotlin.ir.expressions.IrBlock
import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.ir.expressions.IrGetValue
@@ -30,6 +28,8 @@ import org.jetbrains.kotlin.ir.expressions.impl.*
import org.jetbrains.kotlin.ir.symbols.IrConstructorSymbol
import org.jetbrains.kotlin.ir.symbols.IrFunctionSymbol
import org.jetbrains.kotlin.ir.symbols.IrSimpleFunctionSymbol
+import org.jetbrains.kotlin.ir.symbols.impl.IrSimpleFunctionSymbolImpl
+import org.jetbrains.kotlin.ir.symbols.impl.IrValueParameterSymbolImpl
import org.jetbrains.kotlin.ir.types.IrSimpleType
import org.jetbrains.kotlin.ir.types.IrType
import org.jetbrains.kotlin.ir.types.isUnit
@@ -187,59 +187,55 @@ internal class AdapterGenerator(
): IrSimpleFunction {
val returnType = type.arguments.last().typeOrNull!!
val parameterTypes = type.arguments.dropLast(1).map { it.typeOrNull!! }
- val adapterFunctionDescriptor = WrappedSimpleFunctionDescriptor()
- return symbolTable.declareSimpleFunction(adapterFunctionDescriptor) { irAdapterSymbol ->
- irFactory.createFunction(
- startOffset, endOffset,
- IrDeclarationOrigin.ADAPTER_FOR_CALLABLE_REFERENCE,
- irAdapterSymbol,
- adaptee.name,
- DescriptorVisibilities.LOCAL,
- Modality.FINAL,
- returnType,
- isInline = firAdaptee.isInline,
- isExternal = firAdaptee.isExternal,
- isTailrec = firAdaptee.isTailRec,
- isSuspend = firAdaptee.isSuspend || type.isSuspendFunction(),
- isOperator = firAdaptee.isOperator,
- isInfix = firAdaptee.isInfix,
- isExpect = firAdaptee.isExpect,
- isFakeOverride = false
- ).also { irAdapterFunction ->
- adapterFunctionDescriptor.bind(irAdapterFunction)
- irAdapterFunction.metadata = FirMetadataSource.Function(firAdaptee)
+ return irFactory.createFunction(
+ startOffset, endOffset,
+ IrDeclarationOrigin.ADAPTER_FOR_CALLABLE_REFERENCE,
+ IrSimpleFunctionSymbolImpl(),
+ adaptee.name,
+ DescriptorVisibilities.LOCAL,
+ Modality.FINAL,
+ returnType,
+ isInline = firAdaptee.isInline,
+ isExternal = firAdaptee.isExternal,
+ isTailrec = firAdaptee.isTailRec,
+ isSuspend = firAdaptee.isSuspend || type.isSuspendFunction(),
+ isOperator = firAdaptee.isOperator,
+ isInfix = firAdaptee.isInfix,
+ isExpect = firAdaptee.isExpect,
+ isFakeOverride = false
+ ).also { irAdapterFunction ->
+ irAdapterFunction.metadata = FirMetadataSource.Function(firAdaptee)
- symbolTable.enterScope(irAdapterFunction)
- irAdapterFunction.dispatchReceiverParameter = null
- val boundReceiver = boundDispatchReceiver ?: boundExtensionReceiver
- when {
- boundReceiver == null ->
- irAdapterFunction.extensionReceiverParameter = null
- boundDispatchReceiver != null && boundExtensionReceiver != null ->
- error("Bound callable references can't have both receivers: ${callableReferenceAccess.render()}")
- else ->
- irAdapterFunction.extensionReceiverParameter =
- createAdapterParameter(
- irAdapterFunction,
- Name.identifier("receiver"),
- index = UNDEFINED_PARAMETER_INDEX,
- boundReceiver.type,
- IrDeclarationOrigin.ADAPTER_PARAMETER_FOR_CALLABLE_REFERENCE
- )
- }
- irAdapterFunction.valueParameters += parameterTypes.mapIndexed { index, parameterType ->
- createAdapterParameter(
- irAdapterFunction,
- Name.identifier("p$index"),
- index,
- parameterType,
- IrDeclarationOrigin.ADAPTER_PARAMETER_FOR_CALLABLE_REFERENCE
- )
- }
- symbolTable.leaveScope(irAdapterFunction)
-
- irAdapterFunction.parent = conversionScope.parent()!!
+ symbolTable.enterScope(irAdapterFunction)
+ irAdapterFunction.dispatchReceiverParameter = null
+ val boundReceiver = boundDispatchReceiver ?: boundExtensionReceiver
+ when {
+ boundReceiver == null ->
+ irAdapterFunction.extensionReceiverParameter = null
+ boundDispatchReceiver != null && boundExtensionReceiver != null ->
+ error("Bound callable references can't have both receivers: ${callableReferenceAccess.render()}")
+ else ->
+ irAdapterFunction.extensionReceiverParameter =
+ createAdapterParameter(
+ irAdapterFunction,
+ Name.identifier("receiver"),
+ index = UNDEFINED_PARAMETER_INDEX,
+ boundReceiver.type,
+ IrDeclarationOrigin.ADAPTER_PARAMETER_FOR_CALLABLE_REFERENCE
+ )
}
+ irAdapterFunction.valueParameters += parameterTypes.mapIndexed { index, parameterType ->
+ createAdapterParameter(
+ irAdapterFunction,
+ Name.identifier("p$index"),
+ index,
+ parameterType,
+ IrDeclarationOrigin.ADAPTER_PARAMETER_FOR_CALLABLE_REFERENCE
+ )
+ }
+ symbolTable.leaveScope(irAdapterFunction)
+
+ irAdapterFunction.parent = conversionScope.parent()!!
}
}
@@ -249,31 +245,23 @@ internal class AdapterGenerator(
index: Int,
type: IrType,
origin: IrDeclarationOrigin
- ): IrValueParameter {
- val startOffset = adapterFunction.startOffset
- val endOffset = adapterFunction.endOffset
- val descriptor = WrappedValueParameterDescriptor()
- return symbolTable.declareValueParameter(
- startOffset, endOffset, origin, descriptor, type
- ) { irAdapterParameterSymbol ->
- irFactory.createValueParameter(
- startOffset, endOffset,
- origin,
- irAdapterParameterSymbol,
- name,
- index,
- type,
- varargElementType = null,
- isCrossinline = false,
- isNoinline = false,
- isHidden = false,
- isAssignable = false
- ).also { irAdapterValueParameter ->
- descriptor.bind(irAdapterValueParameter)
- irAdapterValueParameter.parent = adapterFunction
- }
+ ): IrValueParameter =
+ irFactory.createValueParameter(
+ adapterFunction.startOffset,
+ adapterFunction.endOffset,
+ origin,
+ IrValueParameterSymbolImpl(),
+ name,
+ index,
+ type,
+ varargElementType = null,
+ isCrossinline = false,
+ isNoinline = false,
+ isHidden = false,
+ isAssignable = false
+ ).also { irAdapterValueParameter ->
+ irAdapterValueParameter.parent = adapterFunction
}
- }
private fun IrValueDeclaration.toIrGetValue(startOffset: Int, endOffset: Int): IrGetValue =
IrGetValueImpl(startOffset, endOffset, this.type, this.symbol)
@@ -446,55 +434,51 @@ internal class AdapterGenerator(
): IrSimpleFunction {
val returnType = type.arguments.last().typeOrNull!!
val parameterTypes = type.arguments.dropLast(1).map { it.typeOrNull!! }
- val adapterFunctionDescriptor = WrappedSimpleFunctionDescriptor()
- return symbolTable.declareSimpleFunction(adapterFunctionDescriptor) { irAdapterSymbol ->
- irFactory.createFunction(
- startOffset, endOffset,
- IrDeclarationOrigin.ADAPTER_FOR_SUSPEND_CONVERSION,
- irAdapterSymbol,
- // TODO: need a better way to avoid name clash
- Name.identifier("suspendConversion"),
- DescriptorVisibilities.LOCAL,
- Modality.FINAL,
- returnType,
- isInline = false,
- isExternal = false,
- isTailrec = false,
- isSuspend = true,
- isOperator = false,
- isInfix = false,
- isExpect = false,
- isFakeOverride = false
- ).also { irAdapterFunction ->
- adapterFunctionDescriptor.bind(irAdapterFunction)
- symbolTable.enterScope(irAdapterFunction)
- irAdapterFunction.extensionReceiverParameter = createAdapterParameter(
+ return irFactory.createFunction(
+ startOffset, endOffset,
+ IrDeclarationOrigin.ADAPTER_FOR_SUSPEND_CONVERSION,
+ IrSimpleFunctionSymbolImpl(),
+ // TODO: need a better way to avoid name clash
+ Name.identifier("suspendConversion"),
+ DescriptorVisibilities.LOCAL,
+ Modality.FINAL,
+ returnType,
+ isInline = false,
+ isExternal = false,
+ isTailrec = false,
+ isSuspend = true,
+ isOperator = false,
+ isInfix = false,
+ isExpect = false,
+ isFakeOverride = false
+ ).also { irAdapterFunction ->
+ symbolTable.enterScope(irAdapterFunction)
+ irAdapterFunction.extensionReceiverParameter = createAdapterParameter(
+ irAdapterFunction,
+ Name.identifier("callee"),
+ UNDEFINED_PARAMETER_INDEX,
+ argumentType,
+ IrDeclarationOrigin.ADAPTER_PARAMETER_FOR_SUSPEND_CONVERSION
+ )
+ irAdapterFunction.valueParameters += parameterTypes.mapIndexed { index, parameterType ->
+ createAdapterParameter(
irAdapterFunction,
- Name.identifier("callee"),
- UNDEFINED_PARAMETER_INDEX,
- argumentType,
+ Name.identifier("p$index"),
+ index,
+ parameterType,
IrDeclarationOrigin.ADAPTER_PARAMETER_FOR_SUSPEND_CONVERSION
)
- irAdapterFunction.valueParameters += parameterTypes.mapIndexed { index, parameterType ->
- createAdapterParameter(
- irAdapterFunction,
- Name.identifier("p$index"),
- index,
- parameterType,
- IrDeclarationOrigin.ADAPTER_PARAMETER_FOR_SUSPEND_CONVERSION
- )
- }
- irAdapterFunction.body = irFactory.createBlockBody(startOffset, endOffset) {
- val irCall = createAdapteeCallForArgument(startOffset, endOffset, irAdapterFunction, invokeSymbol)
- if (returnType.isUnit()) {
- statements.add(irCall)
- } else {
- statements.add(IrReturnImpl(startOffset, endOffset, irBuiltIns.nothingType, irAdapterFunction.symbol, irCall))
- }
- }
- symbolTable.leaveScope(irAdapterFunction)
- irAdapterFunction.parent = conversionScope.parent()!!
}
+ irAdapterFunction.body = irFactory.createBlockBody(startOffset, endOffset) {
+ val irCall = createAdapteeCallForArgument(startOffset, endOffset, irAdapterFunction, invokeSymbol)
+ if (returnType.isUnit()) {
+ statements.add(irCall)
+ } else {
+ statements.add(IrReturnImpl(startOffset, endOffset, irBuiltIns.nothingType, irAdapterFunction.symbol, irCall))
+ }
+ }
+ symbolTable.leaveScope(irAdapterFunction)
+ irAdapterFunction.parent = conversionScope.parent()!!
}
}
diff --git a/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/generators/CallAndReferenceGenerator.kt b/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/generators/CallAndReferenceGenerator.kt
index 35353eda734..b8accddf4cf 100644
--- a/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/generators/CallAndReferenceGenerator.kt
+++ b/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/generators/CallAndReferenceGenerator.kt
@@ -17,9 +17,11 @@ import org.jetbrains.kotlin.fir.references.FirResolvedNamedReference
import org.jetbrains.kotlin.fir.references.FirSuperReference
import org.jetbrains.kotlin.fir.references.impl.FirReferencePlaceholderForResolvedAnnotations
import org.jetbrains.kotlin.fir.render
+import org.jetbrains.kotlin.fir.resolve.FirSamResolverImpl
import org.jetbrains.kotlin.fir.resolve.calls.getExpectedTypeForSAMConversion
import org.jetbrains.kotlin.fir.resolve.calls.isFunctional
import org.jetbrains.kotlin.fir.resolve.fullyExpandedType
+import org.jetbrains.kotlin.fir.resolve.inference.inferenceComponents
import org.jetbrains.kotlin.fir.resolve.inference.isBuiltinFunctionalType
import org.jetbrains.kotlin.fir.resolve.inference.isKMutableProperty
import org.jetbrains.kotlin.fir.resolve.toSymbol
@@ -37,6 +39,7 @@ import org.jetbrains.kotlin.ir.types.*
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.psi2ir.generators.hasNoSideEffects
import org.jetbrains.kotlin.types.AbstractTypeApproximator
+import org.jetbrains.kotlin.types.AbstractTypeChecker
class CallAndReferenceGenerator(
private val components: Fir2IrComponents,
@@ -46,6 +49,7 @@ class CallAndReferenceGenerator(
private val approximator = object : AbstractTypeApproximator(session.typeContext) {}
private val adapterGenerator = AdapterGenerator(components, conversionScope)
+ private val samResolver = FirSamResolverImpl(session, scopeSession)
private fun FirTypeRef.toIrType(): IrType = with(typeConverter) { toIrType() }
@@ -613,13 +617,25 @@ class CallAndReferenceGenerator(
}
private fun needSamConversion(argument: FirExpression, parameter: FirValueParameter): Boolean {
+ // If the type of the argument is already an explicitly subtype of the type of the parameter, we don't need SAM conversion.
+ if (argument.typeRef !is FirResolvedTypeRef ||
+ AbstractTypeChecker.isSubtypeOf(
+ session.inferenceComponents.ctx,
+ argument.typeRef.coneType,
+ parameter.returnTypeRef.coneType,
+ isFromNullabilityConstraint = true
+ )
+ ) {
+ return false
+ }
// If the expected type is a built-in functional type, we don't need SAM conversion.
val expectedType = argument.getExpectedTypeForSAMConversion(parameter)
if (expectedType is ConeTypeParameterType || expectedType.isBuiltinFunctionalType(session)) {
return false
}
- // On the other hand, the actual type should be a functional type.
- return argument.isFunctional(session)
+ // On the other hand, the actual type should be either a functional type or a subtype of a class that has a contributed `invoke`.
+ val expectedFunctionType = samResolver.getFunctionTypeForPossibleSamType(parameter.returnTypeRef.coneType)
+ return argument.isFunctional(session, scopeSession, expectedFunctionType)
}
private fun IrExpression.applyAssigningArrayElementsToVarargInNamedForm(
diff --git a/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/generators/ClassMemberGenerator.kt b/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/generators/ClassMemberGenerator.kt
index 2284aa8c562..aa43ea3c266 100644
--- a/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/generators/ClassMemberGenerator.kt
+++ b/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/generators/ClassMemberGenerator.kt
@@ -49,7 +49,6 @@ internal class ClassMemberGenerator(
if (irPrimaryConstructor != null) {
with(declarationStorage) {
enterScope(irPrimaryConstructor)
- irPrimaryConstructor.valueParameters.forEach { symbolTable.introduceValueParameter(it) }
irPrimaryConstructor.putParametersInScope(primaryConstructor)
convertFunctionContent(irPrimaryConstructor, primaryConstructor, containingClass = klass)
}
@@ -86,7 +85,6 @@ internal class ClassMemberGenerator(
// Scope for primary constructor should be entered before class declaration processing
with(declarationStorage) {
enterScope(irFunction)
- irFunction.valueParameters.forEach { symbolTable.introduceValueParameter(it) }
irFunction.putParametersInScope(firFunction)
}
}
diff --git a/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/generators/DataClassMembersGenerator.kt b/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/generators/DataClassMembersGenerator.kt
index 6e59e9879e3..105b6b54a2c 100644
--- a/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/generators/DataClassMembersGenerator.kt
+++ b/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/generators/DataClassMembersGenerator.kt
@@ -30,12 +30,19 @@ import org.jetbrains.kotlin.ir.ObsoleteDescriptorBasedAPI
import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET
import org.jetbrains.kotlin.ir.builders.IrGeneratorContextBase
import org.jetbrains.kotlin.ir.declarations.*
-import org.jetbrains.kotlin.ir.descriptors.WrappedValueParameterDescriptor
import org.jetbrains.kotlin.ir.expressions.IrMemberAccessExpression
+import org.jetbrains.kotlin.ir.symbols.IrClassSymbol
+import org.jetbrains.kotlin.ir.symbols.IrSimpleFunctionSymbol
+import org.jetbrains.kotlin.ir.symbols.IrTypeParameterSymbol
+import org.jetbrains.kotlin.ir.symbols.impl.IrValueParameterSymbolImpl
import org.jetbrains.kotlin.ir.types.IrType
+import org.jetbrains.kotlin.ir.types.classOrNull
+import org.jetbrains.kotlin.ir.types.classifierOrNull
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.ir.util.DataClassMembersGenerator
import org.jetbrains.kotlin.name.Name
+import org.jetbrains.kotlin.types.KotlinType
+import org.jetbrains.kotlin.types.typeUtil.representativeUpperBound
/**
* A generator that generates synthetic members of data class as well as part of inline class.
@@ -93,21 +100,58 @@ class DataClassMembersGenerator(val components: Fir2IrComponents) {
return components.irBuiltIns.anyType
}
- override fun commitSubstituted(irMemberAccessExpression: IrMemberAccessExpression<*>, descriptor: CallableDescriptor) {
- // TODO
+ inner class Fir2IrHashCodeFunctionInfo(override val symbol: IrSimpleFunctionSymbol) : HashCodeFunctionInfo {
+ override fun commitSubstituted(irMemberAccessExpression: IrMemberAccessExpression<*>) {
+ // TODO
+ }
+ }
+
+ private fun getHashCodeFunction(klass: IrClass): IrSimpleFunctionSymbol =
+ klass.functions.singleOrNull {
+ it.name.asString() == "hashCode" && it.valueParameters.isEmpty() && it.extensionReceiverParameter == null
+ }?.symbol
+ ?: context.irBuiltIns.anyClass.functions.single { it.owner.name.asString() == "hashCode" }
+
+
+ val IrTypeParameter.erasedUpperBound: IrClass
+ get() {
+ // Pick the (necessarily unique) non-interface upper bound if it exists
+ for (type in superTypes) {
+ val irClass = type.classOrNull?.owner ?: continue
+ if (!irClass.isInterface && !irClass.isAnnotationClass) return irClass
+ }
+
+ // Otherwise, choose either the first IrClass supertype or recurse.
+ // In the first case, all supertypes are interface types and the choice was arbitrary.
+ // In the second case, there is only a single supertype.
+ return when (val firstSuper = superTypes.first().classifierOrNull?.owner) {
+ is IrClass -> firstSuper
+ is IrTypeParameter -> firstSuper.erasedUpperBound
+ else -> error("unknown supertype kind $firstSuper")
+ }
+ }
+
+
+ override fun getHashCodeFunctionInfo(type: IrType): HashCodeFunctionInfo {
+ val classifier = type.classifierOrNull
+ val symbol = when {
+ classifier.isArrayOrPrimitiveArray -> context.irBuiltIns.dataClassArrayMemberHashCodeSymbol
+ classifier is IrClassSymbol -> getHashCodeFunction(classifier.owner)
+ classifier is IrTypeParameterSymbol -> getHashCodeFunction(classifier.owner.erasedUpperBound)
+ else -> error("Unknown classifier kind $classifier")
+ }
+ return Fir2IrHashCodeFunctionInfo(symbol)
}
}
- fun generateDispatchReceiverParameter(irFunction: IrFunction, valueParameterDescriptor: WrappedValueParameterDescriptor) =
+ fun generateDispatchReceiverParameter(irFunction: IrFunction) =
irFunction.declareThisReceiverParameter(
components.symbolTable,
irClass.defaultType,
origin,
UNDEFINED_OFFSET,
UNDEFINED_OFFSET
- ).apply {
- valueParameterDescriptor.bind(this)
- }
+ )
private val FirSimpleFunction.matchesEqualsSignature: Boolean
@@ -133,7 +177,6 @@ class DataClassMembersGenerator(val components: Fir2IrComponents) {
val properties = irClass.declarations
.filterIsInstance()
.take(propertyParametersCount)
- .map { it.descriptor }
if (properties.isEmpty()) {
return emptyList()
}
@@ -223,7 +266,6 @@ class DataClassMembersGenerator(val components: Fir2IrComponents) {
returnType: IrType,
otherParameterNeeded: Boolean = false
): IrFunction {
- val thisReceiverDescriptor = WrappedValueParameterDescriptor()
val firFunction = buildSimpleFunction {
origin = FirDeclarationOrigin.Synthetic
this.name = name
@@ -273,7 +315,7 @@ class DataClassMembersGenerator(val components: Fir2IrComponents) {
}
}.apply {
parent = irClass
- dispatchReceiverParameter = generateDispatchReceiverParameter(this, thisReceiverDescriptor)
+ dispatchReceiverParameter = generateDispatchReceiverParameter(this)
components.irBuiltIns.anyClass.descriptor.unsubstitutedMemberScope
.getContributedFunctions(this.name, NoLookupLocation.FROM_BACKEND)
.singleOrNull { function -> function.name == this.name }
@@ -283,20 +325,13 @@ class DataClassMembersGenerator(val components: Fir2IrComponents) {
}
}
- private fun createSyntheticIrParameter(irFunction: IrFunction, name: Name, type: IrType, index: Int = 0): IrValueParameter {
- val descriptor = WrappedValueParameterDescriptor()
- return components.symbolTable.declareValueParameter(
- UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin, descriptor, type
- ) { symbol ->
- components.irFactory.createValueParameter(
- UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin, symbol, name, index, type, null,
- isCrossinline = false, isNoinline = false, isHidden = false, isAssignable = false
- )
- }.apply {
+ private fun createSyntheticIrParameter(irFunction: IrFunction, name: Name, type: IrType, index: Int = 0): IrValueParameter =
+ components.irFactory.createValueParameter(
+ UNDEFINED_OFFSET, UNDEFINED_OFFSET, origin, IrValueParameterSymbolImpl(), name, index, type, null,
+ isCrossinline = false, isNoinline = false, isHidden = false, isAssignable = false
+ ).apply {
parent = irFunction
- descriptor.bind(this)
}
- }
}
companion object {
diff --git a/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/lazy/AbstractFir2IrLazyDeclaration.kt b/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/lazy/AbstractFir2IrLazyDeclaration.kt
index 36fa739b032..2c28c04b4e2 100644
--- a/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/lazy/AbstractFir2IrLazyDeclaration.kt
+++ b/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/lazy/AbstractFir2IrLazyDeclaration.kt
@@ -15,11 +15,11 @@ import org.jetbrains.kotlin.ir.declarations.lazy.lazyVar
import org.jetbrains.kotlin.ir.expressions.IrConstructorCall
import kotlin.properties.ReadWriteProperty
-interface AbstractFir2IrLazyDeclaration :
+interface AbstractFir2IrLazyDeclaration :
IrDeclaration, IrDeclarationParent, Fir2IrComponents {
val fir: F
- val symbol: Fir2IrBindableSymbol<*, D>
+ override val symbol: Fir2IrBindableSymbol<*, D>
override val factory: IrFactory
get() = irFactory
diff --git a/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/symbols/Fir2IrBindableSymbol.kt b/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/symbols/Fir2IrBindableSymbol.kt
index 0e9ea949dff..21bed117bba 100644
--- a/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/symbols/Fir2IrBindableSymbol.kt
+++ b/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/symbols/Fir2IrBindableSymbol.kt
@@ -13,7 +13,7 @@ import org.jetbrains.kotlin.ir.symbols.IrBindableSymbol
import org.jetbrains.kotlin.ir.util.IdSignature
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedContainerSource
-abstract class Fir2IrBindableSymbol(
+abstract class Fir2IrBindableSymbol(
override val signature: IdSignature,
private val containerSource: DeserializedContainerSource? = null
) : IrBindableSymbol {
@@ -34,31 +34,13 @@ abstract class Fir2IrBindableSymbol WrappedEnumEntryDescriptor().apply { bind(owner) }
- is IrClass -> WrappedClassDescriptor().apply { bind(owner) }
- is IrConstructor -> WrappedClassConstructorDescriptor().apply { bind(owner) }
- is IrSimpleFunction -> when {
- owner.name.isSpecial && owner.name.asString().startsWith(GETTER_PREFIX) ->
- WrappedPropertyGetterDescriptor()
- owner.name.isSpecial && owner.name.asString().startsWith(SETTER_PREFIX) ->
- WrappedPropertySetterDescriptor()
- else ->
- WrappedSimpleFunctionDescriptor()
- }.apply { bind(owner) }
- is IrVariable -> WrappedVariableDescriptor().apply { bind(owner) }
- is IrValueParameter -> WrappedValueParameterDescriptor().apply { bind(owner) }
- is IrTypeParameter -> WrappedTypeParameterDescriptor().apply { bind(owner) }
- is IrProperty -> WrappedPropertyDescriptor().apply { bind(owner) }
- is IrField -> WrappedFieldDescriptor().apply { bind(owner) }
- is IrTypeAlias -> WrappedTypeAliasDescriptor().apply { bind(owner) }
- else -> throw IllegalStateException("Unsupported owner in Fir2IrBindableSymbol: $owner")
- }
-
+ override val descriptor: D
@Suppress("UNCHECKED_CAST")
- result as D
- }
+ get() = owner.toIrBasedDescriptor() as D
+
+ @ObsoleteDescriptorBasedAPI
+ override val hasDescriptor: Boolean
+ get() = false
companion object {
private const val GETTER_PREFIX = " = mutableListOf()
var valueParameterForValue: FirJavaValueParameter? = null
@@ -411,6 +421,7 @@ class JavaSymbolProvider(
defaultValue = buildExpressionStub()
}
isVararg = returnType is JavaArrayType && methodName == VALUE_METHOD_NAME
+ annotationBuilder = { emptyList() }
}
if (methodName == VALUE_METHOD_NAME) {
valueParametersForAnnotationConstructor.valueParameterForValue = parameterForAnnotationConstructor
diff --git a/compiler/fir/java/src/org/jetbrains/kotlin/fir/java/JavaUtils.kt b/compiler/fir/java/src/org/jetbrains/kotlin/fir/java/JavaUtils.kt
index 4d2a66e9394..34590214bac 100644
--- a/compiler/fir/java/src/org/jetbrains/kotlin/fir/java/JavaUtils.kt
+++ b/compiler/fir/java/src/org/jetbrains/kotlin/fir/java/JavaUtils.kt
@@ -92,9 +92,12 @@ internal fun FirTypeRef.toConeKotlinTypeProbablyFlexible(
}
internal fun JavaType.toFirJavaTypeRef(session: FirSession, javaTypeParameterStack: JavaTypeParameterStack): FirJavaTypeRef {
- val annotations = (this as? JavaClassifierType)?.annotations.orEmpty()
return buildJavaTypeRef {
- annotations.mapTo(this.annotations) { it.toFirAnnotationCall(session, javaTypeParameterStack) }
+ annotationBuilder = {
+ (this@toFirJavaTypeRef as? JavaClassifierType)?.annotations.orEmpty().map {
+ it.toFirAnnotationCall(session, javaTypeParameterStack)
+ }
+ }
type = this@toFirJavaTypeRef
}
}
@@ -578,7 +581,7 @@ internal fun JavaValueParameter.toFirValueParameter(
name = this@toFirValueParameter.name ?: Name.identifier("p$index")
returnTypeRef = type.toFirJavaTypeRef(session, javaTypeParameterStack)
isVararg = this@toFirValueParameter.isVararg
- addAnnotationsFrom(session, this@toFirValueParameter, javaTypeParameterStack)
+ annotationBuilder = { annotations.map { it.toFirAnnotationCall(session, javaTypeParameterStack) }}
}
}
diff --git a/compiler/fir/java/src/org/jetbrains/kotlin/fir/java/declarations/FirJavaValueParameter.kt b/compiler/fir/java/src/org/jetbrains/kotlin/fir/java/declarations/FirJavaValueParameter.kt
index ae2033e7631..abc2d4d2de3 100644
--- a/compiler/fir/java/src/org/jetbrains/kotlin/fir/java/declarations/FirJavaValueParameter.kt
+++ b/compiler/fir/java/src/org/jetbrains/kotlin/fir/java/declarations/FirJavaValueParameter.kt
@@ -9,52 +9,150 @@ import org.jetbrains.kotlin.fir.FirImplementationDetail
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.FirSourceElement
import org.jetbrains.kotlin.fir.builder.FirBuilderDsl
-import org.jetbrains.kotlin.fir.declarations.FirDeclarationAttributes
-import org.jetbrains.kotlin.fir.declarations.FirDeclarationOrigin
-import org.jetbrains.kotlin.fir.declarations.FirResolvePhase
-import org.jetbrains.kotlin.fir.declarations.FirValueParameter
-import org.jetbrains.kotlin.fir.declarations.builder.FirValueParameterBuilder
-import org.jetbrains.kotlin.fir.declarations.impl.FirValueParameterImpl
+import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.expressions.FirAnnotationCall
import org.jetbrains.kotlin.fir.expressions.FirExpression
+import org.jetbrains.kotlin.fir.references.FirControlFlowGraphReference
+import org.jetbrains.kotlin.fir.symbols.impl.FirDelegateFieldSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirVariableSymbol
import org.jetbrains.kotlin.fir.types.FirTypeRef
+import org.jetbrains.kotlin.fir.visitors.FirTransformer
+import org.jetbrains.kotlin.fir.visitors.FirVisitor
+import org.jetbrains.kotlin.fir.visitors.transformSingle
import org.jetbrains.kotlin.name.Name
@OptIn(FirImplementationDetail::class)
class FirJavaValueParameter @FirImplementationDetail constructor(
- source: FirSourceElement?,
- session: FirSession,
- resolvePhase: FirResolvePhase,
- attributes: FirDeclarationAttributes,
- returnTypeRef: FirTypeRef,
- name: Name,
- symbol: FirVariableSymbol,
- annotations: MutableList,
- defaultValue: FirExpression?,
- isCrossinline: Boolean,
- isNoinline: Boolean,
- isVararg: Boolean,
-) : FirValueParameterImpl(
- source,
- session,
- resolvePhase,
- FirDeclarationOrigin.Java,
- attributes,
- returnTypeRef,
- name,
- symbol,
- annotations,
- defaultValue,
- isCrossinline,
- isNoinline,
- isVararg,
-)
+ override val source: FirSourceElement?,
+ override val session: FirSession,
+ override var resolvePhase: FirResolvePhase,
+ override val attributes: FirDeclarationAttributes,
+ override var returnTypeRef: FirTypeRef,
+ override val name: Name,
+ override val symbol: FirVariableSymbol,
+ annotationBuilder: () -> List,
+ override var defaultValue: FirExpression?,
+ override val isVararg: Boolean,
+) : FirValueParameter() {
+ init {
+ symbol.bind(this)
+ }
+
+ override val isCrossinline: Boolean
+ get() = false
+
+ override val isNoinline: Boolean
+ get() = false
+
+ override val isVal: Boolean
+ get() = true
+
+ override val isVar: Boolean
+ get() = false
+
+ override val annotations: List by lazy { annotationBuilder() }
+
+ override val origin: FirDeclarationOrigin
+ get() = FirDeclarationOrigin.Java
+
+ override val receiverTypeRef: FirTypeRef?
+ get() = null
+
+ override val initializer: FirExpression?
+ get() = null
+
+ override val delegate: FirExpression?
+ get() = null
+
+ override val delegateFieldSymbol: FirDelegateFieldSymbol?
+ get() = null
+
+ override val getter: FirPropertyAccessor?
+ get() = null
+
+ override val setter: FirPropertyAccessor?
+ get() = null
+
+ override val controlFlowGraphReference: FirControlFlowGraphReference?
+ get() = null
+
+ override fun acceptChildren(visitor: FirVisitor, data: D) {
+ returnTypeRef.accept(visitor, data)
+ annotations.forEach { it.accept(visitor, data) }
+ defaultValue?.accept(visitor, data)
+ }
+
+ override fun transformChildren(transformer: FirTransformer, data: D): FirValueParameter {
+ transformReturnTypeRef(transformer, data)
+ transformOtherChildren(transformer, data)
+ return this
+ }
+
+ override fun transformReturnTypeRef(transformer: FirTransformer, data: D): FirValueParameter {
+ returnTypeRef = returnTypeRef.transformSingle(transformer, data)
+ return this
+ }
+
+ override fun transformReceiverTypeRef(transformer: FirTransformer, data: D): FirValueParameter {
+ return this
+ }
+
+ override fun transformInitializer(transformer: FirTransformer, data: D): FirValueParameter {
+ return this
+ }
+
+ override fun transformDelegate(transformer: FirTransformer, data: D): FirValueParameter {
+ return this
+ }
+
+ override fun transformGetter(transformer: FirTransformer, data: D): FirValueParameter {
+ return this
+ }
+
+ override fun transformSetter(transformer: FirTransformer, data: D): FirValueParameter {
+ return this
+ }
+
+ override fun transformAnnotations(transformer: FirTransformer, data: D): FirValueParameter {
+ return this
+ }
+
+ override fun transformOtherChildren(transformer: FirTransformer, data: D): FirValueParameter {
+ defaultValue = defaultValue?.transformSingle(transformer, data)
+ return this
+ }
+
+ override fun replaceResolvePhase(newResolvePhase: FirResolvePhase) {
+ resolvePhase = newResolvePhase
+ }
+
+ override fun replaceReturnTypeRef(newReturnTypeRef: FirTypeRef) {
+ returnTypeRef = newReturnTypeRef
+ }
+
+ override fun replaceReceiverTypeRef(newReceiverTypeRef: FirTypeRef?) {
+ }
+
+ override fun replaceInitializer(newInitializer: FirExpression?) {
+ }
+
+ override fun replaceControlFlowGraphReference(newControlFlowGraphReference: FirControlFlowGraphReference?) {
+ }
+}
@FirBuilderDsl
-class FirJavaValueParameterBuilder : FirValueParameterBuilder() {
+class FirJavaValueParameterBuilder {
+ var source: FirSourceElement? = null
+ lateinit var session: FirSession
+ var attributes: FirDeclarationAttributes = FirDeclarationAttributes()
+ lateinit var returnTypeRef: FirTypeRef
+ lateinit var name: Name
+ lateinit var annotationBuilder: () -> List
+ var defaultValue: FirExpression? = null
+ var isVararg: Boolean by kotlin.properties.Delegates.notNull()
+
@OptIn(FirImplementationDetail::class)
- override fun build(): FirJavaValueParameter {
+ fun build(): FirJavaValueParameter {
return FirJavaValueParameter(
source,
session,
@@ -63,48 +161,11 @@ class FirJavaValueParameterBuilder : FirValueParameterBuilder() {
returnTypeRef,
name,
symbol = FirVariableSymbol(name),
- annotations,
+ annotationBuilder,
defaultValue,
- isCrossinline = false,
- isNoinline = false,
isVararg,
)
}
-
- @Deprecated("Modification of 'resolvePhase' has no impact for FirJavaValueParameterBuilder", level = DeprecationLevel.HIDDEN)
- override var resolvePhase: FirResolvePhase
- get() = throw IllegalStateException()
- set(@Suppress("UNUSED_PARAMETER") value) {
- throw IllegalStateException()
- }
-
- @Deprecated("Modification of '' has no impact for FirJavaValueParameterBuilder", level = DeprecationLevel.HIDDEN)
- override var symbol: FirVariableSymbol
- get() = throw IllegalStateException()
- set(@Suppress("UNUSED_PARAMETER") value) {
- throw IllegalStateException()
- }
-
- @Deprecated("Modification of 'isCrossinline' has no impact for FirJavaValueParameterBuilder", level = DeprecationLevel.HIDDEN)
- override var isCrossinline: Boolean
- get() = throw IllegalStateException()
- set(@Suppress("UNUSED_PARAMETER") value) {
- throw IllegalStateException()
- }
-
- @Deprecated("Modification of 'isNoinline' has no impact for FirJavaValueParameterBuilder", level = DeprecationLevel.HIDDEN)
- override var isNoinline: Boolean
- get() = throw IllegalStateException()
- set(@Suppress("UNUSED_PARAMETER") value) {
- throw IllegalStateException()
- }
-
- @Deprecated("Modification of 'origin' has no impact for FirJavaValueParameterBuilder", level = DeprecationLevel.HIDDEN)
- override var origin: FirDeclarationOrigin
- get() = throw IllegalStateException()
- set(@Suppress("UNUSED_PARAMETER") value) {
- throw IllegalStateException()
- }
}
inline fun buildJavaValueParameter(init: FirJavaValueParameterBuilder.() -> Unit): FirJavaValueParameter {
diff --git a/compiler/fir/jvm/src/org/jetbrains/kotlin/fir/types/jvm/FirJavaTypeRef.kt b/compiler/fir/jvm/src/org/jetbrains/kotlin/fir/types/jvm/FirJavaTypeRef.kt
index 2d8b05fa664..edf658289f1 100644
--- a/compiler/fir/jvm/src/org/jetbrains/kotlin/fir/types/jvm/FirJavaTypeRef.kt
+++ b/compiler/fir/jvm/src/org/jetbrains/kotlin/fir/types/jvm/FirJavaTypeRef.kt
@@ -5,39 +5,59 @@
package org.jetbrains.kotlin.fir.types.jvm
+import org.jetbrains.kotlin.fir.FirAnnotationContainer
import org.jetbrains.kotlin.fir.FirSourceElement
import org.jetbrains.kotlin.fir.builder.FirBuilderDsl
import org.jetbrains.kotlin.fir.expressions.FirAnnotationCall
import org.jetbrains.kotlin.fir.types.FirQualifierPart
-import org.jetbrains.kotlin.fir.types.builder.FirUserTypeRefBuilder
-import org.jetbrains.kotlin.fir.types.impl.FirUserTypeRefImpl
+import org.jetbrains.kotlin.fir.types.FirTypeProjection
+import org.jetbrains.kotlin.fir.types.FirUserTypeRef
+import org.jetbrains.kotlin.fir.visitors.FirTransformer
+import org.jetbrains.kotlin.fir.visitors.FirVisitor
+import org.jetbrains.kotlin.fir.visitors.transformInplace
import org.jetbrains.kotlin.load.java.structure.JavaType
class FirJavaTypeRef(
val type: JavaType,
- annotations: MutableList,
- qualifier: MutableList
-) : FirUserTypeRefImpl(
- source = null,
- isMarkedNullable = false,
- qualifier,
- annotations
-)
+ annotationBuilder: () -> List,
+ override val qualifier: MutableList
+) : FirUserTypeRef(), FirAnnotationContainer {
+ override val isMarkedNullable: Boolean
+ get() = false
-@FirBuilderDsl
-class FirJavaTypeRefBuilder : FirUserTypeRefBuilder() {
- override val annotations: MutableList = mutableListOf()
- lateinit var type: JavaType
+ override val source: FirSourceElement?
+ get() = null
- override fun build(): FirJavaTypeRef {
- return FirJavaTypeRef(type, annotations, qualifier)
+ override val annotations: List by lazy { annotationBuilder() }
+
+ override fun acceptChildren(visitor: FirVisitor, data: D) {
+ for (part in qualifier) {
+ part.typeArgumentList.typeArguments.forEach { it.accept(visitor, data) }
+ }
+ annotations.forEach { it.accept(visitor, data) }
}
- @Deprecated("Modification of 'source' has no impact for FirJavaTypeRefBuilder", level = DeprecationLevel.HIDDEN)
- override var source: FirSourceElement? = null
+ override fun transformChildren(transformer: FirTransformer, data: D): FirUserTypeRef {
+ for (part in qualifier) {
+ (part.typeArgumentList.typeArguments as MutableList).transformInplace(transformer, data)
+ }
+ return this
+ }
- @Deprecated("Modification of 'isMarkedNullable' has no impact for FirJavaTypeRefBuilder", level = DeprecationLevel.HIDDEN)
- override var isMarkedNullable: Boolean = false
+ override fun transformAnnotations(transformer: FirTransformer, data: D): FirUserTypeRef {
+ return this
+ }
+}
+
+@FirBuilderDsl
+class FirJavaTypeRefBuilder {
+ lateinit var annotationBuilder: () -> List
+ lateinit var type: JavaType
+ val qualifier: MutableList = mutableListOf()
+
+ fun build(): FirJavaTypeRef {
+ return FirJavaTypeRef(type, annotationBuilder, qualifier)
+ }
}
inline fun buildJavaTypeRef(init: FirJavaTypeRefBuilder.() -> Unit): FirJavaTypeRef {
diff --git a/compiler/fir/modularized-tests/build.gradle.kts b/compiler/fir/modularized-tests/build.gradle.kts
index afe0d62cb39..a36d6f1e0e5 100644
--- a/compiler/fir/modularized-tests/build.gradle.kts
+++ b/compiler/fir/modularized-tests/build.gradle.kts
@@ -30,7 +30,7 @@ dependencies {
testCompileOnly(project(":kotlin-reflect-api"))
testRuntimeOnly(project(":kotlin-reflect"))
testRuntimeOnly(project(":core:descriptors.runtime"))
- testApi(projectTests(":compiler:fir:analysis-tests"))
+ testApi(projectTests(":compiler:fir:analysis-tests:legacy-fir-tests"))
testApi(project(":compiler:fir:resolve"))
testApi(project(":compiler:fir:dump"))
diff --git a/compiler/fir/raw-fir/light-tree2fir/src/org/jetbrains/kotlin/fir/lightTree/converter/BaseConverter.kt b/compiler/fir/raw-fir/light-tree2fir/src/org/jetbrains/kotlin/fir/lightTree/converter/BaseConverter.kt
index d3a94e3be12..c6dd15735af 100644
--- a/compiler/fir/raw-fir/light-tree2fir/src/org/jetbrains/kotlin/fir/lightTree/converter/BaseConverter.kt
+++ b/compiler/fir/raw-fir/light-tree2fir/src/org/jetbrains/kotlin/fir/lightTree/converter/BaseConverter.kt
@@ -126,6 +126,16 @@ abstract class BaseConverter(
return tree.getParent(this)
}
+ fun LighterASTNode.getParents(): Sequence {
+ var node = this
+ return sequence {
+ while (true) {
+ yield(node)
+ node = node.getParent() ?: break
+ }
+ }
+ }
+
fun LighterASTNode?.getChildNodesByType(type: IElementType): List {
return this?.forEachChildrenReturnList { node, container ->
when (node.tokenType) {
diff --git a/compiler/fir/raw-fir/light-tree2fir/src/org/jetbrains/kotlin/fir/lightTree/converter/DeclarationsConverter.kt b/compiler/fir/raw-fir/light-tree2fir/src/org/jetbrains/kotlin/fir/lightTree/converter/DeclarationsConverter.kt
index 7def4ad4f41..5cf75ad4e89 100644
--- a/compiler/fir/raw-fir/light-tree2fir/src/org/jetbrains/kotlin/fir/lightTree/converter/DeclarationsConverter.kt
+++ b/compiler/fir/raw-fir/light-tree2fir/src/org/jetbrains/kotlin/fir/lightTree/converter/DeclarationsConverter.kt
@@ -1410,7 +1410,7 @@ class DeclarationsConverter(
return if (!stubMode) {
val blockTree = LightTree2Fir.buildLightTreeBlockExpression(block.asText)
return DeclarationsConverter(
- baseSession, baseScopeProvider, stubMode, blockTree, offset = tree.getStartOffset(block), context
+ baseSession, baseScopeProvider, stubMode, blockTree, offset = offset + tree.getStartOffset(block), context
).convertBlockExpression(blockTree.root)
} else {
val firExpression = buildExpressionStub()
diff --git a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/LookupTagUtils.kt b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/LookupTagUtils.kt
index 3ed79836a58..14f6da469f7 100644
--- a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/LookupTagUtils.kt
+++ b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/LookupTagUtils.kt
@@ -6,6 +6,7 @@
package org.jetbrains.kotlin.fir.resolve
import org.jetbrains.kotlin.fir.FirSession
+import org.jetbrains.kotlin.fir.declarations.FirRegularClass
import org.jetbrains.kotlin.fir.resolve.providers.FirSymbolProvider
import org.jetbrains.kotlin.fir.symbols.ConeClassLikeLookupTag
import org.jetbrains.kotlin.fir.symbols.ConeClassifierLookupTag
@@ -32,6 +33,9 @@ fun ConeClassLikeLookupTag.toSymbol(useSiteSession: FirSession): FirClassLikeSym
}
}
+fun ConeClassLikeLookupTag.toFirRegularClass(session: FirSession): FirRegularClass? =
+ session.firSymbolProvider.getSymbolByLookupTag(this)?.fir as? FirRegularClass
+
@OptIn(LookupTagInternals::class)
fun ConeClassLikeLookupTagImpl.bindSymbolToLookupTag(session: FirSession, symbol: FirClassLikeSymbol<*>?) {
boundSymbol = OneElementWeakMap(session, symbol)
diff --git a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/SamResolution.kt b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/SamResolution.kt
index 0b8947f2440..ed9ea28cca3 100644
--- a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/SamResolution.kt
+++ b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/SamResolution.kt
@@ -45,7 +45,7 @@ val SAM_PARAMETER_NAME = Name.identifier("block")
class FirSamResolverImpl(
private val firSession: FirSession,
private val scopeSession: ScopeSession,
- private val outerClassManager: FirOuterClassManager,
+ private val outerClassManager: FirOuterClassManager? = null,
) : FirSamResolver() {
private val resolvedFunctionType: MutableMap = mutableMapOf()
@@ -70,11 +70,7 @@ class FirSamResolverImpl(
}
private fun getFunctionTypeForPossibleSamType(type: ConeClassLikeType): ConeLookupTagBasedType? {
- val firRegularClass =
- firSession.firSymbolProvider
- .getSymbolByLookupTag(type.lookupTag)
- ?.fir as? FirRegularClass
- ?: return null
+ val firRegularClass = type.lookupTag.toFirRegularClass(firSession) ?: return null
val unsubstitutedFunctionType = resolveFunctionTypeIfSamInterface(firRegularClass) ?: return null
@@ -210,7 +206,7 @@ class FirSamResolverImpl(
resolvePhase = FirResolvePhase.BODY_RESOLVE
}.apply {
- containingClassAttr = outerClassManager.outerClass(firRegularClass.symbol)?.toLookupTag()
+ containingClassAttr = outerClassManager?.outerClass(firRegularClass.symbol)?.toLookupTag()
}
}
diff --git a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/calls/Arguments.kt b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/calls/Arguments.kt
index 25593e0f709..511470096ca 100644
--- a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/calls/Arguments.kt
+++ b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/calls/Arguments.kt
@@ -24,7 +24,9 @@ import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.resolve.calls.inference.ConstraintSystemBuilder
import org.jetbrains.kotlin.resolve.calls.inference.addSubtypeConstraintIfCompatible
import org.jetbrains.kotlin.resolve.calls.inference.model.SimpleConstraintSystemConstraintPosition
+import org.jetbrains.kotlin.types.AbstractTypeChecker
import org.jetbrains.kotlin.types.model.CaptureStatus
+import org.jetbrains.kotlin.utils.addToStdlib.runIf
fun Candidate.resolveArgumentExpression(
csBuilder: ConstraintSystemBuilder,
@@ -336,10 +338,9 @@ internal fun Candidate.resolveArgument(
sink: CheckerSink,
context: ResolutionContext
) {
-
argument.resultType.ensureResolvedTypeDeclaration(context.session)
- val expectedType = prepareExpectedType(context.session, argument, parameter, context)
+ val expectedType = prepareExpectedType(context.session, context.bodyResolveComponents.scopeSession, argument, parameter, context)
resolveArgumentExpression(
this.system.getBuilder(),
argument,
@@ -354,18 +355,20 @@ internal fun Candidate.resolveArgument(
private fun Candidate.prepareExpectedType(
session: FirSession,
+ scopeSession: ScopeSession,
argument: FirExpression,
parameter: FirValueParameter?,
context: ResolutionContext
): ConeKotlinType? {
if (parameter == null) return null
val basicExpectedType = argument.getExpectedTypeForSAMConversion(parameter/*, LanguageVersionSettings*/)
- val expectedType = getExpectedTypeWithSAMConversion(session, argument, basicExpectedType, context) ?: basicExpectedType
+ val expectedType = getExpectedTypeWithSAMConversion(session, scopeSession, argument, basicExpectedType, context) ?: basicExpectedType
return this.substitutor.substituteOrSelf(expectedType)
}
private fun Candidate.getExpectedTypeWithSAMConversion(
session: FirSession,
+ scopeSession: ScopeSession,
argument: FirExpression,
candidateExpectedType: ConeKotlinType,
context: ResolutionContext
@@ -375,20 +378,70 @@ private fun Candidate.getExpectedTypeWithSAMConversion(
val firFunction = symbol.fir as? FirFunction<*> ?: return null
if (!context.bodyResolveComponents.samResolver.shouldRunSamConversionForFunction(firFunction)) return null
- if (!argument.isFunctional(session)) return null
-
// TODO: resolvedCall.registerArgumentWithSamConversion(argument, SamConversionDescription(convertedTypeByOriginal, convertedTypeByCandidate!!))
- return context.bodyResolveComponents.samResolver.getFunctionTypeForPossibleSamType(candidateExpectedType).apply {
- usesSAM = true
+ val expectedFunctionType = context.bodyResolveComponents.samResolver.getFunctionTypeForPossibleSamType(candidateExpectedType)
+ return runIf(argument.isFunctional(session, scopeSession, expectedFunctionType)) {
+ expectedFunctionType.apply {
+ // Even though the `expectedFunctionalType` could be `null`, we should mark the flag to indicate that the argument is a
+ // functional type. That will help avoid ambiguous `invoke` resolutions. See KT-39824
+ usesSAM = true
+ }
}
}
-fun FirExpression.isFunctional(session: FirSession): Boolean =
+fun FirExpression.isFunctional(
+ session: FirSession,
+ scopeSession: ScopeSession,
+ expectedFunctionType: ConeKotlinType?,
+): Boolean {
when ((this as? FirWrappedArgumentExpression)?.expression ?: this) {
- is FirAnonymousFunction, is FirCallableReferenceAccess -> true
- else -> typeRef.coneTypeSafe()?.isBuiltinFunctionalType(session) == true
+ is FirAnonymousFunction, is FirCallableReferenceAccess -> return true
+ else -> {
+ // Either a functional type or a subtype of a class that has a contributed `invoke`.
+ val coneType = typeRef.coneTypeSafe() ?: return false
+ if (coneType.isBuiltinFunctionalType(session)) {
+ return true
+ }
+ val classLikeExpectedFunctionType = expectedFunctionType?.lowerBoundIfFlexible() as? ConeClassLikeType
+ if (classLikeExpectedFunctionType == null || coneType is ConeIntegerLiteralType) {
+ return false
+ }
+ val invokeSymbol =
+ coneType.findContributedInvokeSymbol(
+ session, scopeSession, classLikeExpectedFunctionType, shouldCalculateReturnTypesOfFakeOverrides = false
+ ) ?: return false
+ // Make sure the contributed `invoke` is indeed a wanted functional type by checking if types are compatible.
+ val expectedReturnType = classLikeExpectedFunctionType.returnType(session)!!.lowerBoundIfFlexible()
+ val returnTypeCompatible =
+ expectedReturnType is ConeTypeParameterType ||
+ AbstractTypeChecker.isSubtypeOf(
+ session.inferenceComponents.ctx,
+ invokeSymbol.fir.returnTypeRef.coneType,
+ expectedReturnType,
+ isFromNullabilityConstraint = false
+ )
+ if (!returnTypeCompatible) {
+ return false
+ }
+ if (invokeSymbol.fir.valueParameters.size != classLikeExpectedFunctionType.typeArguments.size - 1) {
+ return false
+ }
+ val parameterPairs =
+ invokeSymbol.fir.valueParameters.zip(classLikeExpectedFunctionType.valueParameterTypesIncludingReceiver(session))
+ return parameterPairs.all { (invokeParameter, expectedParameter) ->
+ val expectedParameterType = expectedParameter!!.lowerBoundIfFlexible()
+ expectedParameterType is ConeTypeParameterType ||
+ AbstractTypeChecker.isSubtypeOf(
+ session.inferenceComponents.ctx,
+ invokeParameter.returnTypeRef.coneType,
+ expectedParameterType,
+ isFromNullabilityConstraint = false
+ )
+ }
+ }
}
+}
fun FirExpression.getExpectedTypeForSAMConversion(
parameter: FirValueParameter/*, languageVersionSettings: LanguageVersionSettings*/
diff --git a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/calls/CallableReferenceResolution.kt b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/calls/CallableReferenceResolution.kt
index 697b5c25814..3fcf7709d64 100644
--- a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/calls/CallableReferenceResolution.kt
+++ b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/calls/CallableReferenceResolution.kt
@@ -401,6 +401,8 @@ private fun createKPropertyType(
private fun FirVariable<*>.canBeMutableReference(candidate: Candidate): Boolean {
if (!isVar) return false
if (this is FirField) return true
- return source?.kind == FirFakeSourceElementKind.PropertyFromParameter ||
- (setter is FirMemberDeclaration && candidate.callInfo.session.visibilityChecker.isVisible(setter!!, candidate))
+ val original = this.unwrapFakeOverrides()
+ return original.source?.kind == FirFakeSourceElementKind.PropertyFromParameter ||
+ (original.setter is FirMemberDeclaration &&
+ candidate.callInfo.session.visibilityChecker.isVisible(original.setter!!, candidate))
}
diff --git a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/calls/Synthetics.kt b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/calls/Synthetics.kt
index 25e195c42c2..e81090204a9 100644
--- a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/calls/Synthetics.kt
+++ b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/calls/Synthetics.kt
@@ -80,28 +80,22 @@ class FirSyntheticPropertiesScope(
val parameter = setter.valueParameters.singleOrNull() ?: return
if (setter.typeParameters.isNotEmpty() || setter.isStatic) return
val parameterType = (parameter.returnTypeRef as? FirResolvedTypeRef)?.type ?: return
- if (getter.symbol.dispatchReceiverClassOrNull() == setter.symbol.dispatchReceiverClassOrNull()) {
- if (getterReturnType.withNullability(NOT_NULL) != parameterType.withNullability(NOT_NULL)) {
- return
- }
- } else {
- // TODO: at this moment it works for cases like
- // class Base {
- // void setSomething(Object value) {}
- // }
- // class Derived extends Base {
- // String getSomething() { return ""; }
- // }
- // In FE 1.0, we should have also Object getSomething() in class Base for this to work
- // I think details here are worth designing
- if (!AbstractTypeChecker.isSubtypeOf(
- session.typeContext,
- getterReturnType.withNullability(NOT_NULL),
- parameterType.withNullability(NOT_NULL)
- )
- ) {
- return
- }
+ // TODO: at this moment it works for cases like
+ // class Base {
+ // void setSomething(Object value) {}
+ // }
+ // class Derived extends Base {
+ // String getSomething() { return ""; }
+ // }
+ // In FE 1.0, we should have also Object getSomething() in class Base for this to work
+ // I think details here are worth designing
+ if (!AbstractTypeChecker.isSubtypeOf(
+ session.typeContext,
+ getterReturnType.withNullability(NOT_NULL),
+ parameterType.withNullability(NOT_NULL)
+ )
+ ) {
+ return
}
matchingSetter = setter
})
diff --git a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/inference/FirCallCompleter.kt b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/inference/FirCallCompleter.kt
index 217f86e2997..f3dc5091520 100644
--- a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/inference/FirCallCompleter.kt
+++ b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/inference/FirCallCompleter.kt
@@ -5,12 +5,14 @@
package org.jetbrains.kotlin.fir.resolve.inference
+import org.jetbrains.kotlin.fir.FirFakeSourceElementKind
import org.jetbrains.kotlin.fir.declarations.FirAnonymousFunction
import org.jetbrains.kotlin.fir.declarations.FirDeclarationOrigin
import org.jetbrains.kotlin.fir.declarations.builder.buildValueParameter
import org.jetbrains.kotlin.fir.expressions.FirExpression
import org.jetbrains.kotlin.fir.expressions.FirResolvable
import org.jetbrains.kotlin.fir.expressions.FirStatement
+import org.jetbrains.kotlin.fir.fakeElement
import org.jetbrains.kotlin.fir.resolve.ResolutionMode
import org.jetbrains.kotlin.fir.resolve.calls.Candidate
import org.jetbrains.kotlin.fir.resolve.calls.FirNamedReferenceWithCandidate
@@ -33,7 +35,6 @@ import org.jetbrains.kotlin.fir.visitors.transformSingle
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.calls.inference.buildAbstractResultingSubstitutor
import org.jetbrains.kotlin.resolve.calls.inference.components.ConstraintSystemCompletionMode
-import org.jetbrains.kotlin.resolve.calls.inference.model.ArgumentConstraintPosition
import org.jetbrains.kotlin.resolve.calls.inference.model.SimpleConstraintSystemConstraintPosition
import org.jetbrains.kotlin.types.TypeApproximatorConfiguration
import org.jetbrains.kotlin.types.model.StubTypeMarker
@@ -183,6 +184,7 @@ class FirCallCompleter(
val name = Name.identifier("it")
val itType = parameters.single()
buildValueParameter {
+ source = lambdaAtom.atom.source?.fakeElement(FirFakeSourceElementKind.ItLambdaParameter)
session = this@FirCallCompleter.session
origin = FirDeclarationOrigin.Source
returnTypeRef = buildResolvedTypeRef { type = itType.approximateLambdaInputType() }
diff --git a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/transformers/body/resolve/FirAbstractBodyResolveTransformer.kt b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/transformers/body/resolve/FirAbstractBodyResolveTransformer.kt
index 6a9861c2657..a6e34ba1512 100644
--- a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/transformers/body/resolve/FirAbstractBodyResolveTransformer.kt
+++ b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/transformers/body/resolve/FirAbstractBodyResolveTransformer.kt
@@ -60,6 +60,14 @@ abstract class FirAbstractBodyResolveTransformer(phase: FirResolvePhase) : FirAb
context.addLocalScope(localScope)
}
+ protected open fun needReplacePhase(firDeclaration: FirDeclaration) = true
+
+ fun replaceDeclarationResolvePhaseIfNeeded(firDeclaration: FirDeclaration, newResolvePhase: FirResolvePhase) {
+ if (needReplacePhase(firDeclaration)) {
+ firDeclaration.replaceResolvePhase(newResolvePhase)
+ }
+ }
+
@OptIn(PrivateForInline::class)
internal inline fun withFullBodyResolve(crossinline l: () -> T): T {
val shouldSwitchMode = implicitTypeOnly
diff --git a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/transformers/body/resolve/FirDeclarationsResolveTransformer.kt b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/transformers/body/resolve/FirDeclarationsResolveTransformer.kt
index 2772a559120..42881d93694 100644
--- a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/transformers/body/resolve/FirDeclarationsResolveTransformer.kt
+++ b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/transformers/body/resolve/FirDeclarationsResolveTransformer.kt
@@ -57,7 +57,7 @@ open class FirDeclarationsResolveTransformer(transformer: FirBodyResolveTransfor
): CompositeTransformResult {
transformer.onBeforeDeclarationContentResolve(declaration)
return context.withContainer(declaration) {
- declaration.replaceResolvePhase(transformerPhase)
+ transformer.replaceDeclarationResolvePhaseIfNeeded(declaration, transformerPhase)
transformer.transformDeclarationContent(declaration, data)
}
}
@@ -84,7 +84,7 @@ open class FirDeclarationsResolveTransformer(transformer: FirBodyResolveTransfor
if (declaration.typeParameters.isEmpty()) return null
for (typeParameter in declaration.typeParameters) {
- (typeParameter as? FirTypeParameter)?.replaceResolvePhase(FirResolvePhase.STATUS)
+ (typeParameter as? FirTypeParameter)?.let { transformer.replaceDeclarationResolvePhaseIfNeeded(it, FirResolvePhase.STATUS) }
typeParameter.transformChildren(transformer, ResolutionMode.ContextIndependent)
}
@@ -115,7 +115,7 @@ open class FirDeclarationsResolveTransformer(transformer: FirBodyResolveTransfor
if (returnTypeRef !is FirImplicitTypeRef && implicitTypeOnly) return@withTypeParametersOf property.compose()
if (property.resolvePhase == transformerPhase) return@withTypeParametersOf property.compose()
if (property.resolvePhase == FirResolvePhase.IMPLICIT_TYPES_BODY_RESOLVE && transformerPhase == FirResolvePhase.BODY_RESOLVE) {
- property.replaceResolvePhase(transformerPhase)
+ transformer.replaceDeclarationResolvePhaseIfNeeded(property, transformerPhase)
return@withTypeParametersOf property.compose()
}
dataFlowAnalyzer.enterProperty(property)
@@ -142,7 +142,7 @@ open class FirDeclarationsResolveTransformer(transformer: FirBodyResolveTransfor
}
}
}
- property.replaceResolvePhase(transformerPhase)
+ transformer.replaceDeclarationResolvePhaseIfNeeded(property, transformerPhase)
dataFlowAnalyzer.exitProperty(property)?.let {
property.replaceControlFlowGraphReference(FirControlFlowGraphReferenceImpl(it))
}
@@ -267,7 +267,7 @@ open class FirDeclarationsResolveTransformer(transformer: FirBodyResolveTransfor
variable.transformAccessors()
}
context.storeVariable(variable)
- variable.replaceResolvePhase(transformerPhase)
+ transformer.replaceDeclarationResolvePhaseIfNeeded(variable, transformerPhase)
dataFlowAnalyzer.exitLocalVariableDeclaration(variable)
return variable.compose()
}
@@ -449,7 +449,7 @@ open class FirDeclarationsResolveTransformer(transformer: FirBodyResolveTransfor
): CompositeTransformResult {
if (simpleFunction.resolvePhase == transformerPhase) return simpleFunction.compose()
if (simpleFunction.resolvePhase == FirResolvePhase.IMPLICIT_TYPES_BODY_RESOLVE && transformerPhase == FirResolvePhase.BODY_RESOLVE) {
- simpleFunction.replaceResolvePhase(transformerPhase)
+ transformer.replaceDeclarationResolvePhaseIfNeeded(simpleFunction, transformerPhase)
return simpleFunction.compose()
}
val returnTypeRef = simpleFunction.returnTypeRef
@@ -546,7 +546,7 @@ open class FirDeclarationsResolveTransformer(transformer: FirBodyResolveTransfor
private fun doTransformConstructor(constructor: FirConstructor, data: ResolutionMode): CompositeTransformResult {
return context.withContainer(constructor) {
- constructor.replaceResolvePhase(transformerPhase)
+ transformer.replaceDeclarationResolvePhaseIfNeeded(constructor, transformerPhase)
dataFlowAnalyzer.enterFunction(constructor)
constructor.transformTypeParameters(transformer, data)
@@ -640,7 +640,7 @@ open class FirDeclarationsResolveTransformer(transformer: FirBodyResolveTransfor
override fun transformValueParameter(valueParameter: FirValueParameter, data: ResolutionMode): CompositeTransformResult {
context.storeVariable(valueParameter)
if (valueParameter.returnTypeRef is FirImplicitTypeRef) {
- valueParameter.replaceResolvePhase(transformerPhase)
+ transformer.replaceDeclarationResolvePhaseIfNeeded(valueParameter, transformerPhase)
return valueParameter.compose()
}
diff --git a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/transformers/body/resolve/FirImplicitBodyResolve.kt b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/transformers/body/resolve/FirImplicitBodyResolve.kt
index 725bf09fb9e..caccfb7499b 100644
--- a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/transformers/body/resolve/FirImplicitBodyResolve.kt
+++ b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/transformers/body/resolve/FirImplicitBodyResolve.kt
@@ -73,6 +73,7 @@ fun > F.runContractAndBodiesResolutionForLocalClass(
components.scopeSession,
implicitBodyResolveComputationSession,
designationMap,
+ createTransformer = components.returnTypeCalculator.getTransformerCreator()
)
val newContext = components.context.createSnapshotForLocalClasses(returnTypeCalculator, targetedClasses)
@@ -98,6 +99,11 @@ fun > F.runContractAndBodiesResolutionForLocalClass(
}
}
+private fun ReturnTypeCalculator.getTransformerCreator() = when (this) {
+ is ReturnTypeCalculatorWithJump -> createTransformer
+ else -> ::FirDesignatedBodyResolveTransformerForReturnTypeCalculator
+}
+
fun createReturnTypeCalculatorForIDE(
session: FirSession,
scopeSession: ScopeSession,
@@ -178,7 +184,7 @@ private class ReturnTypeCalculatorWithJump(
private val scopeSession: ScopeSession,
val implicitBodyResolveComputationSession: ImplicitBodyResolveComputationSession,
val designationMapForLocalClasses: Map, List>> = mapOf(),
- private val createTransformer: (
+ val createTransformer: (
designation: Iterator,
session: FirSession,
scopeSession: ScopeSession,
diff --git a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/transformers/contracts/FirContractResolveTransformer.kt b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/transformers/contracts/FirContractResolveTransformer.kt
index a3029da24a2..8d459fcd262 100644
--- a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/transformers/contracts/FirContractResolveTransformer.kt
+++ b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/transformers/contracts/FirContractResolveTransformer.kt
@@ -275,7 +275,7 @@ open class FirContractResolveTransformer(
get() = contractDescription is FirLegacyRawContractDescription || contractDescription is FirRawContractDescription
private fun FirDeclaration.updatePhase() {
- replaceResolvePhase(FirResolvePhase.CONTRACTS)
+ replaceDeclarationResolvePhaseIfNeeded(this, FirResolvePhase.CONTRACTS)
}
}
}
diff --git a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/scopes/Scopes.kt b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/scopes/Scopes.kt
index 37f4fdc2828..74af476098c 100644
--- a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/scopes/Scopes.kt
+++ b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/scopes/Scopes.kt
@@ -8,13 +8,9 @@ package org.jetbrains.kotlin.fir.scopes
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.declarations.FirFile
import org.jetbrains.kotlin.fir.declarations.FirRegularClass
-import org.jetbrains.kotlin.fir.resolve.ScopeSession
-import org.jetbrains.kotlin.fir.resolve.ScopeSessionKey
-import org.jetbrains.kotlin.fir.resolve.firSymbolProvider
-import org.jetbrains.kotlin.fir.resolve.scopeSessionKey
+import org.jetbrains.kotlin.fir.resolve.*
import org.jetbrains.kotlin.fir.scopes.impl.*
import org.jetbrains.kotlin.fir.symbols.ConeClassLikeLookupTag
-import org.jetbrains.kotlin.fir.symbols.impl.ConeClassLookupTagWithFixedSymbol
import org.jetbrains.kotlin.name.FqName
private object FirDefaultStarImportingScopeKey : ScopeSessionKey()
@@ -67,9 +63,6 @@ private fun doCreateImportingScopes(
private val PACKAGE_MEMBER = scopeSessionKey()
fun ConeClassLikeLookupTag.getNestedClassifierScope(session: FirSession, scopeSession: ScopeSession): FirScope? {
- val klass = when (this) {
- is ConeClassLookupTagWithFixedSymbol -> symbol.fir
- else -> session.firSymbolProvider.getClassLikeSymbolByFqName(classId)?.fir as? FirRegularClass ?: return null
- }
+ val klass = toSymbol(session)?.fir as? FirRegularClass ?: return null
return klass.scopeProvider.getNestedClassifierScope(klass, session, scopeSession)
}
diff --git a/compiler/fir/tree/gen/org/jetbrains/kotlin/fir/declarations/builder/FirValueParameterBuilder.kt b/compiler/fir/tree/gen/org/jetbrains/kotlin/fir/declarations/builder/FirValueParameterBuilder.kt
index bd059d3da02..2c7fe43fc43 100644
--- a/compiler/fir/tree/gen/org/jetbrains/kotlin/fir/declarations/builder/FirValueParameterBuilder.kt
+++ b/compiler/fir/tree/gen/org/jetbrains/kotlin/fir/declarations/builder/FirValueParameterBuilder.kt
@@ -6,7 +6,6 @@
package org.jetbrains.kotlin.fir.declarations.builder
import kotlin.contracts.*
-import org.jetbrains.kotlin.fir.FirImplementationDetail
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.FirSourceElement
import org.jetbrains.kotlin.fir.builder.FirAnnotationContainerBuilder
@@ -47,7 +46,6 @@ open class FirValueParameterBuilder : FirAnnotationContainerBuilder {
open var isNoinline: Boolean by kotlin.properties.Delegates.notNull()
open var isVararg: Boolean by kotlin.properties.Delegates.notNull()
- @OptIn(FirImplementationDetail::class)
override fun build(): FirValueParameter {
return FirValueParameterImpl(
source,
diff --git a/compiler/fir/tree/gen/org/jetbrains/kotlin/fir/declarations/impl/FirValueParameterImpl.kt b/compiler/fir/tree/gen/org/jetbrains/kotlin/fir/declarations/impl/FirValueParameterImpl.kt
index ea6ba94573c..760da4f6c9d 100644
--- a/compiler/fir/tree/gen/org/jetbrains/kotlin/fir/declarations/impl/FirValueParameterImpl.kt
+++ b/compiler/fir/tree/gen/org/jetbrains/kotlin/fir/declarations/impl/FirValueParameterImpl.kt
@@ -5,7 +5,6 @@
package org.jetbrains.kotlin.fir.declarations.impl
-import org.jetbrains.kotlin.fir.FirImplementationDetail
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.FirSourceElement
import org.jetbrains.kotlin.fir.declarations.FirDeclarationAttributes
@@ -27,7 +26,7 @@ import org.jetbrains.kotlin.fir.visitors.*
* DO NOT MODIFY IT MANUALLY
*/
-open class FirValueParameterImpl @FirImplementationDetail constructor(
+internal class FirValueParameterImpl(
override val source: FirSourceElement?,
override val session: FirSession,
override var resolvePhase: FirResolvePhase,
diff --git a/compiler/fir/tree/src/org/jetbrains/kotlin/fir/FirRenderer.kt b/compiler/fir/tree/src/org/jetbrains/kotlin/fir/FirRenderer.kt
index 0ffe3c50a01..52db4dc41f5 100644
--- a/compiler/fir/tree/src/org/jetbrains/kotlin/fir/FirRenderer.kt
+++ b/compiler/fir/tree/src/org/jetbrains/kotlin/fir/FirRenderer.kt
@@ -340,9 +340,7 @@ class FirRenderer(builder: StringBuilder, private val mode: RenderMode = RenderM
}
override fun visitDeclaration(declaration: FirDeclaration) {
- if (mode.renderDeclarationResolvePhase) {
- print("[${declaration.resolvePhase}] ")
- }
+ declaration.renderPhaseIfNeeded()
print(
when (declaration) {
is FirRegularClass -> declaration.classKind.name.toLowerCase().replace("_", " ")
@@ -359,6 +357,12 @@ class FirRenderer(builder: StringBuilder, private val mode: RenderMode = RenderM
)
}
+ private fun FirDeclaration.renderPhaseIfNeeded() {
+ if (mode.renderDeclarationResolvePhase) {
+ print("[${resolvePhase}] ")
+ }
+ }
+
private fun List.renderDeclarations() {
renderInBraces {
for (declaration in this) {
@@ -458,6 +462,7 @@ class FirRenderer(builder: StringBuilder, private val mode: RenderMode = RenderM
if (constructor.isActual) {
print("actual ")
}
+ constructor.renderPhaseIfNeeded()
print("constructor")
constructor.typeParameters.renderTypeParameters()
constructor.valueParameters.renderParameters()
diff --git a/compiler/fir/tree/src/org/jetbrains/kotlin/fir/FirSourceElement.kt b/compiler/fir/tree/src/org/jetbrains/kotlin/fir/FirSourceElement.kt
index cc05f1bb283..bab6e154260 100644
--- a/compiler/fir/tree/src/org/jetbrains/kotlin/fir/FirSourceElement.kt
+++ b/compiler/fir/tree/src/org/jetbrains/kotlin/fir/FirSourceElement.kt
@@ -157,6 +157,10 @@ sealed class FirFakeSourceElementKind : FirSourceElementKind() {
// Part of desugared x?.y
object CheckedSafeCallSubject : FirFakeSourceElementKind()
+
+ // { it + 1} --> { it -> it + 1 }
+ // where `it` parameter declaration has fake source
+ object ItLambdaParameter : FirFakeSourceElementKind()
}
sealed class FirSourceElement {
diff --git a/compiler/fir/tree/src/org/jetbrains/kotlin/fir/types/FirTypeUtils.kt b/compiler/fir/tree/src/org/jetbrains/kotlin/fir/types/FirTypeUtils.kt
index d3f114085c1..d0f4e6af615 100644
--- a/compiler/fir/tree/src/org/jetbrains/kotlin/fir/types/FirTypeUtils.kt
+++ b/compiler/fir/tree/src/org/jetbrains/kotlin/fir/types/FirTypeUtils.kt
@@ -7,6 +7,7 @@ package org.jetbrains.kotlin.fir.types
import org.jetbrains.kotlin.fir.expressions.FirAnnotationCall
import org.jetbrains.kotlin.fir.expressions.FirConstKind
+import org.jetbrains.kotlin.fir.render
import org.jetbrains.kotlin.fir.symbols.StandardClassIds
import org.jetbrains.kotlin.fir.types.impl.FirImplicitBuiltinTypeRef
import org.jetbrains.kotlin.name.ClassId
@@ -23,7 +24,9 @@ inline fun FirTypeRef.coneTypeSafe(): T? {
return (this as? FirResolvedTypeRef)?.type as? T
}
-inline val FirTypeRef.coneType: ConeKotlinType get() = coneTypeUnsafe()
+inline val FirTypeRef.coneType: ConeKotlinType
+ get() = coneTypeSafe()
+ ?: error("Expected FirResolvedTypeRef with ConeKotlinType but was ${this::class.simpleName} ${render()}")
val FirTypeRef.isAny: Boolean get() = isBuiltinType(StandardClassIds.Any, false)
val FirTypeRef.isNullableAny: Boolean get() = isBuiltinType(StandardClassIds.Any, true)
diff --git a/compiler/fir/tree/src/org/jetbrains/kotlin/fir/types/impl/FirUserTypeRefImpl.kt b/compiler/fir/tree/src/org/jetbrains/kotlin/fir/types/impl/FirUserTypeRefImpl.kt
index 3479d2782ad..7f6740bcfc7 100644
--- a/compiler/fir/tree/src/org/jetbrains/kotlin/fir/types/impl/FirUserTypeRefImpl.kt
+++ b/compiler/fir/tree/src/org/jetbrains/kotlin/fir/types/impl/FirUserTypeRefImpl.kt
@@ -15,7 +15,7 @@ import org.jetbrains.kotlin.fir.visitors.FirTransformer
import org.jetbrains.kotlin.fir.visitors.FirVisitor
import org.jetbrains.kotlin.fir.visitors.transformInplace
-open class FirUserTypeRefImpl(
+class FirUserTypeRefImpl(
override val source: FirSourceElement?,
override val isMarkedNullable: Boolean,
override val qualifier: MutableList,
diff --git a/compiler/fir/tree/tree-generator/src/org/jetbrains/kotlin/fir/tree/generator/ImplementationConfigurator.kt b/compiler/fir/tree/tree-generator/src/org/jetbrains/kotlin/fir/tree/generator/ImplementationConfigurator.kt
index 634ec2f9339..12becc42cf6 100644
--- a/compiler/fir/tree/tree-generator/src/org/jetbrains/kotlin/fir/tree/generator/ImplementationConfigurator.kt
+++ b/compiler/fir/tree/tree-generator/src/org/jetbrains/kotlin/fir/tree/generator/ImplementationConfigurator.kt
@@ -440,7 +440,6 @@ object ImplementationConfigurator : AbstractFirTreeImplementationConfigurator()
}
impl(valueParameter) {
- kind = OpenClass
defaultTrue("isVal", withGetter = true)
defaultFalse("isVar", withGetter = true)
defaultNull("getter", "setter", "initializer", "delegate", "receiverTypeRef", "delegateFieldSymbol", withGetter = true)
diff --git a/compiler/frontend.java/src/org/jetbrains/kotlin/frontend/java/di/injection.kt b/compiler/frontend.java/src/org/jetbrains/kotlin/frontend/java/di/injection.kt
index 8c45cf0a20c..21d9e76a569 100644
--- a/compiler/frontend.java/src/org/jetbrains/kotlin/frontend/java/di/injection.kt
+++ b/compiler/frontend.java/src/org/jetbrains/kotlin/frontend/java/di/injection.kt
@@ -28,7 +28,6 @@ import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.frontend.di.configureIncrementalCompilation
import org.jetbrains.kotlin.frontend.di.configureModule
import org.jetbrains.kotlin.frontend.di.configureStandardResolveComponents
-import org.jetbrains.kotlin.idea.MainFunctionDetector
import org.jetbrains.kotlin.incremental.components.ExpectActualTracker
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.load.java.AbstractJavaClassFinder
@@ -127,7 +126,7 @@ fun StorageComponentContainer.configureJavaSpecificComponents(
useInstance(languageVersionSettings.getFlag(JvmAnalysisFlags.javaTypeEnhancementState))
if (useBuiltInsProvider) {
- useInstance((moduleContext.module.builtIns as JvmBuiltIns).settings)
+ useInstance((moduleContext.module.builtIns as JvmBuiltIns).customizer)
useImpl()
}
useImpl()
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/Errors.java b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/Errors.java
index f0f38f9ac6f..6c449bc8fc9 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/Errors.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/Errors.java
@@ -118,7 +118,8 @@ public interface Errors {
DiagnosticFactory1 MISSING_IMPORTED_SCRIPT_PSI = DiagnosticFactory1.create(ERROR);
DiagnosticFactory1 MISSING_SCRIPT_PROVIDED_PROPERTY_CLASS = DiagnosticFactory1.create(ERROR);
DiagnosticFactory1 PRE_RELEASE_CLASS = DiagnosticFactory1.create(ERROR);
- DiagnosticFactory1 IR_COMPILED_CLASS = DiagnosticFactory1.create(ERROR);
+ DiagnosticFactory1 IR_WITH_UNSTABLE_ABI_COMPILED_CLASS = DiagnosticFactory1.create(ERROR);
+ DiagnosticFactory1 FIR_COMPILED_CLASS = DiagnosticFactory1.create(ERROR);
DiagnosticFactory2> INCOMPATIBLE_CLASS = DiagnosticFactory2.create(ERROR);
//Elements with "INVISIBLE_REFERENCE" error are marked as unresolved, unlike elements with "INVISIBLE_MEMBER" error
@@ -802,6 +803,7 @@ public interface Errors {
DiagnosticFactory1 TYPE_INFERENCE_UPPER_BOUND_VIOLATED = DiagnosticFactory1.create(ERROR);
DiagnosticFactory2 TYPE_INFERENCE_EXPECTED_TYPE_MISMATCH = DiagnosticFactory2.create(ERROR);
DiagnosticFactory0 TYPE_INFERENCE_CANDIDATE_WITH_SAM_AND_VARARG = DiagnosticFactory0.create(WARNING);
+ DiagnosticFactory0 TYPE_INFERENCE_POSTPONED_VARIABLE_IN_RECEIVER_TYPE = DiagnosticFactory0.create(ERROR);
DiagnosticFactory0 TYPE_INFERENCE_FAILED_ON_SPECIAL_CONSTRUCT = DiagnosticFactory0.create(ERROR, SPECIAL_CONSTRUCT_TOKEN);
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DefaultErrorMessages.java b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DefaultErrorMessages.java
index 75f9a22e5b8..4d5c0410f94 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DefaultErrorMessages.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DefaultErrorMessages.java
@@ -11,7 +11,6 @@ import kotlin.collections.CollectionsKt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.config.LanguageVersion;
-import org.jetbrains.kotlin.diagnostics.Diagnostic;
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory;
import org.jetbrains.kotlin.diagnostics.Errors;
import org.jetbrains.kotlin.diagnostics.UnboundDiagnostic;
@@ -401,7 +400,8 @@ public class DefaultErrorMessages {
MAP.put(MISSING_IMPORTED_SCRIPT_PSI, "Imported script file ''{0}'' is not loaded. Check your script imports", TO_STRING);
MAP.put(MISSING_SCRIPT_PROVIDED_PROPERTY_CLASS, "Cannot access script provided property class ''{0}''. Check your module classpath for missing or conflicting dependencies", TO_STRING);
MAP.put(PRE_RELEASE_CLASS, "{0} is compiled by a pre-release version of Kotlin and cannot be loaded by this version of the compiler", TO_STRING);
- MAP.put(IR_COMPILED_CLASS, "{0} is compiled by a new Kotlin compiler backend and cannot be loaded by the old compiler", TO_STRING);
+ MAP.put(IR_WITH_UNSTABLE_ABI_COMPILED_CLASS, "{0} is compiled by an unstable version of the Kotlin compiler and cannot be loaded by this compiler", TO_STRING);
+ MAP.put(FIR_COMPILED_CLASS, "{0} is compiled by the new Kotlin compiler frontend and cannot be loaded by the old compiler", TO_STRING);
MAP.put(INCOMPATIBLE_CLASS,
"{0} was compiled with an incompatible version of Kotlin. {1}",
TO_STRING,
@@ -632,7 +632,7 @@ public class DefaultErrorMessages {
MAP.put(DATA_CLASS_CANNOT_HAVE_CLASS_SUPERTYPES, "Data class inheritance from other classes is forbidden");
MAP.put(SEALED_SUPERTYPE, "This type is sealed, so it can be inherited by only its own nested classes or objects");
MAP.put(SEALED_SUPERTYPE_IN_LOCAL_CLASS, "Local class cannot extend a sealed class");
- MAP.put(SEALED_INHERITOR_IN_DIFFERENT_PACKAGE, "Inheritor of sealed class or interface declared in package {1} but it must be in package {2} where base class is declared", TO_STRING, TO_STRING);
+ MAP.put(SEALED_INHERITOR_IN_DIFFERENT_PACKAGE, "Inheritor of sealed class or interface declared in package {0} but it must be in package {1} where base class is declared", TO_STRING, TO_STRING);
MAP.put(SEALED_INHERITOR_IN_DIFFERENT_MODULE, "Inheritance of sealed classes or interfaces from different module is prohibited");
MAP.put(CLASS_INHERITS_JAVA_SEALED_CLASS, "Inheritance of java sealed classes is prohibited");
MAP.put(SINGLETON_IN_SUPERTYPE, "Cannot inherit from a singleton");
@@ -899,6 +899,7 @@ public class DefaultErrorMessages {
MAP.put(TYPE_INFERENCE_UPPER_BOUND_VIOLATED, "{0}", TYPE_INFERENCE_UPPER_BOUND_VIOLATED_RENDERER);
MAP.put(TYPE_INFERENCE_EXPECTED_TYPE_MISMATCH, "Type inference failed. Expected type mismatch: inferred type is {1} but {0} was expected", RENDER_TYPE, RENDER_TYPE);
MAP.put(TYPE_INFERENCE_CANDIDATE_WITH_SAM_AND_VARARG, "Please use spread operator to pass an array as vararg. It will be an error in 1.5.");
+ MAP.put(TYPE_INFERENCE_POSTPONED_VARIABLE_IN_RECEIVER_TYPE, "Postponed type variable (type variable of the builder inference) can't be used in the receiver type. Use a member function instead of extension one or specify type arguments of a function which uses the builder inference, explicitly.");
MAP.put(TYPE_INFERENCE_FAILED_ON_SPECIAL_CONSTRUCT, "Type inference for control flow expression failed. Please specify its type explicitly.");
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/CompilerDeserializationConfiguration.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/CompilerDeserializationConfiguration.kt
index 84fe95ab7e3..23758d853c3 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/CompilerDeserializationConfiguration.kt
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/CompilerDeserializationConfiguration.kt
@@ -19,7 +19,7 @@ class CompilerDeserializationConfiguration(languageVersionSettings: LanguageVers
override val reportErrorsOnPreReleaseDependencies =
!skipPrereleaseCheck && !languageVersionSettings.isPreRelease() && !KotlinCompilerVersion.isPreRelease()
- override val reportErrorsOnIrDependencies = languageVersionSettings.getFlag(AnalysisFlags.reportErrorsOnIrDependencies)
+ override val allowUnstableDependencies = languageVersionSettings.getFlag(AnalysisFlags.allowUnstableDependencies)
override val typeAliasesAllowed = languageVersionSettings.supportsFeature(LanguageFeature.TypeAliases)
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/DelegatedPropertyResolver.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/DelegatedPropertyResolver.kt
index 765afd913b8..52ea1b1df76 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/DelegatedPropertyResolver.kt
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/DelegatedPropertyResolver.kt
@@ -545,7 +545,12 @@ class DelegatedPropertyResolver(
traceToResolveDelegatedProperty, false, delegateExpression, ContextDependency.DEPENDENT
)
- var delegateType = delegateTypeInfo.type ?: return null
+ if (delegateTypeInfo.type == null) {
+ traceToResolveDelegatedProperty.commit()
+ return null
+ }
+
+ var delegateType = delegateTypeInfo.type
var delegateDataFlow = delegateTypeInfo.dataFlowInfo
val delegateTypeConstructor = delegateType.constructor
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/DescriptorResolver.java b/compiler/frontend/src/org/jetbrains/kotlin/resolve/DescriptorResolver.java
index 2714eeef1ff..ac2ed637f87 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/DescriptorResolver.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/DescriptorResolver.java
@@ -328,7 +328,8 @@ public class DescriptorResolver {
}
destructuringVariables = () -> {
- assert owner.getDispatchReceiverParameter() == null
+ ReceiverParameterDescriptor dispatchReceiver = owner.getDispatchReceiverParameter();
+ assert dispatchReceiver == null || dispatchReceiver.getContainingDeclaration() instanceof ScriptDescriptor
: "Destructuring declarations are only be parsed for lambdas, and they must not have a dispatch receiver";
LexicalScope scopeForDestructuring =
ScopeUtilsKt.createScopeForDestructuring(scope, owner.getExtensionReceiverParameter());
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/DiagnosticReporterByTrackingStrategy.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/DiagnosticReporterByTrackingStrategy.kt
index 3ff54236166..4827e3e4d9a 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/DiagnosticReporterByTrackingStrategy.kt
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/DiagnosticReporterByTrackingStrategy.kt
@@ -31,13 +31,21 @@ import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluat
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedCallableMemberDescriptor
+import org.jetbrains.kotlin.types.ErrorUtils
import org.jetbrains.kotlin.types.KotlinType
+import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.checker.intersectWrappedTypes
import org.jetbrains.kotlin.types.expressions.ControlStructureTypingUtils
+import org.jetbrains.kotlin.types.model.TypeSystemInferenceExtensionContextDelegate
+import org.jetbrains.kotlin.types.model.TypeVariableMarker
+import org.jetbrains.kotlin.types.model.freshTypeConstructor
+import org.jetbrains.kotlin.types.typeUtil.contains
import org.jetbrains.kotlin.types.typeUtil.isNullableNothing
import org.jetbrains.kotlin.types.typeUtil.makeNullable
import org.jetbrains.kotlin.utils.addToStdlib.cast
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
+import kotlin.contracts.ExperimentalContracts
+import kotlin.contracts.contract
class DiagnosticReporterByTrackingStrategy(
val constantExpressionEvaluator: ConstantExpressionEvaluator,
@@ -45,7 +53,8 @@ class DiagnosticReporterByTrackingStrategy(
val psiKotlinCall: PSIKotlinCall,
val dataFlowValueFactory: DataFlowValueFactory,
val allDiagnostics: List,
- private val smartCastManager: SmartCastManager
+ private val smartCastManager: SmartCastManager,
+ private val typeSystemContext: TypeSystemInferenceExtensionContextDelegate
) : DiagnosticReporter {
private val trace = context.trace as TrackingBindingTrace
private val tracingStrategy: TracingStrategy get() = psiKotlinCall.tracingStrategy
@@ -421,21 +430,21 @@ class DiagnosticReporterByTrackingStrategy(
NotEnoughInformationForTypeParameterImpl::class.java -> {
error as NotEnoughInformationForTypeParameterImpl
- if (allDiagnostics.any {
- when (it) {
- is WrongCountOfTypeArguments -> true
- is KotlinConstraintSystemDiagnostic -> {
- val otherError = it.error
- (otherError is ConstrainingTypeIsError && otherError.typeVariable == error.typeVariable)
- || otherError is NewConstraintError
- }
- else -> false
- }
- }
- ) return
- if (isSpecialFunction(error.resolvedAtom))
- return
+ val resolvedAtom = error.resolvedAtom
+ val isDiagnosticRedundant = !isSpecialFunction(resolvedAtom) && allDiagnostics.any {
+ when (it) {
+ is WrongCountOfTypeArguments -> true
+ is KotlinConstraintSystemDiagnostic -> {
+ val otherError = it.error
+ (otherError is ConstrainingTypeIsError && otherError.typeVariable == error.typeVariable)
+ || otherError is NewConstraintError
+ }
+ else -> false
+ }
+ }
+
+ if (isDiagnosticRedundant) return
val expression = when (val atom = error.resolvedAtom.atom) {
is PSIKotlinCallForInvoke -> (atom.psiCall as? CallTransformer.CallForImplicitInvoke)?.outerCall?.calleeExpression
is PSIKotlinCall -> atom.psiCall.calleeExpression
@@ -443,12 +452,21 @@ class DiagnosticReporterByTrackingStrategy(
else -> call.calleeExpression
} ?: return
- val typeVariableName = when (val typeVariable = error.typeVariable) {
- is TypeVariableFromCallableDescriptor -> typeVariable.originalTypeParameter.name.asString()
- is TypeVariableForLambdaReturnType -> "return type of lambda"
- else -> error("Unsupported type variable: $typeVariable")
+ if (isSpecialFunction(resolvedAtom)) {
+ // We locally report errors on some arguments of special calls, on which the error may not be reported directly
+ reportNotEnoughInformationForTypeParameterForSpecialCall(resolvedAtom, error)
+ } else {
+ val typeVariableName = when (val typeVariable = error.typeVariable) {
+ is TypeVariableFromCallableDescriptor -> typeVariable.originalTypeParameter.name.asString()
+ is TypeVariableForLambdaReturnType -> "return type of lambda"
+ else -> error("Unsupported type variable: $typeVariable")
+ }
+ val unwrappedExpression = if (expression is KtBlockExpression) {
+ expression.statements.lastOrNull() ?: expression
+ } else expression
+
+ trace.reportDiagnosticOnce(NEW_INFERENCE_NO_INFORMATION_FOR_PARAMETER.on(unwrappedExpression, typeVariableName))
}
- trace.reportDiagnosticOnce(NEW_INFERENCE_NO_INFORMATION_FOR_PARAMETER.on(expression, typeVariableName))
}
OnlyInputTypesDiagnostic::class.java -> {
@@ -463,7 +481,77 @@ class DiagnosticReporterByTrackingStrategy(
}
}
+ private fun reportNotEnoughInformationForTypeParameterForSpecialCall(
+ resolvedAtom: ResolvedCallAtom,
+ error: NotEnoughInformationForTypeParameterImpl
+ ) {
+ val subResolvedAtomsToReportError =
+ getSubResolvedAtomsOfSpecialCallToReportUninferredTypeParameter(resolvedAtom, error.typeVariable)
+
+ if (subResolvedAtomsToReportError.isEmpty()) return
+
+ for (subResolvedAtom in subResolvedAtomsToReportError) {
+ val atom = subResolvedAtom.atom as? PSIKotlinCallArgument ?: continue
+ val argumentsExpression = getArgumentsExpressionOrLastExpressionInBlock(atom)
+
+ if (argumentsExpression != null) {
+ val specialFunctionName = requireNotNull(
+ ControlStructureTypingUtils.ResolveConstruct.values().find { specialFunction ->
+ specialFunction.specialFunctionName == resolvedAtom.candidateDescriptor.name
+ }
+ ) { "Unsupported special construct: ${resolvedAtom.candidateDescriptor.name} not found in special construct names" }
+
+ trace.reportDiagnosticOnce(
+ NEW_INFERENCE_NO_INFORMATION_FOR_PARAMETER.on(
+ argumentsExpression, " for subcalls of ${specialFunctionName.getName()} expression"
+ )
+ )
+ }
+ }
+ }
+
+ private fun getArgumentsExpressionOrLastExpressionInBlock(atom: PSIKotlinCallArgument): KtExpression? {
+ val valueArgumentExpression = atom.valueArgument.getArgumentExpression()
+
+ return if (valueArgumentExpression is KtBlockExpression) valueArgumentExpression.statements.lastOrNull() else valueArgumentExpression
+ }
+
+ private fun KotlinType.containsUninferredTypeParameter(uninferredTypeVariable: TypeVariableMarker) = contains {
+ ErrorUtils.isUninferredParameter(it) || it == TypeUtils.DONT_CARE
+ || it.constructor == uninferredTypeVariable.freshTypeConstructor(typeSystemContext)
+ }
+
+ @OptIn(ExperimentalStdlibApi::class)
+ private fun getSubResolvedAtomsOfSpecialCallToReportUninferredTypeParameter(
+ resolvedAtom: ResolvedAtom,
+ uninferredTypeVariable: TypeVariableMarker
+ ): Set =
+ buildSet {
+ for (subResolvedAtom in resolvedAtom.subResolvedAtoms ?: return@buildSet) {
+ val atom = subResolvedAtom.atom
+ val typeToCheck = when {
+ subResolvedAtom is PostponedResolvedAtom -> subResolvedAtom.expectedType ?: return@buildSet
+ atom is SimpleKotlinCallArgument -> atom.receiver.receiverValue.type
+ else -> return@buildSet
+ }
+
+ if (typeToCheck.containsUninferredTypeParameter(uninferredTypeVariable)) {
+ add(subResolvedAtom)
+ }
+
+ if (!subResolvedAtom.subResolvedAtoms.isNullOrEmpty()) {
+ addAll(
+ getSubResolvedAtomsOfSpecialCallToReportUninferredTypeParameter(subResolvedAtom, uninferredTypeVariable)
+ )
+ }
+ }
+ }
+
+ @OptIn(ExperimentalContracts::class)
private fun isSpecialFunction(atom: ResolvedAtom): Boolean {
+ contract {
+ returns(true) implies (atom is ResolvedCallAtom)
+ }
if (atom !is ResolvedCallAtom) return false
return ControlStructureTypingUtils.ResolveConstruct.values().any { specialFunction ->
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/KotlinToResolvedCallTransformer.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/KotlinToResolvedCallTransformer.kt
index 547442b4c47..fd143748cf1 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/KotlinToResolvedCallTransformer.kt
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/KotlinToResolvedCallTransformer.kt
@@ -519,6 +519,7 @@ class KotlinToResolvedCallTransformer(
context.dataFlowValueFactory,
allDiagnostics,
smartCastManager,
+ typeSystemContext
)
for (diagnostic in allDiagnostics) {
@@ -566,6 +567,8 @@ sealed class NewAbstractResolvedCall() : ResolvedCall
private var nonTrivialUpdatedResultInfo: DataFlowInfo? = null
+ abstract fun containsOnlyOnlyInputTypesErrors(): Boolean
+
override fun getCall(): Call = kotlinCall.psiKotlinCall.psiCall
override fun getValueArguments(): Map {
@@ -710,6 +713,9 @@ class NewResolvedCallImpl(
return typeParameters.zip(typeArguments).toMap()
}
+ override fun containsOnlyOnlyInputTypesErrors() =
+ diagnostics.all { it is KotlinConstraintSystemDiagnostic && it.error is OnlyInputTypesDiagnostic }
+
override fun getSmartCastDispatchReceiverType(): KotlinType? = smartCastDispatchReceiverType
fun updateExtensionReceiverWithSmartCastIfNeeded(smartCastExtensionReceiverType: KotlinType) {
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/ResolvedAtomCompleter.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/ResolvedAtomCompleter.kt
index 14b058e6443..d43f8c8a041 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/ResolvedAtomCompleter.kt
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/ResolvedAtomCompleter.kt
@@ -11,10 +11,9 @@ import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.impl.FunctionDescriptorImpl
import org.jetbrains.kotlin.descriptors.impl.ReceiverParameterDescriptorImpl
import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl
-import org.jetbrains.kotlin.psi.KtElement
-import org.jetbrains.kotlin.psi.KtExpression
-import org.jetbrains.kotlin.psi.KtNamedFunction
-import org.jetbrains.kotlin.psi.ValueArgument
+import org.jetbrains.kotlin.diagnostics.Errors
+import org.jetbrains.kotlin.diagnostics.reportDiagnosticOnce
+import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.BindingTrace
import org.jetbrains.kotlin.resolve.MissingSupertypesResolver
@@ -24,6 +23,7 @@ import org.jetbrains.kotlin.resolve.calls.NewCommonSuperTypeCalculator
import org.jetbrains.kotlin.resolve.calls.checkers.CallCheckerContext
import org.jetbrains.kotlin.resolve.calls.commonSuperType
import org.jetbrains.kotlin.resolve.calls.components.CallableReferenceAdaptation
+import org.jetbrains.kotlin.resolve.calls.components.CallableReferenceCandidate
import org.jetbrains.kotlin.resolve.calls.components.SuspendConversionStrategy
import org.jetbrains.kotlin.resolve.calls.components.isVararg
import org.jetbrains.kotlin.resolve.calls.context.BasicCallResolutionContext
@@ -46,6 +46,7 @@ import org.jetbrains.kotlin.types.expressions.DoubleColonExpressionResolver
import org.jetbrains.kotlin.types.expressions.ExpressionTypingServices
import org.jetbrains.kotlin.types.expressions.typeInfoFactory.createTypeInfo
import org.jetbrains.kotlin.types.typeUtil.asTypeProjection
+import org.jetbrains.kotlin.types.typeUtil.contains
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.types.typeUtil.shouldBeSubstituted
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
@@ -69,6 +70,14 @@ class ResolvedAtomCompleter(
)
private val topLevelTrace = topLevelCallCheckerContext.trace
+ private data class CallableReferenceResultTypeInfo(
+ val dispatchReceiver: ReceiverValue?,
+ val extensionReceiver: ReceiverValue?,
+ val explicitReceiver: ReceiverValue?,
+ val substitutor: TypeSubstitutor,
+ val resultType: KotlinType
+ )
+
private fun complete(resolvedAtom: ResolvedAtom) {
if (topLevelCallContext.inferenceSession.callCompleted(resolvedAtom)) {
return
@@ -212,6 +221,7 @@ class ResolvedAtomCompleter(
} else {
resultSubstitutor.safeSubstitute(lambda.returnType)
}
+ val receiverType = lambda.receiver
val approximatedValueParameterTypes = lambda.parameters.map { parameterType ->
if (parameterType.shouldBeSubstituted()) {
@@ -229,7 +239,16 @@ class ResolvedAtomCompleter(
local = true,
languageVersionSettings = topLevelCallContext.languageVersionSettings
)
- updateTraceForLambda(lambda, topLevelTrace, approximatedReturnType, approximatedValueParameterTypes)
+
+ val approximatedReceiverType = if (receiverType != null) {
+ typeApproximator.approximateDeclarationType(
+ resultSubstitutor.safeSubstitute(receiverType),
+ local = true,
+ languageVersionSettings = topLevelCallContext.languageVersionSettings
+ )
+ } else null
+
+ updateTraceForLambda(lambda, topLevelTrace, approximatedReturnType, approximatedValueParameterTypes, approximatedReceiverType)
for (lambdaResult in resultArgumentsInfo.nonErrorArguments) {
val resultValueArgument = lambdaResult as? PSIKotlinCallArgument ?: continue
@@ -253,7 +272,8 @@ class ResolvedAtomCompleter(
lambda: ResolvedLambdaAtom,
trace: BindingTrace,
returnType: UnwrappedType,
- valueParameters: List
+ valueParameters: List,
+ receiverType: UnwrappedType?
) {
val psiCallArgument = lambda.atom.psiCallArgument
@@ -276,6 +296,12 @@ class ResolvedAtomCompleter(
functionDescriptor.setReturnType(returnType)
+ val extensionReceiverParameter = functionDescriptor.extensionReceiverParameter
+
+ if (receiverType != null && extensionReceiverParameter is ReceiverParameterDescriptorImpl && extensionReceiverParameter.type.shouldBeSubstituted()) {
+ extensionReceiverParameter.setOutType(receiverType)
+ }
+
for ((i, valueParameter) in functionDescriptor.valueParameters.withIndex()) {
if (valueParameter !is ValueParameterDescriptorImpl || !valueParameter.type.shouldBeSubstituted()) continue
valueParameter.setOutType(valueParameters[i])
@@ -328,21 +354,16 @@ class ResolvedAtomCompleter(
}
}
- private fun completeCallableReference(
- resolvedAtom: ResolvedCallableReferenceAtom
- ) {
- val callableCandidate = resolvedAtom.candidate
- if (callableCandidate == null || resolvedAtom.completed) {
- // todo report meanfull diagnostic here
- return
- }
+ private fun updateCallableReferenceResultType(
+ callableCandidate: CallableReferenceCandidate,
+ callableReferenceExpression: KtCallableReferenceExpression
+ ): CallableReferenceResultTypeInfo {
val resultTypeParameters =
callableCandidate.freshSubstitutor!!.freshVariables.map { resultSubstitutor.safeSubstitute(it.defaultType) }
- val typeParametersSubstitutor =
- NewTypeSubstitutorByConstructorMap(
- (callableCandidate.candidate.typeParameters.map { it.typeConstructor } zip resultTypeParameters).toMap()
- )
+ val typeParametersSubstitutor = NewTypeSubstitutorByConstructorMap(
+ (callableCandidate.candidate.typeParameters.map { it.typeConstructor } zip resultTypeParameters).toMap()
+ )
val resultSubstitutor = if (callableCandidate.candidate.isSupportedForCallableReference()) {
val firstSubstitution = typeParametersSubstitutor.toOldSubstitution()
@@ -350,49 +371,16 @@ class ResolvedAtomCompleter(
TypeSubstitutor.createChainedSubstitutor(firstSubstitution, secondSubstitution)
} else TypeSubstitutor.EMPTY
- val psiCallArgument = resolvedAtom.atom.psiCallArgument as CallableReferenceKotlinCallArgumentImpl
- val callableReferenceExpression = psiCallArgument.ktCallableReferenceExpression
-
// write down type for callable reference expression
val resultType = resultSubstitutor.safeSubstitute(callableCandidate.reflectionCandidateType, Variance.INVARIANT)
+
argumentTypeResolver.updateResultArgumentTypeIfNotDenotable(
- topLevelTrace, expressionTypingServices.statementFilter,
- resultType,
- callableReferenceExpression
+ topLevelTrace, expressionTypingServices.statementFilter, resultType, callableReferenceExpression
)
- val reference = callableReferenceExpression.callableReference
-
- val explicitCallableReceiver = when (callableCandidate.explicitReceiverKind) {
- ExplicitReceiverKind.DISPATCH_RECEIVER -> callableCandidate.dispatchReceiver
- ExplicitReceiverKind.EXTENSION_RECEIVER -> callableCandidate.extensionReceiver
- else -> null
- }
-
- val explicitReceiver = explicitCallableReceiver?.receiver?.receiverValue?.updateReceiverValue(resultSubstitutor)
- val psiCall = CallMaker.makeCall(reference, explicitReceiver, null, reference, emptyList())
-
- val tracing = TracingStrategyImpl.create(reference, psiCall)
- val temporaryTrace = TemporaryBindingTrace.create(topLevelTrace, "callable reference fake call")
val dispatchReceiver = callableCandidate.dispatchReceiver?.receiver?.receiverValue?.updateReceiverValue(resultSubstitutor)
val extensionReceiver = callableCandidate.extensionReceiver?.receiver?.receiverValue?.updateReceiverValue(resultSubstitutor)
- val resolvedCall = ResolvedCallImpl(
- psiCall, callableCandidate.candidate, dispatchReceiver,
- extensionReceiver, callableCandidate.explicitReceiverKind,
- null, temporaryTrace, tracing, MutableDataFlowInfoForArguments.WithoutArgumentsCheck(DataFlowInfo.EMPTY)
- )
- resolvedCall.setResultingSubstitutor(resultSubstitutor)
-
- recordArgumentAdaptationForCallableReference(resolvedCall, callableCandidate.callableReferenceAdaptation)
-
- tracing.bindCall(topLevelTrace, psiCall)
- tracing.bindReference(topLevelTrace, resolvedCall)
- tracing.bindResolvedCall(topLevelTrace, resolvedCall)
-
- resolvedCall.setStatusToSuccess()
- resolvedCall.markCallAsCompleted()
-
when (callableCandidate.candidate) {
is FunctionDescriptor -> doubleColonExpressionResolver.bindFunctionReference(
callableReferenceExpression,
@@ -407,17 +395,97 @@ class ResolvedAtomCompleter(
)
}
- // TODO: probably we should also record key 'DATA_FLOW_INFO_BEFORE', see ExpressionTypingVisitorDispatcher.getTypeInfo
- val typeInfo = createTypeInfo(resultType, resolvedAtom.atom.psiCallArgument.dataFlowInfoAfterThisArgument)
- topLevelTrace.record(BindingContext.EXPRESSION_TYPE_INFO, callableReferenceExpression, typeInfo)
- topLevelTrace.record(BindingContext.PROCESSED, callableReferenceExpression)
-
doubleColonExpressionResolver.checkReferenceIsToAllowedMember(
callableCandidate.candidate,
topLevelCallContext.trace,
callableReferenceExpression
)
+ val explicitCallableReceiver = when (callableCandidate.explicitReceiverKind) {
+ ExplicitReceiverKind.DISPATCH_RECEIVER -> callableCandidate.dispatchReceiver
+ ExplicitReceiverKind.EXTENSION_RECEIVER -> callableCandidate.extensionReceiver
+ else -> null
+ }
+ val explicitReceiver = explicitCallableReceiver?.receiver?.receiverValue?.updateReceiverValue(resultSubstitutor)
+
+ return CallableReferenceResultTypeInfo(dispatchReceiver, extensionReceiver, explicitReceiver, resultSubstitutor, resultType)
+ }
+
+ private fun extractCallableReferenceResultTypeInfoFromDescriptor(
+ callableCandidate: CallableReferenceCandidate,
+ recorderDescriptor: CallableDescriptor
+ ): CallableReferenceResultTypeInfo {
+ val explicitCallableReceiver = when (callableCandidate.explicitReceiverKind) {
+ ExplicitReceiverKind.DISPATCH_RECEIVER -> callableCandidate.dispatchReceiver
+ ExplicitReceiverKind.EXTENSION_RECEIVER -> callableCandidate.extensionReceiver
+ else -> null
+ }
+ return CallableReferenceResultTypeInfo(
+ recorderDescriptor.dispatchReceiverParameter?.value,
+ recorderDescriptor.extensionReceiverParameter?.value,
+ explicitCallableReceiver?.receiver?.receiverValue,
+ TypeSubstitutor.EMPTY,
+ callableCandidate.reflectionCandidateType
+ )
+ }
+
+ private fun completeCallableReference(resolvedAtom: ResolvedCallableReferenceAtom) {
+ val psiCallArgument = resolvedAtom.atom.psiCallArgument as CallableReferenceKotlinCallArgumentImpl
+ val callableReferenceExpression = psiCallArgument.ktCallableReferenceExpression
+ val callableCandidate = resolvedAtom.candidate
+ if (callableCandidate == null || resolvedAtom.completed) {
+ // todo report meanfull diagnostic here
+ return
+ }
+ val recorderDescriptor = when (callableCandidate.candidate) {
+ is FunctionDescriptor -> topLevelCallContext.trace.get(BindingContext.FUNCTION, callableReferenceExpression)
+ is PropertyDescriptor -> topLevelCallContext.trace.get(BindingContext.VARIABLE, callableReferenceExpression)
+ else -> null
+ }
+
+ val rawExtensionReceiver = callableCandidate.extensionReceiver
+
+ if (rawExtensionReceiver != null && rawExtensionReceiver.receiver.receiverValue.type.contains { it is StubType }) {
+ topLevelTrace.reportDiagnosticOnce(Errors.TYPE_INFERENCE_POSTPONED_VARIABLE_IN_RECEIVER_TYPE.on(callableReferenceExpression))
+ return
+ }
+
+ // For some callable references we can already have recorder descriptor (see `DoubleColonExpressionResolver.getCallableReferenceType`)
+ val resultTypeInfo = if (recorderDescriptor != null) {
+ extractCallableReferenceResultTypeInfoFromDescriptor(callableCandidate, recorderDescriptor)
+ } else {
+ updateCallableReferenceResultType(callableCandidate, psiCallArgument.ktCallableReferenceExpression)
+ }
+
+ val reference = callableReferenceExpression.callableReference
+ val psiCall = CallMaker.makeCall(reference, resultTypeInfo.explicitReceiver, null, reference, emptyList())
+
+ val tracing = TracingStrategyImpl.create(reference, psiCall)
+ val temporaryTrace = TemporaryBindingTrace.create(topLevelTrace, "callable reference fake call")
+
+ val resolvedCall = ResolvedCallImpl(
+ psiCall, callableCandidate.candidate, resultTypeInfo.dispatchReceiver,
+ resultTypeInfo.extensionReceiver, callableCandidate.explicitReceiverKind,
+ null, temporaryTrace, tracing, MutableDataFlowInfoForArguments.WithoutArgumentsCheck(DataFlowInfo.EMPTY)
+ )
+
+ resolvedCall.setResultingSubstitutor(resultTypeInfo.substitutor)
+
+ recordArgumentAdaptationForCallableReference(resolvedCall, callableCandidate.callableReferenceAdaptation)
+
+ tracing.bindCall(topLevelTrace, psiCall)
+ tracing.bindReference(topLevelTrace, resolvedCall)
+ tracing.bindResolvedCall(topLevelTrace, resolvedCall)
+
+ resolvedCall.setStatusToSuccess()
+ resolvedCall.markCallAsCompleted()
+
+ // TODO: probably we should also record key 'DATA_FLOW_INFO_BEFORE', see ExpressionTypingVisitorDispatcher.getTypeInfo
+ val typeInfo = createTypeInfo(resultTypeInfo.resultType, resolvedAtom.atom.psiCallArgument.dataFlowInfoAfterThisArgument)
+
+ topLevelTrace.record(BindingContext.EXPRESSION_TYPE_INFO, callableReferenceExpression, typeInfo)
+ topLevelTrace.record(BindingContext.PROCESSED, callableReferenceExpression)
+
kotlinToResolvedCallTransformer.runCallCheckers(resolvedCall, topLevelCallCheckerContext)
resolvedAtom.completed = true
}
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/MissingDependencyClassChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/MissingDependencyClassChecker.kt
index b1f6bcd4ef5..2df4da03bc9 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/MissingDependencyClassChecker.kt
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/MissingDependencyClassChecker.kt
@@ -25,6 +25,7 @@ import org.jetbrains.kotlin.resolve.calls.checkers.CallCheckerContext
import org.jetbrains.kotlin.resolve.calls.checkers.isComputingDeferredType
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
+import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedContainerAbiStability
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedContainerSource
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedMemberDescriptor
import org.jetbrains.kotlin.types.KotlinType
@@ -58,8 +59,11 @@ object MissingDependencyClassChecker : CallChecker {
if (source.isPreReleaseInvisible) {
return PRE_RELEASE_CLASS.on(reportOn, source.presentableString)
}
- if (source.isInvisibleIrDependency) {
- return IR_COMPILED_CLASS.on(reportOn, source.presentableString)
+ if (source.abiStability == DeserializedContainerAbiStability.FIR_UNSTABLE) {
+ return FIR_COMPILED_CLASS.on(reportOn, source.presentableString)
+ }
+ if (source.abiStability == DeserializedContainerAbiStability.IR_UNSTABLE) {
+ return IR_WITH_UNSTABLE_ABI_COMPILED_CLASS.on(reportOn, source.presentableString)
}
}
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/AbstractLazyMemberScope.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/AbstractLazyMemberScope.kt
index 7bced7ad3e1..08310b5da60 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/AbstractLazyMemberScope.kt
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/AbstractLazyMemberScope.kt
@@ -50,7 +50,7 @@ protected constructor(
private val propertyDescriptors: MemoizedFunctionToNotNull> =
storageManager.createMemoizedFunction { doGetProperties(it) }
private val typeAliasDescriptors: MemoizedFunctionToNotNull> =
- storageManager.createMemoizedFunction { doGetTypeAliases(it) }
+ storageManager.createMemoizedFunction( { doGetTypeAliases(it) }, onRecursiveCall = { _,_ -> emptyList() })
private val declaredFunctionDescriptors: MemoizedFunctionToNotNull> =
storageManager.createMemoizedFunction { getDeclaredFunctions(it) }
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/LazyAnnotations.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/LazyAnnotations.kt
index 0753c42af28..4e37ce2acb5 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/LazyAnnotations.kt
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/LazyAnnotations.kt
@@ -19,6 +19,8 @@ package org.jetbrains.kotlin.resolve.lazy.descriptors
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotations
+import org.jetbrains.kotlin.descriptors.annotations.FilteredByPredicateAnnotations
+import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.resolve.AnnotationResolver
@@ -32,6 +34,8 @@ import org.jetbrains.kotlin.resolve.scopes.LexicalScope
import org.jetbrains.kotlin.resolve.source.toSourceElement
import org.jetbrains.kotlin.storage.StorageManager
import org.jetbrains.kotlin.storage.getValue
+import org.jetbrains.kotlin.types.AbbreviatedType
+import org.jetbrains.kotlin.types.ErrorUtils
abstract class LazyAnnotationsContext(
val annotationResolver: AnnotationResolver,
@@ -77,17 +81,30 @@ class LazyAnnotationDescriptor(
c.trace.record(BindingContext.ANNOTATION, annotationEntry, this)
}
- override val type by c.storageManager.createLazyValue {
- c.annotationResolver.resolveAnnotationType(scope, annotationEntry, c.trace)
- }
+ override val type by c.storageManager.createLazyValue(
+ computable = lazy@{
+ val annotationType = c.annotationResolver.resolveAnnotationType(scope, annotationEntry, c.trace)
+ if (annotationType is AbbreviatedType) {
+ // This is needed to prevent recursion in cases like this: typealias S = @S Ann
+ if (annotationType.annotations.any { it == this }) {
+ annotationType.abbreviation.constructor.declarationDescriptor?.let { typeAliasDescriptor ->
+ c.trace.report(Errors.RECURSIVE_TYPEALIAS_EXPANSION.on(annotationEntry, typeAliasDescriptor))
+ }
+ return@lazy annotationType.replaceAnnotations(FilteredByPredicateAnnotations(annotationType.annotations) { it != this })
+ }
+ }
+ annotationType
+ },
+ onRecursiveCall = {
+ ErrorUtils.createErrorType("Recursion in type of annotation detected")
+ }
+ )
override val source = annotationEntry.toSourceElement()
- private val scope = if (c.scope.ownerDescriptor is PackageFragmentDescriptor) {
- LexicalScope.Base(c.scope, FileDescriptorForVisibilityChecks(source, c.scope.ownerDescriptor))
- } else {
- c.scope
- }
+ private val scope = (c.scope.ownerDescriptor as? PackageFragmentDescriptor)?.let {
+ LexicalScope.Base(c.scope, FileDescriptorForVisibilityChecks(source, it))
+ } ?: c.scope
override val allValueArguments by c.storageManager.createLazyValue {
val resolutionResults = c.annotationResolver.resolveAnnotationCall(annotationEntry, scope, c.trace)
@@ -110,10 +127,9 @@ class LazyAnnotationDescriptor(
private class FileDescriptorForVisibilityChecks(
private val source: SourceElement,
- private val containingDeclaration: DeclarationDescriptor
- ) : DeclarationDescriptorWithSource {
+ private val containingDeclaration: PackageFragmentDescriptor
+ ) : DeclarationDescriptorWithSource, PackageFragmentDescriptor by containingDeclaration {
override val annotations: Annotations get() = Annotations.EMPTY
- override fun getContainingDeclaration() = containingDeclaration
override fun getSource() = source
override fun getOriginal() = this
override fun getName() = Name.special("< file descriptor for annotation resolution >")
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/BasicExpressionTypingVisitor.java b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/BasicExpressionTypingVisitor.java
index 99fd1c63a4b..817a738da66 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/BasicExpressionTypingVisitor.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/BasicExpressionTypingVisitor.java
@@ -60,6 +60,7 @@ import org.jetbrains.kotlin.resolve.calls.smartcasts.Nullability;
import org.jetbrains.kotlin.resolve.calls.tasks.ExplicitReceiverKind;
import org.jetbrains.kotlin.resolve.calls.tasks.ResolutionCandidate;
import org.jetbrains.kotlin.resolve.calls.tasks.TracingStrategy;
+import org.jetbrains.kotlin.resolve.calls.tower.NewAbstractResolvedCall;
import org.jetbrains.kotlin.resolve.calls.util.CallMaker;
import org.jetbrains.kotlin.resolve.checkers.UnderscoreChecker;
import org.jetbrains.kotlin.resolve.constants.*;
@@ -823,10 +824,7 @@ public class BasicExpressionTypingVisitor extends ExpressionTypingVisitor {
DiagnosticFactory0 diagnosticFactory =
isFunctionLiteral ? NOT_NULL_ASSERTION_ON_LAMBDA_EXPRESSION : NOT_NULL_ASSERTION_ON_CALLABLE_REFERENCE;
context.trace.report(diagnosticFactory.on(operationSign));
- if (baseTypeInfo == null) {
- return TypeInfoFactoryKt.createTypeInfo(ErrorUtils.createErrorType("Unresolved lambda expression"), context);
- }
- return baseTypeInfo;
+ return baseTypeInfo != null ? baseTypeInfo : components.expressionTypingServices.getTypeInfo(baseExpression, context);
}
assert baseTypeInfo != null : "Base expression was not processed: " + expression;
KotlinType baseType = baseTypeInfo.getType();
@@ -1397,14 +1395,26 @@ public class BasicExpressionTypingVisitor extends ExpressionTypingVisitor {
rightTypeInfo = rightTypeInfo.replaceDataFlowInfo(dataFlowInfo);
}
- if (resolutionResult.isSuccess()) {
+ if (resolutionResult.isSuccess() || isResolutionSuccessfulWithOnlyInputTypesWarnings(resolutionResult.getResultingCalls(), context)) {
return rightTypeInfo.replaceType(components.builtIns.getBooleanType());
- }
- else {
+ } else {
return rightTypeInfo.clearType();
}
}
+ private static boolean isResolutionSuccessfulWithOnlyInputTypesWarnings(
+ @Nullable Collection extends ResolvedCall> allCandidates,
+ @NotNull ExpressionTypingContext context
+ ) {
+ if (allCandidates == null || allCandidates.isEmpty()) return false;
+
+ boolean areAllCandidatesFailedWithOnlyInputTypesError = allCandidates.stream().allMatch((resolvedCall) ->
+ resolvedCall instanceof NewAbstractResolvedCall> && ((NewAbstractResolvedCall>) resolvedCall).containsOnlyOnlyInputTypesErrors()
+ );
+ boolean isNonStrictOnlyInputTypesCheckEnabled = context.languageVersionSettings.supportsFeature(LanguageFeature.NonStrictOnlyInputTypesChecks);
+
+ return areAllCandidatesFailedWithOnlyInputTypesError && isNonStrictOnlyInputTypesCheckEnabled;
+ }
private boolean ensureBooleanResult(KtExpression operationSign, Name name, KotlinType resultType, ExpressionTypingContext context) {
return ensureBooleanResultWithCustomSubject(operationSign, resultType, "'" + name + "'", context);
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/DoubleColonExpressionResolver.kt b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/DoubleColonExpressionResolver.kt
index 2f2a5942567..604a8d18588 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/DoubleColonExpressionResolver.kt
+++ b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/DoubleColonExpressionResolver.kt
@@ -15,8 +15,8 @@ import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor
import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor
-import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.diagnostics.Errors.*
+import org.jetbrains.kotlin.diagnostics.reportDiagnosticOnce
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
@@ -49,6 +49,7 @@ import org.jetbrains.kotlin.types.TypeUtils.NO_EXPECTED_TYPE
import org.jetbrains.kotlin.types.checker.KotlinTypeRefiner
import org.jetbrains.kotlin.types.expressions.FunctionWithBigAritySupport.LanguageVersionDependent
import org.jetbrains.kotlin.types.expressions.typeInfoFactory.createTypeInfo
+import org.jetbrains.kotlin.types.expressions.typeInfoFactory.noTypeInfo
import org.jetbrains.kotlin.types.refinement.TypeRefinement
import org.jetbrains.kotlin.types.typeUtil.*
import org.jetbrains.kotlin.utils.yieldIfNotNull
@@ -540,6 +541,16 @@ class DoubleColonExpressionResolver(
val (lhs, resolutionResults) = resolveCallableReference(expression, c, ResolveArgumentsMode.RESOLVE_FUNCTION_ARGUMENTS)
val result = getCallableReferenceType(expression, lhs, resolutionResults, c)
+ val doesSomeExtensionReceiverContainsStubType =
+ resolutionResults != null && resolutionResults.resultingCalls.any { resolvedCall ->
+ resolvedCall.extensionReceiver?.type?.contains { it is StubType } == true
+ }
+
+ if (doesSomeExtensionReceiverContainsStubType) {
+ c.trace.reportDiagnosticOnce(TYPE_INFERENCE_POSTPONED_VARIABLE_IN_RECEIVER_TYPE.on(expression))
+ return noTypeInfo(c)
+ }
+
val dataFlowInfo = (lhs as? DoubleColonLHS.Expression)?.dataFlowInfo ?: c.dataFlowInfo
if (c.inferenceSession is CoroutineInferenceSession && result?.contains { it is StubType } == true) {
@@ -637,9 +648,9 @@ class DoubleColonExpressionResolver(
bigAritySupport.shouldCheckLanguageVersionSettings &&
!languageVersionSettings.supportsFeature(LanguageFeature.FunctionTypesWithBigArity)
) {
- context.trace.report(Errors.UNSUPPORTED_FEATURE.on(
- expression, LanguageFeature.FunctionTypesWithBigArity to languageVersionSettings
- ))
+ context.trace.report(
+ UNSUPPORTED_FEATURE.on(expression, LanguageFeature.FunctionTypesWithBigArity to languageVersionSettings)
+ )
}
}
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/ExpressionTypingServices.java b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/ExpressionTypingServices.java
index e47863a21e8..907a1a3cca8 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/ExpressionTypingServices.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/ExpressionTypingServices.java
@@ -22,6 +22,7 @@ import org.jetbrains.kotlin.resolve.*;
import org.jetbrains.kotlin.resolve.calls.components.InferenceSession;
import org.jetbrains.kotlin.resolve.calls.context.ContextDependency;
import org.jetbrains.kotlin.resolve.calls.context.ResolutionContext;
+import org.jetbrains.kotlin.resolve.calls.inference.CoroutineInferenceSession;
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo;
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValue;
import org.jetbrains.kotlin.resolve.calls.tower.KotlinResolutionCallbacksImpl;
@@ -423,7 +424,8 @@ public class ExpressionTypingServices {
@NotNull KtExpression statementExpression,
@NotNull ExpressionTypingContext context
) {
- if (!context.languageVersionSettings.supportsFeature(LanguageFeature.NewInference)) return null;
+ if (!context.languageVersionSettings.supportsFeature(LanguageFeature.NewInference) || context.inferenceSession instanceof CoroutineInferenceSession)
+ return null;
KtFunctionLiteral functionLiteral = PsiUtilsKt.getNonStrictParentOfType(statementExpression, KtFunctionLiteral.class);
if (functionLiteral != null) {
KotlinResolutionCallbacksImpl.LambdaInfo info =
diff --git a/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/DeepCopyIrTreeWithDeclarations.kt b/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/DeepCopyIrTreeWithDeclarations.kt
index 614ef1cf05a..30859ffb09f 100644
--- a/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/DeepCopyIrTreeWithDeclarations.kt
+++ b/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/DeepCopyIrTreeWithDeclarations.kt
@@ -16,26 +16,16 @@
package org.jetbrains.kotlin.backend.common
-import org.jetbrains.kotlin.descriptors.VariableDescriptor
import org.jetbrains.kotlin.ir.ObsoleteDescriptorBasedAPI
import org.jetbrains.kotlin.ir.IrElement
-import org.jetbrains.kotlin.ir.declarations.IrVariable
-import org.jetbrains.kotlin.ir.descriptors.WrappedVariableDescriptor
import org.jetbrains.kotlin.ir.expressions.IrLoop
-import org.jetbrains.kotlin.ir.util.DeepCopyIrTreeWithSymbols
-import org.jetbrains.kotlin.ir.util.DeepCopySymbolRemapper
-import org.jetbrains.kotlin.ir.util.DeepCopyTypeRemapper
-import org.jetbrains.kotlin.ir.util.DescriptorsRemapper
+import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.ir.visitors.acceptVoid
@Suppress("UNCHECKED_CAST")
@OptIn(ObsoleteDescriptorBasedAPI::class)
fun T.deepCopyWithVariables(): T {
- val descriptorsRemapper = object : DescriptorsRemapper {
- override fun remapDeclaredVariable(descriptor: VariableDescriptor) = WrappedVariableDescriptor()
- }
-
- val symbolsRemapper = DeepCopySymbolRemapper(descriptorsRemapper)
+ val symbolsRemapper = DeepCopySymbolRemapper(NullDescriptorsRemapper)
acceptVoid(symbolsRemapper)
val typesRemapper = DeepCopyTypeRemapper(symbolsRemapper)
@@ -45,12 +35,6 @@ fun T.deepCopyWithVariables(): T {
override fun getNonTransformedLoop(irLoop: IrLoop): IrLoop {
return irLoop
}
-
- override fun visitVariable(declaration: IrVariable): IrVariable {
- val variable = super.visitVariable(declaration)
- variable.descriptor.let { if (it is WrappedVariableDescriptor) it.bind(variable) }
- return variable
- }
},
null
) as T
diff --git a/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/ir/IrInlineUtils.kt b/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/ir/IrInlineUtils.kt
index efbdfc2fe6e..44671ca21a8 100644
--- a/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/ir/IrInlineUtils.kt
+++ b/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/ir/IrInlineUtils.kt
@@ -6,11 +6,9 @@
package org.jetbrains.kotlin.backend.common.ir
import org.jetbrains.kotlin.backend.common.lower.VariableRemapper
-import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.ir.IrStatement
+import org.jetbrains.kotlin.ir.ObsoleteDescriptorBasedAPI
import org.jetbrains.kotlin.ir.declarations.*
-import org.jetbrains.kotlin.ir.descriptors.WrappedClassConstructorDescriptor
-import org.jetbrains.kotlin.ir.descriptors.WrappedSimpleFunctionDescriptor
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.IrReturnImpl
import org.jetbrains.kotlin.ir.expressions.impl.IrReturnableBlockImpl
@@ -83,12 +81,6 @@ private fun IrBody.move(
// TODO use a generic inliner (e.g. JS/Native's FunctionInlining.Inliner)
// Inline simple function calls without type parameters, default parameters, or varargs.
fun IrFunction.inline(target: IrDeclarationParent, arguments: List = listOf()): IrReturnableBlock =
- IrReturnableBlockImpl(startOffset, endOffset, returnType, IrReturnableBlockSymbolImpl(getNewWrappedDescriptor()), null, symbol).apply {
+ IrReturnableBlockImpl(startOffset, endOffset, returnType, IrReturnableBlockSymbolImpl(), null, symbol).apply {
statements += body!!.move(this@inline, target, symbol, valueParameters.zip(arguments).toMap()).statements
- }
-
-fun IrFunction.getNewWrappedDescriptor(): FunctionDescriptor = when (this) {
- is IrConstructor -> WrappedClassConstructorDescriptor().apply { bind(this@getNewWrappedDescriptor) }
- is IrSimpleFunction -> WrappedSimpleFunctionDescriptor().apply { bind(this@getNewWrappedDescriptor) }
- else -> error("Unknown IrFunction kind: $this")
-}
+ }
\ No newline at end of file
diff --git a/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/ir/IrUtils.kt b/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/ir/IrUtils.kt
index 9ea06bc92a7..358e6b8fdfe 100644
--- a/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/ir/IrUtils.kt
+++ b/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/ir/IrUtils.kt
@@ -36,7 +36,6 @@ import org.jetbrains.kotlin.ir.types.impl.makeTypeProjection
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.ir.visitors.IrElementVisitor
import org.jetbrains.kotlin.name.Name
-import org.jetbrains.kotlin.serialization.deserialization.descriptors.DescriptorWithContainerSource
import java.io.StringWriter
fun ir2string(ir: IrElement?): String = ir?.render() ?: ""
@@ -129,12 +128,7 @@ fun IrValueParameter.copyTo(
isNoinline: Boolean = this.isNoinline,
isAssignable: Boolean = this.isAssignable
): IrValueParameter {
- val descriptor = if (index < 0) {
- WrappedReceiverParameterDescriptor()
- } else {
- WrappedValueParameterDescriptor()
- }
- val symbol = IrValueParameterSymbolImpl(descriptor)
+ val symbol = IrValueParameterSymbolImpl()
val defaultValueCopy = defaultValue?.let { originalDefault ->
factory.createExpressionBody(originalDefault.startOffset, originalDefault.endOffset) {
expression = originalDefault.expression.deepCopyWithVariables().also {
@@ -147,7 +141,6 @@ fun IrValueParameter.copyTo(
name, index, type, varargElementType, isCrossinline = isCrossinline,
isNoinline = isNoinline, isHidden = false, isAssignable = isAssignable
).also {
- descriptor.bind(it)
it.parent = irFunction
it.defaultValue = defaultValueCopy
it.copyAnnotationsFrom(this)
@@ -167,10 +160,9 @@ fun IrTypeParameter.copyToWithoutSuperTypes(
fun IrFunction.copyReceiverParametersFrom(from: IrFunction, substitutionMap: Map) {
dispatchReceiverParameter = from.dispatchReceiverParameter?.run {
- val newDescriptor = WrappedReceiverParameterDescriptor()
factory.createValueParameter(
startOffset, endOffset, origin,
- IrValueParameterSymbolImpl(newDescriptor),
+ IrValueParameterSymbolImpl(),
name, index,
type.substitute(substitutionMap),
varargElementType?.substitute(substitutionMap),
@@ -178,7 +170,6 @@ fun IrFunction.copyReceiverParametersFrom(from: IrFunction, substitutionMap: Map
isHidden, isAssignable
).also { parameter ->
parameter.parent = this@copyReceiverParametersFrom
- newDescriptor.bind(this)
}
}
extensionReceiverParameter = from.extensionReceiverParameter?.copyTo(this)
@@ -428,11 +419,10 @@ fun IrClass.createParameterDeclarations() {
fun IrFunction.createDispatchReceiverParameter(origin: IrDeclarationOrigin? = null) {
assert(dispatchReceiverParameter == null)
- val newDescriptor = WrappedReceiverParameterDescriptor()
dispatchReceiverParameter = factory.createValueParameter(
startOffset, endOffset,
origin ?: parentAsClass.origin,
- IrValueParameterSymbolImpl(newDescriptor),
+ IrValueParameterSymbolImpl(),
Name.special(""),
-1,
parentAsClass.defaultType,
@@ -443,7 +433,6 @@ fun IrFunction.createDispatchReceiverParameter(origin: IrDeclarationOrigin? = nu
isAssignable = false
).apply {
parent = this@createDispatchReceiverParameter
- newDescriptor.bind(this)
}
}
@@ -469,11 +458,11 @@ val IrFunction.allParametersCount: Int
private class FakeOverrideBuilderForLowerings : FakeOverrideBuilderStrategy() {
override fun linkFunctionFakeOverride(declaration: IrFakeOverrideFunction) {
- declaration.acquireSymbol(IrSimpleFunctionSymbolImpl(WrappedSimpleFunctionDescriptor()))
+ declaration.acquireSymbol(IrSimpleFunctionSymbolImpl())
}
override fun linkPropertyFakeOverride(declaration: IrFakeOverrideProperty) {
- val propertySymbol = IrPropertySymbolImpl(WrappedPropertyDescriptor())
+ val propertySymbol = IrPropertySymbolImpl()
declaration.getter?.let { it.correspondingPropertySymbol = propertySymbol }
declaration.setter?.let { it.correspondingPropertySymbol = propertySymbol }
@@ -509,11 +498,10 @@ fun IrFactory.createStaticFunctionWithReceivers(
copyMetadata: Boolean = true,
typeParametersFromContext: List = listOf()
): IrSimpleFunction {
- val descriptor = WrappedSimpleFunctionDescriptor()
return createFunction(
oldFunction.startOffset, oldFunction.endOffset,
origin,
- IrSimpleFunctionSymbolImpl(descriptor),
+ IrSimpleFunctionSymbolImpl(),
name,
visibility,
modality,
@@ -528,7 +516,6 @@ fun IrFactory.createStaticFunctionWithReceivers(
isInfix = oldFunction is IrSimpleFunction && oldFunction.isInfix,
containerSource = oldFunction.containerSource,
).apply {
- descriptor.bind(this)
parent = irParent
val newTypeParametersFromContext = copyAndRenameConflictingTypeParametersFrom(
diff --git a/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/FinallyBlocksLowering.kt b/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/FinallyBlocksLowering.kt
index 2faee457a37..b2f7bb156b6 100644
--- a/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/FinallyBlocksLowering.kt
+++ b/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/FinallyBlocksLowering.kt
@@ -14,7 +14,6 @@ import org.jetbrains.kotlin.ir.builders.declarations.buildVariable
import org.jetbrains.kotlin.ir.declarations.IrDeclarationOrigin
import org.jetbrains.kotlin.ir.declarations.IrFile
import org.jetbrains.kotlin.ir.declarations.IrFunction
-import org.jetbrains.kotlin.ir.descriptors.WrappedSimpleFunctionDescriptor
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.*
import org.jetbrains.kotlin.ir.symbols.IrReturnTargetSymbol
@@ -175,7 +174,7 @@ class FinallyBlocksLowering(val context: CommonBackendContext, private val throw
currentTryScope.jumps.getOrPut(jump) {
val type = (jump as? Return)?.target?.owner?.returnType(context) ?: value.type
jump.toString()
- val symbol = IrReturnableBlockSymbolImpl(WrappedSimpleFunctionDescriptor())
+ val symbol = IrReturnableBlockSymbolImpl()
with(currentTryScope) {
irBuilder.run {
val inlinedFinally = irInlineFinally(symbol, type, expression, finallyExpression)
@@ -234,7 +233,7 @@ class FinallyBlocksLowering(val context: CommonBackendContext, private val throw
using(TryScope(syntheticTry, transformedFinallyExpression, this)) {
val fallThroughType = aTry.type
- val fallThroughSymbol = IrReturnableBlockSymbolImpl(WrappedSimpleFunctionDescriptor())
+ val fallThroughSymbol = IrReturnableBlockSymbolImpl()
val transformedResult = aTry.tryResult.transform(transformer, null)
val returnedResult = irReturn(fallThroughSymbol, transformedResult)
diff --git a/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/InlineClassDeclarationLowering.kt b/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/InlineClassDeclarationLowering.kt
index 5c8c782a254..c6781ef62db 100644
--- a/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/InlineClassDeclarationLowering.kt
+++ b/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/InlineClassDeclarationLowering.kt
@@ -39,8 +39,9 @@ class InlineClassLowering(val context: CommonBackendContext) {
}
}
- private fun transformConstructor(irConstructor: IrConstructor): List? {
- if (irConstructor.isPrimary) return null
+ private fun transformConstructor(irConstructor: IrConstructor): List {
+ if (irConstructor.isPrimary)
+ return transformPrimaryConstructor(irConstructor)
// Secondary constructors are lowered into static function
val result = getOrCreateStaticMethod(irConstructor)
@@ -67,6 +68,72 @@ class InlineClassLowering(val context: CommonBackendContext) {
return listOf(function, staticMethod)
}
+ private fun transformPrimaryConstructor(irConstructor: IrConstructor): List {
+ val klass = irConstructor.parentAsClass
+ val inlineClassType = klass.defaultType
+ val initFunction = getOrCreateStaticMethod(irConstructor).also {
+ it.returnType = inlineClassType
+ }
+ var delegatingCtorCall: IrDelegatingConstructorCall? = null
+ var setMemberField: IrSetField? = null
+
+ initFunction.body = context.irFactory.createBlockBody(UNDEFINED_OFFSET, UNDEFINED_OFFSET) {
+ val origParameterSymbol = irConstructor.valueParameters.single().symbol
+ statements += context.createIrBuilder(initFunction.symbol).irBlockBody(initFunction) {
+ val builder = this
+ fun unboxedInlineClassValue() = builder.irReinterpretCast(
+ builder.irGet(initFunction.valueParameters.single()),
+ type = klass.defaultType,
+ )
+
+ (irConstructor.body as IrBlockBody).deepCopyWithSymbols(initFunction).statements.forEach { statement ->
+ +statement.transformStatement(object : IrElementTransformerVoid() {
+ override fun visitDelegatingConstructorCall(expression: IrDelegatingConstructorCall): IrExpression {
+ delegatingCtorCall = expression.deepCopyWithSymbols(irConstructor)
+ return builder.irBlock {} // Removing delegating constructor call
+ }
+
+ override fun visitSetField(expression: IrSetField): IrExpression {
+ val isMemberFieldSet = expression.symbol.owner.parent == klass
+ if (isMemberFieldSet) {
+ setMemberField = expression.deepCopyWithSymbols(irConstructor)
+ }
+ expression.transformChildrenVoid()
+ if (isMemberFieldSet) {
+ return expression.value
+ }
+ return expression
+ }
+
+ override fun visitGetField(expression: IrGetField): IrExpression {
+ expression.transformChildrenVoid()
+ if (expression.symbol.owner.parent == klass)
+ return builder.irGet(initFunction.valueParameters.single())
+ return expression
+ }
+
+ override fun visitGetValue(expression: IrGetValue): IrExpression {
+ expression.transformChildrenVoid()
+ if (expression.symbol.owner.parent == klass)
+ return unboxedInlineClassValue()
+ if (expression.symbol == origParameterSymbol)
+ return builder.irGet(initFunction.valueParameters.single())
+ return expression
+ }
+ })
+ }
+ +irReturn(unboxedInlineClassValue())
+ }.statements
+ }
+
+ irConstructor.body = context.irFactory.createBlockBody(UNDEFINED_OFFSET, UNDEFINED_OFFSET) {
+ statements += delegatingCtorCall!!
+ statements += setMemberField!!
+ }
+
+ return listOf(irConstructor, initFunction)
+ }
+
private fun transformConstructorBody(irConstructor: IrConstructor, staticMethod: IrSimpleFunction) {
if (irConstructor.isPrimary) return // TODO error() maybe?
@@ -232,7 +299,7 @@ class InlineClassLowering(val context: CommonBackendContext) {
override fun visitConstructorCall(expression: IrConstructorCall): IrExpression {
expression.transformChildrenVoid(this)
val function = expression.symbol.owner
- if (!function.parentAsClass.isInline || function.isPrimary) {
+ if (!function.parentAsClass.isInline) {
return expression
}
@@ -263,7 +330,6 @@ class InlineClassLowering(val context: CommonBackendContext) {
val klass = function.parentAsClass
return when {
!klass.isInline -> expression
- function.isPrimary -> irConstructorCall(expression, function.symbol)
else -> irCall(expression, getOrCreateStaticMethod(function))
}
}
diff --git a/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/KotlinNothingValueExceptionLowering.kt b/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/KotlinNothingValueExceptionLowering.kt
index f41342edce7..f904a5a1797 100644
--- a/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/KotlinNothingValueExceptionLowering.kt
+++ b/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/KotlinNothingValueExceptionLowering.kt
@@ -9,7 +9,6 @@ import org.jetbrains.kotlin.backend.common.BodyLoweringPass
import org.jetbrains.kotlin.backend.common.CommonBackendContext
import org.jetbrains.kotlin.ir.builders.irCall
import org.jetbrains.kotlin.ir.declarations.IrDeclaration
-import org.jetbrains.kotlin.ir.declarations.IrSymbolDeclaration
import org.jetbrains.kotlin.ir.expressions.IrBody
import org.jetbrains.kotlin.ir.expressions.IrCall
import org.jetbrains.kotlin.ir.expressions.IrExpression
@@ -23,7 +22,7 @@ class KotlinNothingValueExceptionLowering(
) : BodyLoweringPass {
override fun lower(irBody: IrBody, container: IrDeclaration) {
if (!skip(container)) {
- irBody.transformChildrenVoid(Transformer((container as IrSymbolDeclaration<*>).symbol))
+ irBody.transformChildrenVoid(Transformer(container.symbol))
}
}
diff --git a/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/StringConcatenationLowering.kt b/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/StringConcatenationLowering.kt
index e164769b05d..a2cb3dcca7b 100644
--- a/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/StringConcatenationLowering.kt
+++ b/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/StringConcatenationLowering.kt
@@ -121,10 +121,6 @@ private class StringConcatenationTransformer(val lower: StringConcatenationLower
}
override fun visitDeclaration(declaration: IrDeclarationBase): IrStatement {
- if (declaration !is IrSymbolDeclaration<*>) {
- return super.visitDeclaration(declaration)
- }
-
with(declaration) {
buildersStack.add(
context.createIrBuilder(declaration.symbol, startOffset, endOffset)
diff --git a/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/inline/DeepCopyIrTreeWithDescriptors.kt b/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/inline/DeepCopyIrTreeWithDescriptors.kt
index 7c4789271a3..9f76c576905 100644
--- a/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/inline/DeepCopyIrTreeWithDescriptors.kt
+++ b/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/inline/DeepCopyIrTreeWithDescriptors.kt
@@ -5,8 +5,6 @@
package org.jetbrains.kotlin.backend.common.lower.inline
-import org.jetbrains.kotlin.ir.util.DescriptorsToIrRemapper
-import org.jetbrains.kotlin.ir.util.WrappedDescriptorPatcher
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.declarations.IrDeclarationParent
import org.jetbrains.kotlin.ir.declarations.IrTypeParametersContainer
@@ -37,9 +35,6 @@ internal class DeepCopyIrTreeWithSymbolsForInliner(
// Copy IR.
val result = irElement.transform(copier, data = null)
- // Bind newly created IR with wrapped descriptors.
- result.acceptVoid(WrappedDescriptorPatcher)
-
result.patchDeclarationParents(parent)
return result
}
@@ -133,7 +128,7 @@ internal class DeepCopyIrTreeWithSymbolsForInliner(
}
}
- private val symbolRemapper = SymbolRemapperImpl(DescriptorsToIrRemapper)
+ private val symbolRemapper = SymbolRemapperImpl(NullDescriptorsRemapper)
private val typeRemapper = InlinerTypeRemapper(symbolRemapper, typeArguments)
private val copier = object : DeepCopyIrTreeWithSymbols(symbolRemapper, typeRemapper, InlinerSymbolRenamer()) {
private fun IrType.remapTypeAndErase() = typeRemapper.remapTypeAndOptionallyErase(this, erase = true)
diff --git a/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/inline/FunctionInlining.kt b/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/inline/FunctionInlining.kt
index 370e2487544..1a29f8e91c9 100644
--- a/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/inline/FunctionInlining.kt
+++ b/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/inline/FunctionInlining.kt
@@ -8,7 +8,6 @@ package org.jetbrains.kotlin.backend.common.lower.inline
import org.jetbrains.kotlin.backend.common.*
import org.jetbrains.kotlin.backend.common.ir.Symbols
-import org.jetbrains.kotlin.backend.common.ir.getNewWrappedDescriptor
import org.jetbrains.kotlin.backend.common.lower.createIrBuilder
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersionSettings
@@ -178,7 +177,7 @@ class FunctionInlining(
val evaluationStatements = evaluateArguments(callSite, copiedCallee)
val statements = (copiedCallee.body as IrBlockBody).statements
- val irReturnableBlockSymbol = IrReturnableBlockSymbolImpl(callee.getNewWrappedDescriptor())
+ val irReturnableBlockSymbol = IrReturnableBlockSymbolImpl()
val endOffset = callee.endOffset
/* creates irBuilder appending to the end of the given returnable block: thus why we initialize
* irBuilder with (..., endOffset, endOffset).
diff --git a/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/phaser/DumperVerifier.kt b/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/phaser/DumperVerifier.kt
index db767d4bacf..5fd4ecc7905 100644
--- a/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/phaser/DumperVerifier.kt
+++ b/compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/phaser/DumperVerifier.kt
@@ -1,5 +1,5 @@
/*
- * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
+ * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@@ -12,6 +12,7 @@ import org.jetbrains.kotlin.backend.common.IrValidatorConfig
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.util.dump
+import org.jetbrains.kotlin.ir.util.dumpKotlinLike
import org.jetbrains.kotlin.ir.util.fqNameWhenAvailable
import org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid
import org.jetbrains.kotlin.ir.visitors.acceptChildrenVoid
@@ -62,6 +63,9 @@ fun dumpIrElement(actionState: ActionState, data: IrElement, @Suppress("UNUSED_P
var dumpText: String = ""
val elementName: String
+ val dumpStrategy = System.getProperty("org.jetbrains.kotlin.compiler.ir.dump.strategy")
+ val dump: IrElement.() -> String = if (dumpStrategy == "KotlinLike") IrElement::dumpKotlinLike else IrElement::dump
+
val dumpOnlyFqName = actionState.config.dumpOnlyFqName
if (dumpOnlyFqName != null) {
elementName = dumpOnlyFqName
diff --git a/compiler/ir/backend.common/src/org/jetbrains/kotlin/ir/builders/declarations/declarationBuilders.kt b/compiler/ir/backend.common/src/org/jetbrains/kotlin/ir/builders/declarations/declarationBuilders.kt
index 4314229c78f..546b0615482 100644
--- a/compiler/ir/backend.common/src/org/jetbrains/kotlin/ir/builders/declarations/declarationBuilders.kt
+++ b/compiler/ir/backend.common/src/org/jetbrains/kotlin/ir/builders/declarations/declarationBuilders.kt
@@ -21,15 +21,12 @@ import org.jetbrains.kotlin.types.Variance
@PublishedApi
internal fun IrFactory.buildClass(builder: IrClassBuilder): IrClass = with(builder) {
- val wrappedDescriptor = WrappedClassDescriptor()
createClass(
startOffset, endOffset, origin,
- IrClassSymbolImpl(wrappedDescriptor),
+ IrClassSymbolImpl(),
name, kind, visibility, modality,
isCompanion, isInner, isData, isExternal, isInline, isExpect, isFun
- ).also {
- wrappedDescriptor.bind(it)
- }
+ )
}
inline fun IrFactory.buildClass(builder: IrClassBuilder.() -> Unit) =
@@ -40,14 +37,12 @@ inline fun IrFactory.buildClass(builder: IrClassBuilder.() -> Unit) =
@PublishedApi
internal fun IrFactory.buildField(builder: IrFieldBuilder): IrField = with(builder) {
- val wrappedDescriptor = WrappedFieldDescriptor()
createField(
startOffset, endOffset, origin,
- IrFieldSymbolImpl(wrappedDescriptor),
+ IrFieldSymbolImpl(),
name, type, visibility, isFinal, isExternal, isStatic,
).also {
it.metadata = metadata
- wrappedDescriptor.bind(it)
}
}
@@ -75,17 +70,13 @@ fun IrClass.addField(fieldName: String, fieldType: IrType, fieldVisibility: Desc
@PublishedApi
internal fun IrFactory.buildProperty(builder: IrPropertyBuilder): IrProperty = with(builder) {
- val wrappedDescriptor = WrappedPropertyDescriptor()
-
createProperty(
startOffset, endOffset, origin,
- IrPropertySymbolImpl(wrappedDescriptor),
+ IrPropertySymbolImpl(),
name, visibility, modality,
isVar, isConst, isLateinit, isDelegated, isExternal, isExpect, isFakeOverride,
containerSource,
- ).also {
- wrappedDescriptor.bind(it)
- }
+ )
}
inline fun IrFactory.buildProperty(builder: IrPropertyBuilder.() -> Unit) =
@@ -113,31 +104,25 @@ inline fun IrProperty.addGetter(builder: IrFunctionBuilder.() -> Unit = {}): IrS
@PublishedApi
internal fun IrFactory.buildFunction(builder: IrFunctionBuilder): IrSimpleFunction = with(builder) {
- val wrappedDescriptor = WrappedSimpleFunctionDescriptor()
createFunction(
startOffset, endOffset, origin,
- IrSimpleFunctionSymbolImpl(wrappedDescriptor),
+ IrSimpleFunctionSymbolImpl(),
name, visibility, modality, returnType,
isInline, isExternal, isTailrec, isSuspend, isOperator, isInfix, isExpect, isFakeOverride,
containerSource,
- ).also {
- wrappedDescriptor.bind(it)
- }
+ )
}
@PublishedApi
internal fun IrFactory.buildConstructor(builder: IrFunctionBuilder): IrConstructor = with(builder) {
- val wrappedDescriptor = WrappedClassConstructorDescriptor()
return createConstructor(
startOffset, endOffset, origin,
- IrConstructorSymbolImpl(wrappedDescriptor),
+ IrConstructorSymbolImpl(),
Name.special(""),
visibility, returnType,
isInline = isInline, isExternal = isExternal, isPrimary = isPrimary, isExpect = isExpect,
containerSource = containerSource
- ).also {
- wrappedDescriptor.bind(it)
- }
+ )
}
inline fun IrFactory.buildFun(builder: IrFunctionBuilder.() -> Unit): IrSimpleFunction =
@@ -207,28 +192,24 @@ fun buildReceiverParameter(
startOffset: Int = parent.startOffset,
endOffset: Int = parent.endOffset
): IrValueParameter
- where D : IrDeclaration, D : IrDeclarationParent = WrappedReceiverParameterDescriptor().let { wrappedDescriptor ->
+ where D : IrDeclaration, D : IrDeclarationParent =
parent.factory.createValueParameter(
startOffset, endOffset, origin,
- IrValueParameterSymbolImpl(wrappedDescriptor),
+ IrValueParameterSymbolImpl(),
RECEIVER_PARAMETER_NAME, -1, type, null, isCrossinline = false, isNoinline = false,
isHidden = false, isAssignable = false
).also {
- wrappedDescriptor.bind(it)
it.parent = parent
}
-}
@PublishedApi
internal fun IrFactory.buildValueParameter(builder: IrValueParameterBuilder, parent: IrDeclarationParent): IrValueParameter =
with(builder) {
- val wrappedDescriptor = WrappedValueParameterDescriptor()
return createValueParameter(
startOffset, endOffset, origin,
- IrValueParameterSymbolImpl(wrappedDescriptor),
+ IrValueParameterSymbolImpl(),
name, index, type, varargElementType, isCrossInline, isNoinline, isHidden, isAssignable
).also {
- wrappedDescriptor.bind(it)
it.parent = parent
}
}
@@ -283,13 +264,11 @@ fun IrSimpleFunction.addExtensionReceiver(type: IrType, origin: IrDeclarationOri
@PublishedApi
internal fun IrFactory.buildTypeParameter(builder: IrTypeParameterBuilder, parent: IrDeclarationParent): IrTypeParameter =
with(builder) {
- val wrappedDescriptor = WrappedTypeParameterDescriptor()
createTypeParameter(
startOffset, endOffset, origin,
- IrTypeParameterSymbolImpl(wrappedDescriptor),
+ IrTypeParameterSymbolImpl(),
name, index, isReified, variance
).also {
- wrappedDescriptor.bind(it)
it.superTypes = superTypes
it.parent = parent
}
@@ -330,13 +309,11 @@ fun buildVariable(
isConst: Boolean = false,
isLateinit: Boolean = false,
): IrVariable {
- val wrappedDescriptor = WrappedVariableDescriptor()
return IrVariableImpl(
startOffset, endOffset, origin,
- IrVariableSymbolImpl(wrappedDescriptor),
+ IrVariableSymbolImpl(),
name, type, isVar, isConst, isLateinit
).also {
- wrappedDescriptor.bind(it)
if (parent != null) {
it.parent = parent
}
diff --git a/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/JsIntrinsics.kt b/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/JsIntrinsics.kt
index f58a6310878..d20400aab4a 100644
--- a/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/JsIntrinsics.kt
+++ b/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/JsIntrinsics.kt
@@ -17,11 +17,9 @@ import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction
import org.jetbrains.kotlin.ir.declarations.impl.IrExternalPackageFragmentImpl
import org.jetbrains.kotlin.ir.descriptors.IrBuiltIns
import org.jetbrains.kotlin.ir.symbols.IrSimpleFunctionSymbol
-import org.jetbrains.kotlin.ir.types.IrType
-import org.jetbrains.kotlin.ir.types.defaultType
+import org.jetbrains.kotlin.ir.types.*
import org.jetbrains.kotlin.ir.types.impl.IrSimpleTypeBuilder
import org.jetbrains.kotlin.ir.types.impl.buildSimpleType
-import org.jetbrains.kotlin.ir.types.isLong
import org.jetbrains.kotlin.ir.util.constructors
import org.jetbrains.kotlin.ir.util.findDeclaration
import org.jetbrains.kotlin.ir.util.kotlinPackageFqn
@@ -169,7 +167,9 @@ class JsIntrinsics(private val irBuiltIns: IrBuiltIns, val context: JsIrBackendC
val jsGetContinuation = getInternalFunction("getContinuation")
val jsGetKClass = getInternalWithoutPackage("getKClass")
val jsGetKClassFromExpression = getInternalWithoutPackage("getKClassFromExpression")
- val jsClass = getInternalFunction("jsClass")
+
+ private val jsClassClassSymbol = getInternalClassWithoutPackage("kotlin.js.JsClass")
+ val jsClass = defineJsClassIntrinsic().symbol
val jsNumberRangeToNumber = getInternalFunction("numberRangeToNumber")
val jsNumberRangeToLong = getInternalFunction("numberRangeToLong")
@@ -448,6 +448,21 @@ class JsIntrinsics(private val irBuiltIns: IrBuiltIns, val context: JsIrBackendC
}
}
+ private fun defineJsClassIntrinsic(): IrSimpleFunction {
+ return irFactory.addFunction(externalPackageFragment) {
+ name = Name.identifier("jsClass")
+ origin = JsLoweredDeclarationOrigin.JS_INTRINSICS_STUB
+ isInline = true
+ }.apply {
+ val typeParameter = addTypeParameter {
+ name = Name.identifier("T")
+ isReified = true
+ superTypes += irBuiltIns.anyType
+ }
+ returnType = jsClassClassSymbol.typeWithParameters(listOf(typeParameter))
+ }
+ }
+
private fun unOp(name: String, returnType: IrType = irBuiltIns.anyNType) =
irBuiltIns.run { defineOperator(name, returnType, listOf(anyNType)) }
diff --git a/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/JsLoweringPhases.kt b/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/JsLoweringPhases.kt
index 7b66b386d04..871a74b222f 100644
--- a/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/JsLoweringPhases.kt
+++ b/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/JsLoweringPhases.kt
@@ -1,5 +1,5 @@
/*
- * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
+ * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@@ -21,7 +21,7 @@ import org.jetbrains.kotlin.ir.backend.js.lower.calls.CallsLowering
import org.jetbrains.kotlin.ir.backend.js.lower.cleanup.CleanupLowering
import org.jetbrains.kotlin.ir.backend.js.lower.coroutines.JsSuspendFunctionsLowering
import org.jetbrains.kotlin.ir.backend.js.lower.inline.CopyInlineFunctionBodyLowering
-import org.jetbrains.kotlin.ir.backend.js.lower.inline.RemoveInlineFunctionsWithReifiedTypeParametersLowering
+import org.jetbrains.kotlin.ir.backend.js.lower.inline.RemoveInlineDeclarationsWithReifiedTypeParametersLowering
import org.jetbrains.kotlin.ir.declarations.IrFile
import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
@@ -234,8 +234,8 @@ private val copyInlineFunctionBodyLoweringPhase = makeDeclarationTransformerPhas
prerequisite = setOf(functionInliningPhase)
)
-private val removeInlineFunctionsWithReifiedTypeParametersLoweringPhase = makeDeclarationTransformerPhase(
- { RemoveInlineFunctionsWithReifiedTypeParametersLowering() },
+private val removeInlineDeclarationsWithReifiedTypeParametersLoweringPhase = makeDeclarationTransformerPhase(
+ { RemoveInlineDeclarationsWithReifiedTypeParametersLowering() },
name = "RemoveInlineFunctionsWithReifiedTypeParametersLowering",
description = "Remove Inline functions with reified parameters from context",
prerequisite = setOf(functionInliningPhase)
@@ -370,6 +370,13 @@ private val propertyAccessorInlinerLoweringPhase = makeBodyLoweringPhase(
description = "[Optimization] Inline property accessors"
)
+private val copyPropertyAccessorBodiesLoweringPass = makeDeclarationTransformerPhase(
+ ::CopyAccessorBodyLowerings,
+ name = "CopyAccessorBodyLowering",
+ description = "Copy accessor bodies so that ist can be safely read in PropertyAccessorInlineLowering",
+ prerequisite = setOf(propertyAccessorInlinerLoweringPhase)
+)
+
private val foldConstantLoweringPhase = makeBodyLoweringPhase(
{ FoldConstantLowering(it, true) },
name = "FoldConstantLowering",
@@ -571,7 +578,7 @@ private val typeOperatorLoweringPhase = makeBodyLoweringPhase(
description = "Lower IrTypeOperator with corresponding logic",
prerequisite = setOf(
bridgesConstructionPhase,
- removeInlineFunctionsWithReifiedTypeParametersLoweringPhase,
+ removeInlineDeclarationsWithReifiedTypeParametersLoweringPhase,
singleAbstractMethodPhase, errorExpressionLoweringPhase
)
)
@@ -603,6 +610,12 @@ private val secondaryFactoryInjectorLoweringPhase = makeBodyLoweringPhase(
prerequisite = setOf(innerClassesLoweringPhase)
)
+private val constLoweringPhase = makeBodyLoweringPhase(
+ ::ConstLowering,
+ name = "ConstLowering",
+ description = "Wrap Long and Char constants into constructor invocation"
+)
+
private val inlineClassDeclarationLoweringPhase = makeDeclarationTransformerPhase(
{ InlineClassLowering(it).inlineClassDeclarationLowering },
name = "InlineClassDeclarationLowering",
@@ -612,7 +625,12 @@ private val inlineClassDeclarationLoweringPhase = makeDeclarationTransformerPhas
private val inlineClassUsageLoweringPhase = makeBodyLoweringPhase(
{ InlineClassLowering(it).inlineClassUsageLowering },
name = "InlineClassUsageLowering",
- description = "Handle inline class usages"
+ description = "Handle inline class usages",
+ prerequisite = setOf(
+ // Const lowering generates inline class constructors for unsigned integers
+ // which should be lowered by this lowering
+ constLoweringPhase
+ )
)
private val autoboxingTransformerPhase = makeBodyLoweringPhase(
@@ -640,12 +658,6 @@ private val primitiveCompanionLoweringPhase = makeBodyLoweringPhase(
description = "Replace common companion object access with platform one"
)
-private val constLoweringPhase = makeBodyLoweringPhase(
- ::ConstLowering,
- name = "ConstLowering",
- description = "Wrap Long and Char constants into constructor invocation"
-)
-
private val callsLoweringPhase = makeBodyLoweringPhase(
::CallsLowering,
name = "CallsLowering",
@@ -704,6 +716,7 @@ val loweringList = listOf(
localClassesExtractionFromInlineFunctionsPhase,
functionInliningPhase,
copyInlineFunctionBodyLoweringPhase,
+ removeInlineDeclarationsWithReifiedTypeParametersLoweringPhase,
createScriptFunctionsPhase,
callableReferenceLowering,
singleAbstractMethodPhase,
@@ -742,6 +755,7 @@ val loweringList = listOf(
propertyLazyInitLoweringPhase,
removeInitializersForLazyProperties,
propertyAccessorInlinerLoweringPhase,
+ copyPropertyAccessorBodiesLoweringPass,
foldConstantLoweringPhase,
privateMembersLoweringPhase,
privateMemberUsagesLoweringPhase,
@@ -750,7 +764,6 @@ val loweringList = listOf(
defaultParameterInjectorPhase,
defaultParameterCleanerPhase,
jsDefaultCallbackGeneratorPhase,
- removeInlineFunctionsWithReifiedTypeParametersLoweringPhase,
throwableSuccessorsLoweringPhase,
es6AddInternalParametersToConstructorPhase,
es6ConstructorLowering,
@@ -763,11 +776,11 @@ val loweringList = listOf(
secondaryConstructorLoweringPhase,
secondaryFactoryInjectorLoweringPhase,
classReferenceLoweringPhase,
+ constLoweringPhase,
inlineClassDeclarationLoweringPhase,
inlineClassUsageLoweringPhase,
autoboxingTransformerPhase,
blockDecomposerLoweringPhase,
- constLoweringPhase,
objectDeclarationLoweringPhase,
invokeStaticInitializersPhase,
objectUsageLoweringPhase,
diff --git a/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/lower/CopyAccessorBodyLowerings.kt b/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/lower/CopyAccessorBodyLowerings.kt
new file mode 100644
index 00000000000..b96406de4ae
--- /dev/null
+++ b/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/lower/CopyAccessorBodyLowerings.kt
@@ -0,0 +1,37 @@
+/*
+ * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
+ * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
+ */
+
+package org.jetbrains.kotlin.ir.backend.js.lower
+
+import org.jetbrains.kotlin.backend.common.CommonBackendContext
+import org.jetbrains.kotlin.backend.common.DeclarationTransformer
+import org.jetbrains.kotlin.ir.declarations.IrDeclaration
+import org.jetbrains.kotlin.ir.declarations.IrField
+import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction
+import org.jetbrains.kotlin.ir.expressions.IrBlockBody
+import org.jetbrains.kotlin.ir.util.deepCopyWithSymbols
+
+// Copies property accessors and initializers so that the PropertyAccessorInilineLowering may access them safely.
+class CopyAccessorBodyLowerings(private val context: CommonBackendContext) : DeclarationTransformer {
+ override fun transformFlat(declaration: IrDeclaration): List? {
+ if (declaration is IrSimpleFunction && declaration.correspondingPropertySymbol != null) {
+ declaration.body?.let { originalBody ->
+ declaration.body = context.irFactory.createBlockBody(originalBody.startOffset, originalBody.endOffset) {
+ statements += (originalBody.deepCopyWithSymbols(declaration) as IrBlockBody).statements
+ }
+ }
+ }
+
+ if (declaration is IrField) {
+ declaration.initializer?.let { originalBody ->
+ declaration.initializer = context.irFactory.createExpressionBody(originalBody.startOffset, originalBody.endOffset) {
+ this.expression = originalBody.expression.deepCopyWithSymbols(declaration)
+ }
+ }
+ }
+
+ return null
+ }
+}
\ No newline at end of file
diff --git a/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/lower/MoveBodilessDeclarationsToSeparatePlace.kt b/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/lower/MoveBodilessDeclarationsToSeparatePlace.kt
index 371f0c2c74c..948a3b33230 100644
--- a/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/lower/MoveBodilessDeclarationsToSeparatePlace.kt
+++ b/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/lower/MoveBodilessDeclarationsToSeparatePlace.kt
@@ -54,6 +54,10 @@ private class DescriptorlessIrFileSymbol : IrFileSymbol {
override val descriptor: PackageFragmentDescriptor
get() = error("Operation is unsupported")
+ @ObsoleteDescriptorBasedAPI
+ override val hasDescriptor: Boolean
+ get() = error("Operation is unsupported")
+
private var _owner: IrFile? = null
override val owner get() = _owner!!
diff --git a/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/lower/calls/CallsLowering.kt b/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/lower/calls/CallsLowering.kt
index a77455da59d..20d3ff41a5c 100644
--- a/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/lower/calls/CallsLowering.kt
+++ b/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/lower/calls/CallsLowering.kt
@@ -16,8 +16,6 @@ import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.ir.expressions.IrFunctionAccessExpression
import org.jetbrains.kotlin.ir.util.hasAnnotation
import org.jetbrains.kotlin.ir.visitors.IrElementTransformer
-import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid
-import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
class CallsLowering(val context: JsIrBackendContext) : BodyLoweringPass {
private val transformers = listOf(
@@ -32,6 +30,7 @@ class CallsLowering(val context: JsIrBackendContext) : BodyLoweringPass {
BuiltInConstructorCalls(context),
JsonIntrinsics(context),
NativeGetterSetterTransformer(context),
+ ReplaceCallsWithInvalidTypeArgumentForReifiedParameters(context),
)
override fun lower(irBody: IrBody, container: IrDeclaration) {
diff --git a/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/lower/calls/ReplaceCallsWithInvalidTypeArgumentForReifiedParameters.kt b/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/lower/calls/ReplaceCallsWithInvalidTypeArgumentForReifiedParameters.kt
new file mode 100644
index 00000000000..35637c6ad82
--- /dev/null
+++ b/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/lower/calls/ReplaceCallsWithInvalidTypeArgumentForReifiedParameters.kt
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
+ * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
+ */
+
+package org.jetbrains.kotlin.ir.backend.js.lower.calls
+
+import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET
+import org.jetbrains.kotlin.ir.backend.js.JsIrBackendContext
+import org.jetbrains.kotlin.ir.backend.js.ir.JsIrBuilder
+import org.jetbrains.kotlin.ir.expressions.IrExpression
+import org.jetbrains.kotlin.ir.expressions.IrFunctionAccessExpression
+import org.jetbrains.kotlin.ir.expressions.impl.IrCompositeImpl
+import org.jetbrains.kotlin.ir.expressions.impl.IrConstImpl
+import org.jetbrains.kotlin.ir.types.classOrNull
+import org.jetbrains.kotlin.ir.util.getArgumentsWithIr
+import org.jetbrains.kotlin.ir.util.render
+
+
+class ReplaceCallsWithInvalidTypeArgumentForReifiedParameters(val context: JsIrBackendContext) : CallsTransformer {
+ override fun transformFunctionAccess(call: IrFunctionAccessExpression, doNotIntrinsify: Boolean): IrExpression {
+ if (!context.errorPolicy.allowErrors) return call
+
+ val function = call.symbol.owner
+
+ for (typeParameter in function.typeParameters) {
+ if (!typeParameter.isReified) continue
+ val typeArgument = call.getTypeArgument(typeParameter.index)
+
+ if (typeArgument?.classOrNull == null) {
+ val args = call.getArgumentsWithIr().map { it.second }
+
+ val callErrorCode = JsIrBuilder.buildCall(context.errorCodeSymbol!!).apply {
+ putValueArgument(
+ 0,
+ IrConstImpl.string(
+ UNDEFINED_OFFSET,
+ UNDEFINED_OFFSET,
+ context.irBuiltIns.stringType,
+ "Invalid type argument (${typeArgument?.render()}) for reified type parameter (${typeParameter.render()})"
+ )
+ )
+ }
+
+ if (args.isEmpty()) return callErrorCode
+
+ return IrCompositeImpl(-1, -1, call.type, call.origin, args + listOf(callErrorCode))
+ }
+ }
+
+ return call
+ }
+}
diff --git a/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/lower/inline/RemoveInlineFunctionsWithReifiedTypeParametersLowering.kt b/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/lower/inline/RemoveInlineDeclarationsWithReifiedTypeParametersLowering.kt
similarity index 78%
rename from compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/lower/inline/RemoveInlineFunctionsWithReifiedTypeParametersLowering.kt
rename to compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/lower/inline/RemoveInlineDeclarationsWithReifiedTypeParametersLowering.kt
index c7e0a16fdf9..043f1fd8d93 100644
--- a/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/lower/inline/RemoveInlineFunctionsWithReifiedTypeParametersLowering.kt
+++ b/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/lower/inline/RemoveInlineDeclarationsWithReifiedTypeParametersLowering.kt
@@ -1,5 +1,5 @@
/*
- * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
+ * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@@ -9,15 +9,19 @@ import org.jetbrains.kotlin.backend.common.DeclarationTransformer
import org.jetbrains.kotlin.ir.backend.js.JsIrBackendContext
import org.jetbrains.kotlin.ir.declarations.IrDeclaration
import org.jetbrains.kotlin.ir.declarations.IrFunction
+import org.jetbrains.kotlin.ir.declarations.IrProperty
import org.jetbrains.kotlin.ir.declarations.IrValueParameter
import org.jetbrains.kotlin.ir.expressions.IrBlockBody
import org.jetbrains.kotlin.ir.util.deepCopyWithSymbols
-class RemoveInlineFunctionsWithReifiedTypeParametersLowering: DeclarationTransformer {
+class RemoveInlineDeclarationsWithReifiedTypeParametersLowering: DeclarationTransformer {
override fun transformFlat(declaration: IrDeclaration): List? {
+ fun IrFunction.isInlineFunWithReifiedParameter() = isInline && typeParameters.any { it.isReified }
- if (declaration is IrFunction && declaration.isInline && declaration.typeParameters.any { it.isReified }) {
+ if (declaration is IrFunction && declaration.isInlineFunWithReifiedParameter() ||
+ declaration is IrProperty && declaration.getter?.isInlineFunWithReifiedParameter() == true
+ ) {
return emptyList()
}
diff --git a/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/transformers/irToJs/IrElementToJsExpressionTransformer.kt b/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/transformers/irToJs/IrElementToJsExpressionTransformer.kt
index 0c3334b390a..2889b4cc274 100644
--- a/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/transformers/irToJs/IrElementToJsExpressionTransformer.kt
+++ b/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/transformers/irToJs/IrElementToJsExpressionTransformer.kt
@@ -7,7 +7,10 @@ package org.jetbrains.kotlin.ir.backend.js.transformers.irToJs
import org.jetbrains.kotlin.backend.common.ir.isElseBranch
import org.jetbrains.kotlin.descriptors.ClassKind
-import org.jetbrains.kotlin.ir.backend.js.utils.*
+import org.jetbrains.kotlin.ir.backend.js.utils.JsGenerationContext
+import org.jetbrains.kotlin.ir.backend.js.utils.Namer
+import org.jetbrains.kotlin.ir.backend.js.utils.emptyScope
+import org.jetbrains.kotlin.ir.backend.js.utils.getJsNameOrKotlinName
import org.jetbrains.kotlin.ir.declarations.IrClass
import org.jetbrains.kotlin.ir.declarations.IrConstructor
import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction
@@ -20,6 +23,18 @@ import org.jetbrains.kotlin.js.backend.ast.*
@Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE")
class IrElementToJsExpressionTransformer : BaseIrElementToJsNodeTransformer {
+ override fun visitComposite(expression: IrComposite, data: JsGenerationContext): JsExpression {
+ val size = expression.statements.size
+ if (size == 0) TODO("Empty IrComposite is not supported")
+
+ val first = expression.statements[0].accept(this, data)
+ if (size == 1) return first
+
+ return expression.statements.fold(first) { left, right ->
+ JsBinaryOperation(JsBinaryOperator.COMMA, left, right.accept(this, data))
+ }
+ }
+
override fun visitVararg(expression: IrVararg, context: JsGenerationContext): JsExpression {
assert(expression.elements.none { it is IrSpreadElement })
return JsArrayLiteral(expression.elements.map { it.accept(this, context) })
@@ -146,39 +161,36 @@ class IrElementToJsExpressionTransformer : BaseIrElementToJsNodeTransformer {
+ val refForExternalClass = context.getRefForExternalClass(klass)
+ val varargParameterIndex = expression.symbol.owner.varargParameterIndex()
+ if (varargParameterIndex == -1) {
+ JsNew(refForExternalClass, arguments)
+ } else {
+ val argumentsAsSingleArray = argumentsWithVarargAsSingleArray(
+ JsNullLiteral(),
+ arguments,
+ varargParameterIndex
+ )
+ JsNew(
+ JsInvocation(
+ JsNameRef("apply", JsNameRef("bind", JsNameRef("Function"))),
+ refForExternalClass,
+ argumentsAsSingleArray
+ ),
+ emptyList()
+ )
+ }
}
- // Argument value constructs unboxed inline class instance
- arguments.single()
- } else {
- when {
- klass.isEffectivelyExternal() -> {
- val refForExternalClass = context.getRefForExternalClass(klass)
- val varargParameterIndex = expression.symbol.owner.varargParameterIndex()
- if (varargParameterIndex == -1) {
- JsNew(refForExternalClass, arguments)
- } else {
- val argumentsAsSingleArray = argumentsWithVarargAsSingleArray(
- JsNullLiteral(),
- arguments,
- varargParameterIndex
- )
- JsNew(
- JsInvocation(
- JsNameRef("apply", JsNameRef("bind", JsNameRef("Function"))),
- refForExternalClass,
- argumentsAsSingleArray
- ),
- emptyList()
- )
- }
- }
- else -> {
- val ref = context.getNameForClass(klass).makeRef()
- JsNew(ref, arguments)
- }
+ else -> {
+ val ref = context.getNameForClass(klass).makeRef()
+ JsNew(ref, arguments)
}
}
}
diff --git a/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/transformers/irToJs/JsIntrinsicTransformers.kt b/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/transformers/irToJs/JsIntrinsicTransformers.kt
index 004be491487..22f1aa5ab77 100644
--- a/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/transformers/irToJs/JsIntrinsicTransformers.kt
+++ b/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/transformers/irToJs/JsIntrinsicTransformers.kt
@@ -1,5 +1,5 @@
/*
- * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
+ * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@@ -17,9 +17,11 @@ import org.jetbrains.kotlin.ir.expressions.IrFunctionReference
import org.jetbrains.kotlin.ir.symbols.IrClassifierSymbol
import org.jetbrains.kotlin.ir.symbols.IrSimpleFunctionSymbol
import org.jetbrains.kotlin.ir.symbols.IrSymbol
+import org.jetbrains.kotlin.ir.types.classOrNull
import org.jetbrains.kotlin.ir.types.classifierOrFail
import org.jetbrains.kotlin.ir.util.getInlineClassBackingField
import org.jetbrains.kotlin.ir.util.isEffectivelyExternal
+import org.jetbrains.kotlin.ir.util.render
import org.jetbrains.kotlin.js.backend.ast.*
typealias IrCallTransformer = (IrCall, context: JsGenerationContext) -> JsExpression
@@ -89,15 +91,18 @@ class JsIntrinsicTransformers(backendContext: JsIrBackendContext) {
}
add(intrinsics.jsClass) { call, context ->
- val classifier: IrClassifierSymbol = call.getTypeArgument(0)!!.classifierOrFail
- val owner = classifier.owner
+ val typeArgument = call.getTypeArgument(0)
+ val classSymbol = typeArgument?.classOrNull
+ ?: error("Type argument of jsClass must be statically known class, but " + typeArgument?.render())
+
+ val klass = classSymbol.owner
when {
- owner is IrClass && owner.isEffectivelyExternal() ->
- context.getRefForExternalClass(owner)
+ klass.isEffectivelyExternal() ->
+ context.getRefForExternalClass(klass)
else ->
- context.getNameForStaticDeclaration(owner as IrDeclarationWithName).makeRef()
+ context.getNameForStaticDeclaration(klass as IrDeclarationWithName).makeRef()
}
}
diff --git a/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/utils/NameTables.kt b/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/utils/NameTables.kt
index 09fb29e1ce7..ee950a66aa4 100644
--- a/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/utils/NameTables.kt
+++ b/compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/utils/NameTables.kt
@@ -1,5 +1,5 @@
/*
- * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
+ * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@@ -26,24 +26,24 @@ import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.utils.addToStdlib.ifNotEmpty
import java.util.*
-fun mapToKey(declaration: T): String {
+// TODO remove direct usages of [mapToKey] from [NameTable] & co and move it to scripting & REPL infrastructure. Review usages.
+private fun mapToKey(declaration: T): String {
return with(JsManglerIr) {
- if (declaration is IrDeclaration && isPublic(declaration)) {
+ if (declaration is IrDeclaration) {
declaration.hashedMangle.toString()
} else if (declaration is Signature) {
declaration.toString().hashMangle.toString()
- } else "key_have_not_generated"
+ } else {
+ error("Key is not generated for " + declaration?.let { it::class.simpleName })
+ }
}
}
-fun JsManglerIr.isPublic(declaration: IrDeclaration) =
- declaration.isExported() && declaration !is IrScript && declaration !is IrVariable && declaration !is IrValueParameter
-
class NameTable(
val parent: NameTable<*>? = null,
val reserved: MutableSet = mutableSetOf(),
val sanitizer: (String) -> String = ::sanitizeName,
- val mappedNames: MutableMap = mutableMapOf()
+ val mappedNames: MutableMap? = null
) {
var finished = false
val names = mutableMapOf()
@@ -59,7 +59,7 @@ class NameTable(
assert(!finished)
names[declaration] = name
reserved.add(name)
- mappedNames[mapToKey(declaration)] = name
+ mappedNames?.set(mapToKey(declaration), name)
}
fun declareFreshName(declaration: T, suggestedName: String): String {
@@ -151,7 +151,7 @@ class NameTables(
packages: List,
reservedForGlobal: MutableSet = mutableSetOf(),
reservedForMember: MutableSet = mutableSetOf(),
- val mappedNames: MutableMap = mutableMapOf()
+ val mappedNames: MutableMap? = null
) {
val globalNames: NameTable
private val memberNames: NameTable
@@ -172,8 +172,6 @@ class NameTables(
mappedNames = mappedNames
)
- mappedNames.addAllIfAbsent(mappedNames)
-
val classDeclaration = mutableListOf()
for (p in packages) {
for (declaration in p.declarations) {
@@ -249,7 +247,7 @@ class NameTables(
this += other.filter { it.key !in this }
}
- private fun packagesAdded() = mappedNames.isEmpty()
+ private fun packagesAdded() = mappedNames.isNullOrEmpty()
fun merge(files: List, additionalPackages: List) {
val packages = mutableListOf().also { it.addAll(files) }
@@ -311,13 +309,17 @@ class NameTables(
parent = parent.parent
}
- return mappedNames[mapToKey(declaration)]
- ?: error("Can't find name for declaration ${declaration.render()}")
+
+ mappedNames?.get(mapToKey(declaration))?.let {
+ return it
+ }
+
+ error("Can't find name for declaration ${declaration.render()}")
}
fun getNameForMemberField(field: IrField): String {
val signature = fieldSignature(field)
- val name = memberNames.names[signature] ?: mappedNames[mapToKey(signature)]
+ val name = memberNames.names[signature] ?: mappedNames?.get(mapToKey(signature))
// TODO investigate
if (name == null) {
@@ -329,7 +331,7 @@ class NameTables(
fun getNameForMemberFunction(function: IrSimpleFunction): String {
val signature = jsFunctionSignature(function)
- val name = memberNames.names[signature] ?: mappedNames[mapToKey(signature)]
+ val name = memberNames.names[signature] ?: mappedNames?.get(mapToKey(signature))
// TODO Add a compiler flag, which enables this behaviour
// TODO remove in DCE
diff --git a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/JvmBackendContext.kt b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/JvmBackendContext.kt
index 10c4e2dde5a..c46c3929030 100644
--- a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/JvmBackendContext.kt
+++ b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/JvmBackendContext.kt
@@ -19,7 +19,6 @@ import org.jetbrains.kotlin.backend.jvm.lower.CollectionStubComputer
import org.jetbrains.kotlin.backend.jvm.lower.JvmInnerClassesSupport
import org.jetbrains.kotlin.backend.jvm.lower.inlineclasses.InlineClassAbi
import org.jetbrains.kotlin.backend.jvm.lower.inlineclasses.MemoizedInlineClassReplacements
-import org.jetbrains.kotlin.codegen.serialization.JvmSerializationBindings
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
@@ -41,8 +40,6 @@ import org.jetbrains.kotlin.psi2ir.PsiSourceManager
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.org.objectweb.asm.Type
-typealias MetadataSerializerFactory = (JvmBackendContext, IrClass, Type, JvmSerializationBindings, MetadataSerializer?) -> MetadataSerializer
-
class JvmBackendContext(
val state: GenerationState,
val psiSourceManager: PsiSourceManager,
@@ -51,7 +48,7 @@ class JvmBackendContext(
private val symbolTable: SymbolTable,
val phaseConfig: PhaseConfig,
val generatorExtensions: JvmGeneratorExtensions,
- val serializerFactory: MetadataSerializerFactory
+ val backendExtension: JvmBackendExtension,
) : CommonBackendContext {
// If the JVM fqname of a class differs from what is implied by its parent, e.g. if it's a file class
// annotated with @JvmPackageName, the correct name is recorded here.
@@ -131,6 +128,8 @@ class JvmBackendContext(
val inlineClassReplacements = MemoizedInlineClassReplacements(state.functionsWithInlineClassReturnTypesMangled, irFactory, this)
+ internal val continuationClassesVarsCountByType: MutableMap> = hashMapOf()
+
internal fun referenceClass(descriptor: ClassDescriptor): IrClassSymbol =
symbolTable.lazyWrapper.referenceClass(descriptor)
diff --git a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/JvmBackendExtension.kt b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/JvmBackendExtension.kt
new file mode 100644
index 00000000000..6f8185c9a9a
--- /dev/null
+++ b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/JvmBackendExtension.kt
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
+ * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
+ */
+
+package org.jetbrains.kotlin.backend.jvm
+
+import org.jetbrains.kotlin.backend.jvm.codegen.DescriptorMetadataSerializer
+import org.jetbrains.kotlin.backend.jvm.codegen.MetadataSerializer
+import org.jetbrains.kotlin.codegen.serialization.JvmSerializationBindings
+import org.jetbrains.kotlin.config.JvmAbiStability
+import org.jetbrains.kotlin.ir.declarations.IrClass
+import org.jetbrains.kotlin.load.java.JvmAnnotationNames
+import org.jetbrains.org.objectweb.asm.Type
+
+interface JvmBackendExtension {
+ fun createSerializer(
+ context: JvmBackendContext, klass: IrClass, type: Type, bindings: JvmSerializationBindings, parentSerializer: MetadataSerializer?
+ ): MetadataSerializer
+
+ fun generateMetadataExtraFlags(abiStability: JvmAbiStability?): Int
+
+ object Default : JvmBackendExtension {
+ override fun createSerializer(
+ context: JvmBackendContext,
+ klass: IrClass,
+ type: Type,
+ bindings: JvmSerializationBindings,
+ parentSerializer: MetadataSerializer?
+ ): MetadataSerializer {
+ return DescriptorMetadataSerializer(context, klass, type, bindings, parentSerializer)
+ }
+
+ override fun generateMetadataExtraFlags(abiStability: JvmAbiStability?): Int =
+ JvmAnnotationNames.METADATA_JVM_IR_FLAG or
+ (if (abiStability != JvmAbiStability.UNSTABLE) JvmAnnotationNames.METADATA_JVM_IR_STABLE_ABI_FLAG else 0)
+ }
+}
diff --git a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/JvmIrCodegenFactory.kt b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/JvmIrCodegenFactory.kt
index 28fa2b6499d..903e79cfd1e 100644
--- a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/JvmIrCodegenFactory.kt
+++ b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/JvmIrCodegenFactory.kt
@@ -11,7 +11,6 @@ import org.jetbrains.kotlin.backend.common.extensions.IrPluginContextImpl
import org.jetbrains.kotlin.backend.common.ir.BuiltinSymbolsBase
import org.jetbrains.kotlin.backend.common.phaser.PhaseConfig
import org.jetbrains.kotlin.backend.jvm.codegen.ClassCodegen
-import org.jetbrains.kotlin.backend.jvm.codegen.DescriptorMetadataSerializer
import org.jetbrains.kotlin.backend.jvm.lower.MultifileFacadeFileEntry
import org.jetbrains.kotlin.backend.jvm.serialization.JvmIdSignatureDescriptor
import org.jetbrains.kotlin.codegen.CodegenFactory
@@ -41,7 +40,23 @@ import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.CleanableBindingContext
class JvmIrCodegenFactory(private val phaseConfig: PhaseConfig) : CodegenFactory {
+ data class JvmIrBackendInput(
+ val state: GenerationState,
+ val irModuleFragment: IrModuleFragment,
+ val symbolTable: SymbolTable,
+ val sourceManager: PsiSourceManager,
+ val phaseConfig: PhaseConfig,
+ val irProviders: List,
+ val extensions: JvmGeneratorExtensions,
+ val backendExtension: JvmBackendExtension,
+ )
+
override fun generateModule(state: GenerationState, files: Collection) {
+ val input = convertToIr(state, files)
+ doGenerateFilesInternal(input)
+ }
+
+ fun convertToIr(state: GenerationState, files: Collection): JvmIrBackendInput {
val extensions = JvmGeneratorExtensions()
val mangler = JvmManglerDesc(MainFunctionDetector(state.bindingContext, state.languageVersionSettings))
val psi2ir = Psi2IrTranslator(state.languageVersionSettings, Psi2IrConfiguration())
@@ -117,26 +132,23 @@ class JvmIrCodegenFactory(private val phaseConfig: PhaseConfig) : CodegenFactory
?: error("BindingContext should be cleanable in JVM IR to avoid leaking memory: ${state.originalFrontendBindingContext}")
originalBindingContext.clear()
}
-
- doGenerateFilesInternal(
- state, irModuleFragment, psi2irContext.symbolTable, psi2irContext.sourceManager, phaseConfig,
- irProviders, extensions, ::DescriptorMetadataSerializer
+ return JvmIrBackendInput(
+ state,
+ irModuleFragment,
+ symbolTable,
+ psi2irContext.sourceManager,
+ phaseConfig,
+ irProviders,
+ extensions,
+ JvmBackendExtension.Default,
)
}
- fun doGenerateFilesInternal(
- state: GenerationState,
- irModuleFragment: IrModuleFragment,
- symbolTable: SymbolTable,
- sourceManager: PsiSourceManager,
- phaseConfig: PhaseConfig,
- irProviders: List,
- extensions: JvmGeneratorExtensions,
- serializerFactory: MetadataSerializerFactory,
- ) {
+ fun doGenerateFilesInternal(input: JvmIrBackendInput) {
+ val (state, irModuleFragment, symbolTable, sourceManager, phaseConfig, irProviders, extensions, backendExtension) = input
val context = JvmBackendContext(
state, sourceManager, irModuleFragment.irBuiltins, irModuleFragment,
- symbolTable, phaseConfig, extensions, serializerFactory
+ symbolTable, phaseConfig, extensions, backendExtension
)
/* JvmBackendContext creates new unbound symbols, have to resolve them. */
ExternalDependenciesGenerator(symbolTable, irProviders, state.languageVersionSettings).generateUnboundSymbolsAsDependencies()
@@ -178,15 +190,22 @@ class JvmIrCodegenFactory(private val phaseConfig: PhaseConfig) : CodegenFactory
symbolTable: SymbolTable,
sourceManager: PsiSourceManager,
extensions: JvmGeneratorExtensions,
- serializerFactory: MetadataSerializerFactory
+ backendExtension: JvmBackendExtension,
) {
- irModuleFragment.irBuiltins.functionFactory = IrFunctionFactory(irModuleFragment.irBuiltins, symbolTable)
- val irProviders = generateTypicalIrProviderList(
- irModuleFragment.descriptor, irModuleFragment.irBuiltins, symbolTable, extensions = extensions
- )
-
+ val irProviders = configureBuiltInsAndgenerateIrProvidersInFrontendIRMode(irModuleFragment, symbolTable, extensions)
doGenerateFilesInternal(
- state, irModuleFragment, symbolTable, sourceManager, phaseConfig, irProviders, extensions, serializerFactory
+ JvmIrBackendInput(state, irModuleFragment, symbolTable, sourceManager, phaseConfig, irProviders, extensions, backendExtension)
+ )
+ }
+
+ fun configureBuiltInsAndgenerateIrProvidersInFrontendIRMode(
+ irModuleFragment: IrModuleFragment,
+ symbolTable: SymbolTable,
+ extensions: JvmGeneratorExtensions
+ ): List {
+ irModuleFragment.irBuiltins.functionFactory = IrFunctionFactory(irModuleFragment.irBuiltins, symbolTable)
+ return generateTypicalIrProviderList(
+ irModuleFragment.descriptor, irModuleFragment.irBuiltins, symbolTable, extensions = extensions
)
}
}
diff --git a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/codegen/AnnotationCodegen.kt b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/codegen/AnnotationCodegen.kt
index a36bfd41d89..1c0e59c8543 100644
--- a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/codegen/AnnotationCodegen.kt
+++ b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/codegen/AnnotationCodegen.kt
@@ -286,7 +286,8 @@ abstract class AnnotationCodegen(
when {
declaration.origin.isSynthetic ->
true
- declaration.origin == JvmLoweredDeclarationOrigin.INLINE_CLASS_GENERATED_IMPL_METHOD ->
+ declaration.origin == JvmLoweredDeclarationOrigin.INLINE_CLASS_GENERATED_IMPL_METHOD ||
+ declaration.origin == IrDeclarationOrigin.GENERATED_SAM_IMPLEMENTATION ->
true
else ->
false
diff --git a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/codegen/ClassCodegen.kt b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/codegen/ClassCodegen.kt
index 21758e69cd7..01a5d8c4541 100644
--- a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/codegen/ClassCodegen.kt
+++ b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/codegen/ClassCodegen.kt
@@ -10,9 +10,8 @@ import org.jetbrains.kotlin.backend.jvm.JvmLoweredDeclarationOrigin
import org.jetbrains.kotlin.backend.jvm.lower.MultifileFacadeFileEntry
import org.jetbrains.kotlin.backend.jvm.lower.buildAssertionsDisabledField
import org.jetbrains.kotlin.backend.jvm.lower.hasAssertionsDisabledField
-import org.jetbrains.kotlin.codegen.DescriptorAsmUtil
+import org.jetbrains.kotlin.codegen.*
import org.jetbrains.kotlin.codegen.inline.*
-import org.jetbrains.kotlin.codegen.writeKotlinMetadata
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
@@ -190,14 +189,13 @@ class ClassCodegen private constructor(
}
private val metadataSerializer: MetadataSerializer =
- context.serializerFactory(context, irClass, type, visitor.serializationBindings, parentClassCodegen?.metadataSerializer)
+ context.backendExtension.createSerializer(
+ context, irClass, type, visitor.serializationBindings, parentClassCodegen?.metadataSerializer
+ )
private fun generateKotlinMetadataAnnotation() {
// TODO: if `-Xmultifile-parts-inherit` is enabled, write the corresponding flag for parts and facades to [Metadata.extraInt].
- var extraFlags = JvmAnnotationNames.METADATA_JVM_IR_FLAG
- if (state.isIrWithStableAbi) {
- extraFlags += JvmAnnotationNames.METADATA_JVM_IR_STABLE_ABI_FLAG
- }
+ val extraFlags = context.backendExtension.generateMetadataExtraFlags(state.abiStability)
val facadeClassName = context.multifileFacadeForPart[irClass.attributeOwnerId]
val metadata = irClass.metadata
@@ -310,7 +308,7 @@ class ClassCodegen private constructor(
if (irClass.hasAnnotation(JVM_RECORD_ANNOTATION_FQ_NAME) && !field.isStatic) {
// TODO: Write annotations to the component
- visitor.newRecordComponent(fieldName, fieldType.descriptor, fieldSignature)
+ visitor.addRecordComponent(fieldName, fieldType.descriptor, fieldSignature)
}
}
@@ -360,7 +358,19 @@ class ClassCodegen private constructor(
// lazily so that if tail call optimization kicks in, the unused class will not be written to the output.
val continuationClass = method.continuationClass() // null if `SuspendLambda.invokeSuspend` - `this` is continuation itself
val continuationClassCodegen = lazy { if (continuationClass != null) getOrCreate(continuationClass, context, method) else this }
- node.acceptWithStateMachine(method, this, smapCopyingVisitor) { continuationClassCodegen.value.visitor }
+
+ // For suspend lambdas continuation class is null, and we need to use containing class to put L$ fields
+ val attributeContainer = continuationClass?.attributeOwnerId ?: irClass.attributeOwnerId
+
+ node.acceptWithStateMachine(
+ method,
+ this,
+ smapCopyingVisitor,
+ context.continuationClassesVarsCountByType[attributeContainer] ?: emptyMap()
+ ) {
+ continuationClassCodegen.value.visitor
+ }
+
if (continuationClass != null && (continuationClassCodegen.isInitialized() || method.isSuspendCapturingCrossinline())) {
continuationClassCodegen.value.generate()
}
@@ -404,7 +414,7 @@ class ClassCodegen private constructor(
?: containerClass.declarations.firstIsInstanceOrNull()
?: error("Class in a non-static initializer found, but container has no constructors: ${containerClass.render()}")
} else parentFunction
- if (enclosingFunction != null || irClass.isAnonymousObject) {
+ if (enclosingFunction != null || irClass.isAnonymousInnerClass) {
val method = enclosingFunction?.let(context.methodSignatureMapper::mapAsmMethod)
visitor.visitOuterClass(parentClassCodegen.type.internalName, method?.name, method?.descriptor)
}
@@ -413,13 +423,26 @@ class ClassCodegen private constructor(
for (klass in innerClasses) {
val innerClass = typeMapper.classInternalName(klass)
val outerClass =
- if (klass.attributeOwnerId in context.isEnclosedInConstructor) null
- else klass.parent.safeAs()?.let(typeMapper::classInternalName)
- val innerName = klass.name.takeUnless { it.isSpecial }?.asString()
- visitor.visitInnerClass(innerClass, outerClass, innerName, klass.calculateInnerClassAccessFlags(context))
+ if (klass.isSamWrapper || klass.attributeOwnerId in context.isEnclosedInConstructor)
+ null
+ else {
+ when (val parent = klass.parent) {
+ is IrClass -> typeMapper.classInternalName(parent)
+ else -> null
+ }
+ }
+ val innerName = if (klass.isAnonymousInnerClass) null else klass.name.asString()
+ val accessFlags = klass.calculateInnerClassAccessFlags(context)
+ visitor.visitInnerClass(innerClass, outerClass, innerName, accessFlags)
}
}
+ private val IrClass.isAnonymousInnerClass: Boolean
+ get() = isSamWrapper || name.isSpecial // NB '' is treated as anonymous inner class here
+
+ private val IrClass.isSamWrapper: Boolean
+ get() = origin == IrDeclarationOrigin.GENERATED_SAM_IMPLEMENTATION
+
override fun addInnerClassInfoFromAnnotation(innerClass: IrClass) {
// It's necessary for proper recovering of classId by plain string JVM descriptor when loading annotations
// See FileBasedKotlinClass.convertAnnotationVisitor
@@ -458,7 +481,7 @@ private val IrClass.flags: Int
isAnnotationClass -> Opcodes.ACC_ANNOTATION or Opcodes.ACC_INTERFACE or Opcodes.ACC_ABSTRACT
isInterface -> Opcodes.ACC_INTERFACE or Opcodes.ACC_ABSTRACT
isEnumClass -> Opcodes.ACC_ENUM or Opcodes.ACC_SUPER or modality.flags
- hasAnnotation(JVM_RECORD_ANNOTATION_FQ_NAME) -> Opcodes.ACC_RECORD or Opcodes.ACC_SUPER or modality.flags
+ hasAnnotation(JVM_RECORD_ANNOTATION_FQ_NAME) -> VersionIndependentOpcodes.ACC_RECORD or Opcodes.ACC_SUPER or modality.flags
else -> Opcodes.ACC_SUPER or modality.flags
}
diff --git a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/codegen/ClassCodegen.kt.201 b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/codegen/ClassCodegen.kt.201
index f27ad043172..134d805adca 100644
--- a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/codegen/ClassCodegen.kt.201
+++ b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/codegen/ClassCodegen.kt.201
@@ -190,14 +190,13 @@ class ClassCodegen private constructor(
}
private val metadataSerializer: MetadataSerializer =
- context.serializerFactory(context, irClass, type, visitor.serializationBindings, parentClassCodegen?.metadataSerializer)
+ context.backendExtension.createSerializer(
+ context, irClass, type, visitor.serializationBindings, parentClassCodegen?.metadataSerializer
+ )
private fun generateKotlinMetadataAnnotation() {
// TODO: if `-Xmultifile-parts-inherit` is enabled, write the corresponding flag for parts and facades to [Metadata.extraInt].
- var extraFlags = JvmAnnotationNames.METADATA_JVM_IR_FLAG
- if (state.isIrWithStableAbi) {
- extraFlags += JvmAnnotationNames.METADATA_JVM_IR_STABLE_ABI_FLAG
- }
+ val extraFlags = context.backendExtension.generateMetadataExtraFlags(state.abiStability)
val facadeClassName = context.multifileFacadeForPart[irClass.attributeOwnerId]
val metadata = irClass.metadata
@@ -360,7 +359,19 @@ class ClassCodegen private constructor(
// lazily so that if tail call optimization kicks in, the unused class will not be written to the output.
val continuationClass = method.continuationClass() // null if `SuspendLambda.invokeSuspend` - `this` is continuation itself
val continuationClassCodegen = lazy { if (continuationClass != null) getOrCreate(continuationClass, context, method) else this }
- node.acceptWithStateMachine(method, this, smapCopyingVisitor) { continuationClassCodegen.value.visitor }
+
+ // For suspend lambdas continuation class is null, and we need to use containing class to put L$ fields
+ val attributeContainer = continuationClass?.attributeOwnerId ?: irClass.attributeOwnerId
+
+ node.acceptWithStateMachine(
+ method,
+ this,
+ smapCopyingVisitor,
+ context.continuationClassesVarsCountByType[attributeContainer] ?: emptyMap()
+ ) {
+ continuationClassCodegen.value.visitor
+ }
+
if (continuationClass != null && (continuationClassCodegen.isInitialized() || method.isSuspendCapturingCrossinline())) {
continuationClassCodegen.value.generate()
}
diff --git a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/codegen/CoroutineCodegen.kt b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/codegen/CoroutineCodegen.kt
index dcb505a6d3e..4a7e23e4a72 100644
--- a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/codegen/CoroutineCodegen.kt
+++ b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/codegen/CoroutineCodegen.kt
@@ -35,13 +35,15 @@ import org.jetbrains.kotlin.ir.util.parentAsClass
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.org.objectweb.asm.MethodVisitor
+import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.tree.MethodNode
internal fun MethodNode.acceptWithStateMachine(
irFunction: IrFunction,
classCodegen: ClassCodegen,
methodVisitor: MethodVisitor,
- obtainContinuationClassBuilder: () -> ClassBuilder
+ varsCountByType: Map,
+ obtainContinuationClassBuilder: () -> ClassBuilder,
) {
val state = classCodegen.context.state
val languageVersionSettings = state.languageVersionSettings
@@ -82,7 +84,8 @@ internal fun MethodNode.acceptWithStateMachine(
disableTailCallOptimizationForFunctionReturningUnit = irFunction.isSuspend && irFunction.suspendFunctionOriginal().let {
it.returnType.isUnit() && it.anyOfOverriddenFunctionsReturnsNonUnit()
},
- useOldSpilledVarTypeAnalysis = state.configuration.getBoolean(JVMConfigurationKeys.USE_OLD_SPILLED_VAR_TYPE_ANALYSIS)
+ useOldSpilledVarTypeAnalysis = state.configuration.getBoolean(JVMConfigurationKeys.USE_OLD_SPILLED_VAR_TYPE_ANALYSIS),
+ initialVarsCountByType = varsCountByType,
)
accept(visitor)
}
diff --git a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/descriptors/SharedVariablesManager.kt b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/descriptors/SharedVariablesManager.kt
index 352daa678cc..e3f8c554f92 100644
--- a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/descriptors/SharedVariablesManager.kt
+++ b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/descriptors/SharedVariablesManager.kt
@@ -16,7 +16,6 @@ import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.declarations.impl.IrExternalPackageFragmentImpl
import org.jetbrains.kotlin.ir.declarations.impl.IrVariableImpl
import org.jetbrains.kotlin.ir.descriptors.IrBuiltIns
-import org.jetbrains.kotlin.ir.descriptors.WrappedVariableDescriptor
import org.jetbrains.kotlin.ir.expressions.IrConst
import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.ir.expressions.IrGetValue
@@ -95,14 +94,12 @@ class JvmSharedVariablesManager(
typeArguments.forEachIndexed(::putTypeArgument)
}
return with(originalDeclaration) {
- val descriptor = WrappedVariableDescriptor()
IrVariableImpl(
- startOffset, endOffset, origin, IrVariableSymbolImpl(descriptor), name, refType,
+ startOffset, endOffset, origin, IrVariableSymbolImpl(), name, refType,
isVar = false, // writes are remapped to field stores
isConst = false, // const vals could not possibly require ref wrappers
isLateinit = false
).apply {
- descriptor.bind(this)
initializer = refConstructorCall
}
}
diff --git a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/AdditionalClassAnnotationLowering.kt b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/AdditionalClassAnnotationLowering.kt
index ae5a6c1eff5..386a61c9a71 100644
--- a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/AdditionalClassAnnotationLowering.kt
+++ b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/AdditionalClassAnnotationLowering.kt
@@ -22,7 +22,6 @@ import org.jetbrains.kotlin.ir.builders.declarations.buildValueParameter
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.declarations.impl.IrEnumEntryImpl
import org.jetbrains.kotlin.ir.declarations.impl.IrExternalPackageFragmentImpl
-import org.jetbrains.kotlin.ir.descriptors.WrappedEnumEntryDescriptor
import org.jetbrains.kotlin.ir.expressions.IrConstructorCall
import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.ir.expressions.IrGetEnumValue
@@ -84,13 +83,11 @@ private class AdditionalClassAnnotationLowering(private val context: JvmBackendC
}
private fun buildEnumEntry(enumClass: IrClass, entryName: String): IrEnumEntry {
- val descriptor = WrappedEnumEntryDescriptor()
return IrEnumEntryImpl(
UNDEFINED_OFFSET, UNDEFINED_OFFSET, IrDeclarationOrigin.IR_EXTERNAL_JAVA_DECLARATION_STUB,
- IrEnumEntrySymbolImpl(descriptor),
+ IrEnumEntrySymbolImpl(),
Name.identifier(entryName)
).apply {
- descriptor.bind(this)
parent = enumClass
enumClass.addChild(this)
}
diff --git a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/FileClassLowering.kt b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/FileClassLowering.kt
index 020956c48a5..74f5944f4b9 100644
--- a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/FileClassLowering.kt
+++ b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/FileClassLowering.kt
@@ -22,7 +22,6 @@ import org.jetbrains.kotlin.backend.common.phaser.makeIrModulePhase
import org.jetbrains.kotlin.backend.jvm.JvmBackendContext
import org.jetbrains.kotlin.codegen.AsmUtil
import org.jetbrains.kotlin.config.JvmAnalysisFlags
-import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.descriptors.Modality
@@ -31,7 +30,6 @@ import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil
import org.jetbrains.kotlin.fileClasses.JvmSimpleFileClassInfo
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.declarations.impl.IrClassImpl
-import org.jetbrains.kotlin.ir.descriptors.WrappedClassDescriptor
import org.jetbrains.kotlin.ir.symbols.impl.IrClassSymbolImpl
import org.jetbrains.kotlin.ir.util.IdSignature
import org.jetbrains.kotlin.ir.util.NaiveSourceBasedFileEntryImpl
@@ -82,17 +80,14 @@ private class FileClassLowering(val context: JvmBackendContext) : FileLoweringPa
private fun createFileClass(irFile: IrFile, fileClassMembers: List): IrClass {
val fileEntry = irFile.fileEntry
val fileClassInfo: JvmFileClassInfo?
- val descriptor: ClassDescriptor
when (fileEntry) {
is PsiSourceManager.PsiFileEntry -> {
val ktFile = context.psiSourceManager.getKtFile(fileEntry)
?: throw AssertionError("Unexpected file entry: $fileEntry")
fileClassInfo = JvmFileClassUtil.getFileClassInfoNoResolve(ktFile)
- descriptor = WrappedClassDescriptor()
}
is NaiveSourceBasedFileEntryImpl -> {
fileClassInfo = JvmSimpleFileClassInfo(PackagePartClassUtils.getPackagePartFqName(irFile.fqName, fileEntry.name), false)
- descriptor = WrappedClassDescriptor()
}
else -> error("unknown kind of file entry: $fileEntry")
}
@@ -101,13 +96,12 @@ private class FileClassLowering(val context: JvmBackendContext) : FileLoweringPa
0, fileEntry.maxOffset,
if (!isMultifilePart || context.state.languageVersionSettings.getFlag(JvmAnalysisFlags.inheritMultifileParts))
IrDeclarationOrigin.FILE_CLASS else IrDeclarationOrigin.SYNTHETIC_FILE_CLASS,
- symbol = IrClassSymbolImpl(descriptor),
+ symbol = IrClassSymbolImpl(),
name = fileClassInfo.fileClassFqName.shortName(),
kind = ClassKind.CLASS,
visibility = if (!isMultifilePart) DescriptorVisibilities.PUBLIC else JavaDescriptorVisibilities.PACKAGE_VISIBILITY,
modality = Modality.FINAL
).apply {
- descriptor.bind(this)
superTypes = listOf(context.irBuiltIns.anyType)
parent = irFile
declarations.addAll(fileClassMembers)
diff --git a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/ScriptLowering.kt b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/ScriptLowering.kt
index 81472cabd43..501929fb039 100644
--- a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/ScriptLowering.kt
+++ b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/ScriptLowering.kt
@@ -20,7 +20,6 @@ import org.jetbrains.kotlin.ir.builders.*
import org.jetbrains.kotlin.ir.builders.declarations.*
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.declarations.impl.*
-import org.jetbrains.kotlin.ir.descriptors.WrappedClassDescriptor
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.*
import org.jetbrains.kotlin.ir.symbols.*
@@ -425,7 +424,7 @@ private inline fun IrClass.addAnonymousInitializer(builder: IrFunctionBuilder.()
returnType = defaultType
IrAnonymousInitializerImpl(
startOffset, endOffset, origin,
- IrAnonymousInitializerSymbolImpl(WrappedClassDescriptor())
+ IrAnonymousInitializerSymbolImpl()
)
}.also { anonymousInitializer ->
declarations.add(anonymousInitializer)
diff --git a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/SuspendLambdaLowering.kt b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/SuspendLambdaLowering.kt
index b9c7b3ab7d7..29d9c49f08e 100644
--- a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/SuspendLambdaLowering.kt
+++ b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/lower/SuspendLambdaLowering.kt
@@ -5,7 +5,6 @@
package org.jetbrains.kotlin.backend.jvm.lower
-import com.intellij.lang.jvm.source.JvmDeclarationSearch
import org.jetbrains.kotlin.backend.common.FileLoweringPass
import org.jetbrains.kotlin.backend.common.IrElementTransformerVoidWithContext
import org.jetbrains.kotlin.backend.common.ir.*
@@ -19,6 +18,7 @@ import org.jetbrains.kotlin.backend.jvm.ir.IrInlineReferenceLocator
import org.jetbrains.kotlin.codegen.coroutines.COROUTINE_LABEL_FIELD_NAME
import org.jetbrains.kotlin.codegen.coroutines.INVOKE_SUSPEND_METHOD_NAME
import org.jetbrains.kotlin.codegen.coroutines.SUSPEND_FUNCTION_COMPLETION_PARAMETER_NAME
+import org.jetbrains.kotlin.codegen.coroutines.normalize
import org.jetbrains.kotlin.codegen.inline.coroutines.FOR_INLINE_SUFFIX
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.descriptors.Modality
@@ -27,21 +27,20 @@ import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET
import org.jetbrains.kotlin.ir.builders.*
import org.jetbrains.kotlin.ir.builders.declarations.*
import org.jetbrains.kotlin.ir.declarations.*
-import org.jetbrains.kotlin.ir.declarations.impl.IrVariableImpl
-import org.jetbrains.kotlin.ir.descriptors.WrappedVariableDescriptor
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.*
import org.jetbrains.kotlin.ir.symbols.IrSimpleFunctionSymbol
import org.jetbrains.kotlin.ir.symbols.impl.IrVariableSymbolImpl
+import org.jetbrains.kotlin.ir.symbols.IrValueParameterSymbol
import org.jetbrains.kotlin.ir.types.*
import org.jetbrains.kotlin.ir.util.*
-import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid
-import org.jetbrains.kotlin.ir.visitors.IrElementVisitorVoid
-import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
+import org.jetbrains.kotlin.ir.visitors.*
import org.jetbrains.kotlin.load.java.JavaDescriptorVisibilities
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.name.SpecialNames
+import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
+import org.jetbrains.org.objectweb.asm.Type
internal val suspendLambdaPhase = makeIrFilePhase(
::SuspendLambdaLowering,
@@ -168,19 +167,40 @@ private class SuspendLambdaLowering(context: JvmBackendContext) : SuspendLowerin
+ context.irBuiltIns.anyNType
)
superTypes = listOf(suspendLambda.defaultType, functionNType)
+ val usedParams = mutableSetOf()
+
+ // marking the parameters referenced in the function
+ function.acceptChildrenVoid(
+ object : IrElementVisitorVoid {
+ override fun visitElement(element: IrElement) = element.acceptChildrenVoid(this)
+
+ override fun visitGetValue(expression: IrGetValue) {
+ if (expression.symbol is IrValueParameterSymbol && expression.symbol.owner in function.explicitParameters) {
+ usedParams += expression.symbol.owner
+ }
+ }
+ },
+ )
addField(COROUTINE_LABEL_FIELD_NAME, context.irBuiltIns.intType, JavaDescriptorVisibilities.PACKAGE_VISIBILITY)
+ val varsCountByType = HashMap()
val parametersFields = function.explicitParameters.map {
- addField {
+ val field = if (it in usedParams) addField {
+ val normalizedType = context.typeMapper.mapType(it.type).normalize()
+ val index = varsCountByType[normalizedType]?.plus(1) ?: 0
+ varsCountByType[normalizedType] = index
// Rename `$this` to avoid being caught by inlineCodegenUtils.isCapturedFieldName()
- name = if (it.index < 0) Name.identifier("p\$") else it.name
- type = it.type
+ name = Name.identifier("${normalizedType.descriptor[0]}$$index")
+ type = if (normalizedType == AsmTypes.OBJECT_TYPE) context.irBuiltIns.anyNType else it.type
origin = LocalDeclarationsLowering.DECLARATION_ORIGIN_FIELD_FOR_CAPTURED_VALUE
isFinal = false
visibility = if (it.index < 0) DescriptorVisibilities.PRIVATE else JavaDescriptorVisibilities.PACKAGE_VISIBILITY
- }
+ } else null
+ ParameterInfo(field, it.type, it.name)
}
+
+ context.continuationClassesVarsCountByType[attributeOwnerId] = varsCountByType
val constructor = addPrimaryConstructorForLambda(suspendLambda, arity)
val invokeToOverride = functionNClass.functions.single {
it.owner.valueParameters.size == arity + 1 && it.owner.name.asString() == "invoke"
@@ -202,26 +222,34 @@ private class SuspendLambdaLowering(context: JvmBackendContext) : SuspendLowerin
context.suspendLambdaToOriginalFunctionMap[attributeOwnerId as IrFunctionReference] = function
}
- private fun IrClass.addInvokeSuspendForLambda(irFunction: IrFunction, suspendLambda: IrClass, fields: List