FIR checker: report JAVA_TYPE_MISMATCH

This commit is contained in:
Tianyu Geng
2021-05-21 12:01:25 -07:00
committed by TeamCityServer
parent eec5f99e35
commit 758859f198
26 changed files with 526 additions and 29 deletions
@@ -21658,12 +21658,30 @@ public class FirOldFrontendDiagnosticsTestGenerated extends AbstractFirDiagnosti
KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/testData/diagnostics/tests/platformTypes/genericVarianceViolation"), Pattern.compile("^(.+)\\.kt$"), Pattern.compile("^(.+)\\.fir\\.kts?$"), true);
}
@Test
@TestMetadata("deepTypeHierarchy.kt")
public void testDeepTypeHierarchy() throws Exception {
runTest("compiler/testData/diagnostics/tests/platformTypes/genericVarianceViolation/deepTypeHierarchy.kt");
}
@Test
@TestMetadata("inferenceFrom.kt")
public void testInferenceFrom() throws Exception {
runTest("compiler/testData/diagnostics/tests/platformTypes/genericVarianceViolation/inferenceFrom.kt");
}
@Test
@TestMetadata("javaOutProjection.kt")
public void testJavaOutProjection() throws Exception {
runTest("compiler/testData/diagnostics/tests/platformTypes/genericVarianceViolation/javaOutProjection.kt");
}
@Test
@TestMetadata("kotlinOutProjection.kt")
public void testKotlinOutProjection() throws Exception {
runTest("compiler/testData/diagnostics/tests/platformTypes/genericVarianceViolation/kotlinOutProjection.kt");
}
@Test
@TestMetadata("listSuperType.kt")
public void testListSuperType() throws Exception {
@@ -21658,12 +21658,30 @@ public class FirOldFrontendDiagnosticsWithLightTreeTestGenerated extends Abstrac
KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/testData/diagnostics/tests/platformTypes/genericVarianceViolation"), Pattern.compile("^(.+)\\.kt$"), Pattern.compile("^(.+)\\.fir\\.kts?$"), true);
}
@Test
@TestMetadata("deepTypeHierarchy.kt")
public void testDeepTypeHierarchy() throws Exception {
runTest("compiler/testData/diagnostics/tests/platformTypes/genericVarianceViolation/deepTypeHierarchy.kt");
}
@Test
@TestMetadata("inferenceFrom.kt")
public void testInferenceFrom() throws Exception {
runTest("compiler/testData/diagnostics/tests/platformTypes/genericVarianceViolation/inferenceFrom.kt");
}
@Test
@TestMetadata("javaOutProjection.kt")
public void testJavaOutProjection() throws Exception {
runTest("compiler/testData/diagnostics/tests/platformTypes/genericVarianceViolation/javaOutProjection.kt");
}
@Test
@TestMetadata("kotlinOutProjection.kt")
public void testKotlinOutProjection() throws Exception {
runTest("compiler/testData/diagnostics/tests/platformTypes/genericVarianceViolation/kotlinOutProjection.kt");
}
@Test
@TestMetadata("listSuperType.kt")
public void testListSuperType() throws Exception {
@@ -1231,6 +1231,13 @@ object DIAGNOSTICS_LIST : DiagnosticList("FirErrors") {
val MODIFIER_FORM_FOR_NON_BUILT_IN_SUSPEND by error<PsiElement>(PositioningStrategy.REFERENCED_NAME_BY_QUALIFIED)
val RETURN_FOR_BUILT_IN_SUSPEND by error<KtReturnExpression>()
}
val JVM by object : DiagnosticGroup("jvm") {
val JAVA_TYPE_MISMATCH by error<KtExpression> {
parameter<ConeKotlinType>("expectedType")
parameter<ConeKotlinType>("actualType")
}
}
}
private val exposedVisibilityDiagnosticInit: DiagnosticBuilder.() -> Unit = {
@@ -0,0 +1,17 @@
/*
* Copyright 2010-2021 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.analysis.jvm.checkers
import org.jetbrains.kotlin.fir.analysis.checkers.expression.ExpressionCheckers
import org.jetbrains.kotlin.fir.analysis.checkers.expression.FirFunctionCallChecker
import org.jetbrains.kotlin.fir.analysis.jvm.checkers.expression.FirJavaGenericVarianceViolationTypeChecker
object JvmExpressionCheckers : ExpressionCheckers() {
override val functionCallCheckers: Set<FirFunctionCallChecker>
get() = setOf(
FirJavaGenericVarianceViolationTypeChecker,
)
}
@@ -0,0 +1,187 @@
/*
* Copyright 2010-2021 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.analysis.jvm.checkers.expression
import org.jetbrains.kotlin.fir.analysis.checkers.context.CheckerContext
import org.jetbrains.kotlin.fir.analysis.checkers.expression.FirFunctionCallChecker
import org.jetbrains.kotlin.fir.analysis.diagnostics.DiagnosticReporter
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors
import org.jetbrains.kotlin.fir.analysis.diagnostics.reportOn
import org.jetbrains.kotlin.fir.declarations.FirDeclarationOrigin
import org.jetbrains.kotlin.fir.expressions.FirFunctionCall
import org.jetbrains.kotlin.fir.expressions.argumentMapping
import org.jetbrains.kotlin.fir.expressions.toResolvedCallableSymbol
import org.jetbrains.kotlin.fir.originalOrSelf
import org.jetbrains.kotlin.fir.resolve.inference.inferenceComponents
import org.jetbrains.kotlin.fir.resolve.substitution.substitutorByMap
import org.jetbrains.kotlin.fir.symbols.impl.FirFunctionSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirTypeParameterSymbol
import org.jetbrains.kotlin.fir.types.*
import org.jetbrains.kotlin.fir.types.impl.ConeClassLikeTypeImpl
import org.jetbrains.kotlin.types.AbstractTypeChecker
import org.jetbrains.kotlin.types.TypeApproximatorConfiguration
import org.jetbrains.kotlin.types.model.TypeConstructorMarker
import org.jetbrains.kotlin.types.model.typeConstructor
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
/**
* Checks compatibility of variance of type argument for Java collections.
*
* Java collection interfaces all include methods mutating the collection. Hence, they naturally map to mutable versions of Kotlin
* collections. But Kotlin provides immutable collections and it's good practice to enforce immutability when possible. Hence, to make it
* easier to use immutable collections in Kotlin, Java collection types are instead mapped to flexible type with mutable collection as the
* lower type and immutable collection as upper type. However, flexible types make type checking unsound. Hence we have this check that
* catches a common mistake allowed by flexible type.
*
* Consider a Java method accepting type `List<Object>`, which is mapped to `MutableList<Any?>..List<(out) Any?>`. If one passes a mutable
* list of some more concrete type than `Any` (ArrayList<String>, LinkedList<Int>, etc.) to this Java method, then any writes to this
* mutable collection could cause `ClassCastException`s if the same mutable list is read elsewhere. It's the purpose of this checker to
* reject such code.
*
* On the other hand, if one passes an immutable list of some more concrete type, then any writes to it on the Java side would cause
* `UnsupportedOperationException`, which is expected and the price we pay in order to make immutable collection easier to use. This checker
* doesn't do anything to prevent this from happening.
*/
object FirJavaGenericVarianceViolationTypeChecker : FirFunctionCallChecker() {
private val javaOrigin = setOf(FirDeclarationOrigin.Java, FirDeclarationOrigin.Enhancement)
override fun check(expression: FirFunctionCall, context: CheckerContext, reporter: DiagnosticReporter) {
val calleeFunction = expression.calleeReference.toResolvedCallableSymbol() as? FirFunctionSymbol<*> ?: return
if (calleeFunction.originalOrSelf().origin !in javaOrigin) {
return
}
val argumentMapping = expression.argumentMapping ?: return
val typeArgumentMap = mutableMapOf<FirTypeParameterSymbol, ConeKotlinType>()
for (i in 0 until expression.typeArguments.size) {
val type = expression.typeArguments[i].safeAs<FirTypeProjectionWithVariance>()?.typeRef?.coneTypeSafe<ConeKotlinType>()
if (type != null) {
typeArgumentMap[calleeFunction.typeParameterSymbols[i]] = type
}
}
val typeParameterSubstitutor = substitutorByMap(typeArgumentMap, context.session)
for ((arg, param) in argumentMapping) {
val expectedType = typeParameterSubstitutor.substituteOrSelf(param.returnTypeRef.coneType)
// optimization: if no arguments or flexibility, everything is OK
if (expectedType !is ConeFlexibleType || expectedType.typeArguments.isEmpty()) continue
// Anything is acceptable for raw types
if (expectedType is ConeRawType) continue
val argType = arg.typeRef.coneType
val lowerBound = expectedType.lowerBound
val upperBound = expectedType.upperBound
val typeCtx = context.session.inferenceComponents.ctx
val lowerConstructor = lowerBound.typeConstructor(typeCtx)
val upperConstructor = upperBound.typeConstructor(typeCtx)
// Use site variance projection is always the same for flexible types. So there is no need to check if declaration site is the
// same.
if (lowerConstructor == upperConstructor) continue
// If the base class of the argument type is not equal or a sub class of the lower bound, then we simply allow it so that
// Kotlin immutable collections can be used in place of Java collection types.
if (!typeCtx.isTypeConstructorEqualOrSubClassOf(argType, lowerBound)) continue
// In general, out type projection makes a mutable collection "readonly". A priori such a projected type is not a subtype of a
// non-projected type because projection has "removed" the ability to write to this collection. But for the purpose of this
// checker, we don't care about the readability/writability of collections.
//
// More importantly, removing such out projection is a
// shortcut to make this type comparable with the expected type by the function (after removing type capturing below). Consider
// the code below (here we use kotlin code in the example, but the same idea applies to calls to Java methods as well)
//
// ```
// fun get(): MutableList<out String> = ...
// fun <T> take(l: MutableList<T>) = ...
// fun test() {
// take(get())
// }
// ```
//
// The type of `get()` is `MutableList<out String>`. After type parameter instantiation, `take` takes a
// `MutableList<Captured<out String>>`. Obviously, a `MutableList<out String>` is not a subtype of `MutableList<Captured<out
// String>>` because we have lost the identity of the captured type at this point: we no longer know that the captured type is
// actually created because of type projection from `get`. Hence, to workaround this problem, we simply remove all the out
// projection and type capturing and compare the types after such erasure. This way, we won't incorrectly reject any valid code
// though we may accept some invalid code. But in presence of the unsound flexible types, we are allowing invalid code already.
val argTypeWithoutOutProjection = argType.removeOutProjection(true)
val lowerBoundWithoutCapturing = context.session.inferenceComponents.approximator.approximateToSuperType(
lowerBound,
TypeApproximatorConfiguration.FinalApproximationAfterResolutionAndInference
) ?: lowerBound
if (!AbstractTypeChecker.isSubtypeOf(
typeCtx,
argTypeWithoutOutProjection,
lowerBoundWithoutCapturing.withNullability(ConeNullability.NULLABLE, typeCtx)
)
) {
reporter.reportOn(arg.source, FirErrors.JAVA_TYPE_MISMATCH, argType, expectedType, context)
}
}
}
private fun ConeKotlinType.removeOutProjection(positive: Boolean): ConeKotlinType {
return when (this) {
is ConeFlexibleType -> ConeFlexibleType(lowerBound.removeOutProjection(positive), upperBound.removeOutProjection(positive))
is ConeCapturedType -> ConeCapturedType(
captureStatus,
lowerType?.removeOutProjection(positive),
nullability,
constructor.apply {
ConeCapturedTypeConstructor(
projection.removeOutProjection(positive),
supertypes?.map { it.removeOutProjection(positive) },
typeParameterMarker
)
},
attributes,
isProjectionNotNull
)
is ConeDefinitelyNotNullType -> ConeDefinitelyNotNullType(original.removeOutProjection(positive))
is ConeIntersectionType -> ConeIntersectionType(
intersectedTypes.map { it.removeOutProjection(positive) },
alternativeType?.removeOutProjection(positive)
)
is ConeClassLikeTypeImpl -> ConeClassLikeTypeImpl(
lookupTag,
typeArguments.map { it.removeOutProjection(positive) }.toTypedArray(),
isNullable,
attributes
)
else -> this
}
}
private fun ConeTypeProjection.removeOutProjection(positive: Boolean): ConeTypeProjection {
return when (this) {
is ConeKotlinTypeProjectionOut -> if (positive) type else this
is ConeKotlinType -> this.removeOutProjection(true)
is ConeKotlinTypeConflictingProjection -> ConeKotlinTypeConflictingProjection(type.removeOutProjection(true))
is ConeKotlinTypeProjectionIn -> ConeKotlinTypeProjectionIn(type.removeOutProjection(!positive))
is ConeStarProjection -> this
}
}
private fun ConeInferenceContext.isTypeConstructorEqualOrSubClassOf(subType: ConeKotlinType, superType: ConeKotlinType): Boolean {
return isTypeConstructorEqualOrSubClassOf(subType.typeConstructor(), superType.typeConstructor())
}
private fun ConeInferenceContext.isTypeConstructorEqualOrSubClassOf(
subTypeConstructor: TypeConstructorMarker,
superTypeConstructor: TypeConstructorMarker
): Boolean {
if (subTypeConstructor == superTypeConstructor) return true
for (immediateSuperType in subTypeConstructor.supertypes()) {
val immediateSuperTypeConstructor = immediateSuperType.typeConstructor()
if (superTypeConstructor == immediateSuperTypeConstructor) return true
if (this@isTypeConstructorEqualOrSubClassOf.isTypeConstructorEqualOrSubClassOf(immediateSuperTypeConstructor, superTypeConstructor)) return true
}
return false
}
}
@@ -636,4 +636,7 @@ object FirErrors {
val MODIFIER_FORM_FOR_NON_BUILT_IN_SUSPEND by error0<PsiElement>(SourceElementPositioningStrategies.REFERENCED_NAME_BY_QUALIFIED)
val RETURN_FOR_BUILT_IN_SUSPEND by error0<KtReturnExpression>()
// jvm
val JAVA_TYPE_MISMATCH by error2<KtExpression, ConeKotlinType, ConeKotlinType>()
}
@@ -239,6 +239,7 @@ import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.INVALID_TYPE_OF_A
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.INVISIBLE_REFERENCE
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.IS_ENUM_ENTRY
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.ITERATOR_AMBIGUITY
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.JAVA_TYPE_MISMATCH
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.KCLASS_WITH_NULLABLE_TYPE_PARAMETER_IN_SIGNATURE
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.LEAKED_IN_PLACE_LAMBDA
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors.LOCAL_ANNOTATION_CLASS_ERROR
@@ -1579,6 +1580,9 @@ class FirDefaultErrorMessages {
)
map.put(RETURN_FOR_BUILT_IN_SUSPEND, "Using implicit label for this lambda is prohibited")
// JVM
map.put(JAVA_TYPE_MISMATCH, "Java type mismatch expected {0} but found {1}. Use explicit cast", RENDER_TYPE, RENDER_TYPE)
// Extended checkers group
map.put(REDUNDANT_VISIBILITY_MODIFIER, "Redundant visibility modifier")
map.put(REDUNDANT_MODALITY_MODIFIER, "Redundant modality modifier")
@@ -7,6 +7,7 @@ package org.jetbrains.kotlin.fir.checkers
import org.jetbrains.kotlin.fir.analysis.checkers.*
import org.jetbrains.kotlin.fir.analysis.jvm.checkers.JvmDeclarationCheckers
import org.jetbrains.kotlin.fir.analysis.jvm.checkers.JvmExpressionCheckers
import org.jetbrains.kotlin.fir.session.FirSessionFactory
fun FirSessionFactory.FirSessionConfigurator.registerCommonCheckers() {
@@ -22,4 +23,5 @@ fun FirSessionFactory.FirSessionConfigurator.registerExtendedCommonCheckers() {
fun FirSessionFactory.FirSessionConfigurator.registerJvmCheckers() {
useCheckers(JvmDeclarationCheckers)
useCheckers(JvmExpressionCheckers)
}
@@ -0,0 +1,25 @@
// FIR_IDENTICAL
// !DIAGNOSTICS: -UNUSED_VARIABLE
// FILE: A.java
import java.util.*;
public class A {
void foo(List<Object> x) {}
<T> void foo2(List<T> x) {}
}
// FILE: main.kt
fun main(a: A) {
a.foo(<!JAVA_TYPE_MISMATCH!>bar()<!>)
a.foo2(bar())
}
interface MyList1<T>: MutableList<T>
interface MyList2<A, B>: MyList1<B>
interface MyList3<A2, B> : MyList2<Any, B>
fun bar(): MyList3<Int, out String> {
TODO()
}
@@ -0,0 +1,94 @@
package
public fun bar(): MyList3<kotlin.Int, out kotlin.String>
public fun main(/*0*/ a: A): kotlin.Unit
public open class A {
public constructor A()
public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
public/*package*/ open fun foo(/*0*/ x: kotlin.collections.(Mutable)List<kotlin.Any!>!): kotlin.Unit
public/*package*/ open fun </*0*/ T : kotlin.Any!> foo2(/*0*/ x: kotlin.collections.(Mutable)List<T!>!): kotlin.Unit
public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
}
public interface MyList1</*0*/ T> : kotlin.collections.MutableList<T> {
public abstract override /*1*/ /*fake_override*/ val size: kotlin.Int
public abstract override /*1*/ /*fake_override*/ fun add(/*0*/ element: T): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun add(/*0*/ index: kotlin.Int, /*1*/ element: T): kotlin.Unit
public abstract override /*1*/ /*fake_override*/ fun addAll(/*0*/ index: kotlin.Int, /*1*/ elements: kotlin.collections.Collection<T>): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun addAll(/*0*/ elements: kotlin.collections.Collection<T>): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun clear(): kotlin.Unit
public abstract override /*1*/ /*fake_override*/ fun contains(/*0*/ element: T): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun containsAll(/*0*/ elements: kotlin.collections.Collection<T>): kotlin.Boolean
public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun get(/*0*/ index: kotlin.Int): T
public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
public abstract override /*1*/ /*fake_override*/ fun indexOf(/*0*/ element: T): kotlin.Int
public abstract override /*1*/ /*fake_override*/ fun isEmpty(): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun iterator(): kotlin.collections.MutableIterator<T>
public abstract override /*1*/ /*fake_override*/ fun lastIndexOf(/*0*/ element: T): kotlin.Int
public abstract override /*1*/ /*fake_override*/ fun listIterator(): kotlin.collections.MutableListIterator<T>
public abstract override /*1*/ /*fake_override*/ fun listIterator(/*0*/ index: kotlin.Int): kotlin.collections.MutableListIterator<T>
public abstract override /*1*/ /*fake_override*/ fun remove(/*0*/ element: T): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun removeAll(/*0*/ elements: kotlin.collections.Collection<T>): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun removeAt(/*0*/ index: kotlin.Int): T
public abstract override /*1*/ /*fake_override*/ fun retainAll(/*0*/ elements: kotlin.collections.Collection<T>): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun set(/*0*/ index: kotlin.Int, /*1*/ element: T): T
public abstract override /*1*/ /*fake_override*/ fun subList(/*0*/ fromIndex: kotlin.Int, /*1*/ toIndex: kotlin.Int): kotlin.collections.MutableList<T>
public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
}
public interface MyList2</*0*/ A, /*1*/ B> : MyList1<B> {
public abstract override /*1*/ /*fake_override*/ val size: kotlin.Int
public abstract override /*1*/ /*fake_override*/ fun add(/*0*/ element: B): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun add(/*0*/ index: kotlin.Int, /*1*/ element: B): kotlin.Unit
public abstract override /*1*/ /*fake_override*/ fun addAll(/*0*/ index: kotlin.Int, /*1*/ elements: kotlin.collections.Collection<B>): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun addAll(/*0*/ elements: kotlin.collections.Collection<B>): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun clear(): kotlin.Unit
public abstract override /*1*/ /*fake_override*/ fun contains(/*0*/ element: B): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun containsAll(/*0*/ elements: kotlin.collections.Collection<B>): kotlin.Boolean
public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun get(/*0*/ index: kotlin.Int): B
public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
public abstract override /*1*/ /*fake_override*/ fun indexOf(/*0*/ element: B): kotlin.Int
public abstract override /*1*/ /*fake_override*/ fun isEmpty(): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun iterator(): kotlin.collections.MutableIterator<B>
public abstract override /*1*/ /*fake_override*/ fun lastIndexOf(/*0*/ element: B): kotlin.Int
public abstract override /*1*/ /*fake_override*/ fun listIterator(): kotlin.collections.MutableListIterator<B>
public abstract override /*1*/ /*fake_override*/ fun listIterator(/*0*/ index: kotlin.Int): kotlin.collections.MutableListIterator<B>
public abstract override /*1*/ /*fake_override*/ fun remove(/*0*/ element: B): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun removeAll(/*0*/ elements: kotlin.collections.Collection<B>): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun removeAt(/*0*/ index: kotlin.Int): B
public abstract override /*1*/ /*fake_override*/ fun retainAll(/*0*/ elements: kotlin.collections.Collection<B>): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun set(/*0*/ index: kotlin.Int, /*1*/ element: B): B
public abstract override /*1*/ /*fake_override*/ fun subList(/*0*/ fromIndex: kotlin.Int, /*1*/ toIndex: kotlin.Int): kotlin.collections.MutableList<B>
public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
}
public interface MyList3</*0*/ A2, /*1*/ B> : MyList2<kotlin.Any, B> {
public abstract override /*1*/ /*fake_override*/ val size: kotlin.Int
public abstract override /*1*/ /*fake_override*/ fun add(/*0*/ element: B): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun add(/*0*/ index: kotlin.Int, /*1*/ element: B): kotlin.Unit
public abstract override /*1*/ /*fake_override*/ fun addAll(/*0*/ index: kotlin.Int, /*1*/ elements: kotlin.collections.Collection<B>): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun addAll(/*0*/ elements: kotlin.collections.Collection<B>): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun clear(): kotlin.Unit
public abstract override /*1*/ /*fake_override*/ fun contains(/*0*/ element: B): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun containsAll(/*0*/ elements: kotlin.collections.Collection<B>): kotlin.Boolean
public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun get(/*0*/ index: kotlin.Int): B
public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
public abstract override /*1*/ /*fake_override*/ fun indexOf(/*0*/ element: B): kotlin.Int
public abstract override /*1*/ /*fake_override*/ fun isEmpty(): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun iterator(): kotlin.collections.MutableIterator<B>
public abstract override /*1*/ /*fake_override*/ fun lastIndexOf(/*0*/ element: B): kotlin.Int
public abstract override /*1*/ /*fake_override*/ fun listIterator(): kotlin.collections.MutableListIterator<B>
public abstract override /*1*/ /*fake_override*/ fun listIterator(/*0*/ index: kotlin.Int): kotlin.collections.MutableListIterator<B>
public abstract override /*1*/ /*fake_override*/ fun remove(/*0*/ element: B): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun removeAll(/*0*/ elements: kotlin.collections.Collection<B>): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun removeAt(/*0*/ index: kotlin.Int): B
public abstract override /*1*/ /*fake_override*/ fun retainAll(/*0*/ elements: kotlin.collections.Collection<B>): kotlin.Boolean
public abstract override /*1*/ /*fake_override*/ fun set(/*0*/ index: kotlin.Int, /*1*/ element: B): B
public abstract override /*1*/ /*fake_override*/ fun subList(/*0*/ fromIndex: kotlin.Int, /*1*/ toIndex: kotlin.Int): kotlin.collections.MutableList<B>
public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
}
@@ -1,14 +1,18 @@
// FIR_IDENTICAL
// !DIAGNOSTICS: -UNUSED_VARIABLE
// FILE: A.java
import java.util.*;
public class A {
void foo(List<Object> x) {}
List<String> bar() {}
<T> void foo2(List<T> x) {}
List<? extends Number> bar() {}
}
// FILE: main.kt
fun main(a: A) {
a.foo(a.bar())
a.foo(<!JAVA_TYPE_MISMATCH!>a.bar()<!>)
a.foo2(a.bar())
}
@@ -0,0 +1,13 @@
package
public fun main(/*0*/ a: A): kotlin.Unit
public open class A {
public constructor A()
public/*package*/ open fun bar(): (kotlin.collections.MutableList<out kotlin.Number!>..kotlin.collections.List<kotlin.Number!>?)
public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
public/*package*/ open fun foo(/*0*/ x: kotlin.collections.(Mutable)List<kotlin.Any!>!): kotlin.Unit
public/*package*/ open fun </*0*/ T : kotlin.Any!> foo2(/*0*/ x: kotlin.collections.(Mutable)List<T!>!): kotlin.Unit
public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
}
@@ -0,0 +1,21 @@
// FIR_IDENTICAL
// !DIAGNOSTICS: -UNUSED_VARIABLE
// FILE: A.java
import java.util.*;
public class A {
void foo(List<Object> x) {}
<T> void foo2(List<T> x) {}
}
// FILE: main.kt
fun main(a: A) {
a.foo(<!JAVA_TYPE_MISMATCH!>bar()<!>)
a.foo2(bar())
}
fun bar() : MutableList<out Number> {
TODO()
}
@@ -0,0 +1,13 @@
package
public fun bar(): kotlin.collections.MutableList<out kotlin.Number>
public fun main(/*0*/ a: A): kotlin.Unit
public open class A {
public constructor A()
public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
public/*package*/ open fun foo(/*0*/ x: kotlin.collections.(Mutable)List<kotlin.Any!>!): kotlin.Unit
public/*package*/ open fun </*0*/ T : kotlin.Any!> foo2(/*0*/ x: kotlin.collections.(Mutable)List<T!>!): kotlin.Unit
public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
}
@@ -1,16 +0,0 @@
// !DIAGNOSTICS: -UNUSED_VARIABLE
// FILE: A.java
import java.util.*;
public class A {
void foo(List<Object> x) {}
}
// FILE: main.kt
abstract class B : MutableList<String>
fun main(a: A, b: B) {
a.foo(b)
a.foo(b as List<Any>)
}
@@ -1,3 +1,4 @@
// FIR_IDENTICAL
// !DIAGNOSTICS: -UNUSED_VARIABLE
// FILE: A.java
@@ -25,7 +25,7 @@ fun main(
mll: MutableList<MutableList<String>>, ll: List<List<String>>
) {
// Lists
a.foo(ml)
a.foo(<!JAVA_TYPE_MISMATCH!>ml<!>)
a.foo(l)
a.foo(ml as MutableList<Any>)
a.foo(l as List<Any>)
@@ -41,25 +41,25 @@ fun main(
a.foo(l.iterator())
// Sets
a.foo(ms)
a.foo(<!JAVA_TYPE_MISMATCH!>ms<!>)
a.foo(s)
a.foo(ms as MutableSet<Any>)
a.foo(s as Set<Any>)
// Maps
a.foo(mm)
a.foo(<!JAVA_TYPE_MISMATCH!>mm<!>)
a.foo(m)
a.foo(mm as MutableMap<Any, Any>)
a.foo(m as Map<Any, Any>)
// Map entries
a.foo(mme)
a.foo(<!JAVA_TYPE_MISMATCH!>mme<!>)
a.foo(me)
a.foo(mme as MutableMap.MutableEntry<Any, Any>)
a.foo(me as Map.Entry<Any, Any>)
// Lists of lists
a.foo1(mll)
a.foo1(<!JAVA_TYPE_MISMATCH!>mll<!>)
a.foo1(ll)
a.foo1(mll as MutableList<MutableList<Any>>)
a.foo1(ll as List<List<Any>>)
@@ -10,7 +10,7 @@ public class A {
fun main(a: A, ml: Any) {
if (ml is MutableList<String>) {
a.foo(ml)
a.foo(<!JAVA_TYPE_MISMATCH!>ml<!>)
a.foo(ml as List<Any>)
}
}
@@ -1,3 +1,4 @@
// FIR_IDENTICAL
// !DIAGNOSTICS: -UNUSED_VARIABLE
// FILE: A.java
@@ -16,4 +16,4 @@ fun test(ls: List<String>, mls: MutableList<String>, lsn: List<String?>, mlsn: M
J().list(mls)
J().list(lsn)
J().list(mlsn)
}
}
@@ -21664,12 +21664,30 @@ public class DiagnosticTestGenerated extends AbstractDiagnosticTest {
KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/testData/diagnostics/tests/platformTypes/genericVarianceViolation"), Pattern.compile("^(.*)\\.kts?$"), Pattern.compile("^(.+)\\.fir\\.kts?$"), true);
}
@Test
@TestMetadata("deepTypeHierarchy.kt")
public void testDeepTypeHierarchy() throws Exception {
runTest("compiler/testData/diagnostics/tests/platformTypes/genericVarianceViolation/deepTypeHierarchy.kt");
}
@Test
@TestMetadata("inferenceFrom.kt")
public void testInferenceFrom() throws Exception {
runTest("compiler/testData/diagnostics/tests/platformTypes/genericVarianceViolation/inferenceFrom.kt");
}
@Test
@TestMetadata("javaOutProjection.kt")
public void testJavaOutProjection() throws Exception {
runTest("compiler/testData/diagnostics/tests/platformTypes/genericVarianceViolation/javaOutProjection.kt");
}
@Test
@TestMetadata("kotlinOutProjection.kt")
public void testKotlinOutProjection() throws Exception {
runTest("compiler/testData/diagnostics/tests/platformTypes/genericVarianceViolation/kotlinOutProjection.kt");
}
@Test
@TestMetadata("listSuperType.kt")
public void testListSuperType() throws Exception {
@@ -10,13 +10,14 @@ import org.jetbrains.kotlin.fir.analysis.CheckersComponentInternal
import org.jetbrains.kotlin.fir.analysis.checkers.*
import org.jetbrains.kotlin.fir.analysis.checkers.declaration.ComposedDeclarationCheckers
import org.jetbrains.kotlin.fir.analysis.checkers.declaration.DeclarationCheckers
import org.jetbrains.kotlin.fir.analysis.checkers.expression.ComposedExpressionCheckers
import org.jetbrains.kotlin.fir.analysis.checkers.expression.ExpressionCheckers
import org.jetbrains.kotlin.fir.analysis.checkers.type.TypeCheckers
import org.jetbrains.kotlin.fir.analysis.collectors.AbstractDiagnosticCollector
import org.jetbrains.kotlin.fir.analysis.collectors.components.*
import org.jetbrains.kotlin.fir.analysis.diagnostics.DiagnosticReporter
import org.jetbrains.kotlin.fir.analysis.jvm.checkers.JvmDeclarationCheckers
import org.jetbrains.kotlin.fir.checkers.*
import org.jetbrains.kotlin.fir.analysis.jvm.checkers.JvmExpressionCheckers
import org.jetbrains.kotlin.fir.moduleData
import org.jetbrains.kotlin.idea.fir.low.level.api.sessions.moduleSourceInfo
import org.jetbrains.kotlin.platform.SimplePlatform
@@ -42,7 +43,7 @@ private object CheckersFactory {
val moduleInfo = session.moduleData.moduleSourceInfo
val platform = moduleInfo.platform.componentPlatforms.first()
val declarationCheckers = createDeclarationCheckers(useExtendedCheckers, platform)
val expressionCheckers = createExpressionCheckers(useExtendedCheckers)
val expressionCheckers = createExpressionCheckers(useExtendedCheckers, platform)
val typeCheckers = createTypeCheckers(useExtendedCheckers)
@OptIn(ExperimentalStdlibApi::class)
@@ -71,8 +72,18 @@ private object CheckersFactory {
}
}
private fun createExpressionCheckers(useExtendedCheckers: Boolean): ExpressionCheckers =
if (useExtendedCheckers) ExtendedExpressionCheckers else CommonExpressionCheckers
private fun createExpressionCheckers(useExtendedCheckers: Boolean, platform: SimplePlatform): ExpressionCheckers {
return if (useExtendedCheckers) {
ExtendedExpressionCheckers
} else {
createExpressionCheckers {
add(CommonExpressionCheckers)
when (platform) {
is JvmPlatform -> add(JvmExpressionCheckers)
}
}
}
}
private fun createTypeCheckers(useExtendedCheckers: Boolean): TypeCheckers? =
if (useExtendedCheckers) null else CommonTypeCheckers
@@ -94,4 +105,19 @@ private object CheckersFactory {
}
}
}
@OptIn(ExperimentalStdlibApi::class)
private inline fun createExpressionCheckers(
createExpressionCheckers: MutableList<ExpressionCheckers>.() -> Unit
): ExpressionCheckers = createExpressionCheckers(buildList(createExpressionCheckers))
@OptIn(CheckersComponentInternal::class)
private fun createExpressionCheckers(expressionCheckers: List<ExpressionCheckers>): ExpressionCheckers {
return when (expressionCheckers.size) {
1 -> expressionCheckers.single()
else -> ComposedExpressionCheckers().apply {
expressionCheckers.forEach(::register)
}
}
}
}
@@ -21658,12 +21658,30 @@ public class DiagnosisCompilerTestFE10TestdataTestGenerated extends AbstractDiag
KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("compiler/testData/diagnostics/tests/platformTypes/genericVarianceViolation"), Pattern.compile("^(.+)\\.kt$"), Pattern.compile("^(.+)\\.fir\\.kts?$"), true);
}
@Test
@TestMetadata("deepTypeHierarchy.kt")
public void testDeepTypeHierarchy() throws Exception {
runTest("compiler/testData/diagnostics/tests/platformTypes/genericVarianceViolation/deepTypeHierarchy.kt");
}
@Test
@TestMetadata("inferenceFrom.kt")
public void testInferenceFrom() throws Exception {
runTest("compiler/testData/diagnostics/tests/platformTypes/genericVarianceViolation/inferenceFrom.kt");
}
@Test
@TestMetadata("javaOutProjection.kt")
public void testJavaOutProjection() throws Exception {
runTest("compiler/testData/diagnostics/tests/platformTypes/genericVarianceViolation/javaOutProjection.kt");
}
@Test
@TestMetadata("kotlinOutProjection.kt")
public void testKotlinOutProjection() throws Exception {
runTest("compiler/testData/diagnostics/tests/platformTypes/genericVarianceViolation/kotlinOutProjection.kt");
}
@Test
@TestMetadata("listSuperType.kt")
public void testListSuperType() throws Exception {
@@ -3314,6 +3314,14 @@ internal val KT_DIAGNOSTIC_CONVERTER = KtDiagnosticConverterBuilder.buildConvert
token,
)
}
add(FirErrors.JAVA_TYPE_MISMATCH) { firDiagnostic ->
JavaTypeMismatchImpl(
firSymbolBuilder.typeBuilder.buildKtType(firDiagnostic.a),
firSymbolBuilder.typeBuilder.buildKtType(firDiagnostic.b),
firDiagnostic as FirPsiDiagnostic,
token,
)
}
add(FirJvmErrors.CONFLICTING_JVM_DECLARATIONS) { firDiagnostic ->
ConflictingJvmDeclarationsImpl(
firDiagnostic as FirPsiDiagnostic,
@@ -2311,6 +2311,12 @@ sealed class KtFirDiagnostic<PSI : PsiElement> : KtDiagnosticWithPsi<PSI> {
override val diagnosticClass get() = ReturnForBuiltInSuspend::class
}
abstract class JavaTypeMismatch : KtFirDiagnostic<KtExpression>() {
override val diagnosticClass get() = JavaTypeMismatch::class
abstract val expectedType: KtType
abstract val actualType: KtType
}
abstract class ConflictingJvmDeclarations : KtFirDiagnostic<PsiElement>() {
override val diagnosticClass get() = ConflictingJvmDeclarations::class
}
@@ -3737,6 +3737,15 @@ internal class ReturnForBuiltInSuspendImpl(
override val firDiagnostic: FirPsiDiagnostic by weakRef(firDiagnostic)
}
internal class JavaTypeMismatchImpl(
override val expectedType: KtType,
override val actualType: KtType,
firDiagnostic: FirPsiDiagnostic,
override val token: ValidityToken,
) : KtFirDiagnostic.JavaTypeMismatch(), KtAbstractFirDiagnostic<KtExpression> {
override val firDiagnostic: FirPsiDiagnostic by weakRef(firDiagnostic)
}
internal class ConflictingJvmDeclarationsImpl(
firDiagnostic: FirPsiDiagnostic,
override val token: ValidityToken,