FIR: add check of SOURCE retention for EXPRESSION-targeted annotation

This commit is contained in:
Mikhail Glukhikh
2021-05-13 11:22:04 +03:00
parent 4b00a43b22
commit 92ab600081
12 changed files with 210 additions and 77 deletions
@@ -172,6 +172,7 @@ object DIAGNOSTICS_LIST : DiagnosticList() {
val DEPRECATED_SINCE_KOTLIN_OUTSIDE_KOTLIN_SUBPACKAGE by error<PsiElement>(PositioningStrategy.REFERENCED_NAME_BY_QUALIFIED)
val ANNOTATION_ON_SUPERCLASS by error<KtAnnotationEntry>()
val RESTRICTED_RETENTION_FOR_EXPRESSION_ANNOTATION by error<PsiElement>()
}
val EXPOSED_VISIBILITY by object : DiagnosticGroup("Exposed visibility") {
@@ -178,6 +178,7 @@ object FirErrors {
val DEPRECATED_SINCE_KOTLIN_WITH_DEPRECATED_LEVEL by error0<PsiElement>(SourceElementPositioningStrategies.REFERENCED_NAME_BY_QUALIFIED)
val DEPRECATED_SINCE_KOTLIN_OUTSIDE_KOTLIN_SUBPACKAGE by error0<PsiElement>(SourceElementPositioningStrategies.REFERENCED_NAME_BY_QUALIFIED)
val ANNOTATION_ON_SUPERCLASS by error0<KtAnnotationEntry>()
val RESTRICTED_RETENTION_FOR_EXPRESSION_ANNOTATION by error0<PsiElement>()
// Exposed visibility
val EXPOSED_TYPEALIAS_EXPANDED_TYPE by error3<KtNamedDeclaration, EffectiveVisibility, FirMemberDeclaration, EffectiveVisibility>(SourceElementPositioningStrategies.DECLARATION_NAME)
@@ -0,0 +1,89 @@
/*
* 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.checkers
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.declarations.FirAnnotatedDeclaration
import org.jetbrains.kotlin.fir.declarations.FirRegularClass
import org.jetbrains.kotlin.fir.expressions.FirAnnotationCall
import org.jetbrains.kotlin.fir.expressions.FirQualifiedAccessExpression
import org.jetbrains.kotlin.fir.expressions.FirVarargArgumentsExpression
import org.jetbrains.kotlin.fir.expressions.argumentMapping
import org.jetbrains.kotlin.fir.references.FirResolvedNamedReference
import org.jetbrains.kotlin.fir.resolve.toSymbol
import org.jetbrains.kotlin.fir.types.ConeClassLikeType
import org.jetbrains.kotlin.fir.types.coneType
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
private val RETENTION_PARAMETER_NAME = Name.identifier("value")
private val TARGET_PARAMETER_NAME = Name.identifier("allowedTargets")
fun FirAnnotationCall.getRetention(session: FirSession): AnnotationRetention {
val annotationClass = (this.annotationTypeRef.coneType as? ConeClassLikeType)?.lookupTag?.toSymbol(session)?.fir as? FirRegularClass
return annotationClass?.getRetention() ?: AnnotationRetention.RUNTIME
}
fun FirRegularClass.getRetention(): AnnotationRetention {
val retentionAnnotation = getRetentionAnnotation() ?: return AnnotationRetention.RUNTIME
val argumentMapping = retentionAnnotation.argumentMapping ?: return AnnotationRetention.RUNTIME
val retentionArgument = argumentMapping.keys.firstOrNull() as? FirQualifiedAccessExpression
?: return AnnotationRetention.RUNTIME
if (argumentMapping[retentionArgument]?.name != RETENTION_PARAMETER_NAME) {
return AnnotationRetention.RUNTIME
}
val retentionName = (retentionArgument.calleeReference as? FirResolvedNamedReference)?.name?.asString()
?: return AnnotationRetention.RUNTIME
return AnnotationRetention.values().firstOrNull { it.name == retentionName } ?: AnnotationRetention.RUNTIME
}
private val defaultAnnotationTargets = listOf(
AnnotationTarget.CLASS,
AnnotationTarget.PROPERTY,
AnnotationTarget.FIELD,
AnnotationTarget.LOCAL_VARIABLE,
AnnotationTarget.VALUE_PARAMETER,
AnnotationTarget.CONSTRUCTOR,
AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.PROPERTY_SETTER,
)
fun FirAnnotationCall.getAllowedAnnotationTargets(session: FirSession): List<AnnotationTarget> {
val annotationClass = (this.annotationTypeRef.coneType as? ConeClassLikeType)?.lookupTag?.toSymbol(session)?.fir as? FirRegularClass
return annotationClass?.getAllowedAnnotationTargets() ?: defaultAnnotationTargets
}
fun FirRegularClass.getAllowedAnnotationTargets(): List<AnnotationTarget> {
val targetAnnotation = getTargetAnnotation() ?: return defaultAnnotationTargets
val argumentMapping = targetAnnotation.argumentMapping ?: return defaultAnnotationTargets
val targetArgument = argumentMapping.keys.firstOrNull() as? FirVarargArgumentsExpression
?: return defaultAnnotationTargets
if (argumentMapping[targetArgument]?.name != TARGET_PARAMETER_NAME) {
return defaultAnnotationTargets
}
return targetArgument.arguments.mapNotNull { argument ->
val targetExpression = argument as? FirQualifiedAccessExpression
val targetName = (targetExpression?.calleeReference as? FirResolvedNamedReference)?.name?.asString() ?: return@mapNotNull null
AnnotationTarget.values().firstOrNull { target -> target.name == targetName }
}
}
fun FirAnnotatedDeclaration.getRetentionAnnotation(): FirAnnotationCall? {
return getAnnotationByFqName(StandardNames.FqNames.retention)
}
fun FirAnnotatedDeclaration.getTargetAnnotation(): FirAnnotationCall? {
return getAnnotationByFqName(StandardNames.FqNames.target)
}
fun FirAnnotatedDeclaration.getAnnotationByFqName(fqName: FqName): FirAnnotationCall? {
return annotations.find {
(it.annotationTypeRef.coneType as? ConeClassLikeType)?.lookupTag?.classId?.asSingleFqName() == fqName
}
}
@@ -10,6 +10,7 @@ import org.jetbrains.kotlin.KtNodeTypes.VALUE_PARAMETER
import org.jetbrains.kotlin.descriptors.ClassKind.ANNOTATION_CLASS
import org.jetbrains.kotlin.descriptors.ClassKind.ENUM_CLASS
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.analysis.checkers.*
import org.jetbrains.kotlin.fir.analysis.checkers.checkConstantArguments
import org.jetbrains.kotlin.fir.analysis.checkers.context.CheckerContext
import org.jetbrains.kotlin.fir.analysis.diagnostics.*
@@ -29,73 +30,84 @@ object FirAnnotationClassDeclarationChecker : FirRegularClassChecker() {
reporter.reportOn(declaration.source, FirErrors.SUPERTYPES_FOR_ANNOTATION_CLASS, context)
}
for (it in declaration.declarations) {
when {
it is FirConstructor && it.isPrimary -> {
for (parameter in it.valueParameters) {
val source = parameter.source ?: continue
if (!source.hasValOrVar()) {
reporter.reportOn(source, FirErrors.MISSING_VAL_ON_ANNOTATION_PARAMETER, context)
} else if (source.hasVar()) {
reporter.reportOn(source, FirErrors.VAR_ANNOTATION_PARAMETER, context)
}
val defaultValue = parameter.defaultValue
if (defaultValue != null && checkConstantArguments(defaultValue, context.session) != null) {
reporter.reportOn(defaultValue.source, FirErrors.ANNOTATION_PARAMETER_DEFAULT_VALUE_MUST_BE_CONSTANT, context)
}
for (member in declaration.declarations) {
checkAnnotationClassMember(member, context, reporter)
}
val typeRef = parameter.returnTypeRef
val coneType = typeRef.coneTypeSafe<ConeLookupTagBasedType>()
val classId = coneType?.classId
if (declaration.getRetention() != AnnotationRetention.SOURCE &&
AnnotationTarget.EXPRESSION in declaration.getAllowedAnnotationTargets()
) {
val target = declaration.getRetentionAnnotation() ?: declaration.getTargetAnnotation() ?: declaration
reporter.reportOn(target.source, FirErrors.RESTRICTED_RETENTION_FOR_EXPRESSION_ANNOTATION, context)
}
}
if (coneType != null) when {
classId == ClassId.fromString("<error>") -> {
// TODO: replace with UNRESOLVED_REFERENCE check
}
coneType.isNullable -> {
reporter.reportOn(typeRef.source, FirErrors.NULLABLE_TYPE_OF_ANNOTATION_MEMBER, context)
}
coneType.isPrimitiveOrNullablePrimitive -> {
// DO NOTHING: primitives are allowed as annotation class parameter
}
coneType.isUnsignedTypeOrNullableUnsignedType -> {
// TODO: replace with EXPERIMENTAL_UNSIGNED_LITERALS check
}
classId == StandardClassIds.KClass -> {
// DO NOTHING: KClass is allowed
}
classId == StandardClassIds.String -> {
// DO NOTHING: String is allowed
}
classId in primitiveArrayTypeByElementType.values -> {
// DO NOTHING: primitive arrays are allowed
}
classId == StandardClassIds.Array -> {
if (!isAllowedArray(typeRef, context.session))
reporter.reportOn(typeRef.source, FirErrors.INVALID_TYPE_OF_ANNOTATION_MEMBER, context)
}
isAllowedClassKind(coneType, context.session) -> {
// DO NOTHING: annotation or enum classes are allowed
}
else -> {
private fun checkAnnotationClassMember(member: FirDeclaration, context: CheckerContext, reporter: DiagnosticReporter) {
when {
member is FirConstructor && member.isPrimary -> {
for (parameter in member.valueParameters) {
val source = parameter.source ?: continue
if (!source.hasValOrVar()) {
reporter.reportOn(source, FirErrors.MISSING_VAL_ON_ANNOTATION_PARAMETER, context)
} else if (source.hasVar()) {
reporter.reportOn(source, FirErrors.VAR_ANNOTATION_PARAMETER, context)
}
val defaultValue = parameter.defaultValue
if (defaultValue != null && checkConstantArguments(defaultValue, context.session) != null) {
reporter.reportOn(defaultValue.source, FirErrors.ANNOTATION_PARAMETER_DEFAULT_VALUE_MUST_BE_CONSTANT, context)
}
val typeRef = parameter.returnTypeRef
val coneType = typeRef.coneTypeSafe<ConeLookupTagBasedType>()
val classId = coneType?.classId
if (coneType != null) when {
classId == ClassId.fromString("<error>") -> {
// TODO: replace with UNRESOLVED_REFERENCE check
}
coneType.isNullable -> {
reporter.reportOn(typeRef.source, FirErrors.NULLABLE_TYPE_OF_ANNOTATION_MEMBER, context)
}
coneType.isPrimitiveOrNullablePrimitive -> {
// DO NOTHING: primitives are allowed as annotation class parameter
}
coneType.isUnsignedTypeOrNullableUnsignedType -> {
// TODO: replace with EXPERIMENTAL_UNSIGNED_LITERALS check
}
classId == StandardClassIds.KClass -> {
// DO NOTHING: KClass is allowed
}
classId == StandardClassIds.String -> {
// DO NOTHING: String is allowed
}
classId in primitiveArrayTypeByElementType.values -> {
// DO NOTHING: primitive arrays are allowed
}
classId == StandardClassIds.Array -> {
if (!isAllowedArray(typeRef, context.session))
reporter.reportOn(typeRef.source, FirErrors.INVALID_TYPE_OF_ANNOTATION_MEMBER, context)
}
}
isAllowedClassKind(coneType, context.session) -> {
// DO NOTHING: annotation or enum classes are allowed
}
else -> {
reporter.reportOn(typeRef.source, FirErrors.INVALID_TYPE_OF_ANNOTATION_MEMBER, context)
}
}
}
it is FirRegularClass -> {
// DO NOTHING: nested annotation classes are allowed in 1.3+
}
it is FirProperty && it.source?.elementType == VALUE_PARAMETER -> {
// DO NOTHING to avoid reporting constructor properties
}
it is FirSimpleFunction && it.source?.elementType != FUN -> {
// DO NOTHING to avoid reporting synthetic functions
// TODO: replace with origin check
}
else -> {
reporter.reportOn(it.source, FirErrors.ANNOTATION_CLASS_MEMBER, context)
}
}
member is FirRegularClass -> {
// DO NOTHING: nested annotation classes are allowed in 1.3+
}
member is FirProperty && member.source?.elementType == VALUE_PARAMETER -> {
// DO NOTHING to avoid reporting constructor properties
}
member is FirSimpleFunction && member.source?.elementType != FUN -> {
// DO NOTHING to avoid reporting synthetic functions
// TODO: replace with origin check
}
else -> {
reporter.reportOn(member.source, FirErrors.ANNOTATION_CLASS_MEMBER, context)
}
}
}
@@ -0,0 +1,24 @@
/*
* 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.checkers.expression
import org.jetbrains.kotlin.fir.analysis.checkers.context.CheckerContext
import org.jetbrains.kotlin.fir.analysis.checkers.getAllowedAnnotationTargets
import org.jetbrains.kotlin.fir.analysis.checkers.getRetention
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.analysis.diagnostics.withSuppressedDiagnostics
import org.jetbrains.kotlin.fir.expressions.FirStatement
object FirExpressionAnnotationChecker : FirBasicExpressionChecker() {
override fun check(expression: FirStatement, context: CheckerContext, reporter: DiagnosticReporter) {
for (annotation in expression.annotations) {
withSuppressedDiagnostics(annotation, context) {
}
}
}
}
@@ -16,7 +16,8 @@ object CommonExpressionCheckers : ExpressionCheckers() {
override val basicExpressionCheckers: Set<FirBasicExpressionChecker>
get() = setOf(
FirReservedUnderscoreExpressionChecker
FirReservedUnderscoreExpressionChecker,
FirExpressionAnnotationChecker,
)
override val qualifiedAccessCheckers: Set<FirQualifiedAccessChecker>
@@ -1,13 +0,0 @@
// !LANGUAGE: +RestrictRetentionForExpressionAnnotations
@Target(AnnotationTarget.EXPRESSION)
@Retention(AnnotationRetention.SOURCE)
annotation class TestRetentionSource
@Target(AnnotationTarget.EXPRESSION)
@Retention(AnnotationRetention.BINARY)
annotation class TestRetentionBinary
@Target(AnnotationTarget.EXPRESSION)
@Retention(AnnotationRetention.RUNTIME)
annotation class TestRetentionRuntime
@@ -1,3 +1,4 @@
// FIR_IDENTICAL
// !LANGUAGE: +RestrictRetentionForExpressionAnnotations
@Target(AnnotationTarget.EXPRESSION)
@@ -5,9 +5,9 @@
annotation class TestRetentionSource
@Target(AnnotationTarget.EXPRESSION)
@Retention(AnnotationRetention.BINARY)
<!RESTRICTED_RETENTION_FOR_EXPRESSION_ANNOTATION!>@Retention(AnnotationRetention.BINARY)<!>
annotation class TestRetentionBinary
@Target(AnnotationTarget.EXPRESSION)
@Retention(AnnotationRetention.RUNTIME)
<!RESTRICTED_RETENTION_FOR_EXPRESSION_ANNOTATION!>@Retention(AnnotationRetention.RUNTIME)<!>
annotation class TestRetentionRuntime
@@ -607,6 +607,12 @@ internal val KT_DIAGNOSTIC_CONVERTER = KtDiagnosticConverterBuilder.buildConvert
token,
)
}
add(FirErrors.RESTRICTED_RETENTION_FOR_EXPRESSION_ANNOTATION) { firDiagnostic ->
RestrictedRetentionForExpressionAnnotationImpl(
firDiagnostic as FirPsiDiagnostic<*>,
token,
)
}
add(FirErrors.EXPOSED_TYPEALIAS_EXPANDED_TYPE) { firDiagnostic ->
ExposedTypealiasExpandedTypeImpl(
firDiagnostic.a,
@@ -434,6 +434,10 @@ sealed class KtFirDiagnostic<PSI: PsiElement> : KtDiagnosticWithPsi<PSI> {
override val diagnosticClass get() = AnnotationOnSuperclass::class
}
abstract class RestrictedRetentionForExpressionAnnotation : KtFirDiagnostic<PsiElement>() {
override val diagnosticClass get() = RestrictedRetentionForExpressionAnnotation::class
}
abstract class ExposedTypealiasExpandedType : KtFirDiagnostic<KtNamedDeclaration>() {
override val diagnosticClass get() = ExposedTypealiasExpandedType::class
abstract val elementVisibility: EffectiveVisibility
@@ -705,6 +705,13 @@ internal class AnnotationOnSuperclassImpl(
override val firDiagnostic: FirPsiDiagnostic<*> by weakRef(firDiagnostic)
}
internal class RestrictedRetentionForExpressionAnnotationImpl(
firDiagnostic: FirPsiDiagnostic<*>,
override val token: ValidityToken,
) : KtFirDiagnostic.RestrictedRetentionForExpressionAnnotation(), KtAbstractFirDiagnostic<PsiElement> {
override val firDiagnostic: FirPsiDiagnostic<*> by weakRef(firDiagnostic)
}
internal class ExposedTypealiasExpandedTypeImpl(
override val elementVisibility: EffectiveVisibility,
override val restrictingDeclaration: KtSymbol,