Replace some FIR syntax errors with more proper diagnostics

This commit is contained in:
Mikhail Glukhikh
2020-03-24 19:33:34 +03:00
parent 2f63c8a46a
commit b27152f903
53 changed files with 339 additions and 320 deletions
@@ -7,7 +7,7 @@ class B: A() {
<!UNRESOLVED_REFERENCE!>invoke<!>()
<!SUPER_IS_NOT_AN_EXPRESSION!>super<!> {
println('weird')
println(<!ILLEGAL_CONST_EXPRESSION!>'weird'<!>)
}
}
}
@@ -5,5 +5,5 @@ class Foo {
fun test() {
var f = Foo()
<!ASSIGN_OPERATOR_AMBIGUITY, ASSIGN_OPERATOR_AMBIGUITY, ASSIGN_OPERATOR_AMBIGUITY!>f += f<!>
<!ASSIGN_OPERATOR_AMBIGUITY!>f += f<!>
}
@@ -5,6 +5,7 @@
package org.jetbrains.kotlin.fir.analysis.checkers.declaration
import org.jetbrains.kotlin.fir.declarations.FirConstructor
import org.jetbrains.kotlin.fir.declarations.FirDeclaration
import org.jetbrains.kotlin.fir.declarations.FirMemberDeclaration
@@ -15,4 +16,7 @@ object DeclarationCheckers {
val MEMBER_DECLARATIONS: List<FirDeclarationChecker<FirMemberDeclaration>> = DECLARATIONS + listOf(
FirInfixFunctionDeclarationChecker
)
val CONSTRUCTORS: List<FirDeclarationChecker<FirConstructor>> = MEMBER_DECLARATIONS + listOf(
FirConstructorChecker
)
}
@@ -0,0 +1,52 @@
/*
* 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.analysis.checkers.declaration
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.descriptors.Visibilities
import org.jetbrains.kotlin.fir.FirSourceElement
import org.jetbrains.kotlin.fir.analysis.checkers.context.CheckerContext
import org.jetbrains.kotlin.fir.analysis.diagnostics.DiagnosticReporter
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirDiagnosticFactory0
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors
import org.jetbrains.kotlin.fir.declarations.*
object FirConstructorChecker : FirDeclarationChecker<FirConstructor>() {
override fun check(declaration: FirConstructor, context: CheckerContext, reporter: DiagnosticReporter) {
val containingClass = context.containingDeclarations.lastOrNull() as? FirClass<*> ?: return
val source = declaration.source
val elementType = source?.elementType
if (elementType != KtNodeTypes.PRIMARY_CONSTRUCTOR && elementType != KtNodeTypes.SECONDARY_CONSTRUCTOR) {
return
}
when (containingClass.classKind) {
ClassKind.OBJECT -> reporter.report(source, FirErrors.CONSTRUCTOR_IN_OBJECT)
ClassKind.INTERFACE -> reporter.report(source, FirErrors.CONSTRUCTOR_IN_INTERFACE)
ClassKind.ENUM_ENTRY -> reporter.report(source, FirErrors.CONSTRUCTOR_IN_OBJECT)
ClassKind.ENUM_CLASS -> if (declaration.visibility != Visibilities.PRIVATE) {
reporter.report(source, FirErrors.NON_PRIVATE_CONSTRUCTOR_IN_ENUM)
}
ClassKind.CLASS -> if (containingClass is FirRegularClass && containingClass.modality == Modality.SEALED &&
declaration.visibility != Visibilities.PRIVATE
) {
reporter.report(source, FirErrors.NON_PRIVATE_CONSTRUCTOR_IN_SEALED)
}
ClassKind.ANNOTATION_CLASS -> {
// DO NOTHING
}
}
}
private inline fun <reified T : FirSourceElement, P : PsiElement> DiagnosticReporter.report(
source: T?,
factory: FirDiagnosticFactory0<T, P>
) {
source?.let { report(factory.on(it)) }
}
}
@@ -12,6 +12,10 @@ import org.jetbrains.kotlin.fir.analysis.collectors.components.*
import org.jetbrains.kotlin.fir.analysis.diagnostics.DiagnosticReporter
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirDiagnostic
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.expressions.FirBreakExpression
import org.jetbrains.kotlin.fir.expressions.FirContinueExpression
import org.jetbrains.kotlin.fir.expressions.FirErrorLoop
import org.jetbrains.kotlin.fir.expressions.FirLoopJump
import org.jetbrains.kotlin.fir.resolve.ScopeSession
import org.jetbrains.kotlin.fir.resolve.SessionHolder
import org.jetbrains.kotlin.fir.resolve.collectImplicitReceivers
@@ -66,11 +70,38 @@ abstract class AbstractDiagnosticCollector(
element.acceptChildren(this)
}
override fun visitRegularClass(regularClass: FirRegularClass) {
private fun visitJump(loopJump: FirLoopJump) {
loopJump.runComponents()
loopJump.acceptChildren(this)
loopJump.target.labeledElement.takeIf { it is FirErrorLoop }?.accept(this)
}
override fun visitBreakExpression(breakExpression: FirBreakExpression) {
visitJump(breakExpression)
}
override fun visitContinueExpression(continueExpression: FirContinueExpression) {
visitJump(continueExpression)
}
private fun visitClassAndChildren(klass: FirClass<*>, type: ConeKotlinType) {
val typeRef = buildResolvedTypeRef {
type = regularClass.defaultType()
this.type = type
}
visitWithDeclarationAndReceiver(regularClass, regularClass.name, typeRef)
visitWithDeclarationAndReceiver(klass, (klass as? FirRegularClass)?.name, typeRef)
}
override fun visitRegularClass(regularClass: FirRegularClass) {
visitClassAndChildren(regularClass, regularClass.defaultType())
}
override fun visitSealedClass(sealedClass: FirSealedClass) {
visitClassAndChildren(sealedClass, sealedClass.defaultType())
}
override fun visitAnonymousObject(anonymousObject: FirAnonymousObject) {
visitClassAndChildren(anonymousObject, anonymousObject.defaultType())
}
override fun visitSimpleFunction(simpleFunction: FirSimpleFunction) {
@@ -34,7 +34,7 @@ class DeclarationCheckersDiagnosticComponent(collector: AbstractDiagnosticCollec
}
override fun visitConstructor(constructor: FirConstructor, data: CheckerContext) {
runCheck { DeclarationCheckers.MEMBER_DECLARATIONS.check(constructor, data, it) }
runCheck { DeclarationCheckers.CONSTRUCTORS.check(constructor, data, it) }
}
override fun visitAnonymousFunction(anonymousFunction: FirAnonymousFunction, data: CheckerContext) {
@@ -12,10 +12,8 @@ import org.jetbrains.kotlin.fir.analysis.diagnostics.DiagnosticReporter
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirDiagnosticFactory0
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors
import org.jetbrains.kotlin.fir.declarations.FirErrorFunction
import org.jetbrains.kotlin.fir.diagnostics.ConeDiagnostic
import org.jetbrains.kotlin.fir.diagnostics.ConeSimpleDiagnostic
import org.jetbrains.kotlin.fir.diagnostics.ConeStubDiagnostic
import org.jetbrains.kotlin.fir.diagnostics.DiagnosticKind
import org.jetbrains.kotlin.fir.diagnostics.*
import org.jetbrains.kotlin.fir.diagnostics.DiagnosticKind.*
import org.jetbrains.kotlin.fir.expressions.FirErrorExpression
import org.jetbrains.kotlin.fir.expressions.FirErrorLoop
import org.jetbrains.kotlin.fir.references.FirErrorNamedReference
@@ -68,21 +66,24 @@ class ErrorNodeDiagnosticCollectorComponent(collector: AbstractDiagnosticCollect
private fun ConeSimpleDiagnostic.getFactory(): FirDiagnosticFactory0<FirSourceElement, *> {
@Suppress("UNCHECKED_CAST")
return when (kind) {
DiagnosticKind.Syntax -> FirErrors.SYNTAX_ERROR
DiagnosticKind.ReturnNotAllowed -> FirErrors.RETURN_NOT_ALLOWED
DiagnosticKind.UnresolvedLabel -> FirErrors.UNRESOLVED_LABEL
DiagnosticKind.IllegalConstExpression -> FirErrors.ILLEGAL_CONST_EXPRESSION
DiagnosticKind.ConstructorInObject -> FirErrors.CONSTRUCTOR_IN_OBJECT
DiagnosticKind.DeserializationError -> FirErrors.DESERIALIZATION_ERROR
DiagnosticKind.InferenceError -> FirErrors.INFERENCE_ERROR
DiagnosticKind.NoSupertype -> FirErrors.NO_SUPERTYPE
DiagnosticKind.TypeParameterAsSupertype -> FirErrors.TYPE_PARAMETER_AS_SUPERTYPE
DiagnosticKind.EnumAsSupertype -> FirErrors.ENUM_AS_SUPERTYPE
DiagnosticKind.RecursionInSupertypes -> FirErrors.RECURSION_IN_SUPERTYPES
DiagnosticKind.RecursionInImplicitTypes -> FirErrors.RECURSION_IN_IMPLICIT_TYPES
DiagnosticKind.SuperNotAllowed -> FirErrors.SUPER_IS_NOT_AN_EXPRESSION
DiagnosticKind.Java -> FirErrors.ERROR_FROM_JAVA_RESOLUTION
DiagnosticKind.Other -> FirErrors.OTHER_ERROR
Syntax -> FirErrors.SYNTAX_ERROR
ReturnNotAllowed -> FirErrors.RETURN_NOT_ALLOWED
UnresolvedLabel -> FirErrors.UNRESOLVED_LABEL
IllegalConstExpression -> FirErrors.ILLEGAL_CONST_EXPRESSION
DeserializationError -> FirErrors.DESERIALIZATION_ERROR
InferenceError -> FirErrors.INFERENCE_ERROR
NoSupertype -> FirErrors.NO_SUPERTYPE
TypeParameterAsSupertype -> FirErrors.TYPE_PARAMETER_AS_SUPERTYPE
EnumAsSupertype -> FirErrors.ENUM_AS_SUPERTYPE
RecursionInSupertypes -> FirErrors.RECURSION_IN_SUPERTYPES
RecursionInImplicitTypes -> FirErrors.RECURSION_IN_IMPLICIT_TYPES
SuperNotAllowed -> FirErrors.SUPER_IS_NOT_AN_EXPRESSION
Java -> FirErrors.ERROR_FROM_JAVA_RESOLUTION
ExpressionRequired -> FirErrors.EXPRESSION_REQUIRED
JumpOutsideLoop -> FirErrors.BREAK_OR_CONTINUE_OUTSIDE_A_LOOP
NotLoopLabel -> FirErrors.NOT_A_LOOP_LABEL
VariableExpected -> FirErrors.VARIABLE_EXPECTED
Other -> FirErrors.OTHER_ERROR
else -> throw IllegalArgumentException("Unsupported diagnostic kind: $kind at $javaClass")
}
}
@@ -29,6 +29,9 @@ object FirErrors {
val RECURSION_IN_SUPERTYPES by error0<FirSourceElement, PsiElement>()
val RECURSION_IN_IMPLICIT_TYPES by error0<FirSourceElement, PsiElement>()
val ERROR_FROM_JAVA_RESOLUTION by error0<FirSourceElement, PsiElement>()
val EXPRESSION_REQUIRED by error0<FirSourceElement, PsiElement>()
val BREAK_OR_CONTINUE_OUTSIDE_A_LOOP by error0<FirSourceElement, PsiElement>()
val NOT_A_LOOP_LABEL by error0<FirSourceElement, PsiElement>()
val OTHER_ERROR by error0<FirSourceElement, PsiElement>()
val TYPE_MISMATCH by error2<FirSourceElement, PsiElement, ConeKotlinType, ConeKotlinType>()
val VARIABLE_EXPECTED by error0<FirSourceElement, PsiElement>()
@@ -37,9 +40,12 @@ object FirErrors {
val INAPPLICABLE_INFIX_MODIFIER by existing<FirSourceElement, PsiElement, String>(Errors.INAPPLICABLE_INFIX_MODIFIER)
val CONSTRUCTOR_IN_OBJECT by existing<FirSourceElement, KtDeclaration>(Errors.CONSTRUCTOR_IN_OBJECT)
val CONSTRUCTOR_IN_INTERFACE by existing<FirSourceElement, KtDeclaration>(Errors.CONSTRUCTOR_IN_INTERFACE)
val NON_PRIVATE_CONSTRUCTOR_IN_ENUM by existing<FirSourceElement, PsiElement>(Errors.NON_PRIVATE_CONSTRUCTOR_IN_ENUM)
val NON_PRIVATE_CONSTRUCTOR_IN_SEALED by existing<FirSourceElement, PsiElement>(Errors.NON_PRIVATE_CONSTRUCTOR_IN_SEALED)
val REPEATED_MODIFIER by error1<FirSourceElement, KtModifierKeywordToken>()
val REDUNDANT_MODIFIER by error2<FirSourceElement, KtModifierKeywordToken, KtModifierKeywordToken>()
val DEPRECATED_MODIFIER_PAIR by error2<FirSourceElement, KtModifierKeywordToken, KtModifierKeywordToken>()
val INCOMPATIBLE_MODIFIERS by error2<FirSourceElement, KtModifierKeywordToken, KtModifierKeywordToken>()
val REPEATED_MODIFIER by error1<FirSourceElement, PsiElement, KtModifierKeywordToken>()
val REDUNDANT_MODIFIER by error2<FirSourceElement, PsiElement, KtModifierKeywordToken, KtModifierKeywordToken>()
val DEPRECATED_MODIFIER_PAIR by error2<FirSourceElement, PsiElement, KtModifierKeywordToken, KtModifierKeywordToken>()
val INCOMPATIBLE_MODIFIERS by error2<FirSourceElement, PsiElement, KtModifierKeywordToken, KtModifierKeywordToken>()
}
@@ -5,7 +5,6 @@
package org.jetbrains.kotlin.fir.builder
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.IElementType
import org.jetbrains.kotlin.KtNodeTypes.*
import org.jetbrains.kotlin.descriptors.Modality
@@ -36,7 +35,6 @@ import org.jetbrains.kotlin.lexer.KtTokens.OPEN_QUOTE
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
import org.jetbrains.kotlin.psi.KtUnaryExpression
import org.jetbrains.kotlin.resolve.constants.evaluate.*
import org.jetbrains.kotlin.util.OperatorNameConventions
@@ -57,6 +55,7 @@ abstract class BaseFirBuilder<T>(val baseSession: FirSession, val context: Conte
abstract fun T.getReferencedNameAsName(): Name
abstract fun T.getLabelName(): String?
abstract fun T.getExpressionInParentheses(): T?
abstract fun T.getAnnotatedExpression(): T?
abstract fun T.getChildNodeByType(type: IElementType): T?
abstract val T?.selectorExpression: T?
@@ -173,12 +172,13 @@ abstract class BaseFirBuilder<T>(val baseSession: FirSession, val context: Conte
fun FirLoopJumpBuilder.bindLabel(expression: T): FirLoopJumpBuilder {
val labelName = expression.getLabelName()
val lastLoopTarget = context.firLoopTargets.lastOrNull()
val sourceElement = expression.toFirSourceElement()
if (labelName == null) {
target = lastLoopTarget ?: FirLoopTarget(labelName).apply {
bind(
buildErrorLoop(
expression.getSourceOrNull(),
ConeSimpleDiagnostic("Cannot bind unlabeled jump to a loop", DiagnosticKind.Syntax)
sourceElement,
ConeSimpleDiagnostic("Cannot bind unlabeled jump to a loop", DiagnosticKind.JumpOutsideLoop)
)
)
}
@@ -192,7 +192,11 @@ abstract class BaseFirBuilder<T>(val baseSession: FirSession, val context: Conte
target = FirLoopTarget(labelName).apply {
bind(
buildErrorLoop(
expression.getSourceOrNull(), ConeSimpleDiagnostic("Cannot bind label $labelName to a loop", DiagnosticKind.Syntax)
sourceElement,
ConeSimpleDiagnostic(
"Cannot bind label $labelName to a loop",
lastLoopTarget?.let { DiagnosticKind.NotLoopLabel } ?: DiagnosticKind.JumpOutsideLoop
)
)
)
}
@@ -200,14 +204,10 @@ abstract class BaseFirBuilder<T>(val baseSession: FirSession, val context: Conte
return this
}
/**** Conversion utils ****/
private fun <T> T.getSourceOrNull(): FirSourceElement? {
return if (this is PsiElement) FirPsiSourceElement(this) else null
}
fun generateConstantExpressionByLiteral(expression: T): FirExpression {
val type = expression.elementType
val text: String = expression.asText
val sourceElement = expression.toFirSourceElement()
val convertedText: Any? = when (type) {
INTEGER_CONSTANT, FLOAT_CONSTANT -> parseNumericLiteral(text, type)
BOOLEAN_CONSTANT -> parseBoolean(text)
@@ -217,7 +217,7 @@ abstract class BaseFirBuilder<T>(val baseSession: FirSession, val context: Conte
INTEGER_CONSTANT -> {
val kind = when {
convertedText !is Long -> return buildErrorExpression {
source = expression.getSourceOrNull()
source = sourceElement
diagnostic = ConeSimpleDiagnostic(
"Incorrect constant expression: $text",
DiagnosticKind.IllegalConstExpression
@@ -240,44 +240,44 @@ abstract class BaseFirBuilder<T>(val baseSession: FirSession, val context: Conte
}
buildConstOrErrorExpression(
expression.getSourceOrNull(),
sourceElement,
kind,
convertedText,
ConeSimpleDiagnostic("Incorrect integer literal: $text", DiagnosticKind.Syntax)
ConeSimpleDiagnostic("Incorrect integer literal: $text", DiagnosticKind.IllegalConstExpression)
)
}
FLOAT_CONSTANT ->
if (convertedText is Float) {
buildConstOrErrorExpression(
expression.getSourceOrNull(),
sourceElement,
FirConstKind.Float,
convertedText,
ConeSimpleDiagnostic("Incorrect float: $text", DiagnosticKind.Syntax)
ConeSimpleDiagnostic("Incorrect float: $text", DiagnosticKind.IllegalConstExpression)
)
} else {
buildConstOrErrorExpression(
expression.getSourceOrNull(),
sourceElement,
FirConstKind.Double,
convertedText as Double,
ConeSimpleDiagnostic("Incorrect double: $text", DiagnosticKind.Syntax)
ConeSimpleDiagnostic("Incorrect double: $text", DiagnosticKind.IllegalConstExpression)
)
}
CHARACTER_CONSTANT ->
buildConstOrErrorExpression(
expression.getSourceOrNull(),
sourceElement,
FirConstKind.Char,
text.parseCharacter(),
ConeSimpleDiagnostic("Incorrect character: $text", DiagnosticKind.Syntax)
ConeSimpleDiagnostic("Incorrect character: $text", DiagnosticKind.IllegalConstExpression)
)
BOOLEAN_CONSTANT ->
buildConstExpression(
expression.getSourceOrNull(),
sourceElement,
FirConstKind.Boolean,
convertedText as Boolean
)
NULL ->
buildConstExpression(
expression.getSourceOrNull(),
sourceElement,
FirConstKind.Null,
null
)
@@ -287,7 +287,7 @@ abstract class BaseFirBuilder<T>(val baseSession: FirSession, val context: Conte
}
fun Array<out T?>.toInterpolatingCall(
base: KtStringTemplateExpression?,
base: T,
convertTemplateEntry: T?.(String) -> FirExpression
): FirExpression {
return buildStringConcatenationCall {
@@ -300,11 +300,11 @@ abstract class BaseFirBuilder<T>(val baseSession: FirSession, val context: Conte
OPEN_QUOTE, CLOSING_QUOTE -> continue@L
LITERAL_STRING_TEMPLATE_ENTRY -> {
sb.append(entry.asText)
buildConstExpression(entry.getSourceOrNull(), FirConstKind.String, entry.asText)
buildConstExpression(entry.toFirSourceElement(), FirConstKind.String, entry.asText)
}
ESCAPE_STRING_TEMPLATE_ENTRY -> {
sb.append(entry.unescapedValue)
buildConstExpression(entry.getSourceOrNull(), FirConstKind.String, entry.unescapedValue)
buildConstExpression(entry.toFirSourceElement(), FirConstKind.String, entry.unescapedValue)
}
SHORT_STRING_TEMPLATE_ENTRY, LONG_STRING_TEMPLATE_ENTRY -> {
hasExpressions = true
@@ -322,7 +322,7 @@ abstract class BaseFirBuilder<T>(val baseSession: FirSession, val context: Conte
else -> {
hasExpressions = true
buildErrorExpression {
source = entry.getSourceOrNull()
source = entry.toFirSourceElement()
diagnostic = ConeSimpleDiagnostic("Incorrect template entry: ${entry.asText}", DiagnosticKind.Syntax)
}
}
@@ -361,7 +361,8 @@ abstract class BaseFirBuilder<T>(val baseSession: FirSession, val context: Conte
// TODO: Refactor, support receiver capturing in case of a.b
fun generateIncrementOrDecrementBlock(
baseExpression: KtUnaryExpression?,
baseExpression: T,
operationReference: T?,
argument: T?,
callName: Name,
prefix: Boolean,
@@ -383,7 +384,7 @@ abstract class BaseFirBuilder<T>(val baseSession: FirSession, val context: Conte
val resultInitializer = buildFunctionCall {
source = baseSource
calleeReference = buildSimpleNamedReference {
source = baseExpression?.operationReference?.toFirSourceElement()
source = operationReference?.toFirSourceElement()
name = callName
}
explicitReceiver = generateResolvedAccessExpression(source, temporaryVariable)
@@ -432,13 +433,13 @@ abstract class BaseFirBuilder<T>(val baseSession: FirSession, val context: Conte
when (tokenType) {
REFERENCE_EXPRESSION -> {
return buildSimpleNamedReference {
source = left.getSourceOrNull()
source = left.toFirSourceElement()
name = left.getReferencedNameAsName()
}
}
THIS_EXPRESSION -> {
return buildExplicitThisReference {
source = left.getSourceOrNull()
source = left.toFirSourceElement()
labelName = left.getLabelName()
}
}
@@ -450,7 +451,7 @@ abstract class BaseFirBuilder<T>(val baseSession: FirSession, val context: Conte
firMemberAccess.calleeReference
} else {
buildErrorNamedReference {
source = left.getSourceOrNull()
source = left.toFirSourceElement()
diagnostic = ConeSimpleDiagnostic("Unsupported qualified LValue: ${left.asText}", DiagnosticKind.Syntax)
}
}
@@ -458,11 +459,14 @@ abstract class BaseFirBuilder<T>(val baseSession: FirSession, val context: Conte
PARENTHESIZED -> {
return initializeLValue(left.getExpressionInParentheses(), convertQualified)
}
ANNOTATED_EXPRESSION -> {
return initializeLValue(left.getAnnotatedExpression(), convertQualified)
}
}
}
return buildErrorNamedReference {
source = left.getSourceOrNull()
diagnostic = ConeSimpleDiagnostic("Unsupported LValue: $tokenType", DiagnosticKind.Syntax)
source = left?.toFirSourceElement()
diagnostic = ConeSimpleDiagnostic("Unsupported LValue: $tokenType", DiagnosticKind.VariableExpected)
}
}
@@ -497,7 +501,9 @@ abstract class BaseFirBuilder<T>(val baseSession: FirSession, val context: Conte
argumentList = buildBinaryArgumentList(
this@generateAssignment?.convert() ?: buildErrorExpression {
source = null
diagnostic = ConeSimpleDiagnostic("Unsupported left value of assignment: ${baseSource?.psi?.text}", DiagnosticKind.Syntax)
diagnostic = ConeSimpleDiagnostic(
"Unsupported left value of assignment: ${baseSource?.psi?.text}", DiagnosticKind.ExpressionRequired
)
},
value
)
@@ -678,7 +684,7 @@ abstract class BaseFirBuilder<T>(val baseSession: FirSession, val context: Conte
fun List<Pair<T, FirProperty>>.generateCopyFunction(
session: FirSession,
classOrObject: KtClassOrObject?,
classOrObject: T,
classBuilder: AbstractFirRegularClassBuilder,
packageFqName: FqName,
classFqName: FqName,
@@ -71,6 +71,14 @@ open class BaseConverter(
return null
}
override fun LighterASTNode.getAnnotatedExpression(): LighterASTNode? {
this.forEachChildren {
if (it.isExpression()) return it
}
return null
}
override fun LighterASTNode.getChildNodeByType(type: IElementType): LighterASTNode? {
return this.getChildNodesByType(type).firstOrNull()
}
@@ -462,7 +462,7 @@ class DeclarationsConverter(
baseSession, this, context.packageFqName, context.className, firPrimaryConstructor
)
zippedParameters.generateCopyFunction(
baseSession, null, this, context.packageFqName, context.className, firPrimaryConstructor
baseSession, classNode, this, context.packageFqName, context.className, firPrimaryConstructor
)
// TODO: equals, hashCode, toString
}
@@ -718,15 +718,7 @@ class DeclarationsConverter(
}
}
val delegatedSelfTypeRef =
if (classWrapper.isObjectLiteral()) buildErrorTypeRef {
source = secondaryConstructor.toFirSourceElement()
diagnostic = ConeSimpleDiagnostic(
"Constructor in object",
DiagnosticKind.ConstructorInObject
)
}
else classWrapper.delegatedSelfTypeRef
val delegatedSelfTypeRef = classWrapper.delegatedSelfTypeRef
val explicitVisibility = modifiers.getVisibility()
val status = FirDeclarationStatusImpl(explicitVisibility, Modality.FINAL).apply {
@@ -777,15 +769,7 @@ class DeclarationsConverter(
val isImplicit = constructorDelegationCall.asText.isEmpty()
val isThis = (isImplicit && classWrapper.hasPrimaryConstructor) || thisKeywordPresent
val delegatedType =
if (classWrapper.isObjectLiteral() || classWrapper.isInterface()) when {
isThis -> buildErrorTypeRef {
diagnostic = ConeSimpleDiagnostic("Constructor in object", DiagnosticKind.ConstructorInObject)
}
else -> buildErrorTypeRef {
diagnostic = ConeSimpleDiagnostic("No super type", DiagnosticKind.Syntax)
}
}
else when {
when {
isThis -> classWrapper.delegatedSelfTypeRef
else -> classWrapper.delegatedSuperTypeRef
}
@@ -55,7 +55,11 @@ class ExpressionsConverter(
) : BaseConverter(session, tree, offset, context) {
inline fun <reified R : FirElement> getAsFirExpression(expression: LighterASTNode?, errorReason: String = ""): R {
return expression?.let { convertExpression(it, errorReason) } as? R ?: (buildErrorExpression(null, ConeSimpleDiagnostic(errorReason, DiagnosticKind.Syntax)) as R)
return expression?.let {
convertExpression(it, errorReason)
} as? R ?: buildErrorExpression(
null, ConeSimpleDiagnostic(errorReason, DiagnosticKind.ExpressionRequired)
) as R
}
/***** EXPRESSIONS *****/
@@ -103,7 +107,7 @@ class ExpressionsConverter(
OBJECT_LITERAL -> declarationsConverter.convertObjectLiteral(expression)
FUN -> declarationsConverter.convertFunctionDeclaration(expression)
else -> buildErrorExpression(null, ConeSimpleDiagnostic(errorReason, DiagnosticKind.Syntax))
else -> buildErrorExpression(null, ConeSimpleDiagnostic(errorReason, DiagnosticKind.ExpressionRequired))
}
}
@@ -310,9 +314,13 @@ class ExpressionsConverter(
private fun convertUnaryExpression(unaryExpression: LighterASTNode): FirExpression {
lateinit var operationTokenName: String
var argument: LighterASTNode? = null
var operationReference: LighterASTNode? = null
unaryExpression.forEachChildren {
when (it.tokenType) {
OPERATION_REFERENCE -> operationTokenName = it.asText
OPERATION_REFERENCE -> {
operationReference = it
operationTokenName = it.asText
}
else -> if (it.isExpression()) argument = it
}
}
@@ -330,7 +338,8 @@ class ExpressionsConverter(
conventionCallName != null -> {
if (operationToken in OperatorConventions.INCREMENT_OPERATIONS) {
return generateIncrementOrDecrementBlock(
null,
unaryExpression,
operationReference,
argument,
callName = conventionCallName,
prefix = unaryExpression.tokenType == PREFIX_EXPRESSION
@@ -548,7 +557,7 @@ class ExpressionsConverter(
* @see org.jetbrains.kotlin.parsing.KotlinExpressionParsing.parseStringTemplate
*/
private fun convertStringTemplate(stringTemplate: LighterASTNode): FirExpression {
return stringTemplate.getChildrenAsArray().toInterpolatingCall(null) { convertShortOrLongStringTemplate(it) }
return stringTemplate.getChildrenAsArray().toInterpolatingCall(stringTemplate) { convertShortOrLongStringTemplate(it) }
}
private fun LighterASTNode?.convertShortOrLongStringTemplate(errorReason: String): FirExpression {
@@ -1053,8 +1062,9 @@ class ExpressionsConverter(
}
val jumpBuilder = if (isBreak) FirBreakExpressionBuilder() else FirContinueExpressionBuilder()
val sourceElement = jump.toFirSourceElement()
return jumpBuilder.apply {
source = jump.toFirSourceElement()
source = sourceElement
}.bindLabel(jump).build()
}
@@ -82,6 +82,10 @@ class RawFirBuilder(
return (this as KtParenthesizedExpression).expression
}
override fun PsiElement.getAnnotatedExpression(): PsiElement? {
return (this as KtAnnotatedExpression).baseExpression
}
override val PsiElement?.selectorExpression: PsiElement?
get() = (this as? KtQualifiedExpression)?.selectorExpression
@@ -135,14 +139,14 @@ class RawFirBuilder(
if (stubMode) buildExpressionStub()
else with(this()) {
convertSafe() ?: buildErrorExpression(
this?.toFirSourceElement(), ConeSimpleDiagnostic(errorReason, DiagnosticKind.Syntax),
this?.toFirSourceElement(), ConeSimpleDiagnostic(errorReason, DiagnosticKind.ExpressionRequired),
)
}
private fun KtExpression?.toFirExpression(errorReason: String): FirExpression =
if (stubMode) buildExpressionStub()
else convertSafe() ?: buildErrorExpression(
this?.toFirSourceElement(), ConeSimpleDiagnostic(errorReason, DiagnosticKind.Syntax),
this?.toFirSourceElement(), ConeSimpleDiagnostic(errorReason, DiagnosticKind.ExpressionRequired),
)
private fun KtExpression.toFirStatement(errorReason: String): FirStatement =
@@ -152,16 +156,13 @@ class RawFirBuilder(
convert()
private fun KtDeclaration.toFirDeclaration(
delegatedSuperType: FirTypeRef?, delegatedSelfType: FirResolvedTypeRef?, owner: KtClassOrObject, hasPrimaryConstructor: Boolean,
delegatedSuperType: FirTypeRef, delegatedSelfType: FirResolvedTypeRef, owner: KtClassOrObject, hasPrimaryConstructor: Boolean,
): FirDeclaration {
return when (this) {
is KtSecondaryConstructor -> {
toFirConstructor(
delegatedSuperType,
delegatedSelfType ?: buildErrorTypeRef {
source = this@toFirDeclaration.toFirSourceElement()
diagnostic = ConeSimpleDiagnostic("Constructor in object", DiagnosticKind.ConstructorInObject)
},
delegatedSelfType,
owner,
hasPrimaryConstructor,
)
@@ -172,7 +173,7 @@ class RawFirBuilder(
primaryConstructor?.valueParameters?.isEmpty() ?: owner.secondaryConstructors.let { constructors ->
constructors.isEmpty() || constructors.any { it.valueParameters.isEmpty() }
}
toFirEnumEntry(delegatedSelfType!!, ownerClassHasDefaultConstructor)
toFirEnumEntry(delegatedSelfType, ownerClassHasDefaultConstructor)
}
else -> convert()
}
@@ -397,7 +398,7 @@ class RawFirBuilder(
delegatedSelfTypeRef: FirTypeRef?,
delegatedEnumSuperTypeRef: FirTypeRef?,
classKind: ClassKind,
): FirTypeRef? {
): FirTypeRef {
var superTypeCallEntry: KtSuperTypeCallEntry? = null
var delegatedSuperTypeRef: FirTypeRef? = null
for (superTypeListEntry in superTypeListEntries) {
@@ -452,7 +453,7 @@ class RawFirBuilder(
if (container.superTypeRefs.isEmpty()) {
container.superTypeRefs += defaultDelegatedSuperTypeRef
}
if (this is KtClass && this.isInterface()) return delegatedSuperTypeRef
if (this is KtClass && this.isInterface()) return delegatedSuperTypeRef ?: implicitAnyType
// TODO: in case we have no primary constructor,
// it may be not possible to determine delegated super type right here
@@ -687,13 +688,13 @@ class RawFirBuilder(
symbol = FirAnonymousObjectSymbol()
val delegatedSelfType = objectDeclaration.toDelegatedSelfType(this)
objectDeclaration.extractAnnotationsTo(this)
objectDeclaration.extractSuperTypeListEntriesTo(this, delegatedSelfType, null, ClassKind.CLASS)
val delegatedSuperType = objectDeclaration.extractSuperTypeListEntriesTo(this, delegatedSelfType, null, ClassKind.CLASS)
typeRef = delegatedSelfType
for (declaration in objectDeclaration.declarations) {
declarations += declaration.toFirDeclaration(
delegatedSuperType = null,
delegatedSelfType = null,
delegatedSuperType,
delegatedSelfType,
owner = objectDeclaration,
hasPrimaryConstructor = false,
)
@@ -866,7 +867,7 @@ class RawFirBuilder(
}
private fun KtSecondaryConstructor.toFirConstructor(
delegatedSuperTypeRef: FirTypeRef?,
delegatedSuperTypeRef: FirTypeRef,
delegatedSelfTypeRef: FirTypeRef,
owner: KtClassOrObject,
hasPrimaryConstructor: Boolean,
@@ -885,7 +886,11 @@ class RawFirBuilder(
isFromEnumClass = owner.hasModifier(ENUM_KEYWORD)
}
symbol = FirConstructorSymbol(callableIdForClassConstructor())
delegatedConstructor = getDelegationCall().convert(delegatedSuperTypeRef, delegatedSelfTypeRef, hasPrimaryConstructor)
delegatedConstructor = getDelegationCall().convert(
delegatedSuperTypeRef,
delegatedSelfTypeRef,
hasPrimaryConstructor
)
this@RawFirBuilder.context.firFunctionTargets += target
extractAnnotationsTo(this)
typeParameters += typeParametersFromSelfType(delegatedSelfTypeRef)
@@ -898,7 +903,7 @@ class RawFirBuilder(
}
private fun KtConstructorDelegationCall.convert(
delegatedSuperTypeRef: FirTypeRef?,
delegatedSuperTypeRef: FirTypeRef,
delegatedSelfTypeRef: FirTypeRef,
hasPrimaryConstructor: Boolean,
): FirDelegatedConstructorCall {
@@ -906,10 +911,7 @@ class RawFirBuilder(
val source = this.toFirSourceElement()
val delegatedType = when {
isThis -> delegatedSelfTypeRef
else -> delegatedSuperTypeRef ?: buildErrorTypeRef {
this.source = source
diagnostic = ConeSimpleDiagnostic("No super type", DiagnosticKind.Syntax)
}
else -> delegatedSuperTypeRef
}
return buildDelegatedConstructorCall {
this.source = source
@@ -1449,7 +1451,7 @@ class RawFirBuilder(
conventionCallName != null -> {
if (operationToken in OperatorConventions.INCREMENT_OPERATIONS) {
return generateIncrementOrDecrementBlock(
expression, argument,
expression, expression.operationReference, argument,
callName = conventionCallName,
prefix = expression is KtPrefixExpression,
) { (this as KtExpression).toFirExpression("Incorrect expression inside inc/dec") }
@@ -45,8 +45,8 @@ FILE: constructorInObject.kt
}
public? final? val anonObject: <implicit> = object : R|kotlin/Any| {
public? constructor(): <ERROR TYPE REF: Constructor in object> {
super<<ERROR TYPE REF: No super type>>()
public? constructor(): R|anonymous| {
super<R|kotlin/Any|>()
}
}
@@ -10,6 +10,7 @@ import org.jetbrains.kotlin.fir.FirSourceElement
import org.jetbrains.kotlin.fir.builder.FirAnnotationContainerBuilder
import org.jetbrains.kotlin.fir.builder.FirBuilderDsl
import org.jetbrains.kotlin.fir.diagnostics.ConeDiagnostic
import org.jetbrains.kotlin.fir.diagnostics.ConeStubDiagnostic
import org.jetbrains.kotlin.fir.expressions.FirAnnotationCall
import org.jetbrains.kotlin.fir.expressions.FirErrorExpression
import org.jetbrains.kotlin.fir.expressions.builder.FirExpressionBuilder
@@ -11,6 +11,7 @@ import org.jetbrains.kotlin.fir.FirSourceElement
import org.jetbrains.kotlin.fir.builder.FirAnnotationContainerBuilder
import org.jetbrains.kotlin.fir.builder.FirBuilderDsl
import org.jetbrains.kotlin.fir.diagnostics.ConeDiagnostic
import org.jetbrains.kotlin.fir.diagnostics.ConeStubDiagnostic
import org.jetbrains.kotlin.fir.expressions.FirAnnotationCall
import org.jetbrains.kotlin.fir.expressions.FirBlock
import org.jetbrains.kotlin.fir.expressions.FirErrorLoop
@@ -7,6 +7,7 @@ package org.jetbrains.kotlin.fir.expressions.impl
import org.jetbrains.kotlin.fir.FirSourceElement
import org.jetbrains.kotlin.fir.diagnostics.ConeDiagnostic
import org.jetbrains.kotlin.fir.diagnostics.ConeStubDiagnostic
import org.jetbrains.kotlin.fir.expressions.FirAnnotationCall
import org.jetbrains.kotlin.fir.expressions.FirErrorExpression
import org.jetbrains.kotlin.fir.types.FirTypeRef
@@ -22,7 +23,7 @@ internal class FirErrorExpressionImpl(
override val source: FirSourceElement?,
override val diagnostic: ConeDiagnostic,
) : FirErrorExpression() {
override var typeRef: FirTypeRef = FirErrorTypeRefImpl(source, diagnostic)
override var typeRef: FirTypeRef = FirErrorTypeRefImpl(source, ConeStubDiagnostic(diagnostic))
override val annotations: List<FirAnnotationCall> get() = emptyList()
override fun <R, D> acceptChildren(visitor: FirVisitor<R, D>, data: D) {
@@ -8,6 +8,7 @@ package org.jetbrains.kotlin.fir.expressions.impl
import org.jetbrains.kotlin.fir.FirLabel
import org.jetbrains.kotlin.fir.FirSourceElement
import org.jetbrains.kotlin.fir.diagnostics.ConeDiagnostic
import org.jetbrains.kotlin.fir.diagnostics.ConeStubDiagnostic
import org.jetbrains.kotlin.fir.expressions.FirAnnotationCall
import org.jetbrains.kotlin.fir.expressions.FirBlock
import org.jetbrains.kotlin.fir.expressions.FirErrorLoop
@@ -27,7 +28,7 @@ internal class FirErrorLoopImpl(
override val diagnostic: ConeDiagnostic,
) : FirErrorLoop() {
override var block: FirBlock = FirEmptyExpressionBlock()
override var condition: FirExpression = FirErrorExpressionImpl(source, diagnostic)
override var condition: FirExpression = FirErrorExpressionImpl(source, ConeStubDiagnostic(diagnostic))
override fun <R, D> acceptChildren(visitor: FirVisitor<R, D>, data: D) {
annotations.forEach { it.accept(visitor, data) }
@@ -9,10 +9,14 @@ class ConeSimpleDiagnostic(override val reason: String, val kind: DiagnosticKind
enum class DiagnosticKind {
Syntax,
ExpressionRequired,
NotLoopLabel,
JumpOutsideLoop,
VariableExpected,
ReturnNotAllowed,
UnresolvedLabel,
IllegalConstExpression,
ConstructorInObject,
DeserializationError,
InferenceError,
NoSupertype,
@@ -139,8 +139,8 @@ object ImplementationConfigurator : AbstractFirTreeImplementationConfigurator()
impl(errorLoop) {
default("block", "FirEmptyExpressionBlock()")
default("condition", "FirErrorExpressionImpl(source, diagnostic)")
useTypes(emptyExpressionBlock)
default("condition", "FirErrorExpressionImpl(source, ConeStubDiagnostic(diagnostic))")
useTypes(emptyExpressionBlock, coneStubDiagnosticType)
}
impl(expression, "FirExpressionStub") {
@@ -390,8 +390,8 @@ object ImplementationConfigurator : AbstractFirTreeImplementationConfigurator()
impl(errorExpression) {
defaultEmptyList("annotations")
default("typeRef", "FirErrorTypeRefImpl(source, diagnostic)")
useTypes(errorTypeRefImpl)
default("typeRef", "FirErrorTypeRefImpl(source, ConeStubDiagnostic(diagnostic))")
useTypes(errorTypeRefImpl, coneStubDiagnosticType)
}
impl(resolvedFunctionTypeRef) {
@@ -65,6 +65,7 @@ val pureAbstractElementType = generatedType("FirPureAbstractElement")
val effectDeclarationType = type("fir.contracts.description", "ConeEffectDeclaration")
val emptyContractDescriptionType = generatedType("contracts.impl", "FirEmptyContractDescription")
val coneDiagnosticType = generatedType("diagnostics", "ConeDiagnostic")
val coneStubDiagnosticType = generatedType("diagnostics", "ConeStubDiagnostic")
val dslBuilderAnnotationType = generatedType("builder", "FirBuilderDsl")
val firImplementationDetailType = generatedType("FirImplementationDetail")