diff --git a/compiler/frontend/src/org/jetbrains/kotlin/analyzer/AnalysisResult.kt b/compiler/frontend/src/org/jetbrains/kotlin/analyzer/AnalysisResult.kt index 86fcd978a3a..e1b37c26634 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/analyzer/AnalysisResult.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/analyzer/AnalysisResult.kt @@ -22,9 +22,9 @@ import org.jetbrains.kotlin.types.ErrorUtils import java.io.File open class AnalysisResult protected constructor( - val bindingContext: BindingContext, - val moduleDescriptor: ModuleDescriptor, - val shouldGenerateCode: Boolean = true + val bindingContext: BindingContext, + val moduleDescriptor: ModuleDescriptor, + val shouldGenerateCode: Boolean = true ) { override fun equals(other: Any?): Boolean { if (this === other) return true @@ -63,33 +63,37 @@ open class AnalysisResult protected constructor( private class CompilationError(bindingContext: BindingContext) : AnalysisResult(bindingContext, ErrorUtils.getErrorModule()) private class InternalError( - bindingContext: BindingContext, - val exception: Throwable + bindingContext: BindingContext, + val exception: Throwable ) : AnalysisResult(bindingContext, ErrorUtils.getErrorModule()) - + class RetryWithAdditionalJavaRoots( - bindingContext: BindingContext, - moduleDescriptor: ModuleDescriptor, - val additionalJavaRoots: List, - val addToEnvironment: Boolean = true + bindingContext: BindingContext, + moduleDescriptor: ModuleDescriptor, + val additionalJavaRoots: List, + val addToEnvironment: Boolean = true ) : AnalysisResult(bindingContext, moduleDescriptor) companion object { val EMPTY: AnalysisResult = success(BindingContext.EMPTY, ErrorUtils.getErrorModule()) - @JvmStatic fun success(bindingContext: BindingContext, module: ModuleDescriptor): AnalysisResult { + @JvmStatic + fun success(bindingContext: BindingContext, module: ModuleDescriptor): AnalysisResult { return AnalysisResult(bindingContext, module, true) } - @JvmStatic fun success(bindingContext: BindingContext, module: ModuleDescriptor, shouldGenerateCode: Boolean): AnalysisResult { + @JvmStatic + fun success(bindingContext: BindingContext, module: ModuleDescriptor, shouldGenerateCode: Boolean): AnalysisResult { return AnalysisResult(bindingContext, module, shouldGenerateCode) } - @JvmStatic fun internalError(bindingContext: BindingContext, error: Throwable): AnalysisResult { + @JvmStatic + fun internalError(bindingContext: BindingContext, error: Throwable): AnalysisResult { return InternalError(bindingContext, error) } - @JvmStatic fun compilationError(bindingContext: BindingContext): AnalysisResult { + @JvmStatic + fun compilationError(bindingContext: BindingContext): AnalysisResult { return CompilationError(bindingContext) } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/ConstructorConsistencyChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/ConstructorConsistencyChecker.kt index 5ff0193fefb..86d2dd3458b 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/ConstructorConsistencyChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/ConstructorConsistencyChecker.kt @@ -38,19 +38,19 @@ interface LeakingThisDescriptor { data class PropertyIsNull(val property: PropertyDescriptor, override val classOrObject: KtClassOrObject) : LeakingThisDescriptor - data class NonFinalClass(val klass: ClassDescriptor, override val classOrObject: KtClassOrObject): LeakingThisDescriptor + data class NonFinalClass(val klass: ClassDescriptor, override val classOrObject: KtClassOrObject) : LeakingThisDescriptor - data class NonFinalProperty(val property: PropertyDescriptor, override val classOrObject: KtClassOrObject): LeakingThisDescriptor + data class NonFinalProperty(val property: PropertyDescriptor, override val classOrObject: KtClassOrObject) : LeakingThisDescriptor - data class NonFinalFunction(val function: FunctionDescriptor, override val classOrObject: KtClassOrObject): LeakingThisDescriptor + data class NonFinalFunction(val function: FunctionDescriptor, override val classOrObject: KtClassOrObject) : LeakingThisDescriptor } class ConstructorConsistencyChecker private constructor( - private val classOrObject: KtClassOrObject, - private val classDescriptor: ClassDescriptor, - private val trace: BindingTrace, - private val pseudocode: Pseudocode, - private val variablesData: PseudocodeVariablesData + private val classOrObject: KtClassOrObject, + private val classDescriptor: ClassDescriptor, + private val trace: BindingTrace, + private val pseudocode: Pseudocode, + private val variablesData: PseudocodeVariablesData ) { private val finalClass = classDescriptor.isFinalClass @@ -110,77 +110,79 @@ class ConstructorConsistencyChecker private constructor( fun check() { // List of properties to initialize val propertyDescriptors = variablesData.getDeclaredVariables(pseudocode, false) - .filterIsInstance() - .filter { trace.get(BindingContext.BACKING_FIELD_REQUIRED, it) == true } + .filterIsInstance() + .filter { trace.get(BindingContext.BACKING_FIELD_REQUIRED, it) == true } pseudocode.traverse( - TraversalOrder.FORWARD, variablesData.variableInitializers, { instruction, enterData, _ -> + TraversalOrder.FORWARD, variablesData.variableInitializers, { instruction, enterData, _ -> - fun firstUninitializedNotNullProperty() = propertyDescriptors.firstOrNull { - !it.type.isMarkedNullable && !KotlinBuiltIns.isPrimitiveType(it.type) && - !it.isLateInit && !(enterData.getOrNull(it)?.definitelyInitialized() ?: false) - } - - fun handleLeakingThis(expression: KtExpression) { - if (!finalClass) { - trace.record(BindingContext.LEAKING_THIS, target(expression), - LeakingThisDescriptor.NonFinalClass(classDescriptor, classOrObject)) + fun firstUninitializedNotNullProperty() = propertyDescriptors.firstOrNull { + !it.type.isMarkedNullable && !KotlinBuiltIns.isPrimitiveType(it.type) && + !it.isLateInit && !(enterData.getOrNull(it)?.definitelyInitialized() ?: false) } - else { - val uninitializedProperty = firstUninitializedNotNullProperty() - if (uninitializedProperty != null) { - trace.record(BindingContext.LEAKING_THIS, target(expression), - LeakingThisDescriptor.PropertyIsNull(uninitializedProperty, classOrObject)) + + fun handleLeakingThis(expression: KtExpression) { + if (!finalClass) { + trace.record( + BindingContext.LEAKING_THIS, target(expression), + LeakingThisDescriptor.NonFinalClass(classDescriptor, classOrObject) + ) + } else { + val uninitializedProperty = firstUninitializedNotNullProperty() + if (uninitializedProperty != null) { + trace.record( + BindingContext.LEAKING_THIS, target(expression), + LeakingThisDescriptor.PropertyIsNull(uninitializedProperty, classOrObject) + ) + } } } - } - if (instruction.owner != pseudocode) { - return@traverse - } - - if (instruction is KtElementInstruction) { - val element = instruction.element - when (instruction) { - is ReadValueInstruction -> - if (element is KtThisExpression) { - if (!safeThisUsage(element)) { - handleLeakingThis(element) - } - } - is MagicInstruction -> - if (instruction.kind == MagicKind.IMPLICIT_RECEIVER) { - if (element is KtCallExpression) { - if (!safeCallUsage(element)) { - handleLeakingThis(element) - } - } - else if (element is KtReferenceExpression) { - if (!safeReferenceUsage(element)) { - handleLeakingThis(element) - } - } - } + if (instruction.owner != pseudocode) { + return@traverse } - } - }) + + if (instruction is KtElementInstruction) { + val element = instruction.element + when (instruction) { + is ReadValueInstruction -> + if (element is KtThisExpression) { + if (!safeThisUsage(element)) { + handleLeakingThis(element) + } + } + is MagicInstruction -> + if (instruction.kind == MagicKind.IMPLICIT_RECEIVER) { + if (element is KtCallExpression) { + if (!safeCallUsage(element)) { + handleLeakingThis(element) + } + } else if (element is KtReferenceExpression) { + if (!safeReferenceUsage(element)) { + handleLeakingThis(element) + } + } + } + } + } + }) } companion object { @JvmStatic fun check( - constructor: KtSecondaryConstructor, - trace: BindingTrace, - pseudocode: Pseudocode, - pseudocodeVariablesData: PseudocodeVariablesData + constructor: KtSecondaryConstructor, + trace: BindingTrace, + pseudocode: Pseudocode, + pseudocodeVariablesData: PseudocodeVariablesData ) = check(constructor.getContainingClassOrObject(), trace, pseudocode, pseudocodeVariablesData) @JvmStatic fun check( - classOrObject: KtClassOrObject, - trace: BindingTrace, - pseudocode: Pseudocode, - pseudocodeVariablesData: PseudocodeVariablesData + classOrObject: KtClassOrObject, + trace: BindingTrace, + pseudocode: Pseudocode, + pseudocodeVariablesData: PseudocodeVariablesData ) { val classDescriptor = trace.get(BindingContext.CLASS, classOrObject) ?: return ConstructorConsistencyChecker(classOrObject, classDescriptor, trace, pseudocode, pseudocodeVariablesData).check() diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowBuilder.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowBuilder.kt index bed554d724b..f7670ac94f2 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowBuilder.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowBuilder.kt @@ -103,25 +103,29 @@ interface ControlFlowBuilder { fun loadStringTemplate(expression: KtStringTemplateExpression, inputValues: List): InstructionWithValue fun magic( - instructionElement: KtElement, - valueElement: KtElement?, - inputValues: List, - kind: MagicKind): MagicInstruction + instructionElement: KtElement, + valueElement: KtElement?, + inputValues: List, + kind: MagicKind + ): MagicInstruction fun merge( - expression: KtExpression, - inputValues: List): MergeInstruction + expression: KtExpression, + inputValues: List + ): MergeInstruction fun readVariable( - expression: KtExpression, - resolvedCall: ResolvedCall<*>, - receiverValues: Map): ReadValueInstruction + expression: KtExpression, + resolvedCall: ResolvedCall<*>, + receiverValues: Map + ): ReadValueInstruction fun call( - valueElement: KtElement, - resolvedCall: ResolvedCall<*>, - receiverValues: Map, - arguments: Map): CallInstruction + valueElement: KtElement, + resolvedCall: ResolvedCall<*>, + receiverValues: Map, + arguments: Map + ): CallInstruction enum class PredefinedOperation { AND, @@ -130,16 +134,18 @@ interface ControlFlowBuilder { } fun predefinedOperation( - expression: KtExpression, - operation: PredefinedOperation, - inputValues: List): OperationInstruction + expression: KtExpression, + operation: PredefinedOperation, + inputValues: List + ): OperationInstruction fun read(element: KtElement, target: AccessTarget, receiverValues: Map): ReadValueInstruction fun write( - assignment: KtElement, - lValue: KtElement, - rValue: PseudoValue, - target: AccessTarget, - receiverValues: Map) -} + assignment: KtElement, + lValue: KtElement, + rValue: PseudoValue, + target: AccessTarget, + receiverValues: Map + ) +} \ No newline at end of file diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowBuilderAdapter.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowBuilderAdapter.kt index 4957f148fcc..920102af7fe 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowBuilderAdapter.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowBuilderAdapter.kt @@ -35,42 +35,46 @@ abstract class ControlFlowBuilderAdapter : ControlFlowBuilder { } override fun loadConstant(expression: KtExpression, constant: CompileTimeConstant<*>?): InstructionWithValue = - delegateBuilder.loadConstant(expression, constant) + delegateBuilder.loadConstant(expression, constant) override fun createAnonymousObject(expression: KtObjectLiteralExpression): InstructionWithValue = - delegateBuilder.createAnonymousObject(expression) + delegateBuilder.createAnonymousObject(expression) override fun createLambda(expression: KtFunction): InstructionWithValue = delegateBuilder.createLambda(expression) override fun loadStringTemplate(expression: KtStringTemplateExpression, inputValues: List): InstructionWithValue = - delegateBuilder.loadStringTemplate(expression, inputValues) + delegateBuilder.loadStringTemplate(expression, inputValues) override fun magic( - instructionElement: KtElement, - valueElement: KtElement?, - inputValues: List, - kind: MagicKind): MagicInstruction = delegateBuilder.magic(instructionElement, valueElement, inputValues, kind) + instructionElement: KtElement, + valueElement: KtElement?, + inputValues: List, + kind: MagicKind + ): MagicInstruction = delegateBuilder.magic(instructionElement, valueElement, inputValues, kind) override fun merge(expression: KtExpression, inputValues: List): MergeInstruction = - delegateBuilder.merge(expression, inputValues) + delegateBuilder.merge(expression, inputValues) override fun readVariable( - expression: KtExpression, - resolvedCall: ResolvedCall<*>, - receiverValues: Map): ReadValueInstruction = - delegateBuilder.readVariable(expression, resolvedCall, receiverValues) + expression: KtExpression, + resolvedCall: ResolvedCall<*>, + receiverValues: Map + ): ReadValueInstruction = + delegateBuilder.readVariable(expression, resolvedCall, receiverValues) override fun call( - valueElement: KtElement, - resolvedCall: ResolvedCall<*>, - receiverValues: Map, - arguments: Map): CallInstruction = - delegateBuilder.call(valueElement, resolvedCall, receiverValues, arguments) + valueElement: KtElement, + resolvedCall: ResolvedCall<*>, + receiverValues: Map, + arguments: Map + ): CallInstruction = + delegateBuilder.call(valueElement, resolvedCall, receiverValues, arguments) override fun predefinedOperation( - expression: KtExpression, - operation: ControlFlowBuilder.PredefinedOperation, - inputValues: List): OperationInstruction = delegateBuilder.predefinedOperation(expression, operation, inputValues) + expression: KtExpression, + operation: ControlFlowBuilder.PredefinedOperation, + inputValues: List + ): OperationInstruction = delegateBuilder.predefinedOperation(expression, operation, inputValues) override fun createUnboundLabel(): Label = delegateBuilder.createUnboundLabel() @@ -140,7 +144,7 @@ abstract class ControlFlowBuilderAdapter : ControlFlowBuilder { } override fun exitSubroutine(subroutine: KtElement, invocationKind: InvocationKind?): Pseudocode = - delegateBuilder.exitSubroutine(subroutine, invocationKind) + delegateBuilder.exitSubroutine(subroutine, invocationKind) override val currentSubroutine: KtElement get() = delegateBuilder.currentSubroutine @@ -157,14 +161,15 @@ abstract class ControlFlowBuilderAdapter : ControlFlowBuilder { } override fun read(element: KtElement, target: AccessTarget, receiverValues: Map) = - delegateBuilder.read(element, target, receiverValues) + delegateBuilder.read(element, target, receiverValues) override fun write( - assignment: KtElement, - lValue: KtElement, - rValue: PseudoValue, - target: AccessTarget, - receiverValues: Map) { + assignment: KtElement, + lValue: KtElement, + rValue: PseudoValue, + target: AccessTarget, + receiverValues: Map + ) { delegateBuilder.write(assignment, lValue, rValue, target, receiverValues) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowInfo.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowInfo.kt index 7e129c3e3a4..fbc3ac53947 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowInfo.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowInfo.kt @@ -24,7 +24,7 @@ typealias ImmutableHashMap = javaslang.collection.HashMap abstract class ControlFlowInfo, D : Any> internal constructor( - protected val map: ImmutableMap = ImmutableHashMap.empty() + protected val map: ImmutableMap = ImmutableHashMap.empty() ) : ImmutableMap by map, ReadOnlyControlFlowInfo { abstract protected fun copy(newMap: ImmutableMap): S @@ -69,7 +69,7 @@ interface ReadOnlyInitControlFlowInfo : ReadOnlyControlFlowInfo class InitControlFlowInfo(map: ImmutableMap = ImmutableHashMap.empty()) : - ControlFlowInfo(map), ReadOnlyInitControlFlowInfo { + ControlFlowInfo(map), ReadOnlyInitControlFlowInfo { override fun copy(newMap: ImmutableMap) = InitControlFlowInfo(newMap) // this = output of EXHAUSTIVE_WHEN_ELSE instruction @@ -87,7 +87,7 @@ class InitControlFlowInfo(map: ImmutableMap = ImmutableHashMap.empty()) : - ControlFlowInfo(map), ReadOnlyUseControlFlowInfo { + ControlFlowInfo(map), ReadOnlyUseControlFlowInfo { override fun copy(newMap: ImmutableMap) = UseControlFlowInfo(newMap) } @@ -144,13 +144,13 @@ class VariableControlFlowState private constructor(val initState: InitState, val } fun createInitializedExhaustively(isDeclared: Boolean): VariableControlFlowState = - create(InitState.INITIALIZED_EXHAUSTIVELY, isDeclared) + create(InitState.INITIALIZED_EXHAUSTIVELY, isDeclared) fun create(isInitialized: Boolean, isDeclared: Boolean = false): VariableControlFlowState = - create(if (isInitialized) InitState.INITIALIZED else InitState.NOT_INITIALIZED, isDeclared) + create(if (isInitialized) InitState.INITIALIZED else InitState.NOT_INITIALIZED, isDeclared) fun create(isDeclaredHere: Boolean, mergedEdgesData: VariableControlFlowState?): VariableControlFlowState = - create(true, isDeclaredHere || mergedEdgesData != null && mergedEdgesData.isDeclared) + create(true, isDeclaredHere || mergedEdgesData != null && mergedEdgesData.isDeclared) } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowInformationProvider.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowInformationProvider.kt index 304b5c05a8b..4ba4f721aee 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowInformationProvider.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowInformationProvider.kt @@ -51,11 +51,11 @@ import org.jetbrains.kotlin.types.isFlexible import org.jetbrains.kotlin.util.OperatorNameConventions class ControlFlowInformationProvider private constructor( - private val subroutine: KtElement, - private val trace: BindingTrace, - private val pseudocode: Pseudocode, - private val languageVersionSettings: LanguageVersionSettings, - private val diagnosticSuppressor: PlatformDiagnosticSuppressor + private val subroutine: KtElement, + private val trace: BindingTrace, + private val pseudocode: Pseudocode, + private val languageVersionSettings: LanguageVersionSettings, + private val diagnosticSuppressor: PlatformDiagnosticSuppressor ) { private val pseudocodeVariablesData by lazy { @@ -63,16 +63,16 @@ class ControlFlowInformationProvider private constructor( } constructor( - declaration: KtElement, - trace: BindingTrace, - languageVersionSettings: LanguageVersionSettings, - diagnosticSuppressor: PlatformDiagnosticSuppressor + declaration: KtElement, + trace: BindingTrace, + languageVersionSettings: LanguageVersionSettings, + diagnosticSuppressor: PlatformDiagnosticSuppressor ) : this( - declaration, - trace, - ControlFlowProcessor(trace).generatePseudocode(declaration), - languageVersionSettings, - diagnosticSuppressor + declaration, + trace, + ControlFlowProcessor(trace).generatePseudocode(declaration), + languageVersionSettings, + diagnosticSuppressor ) fun checkForLocalClassOrObjectMode() { @@ -161,8 +161,7 @@ class ControlFlowInformationProvider private constructor( override fun visitInstruction(instruction: Instruction) { if (instruction is KtElementInstruction) { returnedExpressions.add(instruction.element) - } - else { + } else { throw IllegalStateException("$instruction precedes the exit point") } } @@ -179,7 +178,7 @@ class ControlFlowInformationProvider private constructor( val expectedType = functionDescriptor?.returnType val providerForLocalDeclaration = ControlFlowInformationProvider( - element, trace, localDeclarationInstruction.body, languageVersionSettings, diagnosticSuppressor + element, trace, localDeclarationInstruction.body, languageVersionSettings, diagnosticSuppressor ) providerForLocalDeclaration.checkFunction(expectedType) @@ -189,7 +188,7 @@ class ControlFlowInformationProvider private constructor( private fun checkDefiniteReturn(expectedReturnType: KotlinType, unreachableCode: UnreachableCode) { val function = subroutine as? KtDeclarationWithBody - ?: throw AssertionError("checkDefiniteReturn is called for ${subroutine.text} which is not KtDeclarationWithBody") + ?: throw AssertionError("checkDefiniteReturn is called for ${subroutine.text} which is not KtDeclarationWithBody") if (!function.hasBody()) return @@ -244,16 +243,15 @@ class ControlFlowInformationProvider private constructor( if (instruction is JumpInstruction) { val isJumpElement = element is KtBreakExpression - || element is KtContinueExpression - || element is KtReturnExpression - || element is KtThrowExpression + || element is KtContinueExpression + || element is KtReturnExpression + || element is KtThrowExpression if (!isJumpElement) continue } if (instruction.dead) { unreachableElements.add(element) - } - else { + } else { reachableElements.add(element) } } @@ -274,10 +272,9 @@ class ControlFlowInformationProvider private constructor( val reportedDiagnosticMap = hashMapOf>() - pseudocode.traverse(TraversalOrder.FORWARD, initializers) { - instruction: Instruction, - enterData: ReadOnlyInitControlFlowInfo, - exitData: ReadOnlyInitControlFlowInfo -> + pseudocode.traverse(TraversalOrder.FORWARD, initializers) { instruction: Instruction, + enterData: ReadOnlyInitControlFlowInfo, + exitData: ReadOnlyInitControlFlowInfo -> val ctxt = VariableInitContext(instruction, reportedDiagnosticMap, enterData, exitData, blockScopeVariableInfo) if (ctxt.variableDescriptor == null) return@traverse @@ -291,8 +288,10 @@ class ControlFlowInformationProvider private constructor( } if (instruction !is WriteValueInstruction) return@traverse val element = instruction.lValue as? KtExpression ?: return@traverse - var error = checkValReassignment(ctxt, element, instruction, - varWithValReassignErrorGenerated) + var error = checkValReassignment( + ctxt, element, instruction, + varWithValReassignErrorGenerated + ) if (!error && processClassOrObject) { error = checkAssignmentBeforeDeclaration(ctxt, element) } @@ -319,9 +318,9 @@ class ControlFlowInformationProvider private constructor( } private fun checkIsInitialized( - ctxt: VariableInitContext, - element: KtElement, - varWithUninitializedErrorGenerated: MutableCollection + ctxt: VariableInitContext, + element: KtElement, + varWithUninitializedErrorGenerated: MutableCollection ) { if (element !is KtSimpleNameExpression) return @@ -333,8 +332,7 @@ class ControlFlowInformationProvider private constructor( if (!isDefinitelyInitialized && !varWithUninitializedErrorGenerated.contains(variableDescriptor)) { if (variableDescriptor !is PropertyDescriptor) { variableDescriptor?.let { varWithUninitializedErrorGenerated.add(it) } - } - else if (variableDescriptor.isLateInit) { + } else if (variableDescriptor.isLateInit) { trace.record(MUST_BE_LATEINIT, variableDescriptor) return } @@ -352,7 +350,8 @@ class ControlFlowInformationProvider private constructor( report(Errors.UNINITIALIZED_ENUM_COMPANION.on(element, container), ctxt) } } - else -> {} + else -> { + } } } is VariableDescriptor -> @@ -365,8 +364,8 @@ class ControlFlowInformationProvider private constructor( } private fun isCapturedWrite( - variableDescriptor: VariableDescriptor, - writeValueInstruction: WriteValueInstruction + variableDescriptor: VariableDescriptor, + writeValueInstruction: WriteValueInstruction ): Boolean { val containingDeclarationDescriptor = variableDescriptor.containingDeclaration // Do not consider top-level properties @@ -405,10 +404,10 @@ class ControlFlowInformationProvider private constructor( } private fun checkValReassignment( - ctxt: VariableInitContext, - expression: KtExpression, - writeValueInstruction: WriteValueInstruction, - varWithValReassignErrorGenerated: MutableCollection + ctxt: VariableInitContext, + expression: KtExpression, + writeValueInstruction: WriteValueInstruction, + varWithValReassignErrorGenerated: MutableCollection ): Boolean { val variableDescriptor = ctxt.variableDescriptor val mayBeInitializedNotHere = ctxt.enterInitState?.mayBeInitialized() ?: false @@ -424,8 +423,12 @@ class ControlFlowInformationProvider private constructor( if (Visibilities.isVisible(receiverValue, variableDescriptor, descriptor) && setterDescriptor != null && !Visibilities.isVisible(receiverValue, setterDescriptor, descriptor)) { - report(Errors.INVISIBLE_SETTER.on(expression, variableDescriptor, setterDescriptor.visibility, - setterDescriptor), ctxt) + report( + Errors.INVISIBLE_SETTER.on( + expression, variableDescriptor, setterDescriptor.visibility, + setterDescriptor + ), ctxt + ) return true } } @@ -436,11 +439,11 @@ class ControlFlowInformationProvider private constructor( var hasReassignMethodReturningUnit = false val parent = expression.parent val operationReference = - when (parent) { - is KtBinaryExpression -> parent.operationReference - is KtUnaryExpression -> parent.operationReference - else -> null - } + when (parent) { + is KtBinaryExpression -> parent.operationReference + is KtUnaryExpression -> parent.operationReference + else -> null + } if (operationReference != null) { val descriptor = trace.get(BindingContext.REFERENCE_TARGET, operationReference) if (descriptor is FunctionDescriptor) { @@ -462,16 +465,13 @@ class ControlFlowInformationProvider private constructor( if (captured && !mayBeInitializedNotHere && hasBackingField && isThisOrNoDispatchReceiver) { if (variableDescriptor.containingDeclaration is ClassDescriptor) { report(Errors.CAPTURED_MEMBER_VAL_INITIALIZATION.on(expression, variableDescriptor), ctxt) - } - else { + } else { report(Errors.CAPTURED_VAL_INITIALIZATION.on(expression, variableDescriptor), ctxt) } - } - else { + } else { if (KtPsiUtil.isBackingFieldReference(variableDescriptor)) { reportValReassigned(expression, variableDescriptor, ctxt) - } - else { + } else { report(Errors.VAL_REASSIGNMENT.on(expression, variableDescriptor), ctxt) } } @@ -497,21 +497,20 @@ class ControlFlowInformationProvider private constructor( } private fun checkAssignmentBeforeDeclaration(ctxt: VariableInitContext, expression: KtExpression) = - if (ctxt.isInitializationBeforeDeclaration()) { - if (ctxt.variableDescriptor != null) { - report(Errors.INITIALIZATION_BEFORE_DECLARATION.on(expression, ctxt.variableDescriptor), ctxt) - } - true - } - else { - false + if (ctxt.isInitializationBeforeDeclaration()) { + if (ctxt.variableDescriptor != null) { + report(Errors.INITIALIZATION_BEFORE_DECLARATION.on(expression, ctxt.variableDescriptor), ctxt) } + true + } else { + false + } private fun VariableInitContext.isInitializationBeforeDeclaration(): Boolean = // is not declared - enterInitState?.isDeclared != true && exitInitState?.isDeclared != true && - // wasn't initialized before current instruction - enterInitState?.mayBeInitialized() != true + enterInitState?.isDeclared != true && exitInitState?.isDeclared != true && + // wasn't initialized before current instruction + enterInitState?.mayBeInitialized() != true private fun checkInitializationForCustomSetter(ctxt: VariableInitContext, expression: KtExpression): Boolean { val variableDescriptor = ctxt.variableDescriptor @@ -524,17 +523,16 @@ class ControlFlowInformationProvider private constructor( } val property = DescriptorToSourceUtils.descriptorToDeclaration(variableDescriptor) as? KtProperty - ?: throw AssertionError("$variableDescriptor is not related to KtProperty") + ?: throw AssertionError("$variableDescriptor is not related to KtProperty") val setter = property.setter if (variableDescriptor.modality == Modality.FINAL && (setter == null || !setter.hasBody())) { return false } val variable = if (expression is KtDotQualifiedExpression && - expression.receiverExpression is KtThisExpression) { + expression.receiverExpression is KtThisExpression) { expression.selectorExpression - } - else { + } else { expression } if (variable is KtSimpleNameExpression) { @@ -545,8 +543,8 @@ class ControlFlowInformationProvider private constructor( } private fun recordInitializedVariables( - pseudocode: Pseudocode, - initializersMap: Map> + pseudocode: Pseudocode, + initializersMap: Map> ) { val initializers = initializersMap[pseudocode.exitInstruction] ?: return val declaredVariables = pseudocodeVariablesData.getDeclaredVariables(pseudocode, false) @@ -566,15 +564,15 @@ class ControlFlowInformationProvider private constructor( val reportedDiagnosticMap = hashMapOf>() val unusedValueExpressions = hashMapOf>() val usedValueExpressions = hashSetOf() - pseudocode.traverse(TraversalOrder.BACKWARD, variableStatusData) { - instruction: Instruction, - enterData: ReadOnlyUseControlFlowInfo, - _: ReadOnlyUseControlFlowInfo -> + pseudocode.traverse(TraversalOrder.BACKWARD, variableStatusData) { instruction: Instruction, + enterData: ReadOnlyUseControlFlowInfo, + _: ReadOnlyUseControlFlowInfo -> val ctxt = VariableUseContext(instruction, reportedDiagnosticMap) val declaredVariables = pseudocodeVariablesData.getDeclaredVariables(instruction.owner, false) val variableDescriptor = PseudocodeUtil.extractVariableDescriptorIfAny( - instruction, trace.bindingContext) + instruction, trace.bindingContext + ) if (variableDescriptor == null || !declaredVariables.contains(variableDescriptor) || !ExpressionTypingUtils.isLocal(variableDescriptor.containingDeclaration, variableDescriptor)) { @@ -587,8 +585,7 @@ class ControlFlowInformationProvider private constructor( val expressionInQuestion = instruction.element as? KtExpression ?: return@traverse if (variableUseState != READ) { unusedValueExpressions.put(expressionInQuestion, variableDescriptor to ctxt) - } - else { + } else { usedValueExpressions.add(expressionInQuestion) } } @@ -618,10 +615,10 @@ class ControlFlowInformationProvider private constructor( } private fun processUnusedDeclaration( - element: KtNamedDeclaration, - variableDescriptor: VariableDescriptor, - ctxt: VariableUseContext, - variableUseState: VariableUseState? + element: KtNamedDeclaration, + variableDescriptor: VariableDescriptor, + ctxt: VariableUseContext, + variableUseState: VariableUseState? ) { element.nameIdentifier ?: return if (!VariableUseState.isUsed(variableUseState)) { @@ -637,11 +634,9 @@ class ControlFlowInformationProvider private constructor( element is KtParameter -> processUnusedParameter(ctxt, element, variableDescriptor) } - } - else if (variableUseState === ONLY_WRITTEN_NEVER_READ && KtPsiUtil.isRemovableVariableDeclaration(element)) { + } else if (variableUseState === ONLY_WRITTEN_NEVER_READ && KtPsiUtil.isRemovableVariableDeclaration(element)) { report(Errors.ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE.on(element, variableDescriptor), ctxt) - } - else if (variableUseState === WRITTEN_AFTER_READ && element is KtVariableDeclaration) { + } else if (variableUseState === WRITTEN_AFTER_READ && element is KtVariableDeclaration) { when (element) { is KtProperty -> element.initializer?.let { @@ -675,8 +670,8 @@ class ControlFlowInformationProvider private constructor( val mainFunctionDetector = MainFunctionDetector(trace.bindingContext) val isMain = owner is KtNamedFunction && mainFunctionDetector.isMain(owner) val functionDescriptor = - trace.get(DECLARATION_TO_DESCRIPTOR, owner) as? FunctionDescriptor - ?: throw AssertionError(owner.text) + trace.get(DECLARATION_TO_DESCRIPTOR, owner) as? FunctionDescriptor + ?: throw AssertionError(owner.text) val functionName = functionDescriptor.name if (isMain || functionDescriptor.isOverridableOrOverrides @@ -691,8 +686,7 @@ class ControlFlowInformationProvider private constructor( } if (anonymous) { report(UNUSED_ANONYMOUS_PARAMETER.on(element, variableDescriptor), ctxt) - } - else { + } else { report(UNUSED_PARAMETER.on(element, variableDescriptor), ctxt) } } @@ -711,10 +705,12 @@ class ControlFlowInformationProvider private constructor( if (element.isUsedAsStatement(trace.bindingContext) && instruction.sideEffectFree) { val context = VariableContext(instruction, reportedDiagnosticMap) - report(when (element) { - is KtLambdaExpression -> Errors.UNUSED_LAMBDA_EXPRESSION.on(element) - else -> Errors.UNUSED_EXPRESSION.on(element) - }, context) + report( + when (element) { + is KtLambdaExpression -> Errors.UNUSED_LAMBDA_EXPRESSION.on(element) + else -> Errors.UNUSED_EXPRESSION.on(element) + }, context + ) } } } @@ -745,8 +741,7 @@ class ControlFlowInformationProvider private constructor( if (thenExpression == null || elseExpression == null) { trace.report(INVALID_IF_AS_EXPRESSION.on(element.ifKeyword)) - } - else { + } else { checkImplicitCastOnConditionalExpression(element) } } @@ -811,8 +806,7 @@ class ControlFlowInformationProvider private constructor( if (usedAsExpression && missingCases.isNotEmpty()) { if (elseEntry != null) continue trace.report(NO_ELSE_IN_WHEN.on(element, missingCases)) - } - else if (subjectExpression != null) { + } else if (subjectExpression != null) { val subjectType = trace.getType(subjectExpression) if (elseEntry != null) { if (missingCases.isEmpty() && subjectType != null && !subjectType.isFlexible()) { @@ -923,17 +917,17 @@ class ControlFlowInformationProvider private constructor( } private fun isInsideTry(element: KtElement) = - getParentOfType( - element, - KtTryExpression::class.java, KtFunction::class.java, KtAnonymousInitializer::class.java - ) is KtTryExpression + getParentOfType( + element, + KtTryExpression::class.java, KtFunction::class.java, KtAnonymousInitializer::class.java + ) is KtTryExpression private fun CallInstruction.isTailCall(subroutine: KtElement = this@ControlFlowInformationProvider.subroutine): Boolean { val tailInstructionDetector = TailInstructionDetector(subroutine) return traverseFollowingInstructions( - this, - hashSetOf(), - TraversalOrder.FORWARD + this, + hashSetOf(), + TraversalOrder.FORWARD ) { if (it == this@isTailCall || it.accept(tailInstructionDetector)) TraverseInstructionResult.CONTINUE @@ -957,8 +951,8 @@ class ControlFlowInformationProvider private constructor( * (depends on whether it should be reported for all or only for one of the copies) */ private fun report( - diagnostic: Diagnostic, - ctxt: VariableContext + diagnostic: Diagnostic, + ctxt: VariableContext ) { val instruction = ctxt.instruction if (instruction.copies.isEmpty()) { @@ -985,8 +979,7 @@ class ControlFlowInformationProvider private constructor( if (sameErrorForAllCopies) { trace.report(diagnostic) } - } - else { + } else { //only one reporting required if (!alreadyReported) { trace.report(diagnostic) @@ -996,26 +989,26 @@ class ControlFlowInformationProvider private constructor( private open inner class VariableContext( - internal val instruction: Instruction, - internal val reportedDiagnosticMap: MutableMap> + internal val instruction: Instruction, + internal val reportedDiagnosticMap: MutableMap> ) { internal val variableDescriptor = PseudocodeUtil.extractVariableDescriptorFromReference(instruction, trace.bindingContext) } private inner class VariableInitContext( - instruction: Instruction, - map: MutableMap>, - `in`: ReadOnlyInitControlFlowInfo, - out: ReadOnlyInitControlFlowInfo, - blockScopeVariableInfo: BlockScopeVariableInfo + instruction: Instruction, + map: MutableMap>, + `in`: ReadOnlyInitControlFlowInfo, + out: ReadOnlyInitControlFlowInfo, + blockScopeVariableInfo: BlockScopeVariableInfo ) : VariableContext(instruction, map) { internal val enterInitState = initialize(variableDescriptor, blockScopeVariableInfo, `in`) internal val exitInitState = initialize(variableDescriptor, blockScopeVariableInfo, out) private fun initialize( - variableDescriptor: VariableDescriptor?, - blockScopeVariableInfo: BlockScopeVariableInfo, - map: ReadOnlyInitControlFlowInfo + variableDescriptor: VariableDescriptor?, + blockScopeVariableInfo: BlockScopeVariableInfo, + map: ReadOnlyInitControlFlowInfo ): VariableControlFlowState? { val state = map.getOrNull(variableDescriptor ?: return null) if (state != null) return state @@ -1024,26 +1017,27 @@ class ControlFlowInformationProvider private constructor( } private inner class VariableUseContext( - instruction: Instruction, - map: MutableMap> + instruction: Instruction, + map: MutableMap> ) : VariableContext(instruction, map) companion object { // Should return KtDeclarationWithBody, KtClassOrObject, or KtClassInitializer fun getElementParentDeclaration(element: KtElement) = - getParentOfType(element, KtDeclarationWithBody::class.java, KtClassOrObject::class.java, KtClassInitializer::class.java) + getParentOfType(element, KtDeclarationWithBody::class.java, KtClassOrObject::class.java, KtClassInitializer::class.java) fun getDeclarationDescriptorIncludingConstructors(context: BindingContext, declaration: KtDeclaration?): DeclarationDescriptor? { - val descriptor = context.get(DECLARATION_TO_DESCRIPTOR, - (declaration as? KtClassInitializer)?.containingDeclaration ?: declaration) + val descriptor = context.get( + DECLARATION_TO_DESCRIPTOR, + (declaration as? KtClassInitializer)?.containingDeclaration ?: declaration + ) return if (descriptor is ClassDescriptor && declaration is KtClassInitializer) { // For a class primary constructor, we cannot directly get ConstructorDescriptor by KtClassInitializer, // so we have to do additional conversion: KtClassInitializer -> KtClassOrObject -> ClassDescriptor -> ConstructorDescriptor descriptor.unsubstitutedPrimaryConstructor - ?: (descriptor as? ClassDescriptorWithResolutionScopes)?.scopeForInitializerResolution?.ownerDescriptor - } - else { + ?: (descriptor as? ClassDescriptorWithResolutionScopes)?.scopeForInitializerResolution?.ownerDescriptor + } else { descriptor } } @@ -1069,8 +1063,8 @@ class ControlFlowInformationProvider private constructor( } private fun collectResultingExpressionsOfConditionalExpressionRec( - expression: KtExpression?, - resultingExpressions: MutableList + expression: KtExpression?, + resultingExpressions: MutableList ) { when (expression) { is KtIfExpression -> { @@ -1084,8 +1078,7 @@ class ControlFlowInformationProvider private constructor( val resultingExpression = getResultingExpression(expression) if (resultingExpression is KtIfExpression || resultingExpression is KtWhenExpression) { collectResultingExpressionsOfConditionalExpressionRec(resultingExpression, resultingExpressions) - } - else { + } else { resultingExpressions.add(resultingExpression) } } @@ -1106,8 +1099,7 @@ class ControlFlowInformationProvider private constructor( private fun combineKinds(kind: TailRecursionKind, existingKind: TailRecursionKind?): TailRecursionKind { return if (existingKind == null || existingKind == kind) { kind - } - else { + } else { when { check(kind, existingKind, IN_TRY, TAIL_CALL) -> IN_TRY check(kind, existingKind, IN_TRY, NON_TAIL) -> IN_TRY @@ -1119,9 +1111,9 @@ class ControlFlowInformationProvider private constructor( private fun check(a: Any, b: Any, x: Any, y: Any) = a === x && b === y || a === y && b === x private fun mustBeReportedOnAllCopies(diagnosticFactory: DiagnosticFactory<*>) = - diagnosticFactory === UNUSED_VARIABLE - || diagnosticFactory === UNUSED_PARAMETER - || diagnosticFactory === UNUSED_ANONYMOUS_PARAMETER - || diagnosticFactory === UNUSED_CHANGED_VALUE + diagnosticFactory === UNUSED_VARIABLE + || diagnosticFactory === UNUSED_PARAMETER + || diagnosticFactory === UNUSED_ANONYMOUS_PARAMETER + || diagnosticFactory === UNUSED_CHANGED_VALUE } -} +} \ No newline at end of file diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowProcessor.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowProcessor.kt index 5e3469d4965..783384069c0 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowProcessor.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowProcessor.kt @@ -88,8 +88,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) { generateImplicitReturnValue(bodyExpression, subroutine) } } - } - else { + } else { cfpVisitor.generateInstructions(subroutine) } return builder.exitSubroutine(subroutine, invocationKind) @@ -130,7 +129,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) { private val conditionVisitor = object : KtVisitorVoid() { private fun getSubjectExpression(condition: KtWhenCondition): KtExpression? = - condition.getStrictParentOfType()?.subjectExpression + condition.getStrictParentOfType()?.subjectExpression override fun visitWhenConditionInRange(condition: KtWhenConditionInRange) { if (!generateCall(condition.operationReference)) { @@ -155,8 +154,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) { if (subjectExpression != null) { // todo: this can be replaced by equals() invocation (when corresponding resolved call is recorded) createNonSyntheticValue(condition, MagicKind.EQUALS_IN_WHEN_CONDITION, subjectExpression, expression) - } - else { + } else { copyValue(expression, condition) } } @@ -193,13 +191,13 @@ class ControlFlowProcessor(private val trace: BindingTrace) { } private fun createSyntheticValue(instructionElement: KtElement, kind: MagicKind, vararg from: KtElement): PseudoValue = - builder.magic(instructionElement, null, elementsToValues(from.asList()), kind).outputValue + builder.magic(instructionElement, null, elementsToValues(from.asList()), kind).outputValue private fun createNonSyntheticValue(to: KtElement, from: List, kind: MagicKind): PseudoValue = - builder.magic(to, to, elementsToValues(from), kind).outputValue + builder.magic(to, to, elementsToValues(from), kind).outputValue private fun createNonSyntheticValue(to: KtElement, kind: MagicKind, vararg from: KtElement?): PseudoValue = - createNonSyntheticValue(to, from.asList(), kind) + createNonSyntheticValue(to, from.asList(), kind) private fun mergeValues(from: List, to: KtExpression) { builder.merge(to, elementsToValues(from)) @@ -217,14 +215,14 @@ class ControlFlowProcessor(private val trace: BindingTrace) { } private fun elementsToValues(from: List): List = - from.mapNotNull { element -> getBoundOrUnreachableValue(element) } + from.mapNotNull { element -> getBoundOrUnreachableValue(element) } private fun generateInitializer(declaration: KtDeclaration, initValue: PseudoValue) { builder.write(declaration, declaration, initValue, getDeclarationAccessTarget(declaration), emptyMap()) } private fun getResolvedCallAccessTarget(element: KtElement?): AccessTarget = - element.getResolvedCall(trace.bindingContext)?.let { AccessTarget.Call(it) } + element.getResolvedCall(trace.bindingContext)?.let { AccessTarget.Call(it) } ?: AccessTarget.BlackBox private fun getDeclarationAccessTarget(element: KtElement): AccessTarget { @@ -276,8 +274,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) { val resolvedCall = expression.getResolvedCall(trace.bindingContext) if (resolvedCall is VariableAsFunctionResolvedCall) { generateCall(resolvedCall.variableCall) - } - else { + } else { if (resolvedCall == null) { val qualifier = trace.bindingContext[BindingContext.QUALIFIER, expression] if (qualifier != null && generateQualifier(expression, qualifier)) return @@ -305,11 +302,9 @@ class ControlFlowProcessor(private val trace: BindingTrace) { val right = expression.right if (operationType === ANDAND || operationType === OROR) { generateBooleanOperation(expression) - } - else if (operationType === EQ) { + } else if (operationType === EQ) { visitAssignment(left, getDeferredValue(right), expression) - } - else if (OperatorConventions.ASSIGNMENT_OPERATIONS.containsKey(operationType)) { + } else if (OperatorConventions.ASSIGNMENT_OPERATIONS.containsKey(operationType)) { val resolvedCall = expression.getResolvedCall(trace.bindingContext) if (resolvedCall != null) { val rhsValue = generateCall(resolvedCall).outputValue @@ -321,12 +316,10 @@ class ControlFlowProcessor(private val trace: BindingTrace) { */ visitAssignment(left, getValueAsFunction(rhsValue), expression) } - } - else { + } else { generateBothArgumentsAndMark(expression) } - } - else if (operationType === ELVIS) { + } else if (operationType === ELVIS) { generateInstructions(left) mark(expression) val afterElvis = builder.createUnboundLabel("after elvis operator") @@ -334,8 +327,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) { generateInstructions(right) builder.bindLabel(afterElvis) mergeValues(listOf(left, right).filterNotNull(), expression) - } - else { + } else { if (!generateCall(expression)) { generateBothArgumentsAndMark(expression) } @@ -351,8 +343,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) { generateInstructions(left) if (operationType === ANDAND) { builder.jumpOnFalse(resultLabel, expression, builder.getBoundValue(left)) - } - else { + } else { builder.jumpOnTrue(resultLabel, expression, builder.getBoundValue(left)) } generateInstructions(right) @@ -382,9 +373,9 @@ class ControlFlowProcessor(private val trace: BindingTrace) { } private fun visitAssignment( - lhs: KtExpression?, - rhsDeferredValue: () -> PseudoValue?, - parentExpression: KtExpression + lhs: KtExpression?, + rhsDeferredValue: () -> PseudoValue?, + parentExpression: KtExpression ) { val left = KtPsiUtil.deparenthesize(lhs) if (left == null) { @@ -405,8 +396,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) { if (accessTarget is AccessTarget.Call) { receiverValues = getReceiverValues(accessTarget.resolvedCall) } - } - else if (left is KtProperty) { + } else if (left is KtProperty) { accessTarget = getDeclarationAccessTarget(left) } @@ -421,9 +411,9 @@ class ControlFlowProcessor(private val trace: BindingTrace) { } private fun generateArrayAssignment( - lhs: KtArrayAccessExpression, - rhsDeferredValue: () -> PseudoValue?, - parentExpression: KtExpression + lhs: KtArrayAccessExpression, + rhsDeferredValue: () -> PseudoValue?, + parentExpression: KtExpression ) { val setResolvedCall = trace.get(BindingContext.INDEXED_LVALUE_SET, lhs) @@ -456,11 +446,11 @@ class ControlFlowProcessor(private val trace: BindingTrace) { * we first generate instructions for 1 and 2 whereas 3 is replaced by pseudo-value corresponding to "a.get(1) + 3" */ private fun getArraySetterArguments( - rhsDeferredValue: () -> PseudoValue?, - setResolvedCall: ResolvedCall + rhsDeferredValue: () -> PseudoValue?, + setResolvedCall: ResolvedCall ): SmartFMap { val valueArguments = setResolvedCall.resultingDescriptor.valueParameters.flatMapTo( - ArrayList() + ArrayList() ) { descriptor -> setResolvedCall.valueArguments[descriptor]?.arguments ?: emptyList() } val rhsArgument = valueArguments.lastOrNull() @@ -470,8 +460,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) { val parameterDescriptor = argumentMapping.valueParameter if (valueArgument !== rhsArgument) { argumentValues = generateValueArgument(valueArgument, parameterDescriptor, argumentValues) - } - else { + } else { val rhsValue = rhsDeferredValue.invoke() if (rhsValue != null) { argumentValues = argumentValues.plus(rhsValue, parameterDescriptor) @@ -525,8 +514,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) { val rhsValue: PseudoValue? = if (resolvedCall != null) { generateCall(resolvedCall).outputValue - } - else { + } else { generateInstructions(baseExpression) createNonSyntheticValue(expression, MagicKind.UNRESOLVED_CALL, baseExpression) } @@ -540,7 +528,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) { } private fun isIncrementOrDecrement(operationType: IElementType): Boolean = - operationType === KtTokens.PLUSPLUS || operationType === KtTokens.MINUSMINUS + operationType === KtTokens.PLUSPLUS || operationType === KtTokens.MINUSMINUS override fun visitIfExpression(expression: KtIfExpression) { mark(expression) @@ -553,8 +541,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) { if (thenBranch != null) { branches.add(thenBranch) generateInstructions(thenBranch) - } - else { + } else { builder.loadUnit(expression) } val resultLabel = builder.createUnboundLabel("'if' expression result") @@ -564,8 +551,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) { if (elseBranch != null) { branches.add(elseBranch) generateInstructions(elseBranch) - } - else { + } else { builder.loadUnit(expression) } builder.bindLabel(resultLabel) @@ -684,8 +670,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) { builder.enterBlockScope(catchClause) if (!isFirst) { builder.bindLabel(catchLabels.remove()) - } - else { + } else { isFirst = false } val catchParameter = catchClause.catchParameter @@ -713,8 +698,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) { mark(expression) if (!CompileTimeConstantUtils.canBeReducedToBooleanConstant(condition, trace.bindingContext, true)) { builder.jumpOnFalse(loopInfo.exitPoint, expression, builder.getBoundValue(condition)) - } - else { + } else { assert(condition != null) { "Invalid while condition: " + expression.text } createSyntheticValue(condition!!, MagicKind.VALUE_CONSUMER, condition) } @@ -741,8 +725,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) { builder.exitBlockScope(expression) if (!CompileTimeConstantUtils.canBeReducedToBooleanConstant(condition, trace.bindingContext, true)) { builder.jumpOnTrue(loopInfo.entryPoint, expression, builder.getBoundValue(expression.condition)) - } - else { + } else { assert(condition != null) { "Invalid do / while condition: " + expression.text } createSyntheticValue(condition!!, MagicKind.VALUE_CONSUMER, condition) builder.jump(loopInfo.entryPoint, expression) @@ -781,8 +764,8 @@ class ControlFlowProcessor(private val trace: BindingTrace) { } private fun generateLoopConventionCall( - loopRange: KtExpression?, - callSlice: ReadOnlySlice> + loopRange: KtExpression?, + callSlice: ReadOnlySlice> ) { if (loopRange == null) return val resolvedCall = trace.bindingContext[callSlice, loopRange] ?: return @@ -795,8 +778,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) { val destructuringDeclaration = loopParameter.destructuringDeclaration if (destructuringDeclaration != null) { visitDestructuringDeclaration(destructuringDeclaration, false) - } - else { + } else { builder.declareParameter(loopParameter) } } @@ -807,10 +789,10 @@ class ControlFlowProcessor(private val trace: BindingTrace) { val loopRange = expression.loopRange val value = builder.magic( - loopRange ?: expression, - null, - ContainerUtil.createMaybeSingletonList(builder.getBoundValue(loopRange)), - MagicKind.LOOP_RANGE_ITERATION + loopRange ?: expression, + null, + ContainerUtil.createMaybeSingletonList(builder.getBoundValue(loopRange)), + MagicKind.LOOP_RANGE_ITERATION ).outputValue if (loopParameter != null) { @@ -819,8 +801,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) { for (entry in destructuringDeclaration.entries) { generateInitializer(entry, value) } - } - else { + } else { generateInitializer(loopParameter, value) } } @@ -857,8 +838,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) { val parentBody = parentLoop.body return if (parentBody != null && parentBody.textRange.contains(expression.textRange)) { parentLoop - } - else { + } else { getNearestLoopExpression(parentLoop) } } @@ -871,20 +851,19 @@ class ControlFlowProcessor(private val trace: BindingTrace) { val labeledElement = trace.get(BindingContext.LABEL_TARGET, targetLabel) loop = if (labeledElement is KtLoopExpression) { labeledElement - } - else { + } else { trace.report(NOT_A_LOOP_LABEL.on(expression, targetLabel.text)) null } - } - else { + } else { loop = getCorrespondingLoopWithoutLabel(expression) if (loop == null) { trace.report(BREAK_OR_CONTINUE_OUTSIDE_A_LOOP.on(expression)) - } - else { - val whenExpression = PsiTreeUtil.getParentOfType(expression, KtWhenExpression::class.java, true, - KtLoopExpression::class.java) + } else { + val whenExpression = PsiTreeUtil.getParentOfType( + expression, KtWhenExpression::class.java, true, + KtLoopExpression::class.java + ) if (whenExpression != null) { trace.report(BREAK_OR_CONTINUE_IN_WHEN.on(expression)) } @@ -931,8 +910,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) { trace.report(BREAK_OR_CONTINUE_JUMPS_ACROSS_FUNCTION_BOUNDARY.on(jumpExpression)) } false - } - else { + } else { true } } @@ -953,12 +931,10 @@ class ControlFlowProcessor(private val trace: BindingTrace) { if (labeledElement != null) { assert(labeledElement is KtElement) labeledElement as KtElement? - } - else { + } else { null } - } - else { + } else { builder.returnSubroutine // TODO : a context check } @@ -967,12 +943,10 @@ class ControlFlowProcessor(private val trace: BindingTrace) { val returnValue = if (returnedExpression != null) builder.getBoundValue(returnedExpression) else null if (returnValue == null) { builder.returnNoValue(expression, subroutine) - } - else { + } else { builder.returnValue(expression, returnValue, subroutine) } - } - else { + } else { createNonSyntheticValue(expression, MagicKind.UNSUPPORTED_ELEMENT, returnedExpression) } } @@ -1018,8 +992,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) { } if (statements.isEmpty()) { builder.loadUnit(expression) - } - else { + } else { copyValue(statements.lastOrNull(), expression) } if (declareBlockScope) { @@ -1035,8 +1008,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) { private fun visitFunction(function: KtFunction, invocationKind: InvocationKind? = null) { if (invocationKind == null) { processLocalDeclaration(function) - } - else { + } else { visitInlinedFunction(function, invocationKind) } @@ -1093,16 +1065,14 @@ class ControlFlowProcessor(private val trace: BindingTrace) { if (selectorExpression is KtCallExpression || selectorExpression is KtSimpleNameExpression) { if (!safe) { generateInstructions(selectorExpression) - } - else { + } else { val resultLabel = builder.createUnboundLabel("result of call") builder.jumpOnFalse(resultLabel, expression, null) generateInstructions(selectorExpression) builder.bindLabel(resultLabel) } copyValue(selectorExpression, expression) - } - else { + } else { generateInstructions(receiverExpression) createNonSyntheticValue(expression, MagicKind.UNSUPPORTED_ELEMENT, receiverExpression) } @@ -1182,12 +1152,12 @@ class ControlFlowProcessor(private val trace: BindingTrace) { val writtenValue: PseudoValue? writtenValue = if (resolvedCall != null) { builder.call( - entry, - resolvedCall, - getReceiverValues(resolvedCall), - emptyMap()).outputValue - } - else { + entry, + resolvedCall, + getReceiverValues(resolvedCall), + emptyMap() + ).outputValue + } else { initializer?.let { createSyntheticValue(entry, MagicKind.UNRESOLVED_CALL, it) } } @@ -1211,8 +1181,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) { if (getBoundOrUnreachableValue(left) != null) { createNonSyntheticValue(expression, MagicKind.CAST, left) } - } - else { + } else { visitKtElement(expression) createNonSyntheticValue(expression, MagicKind.UNSUPPORTED_ELEMENT, left) } @@ -1376,8 +1345,10 @@ class ControlFlowProcessor(private val trace: BindingTrace) { val classDescriptor = trace[BindingContext.DECLARATION_TO_DESCRIPTOR, entryOrObject] if (classDescriptor is ClassDescriptor) { builder.declareEntryOrObject(entryOrObject) - builder.write(entryOrObject, entryOrObject, createSyntheticValue(entryOrObject, MagicKind.FAKE_INITIALIZER), - AccessTarget.Declaration(FakeCallableDescriptorForObject(classDescriptor)), emptyMap()) + builder.write( + entryOrObject, entryOrObject, createSyntheticValue(entryOrObject, MagicKind.FAKE_INITIALIZER), + AccessTarget.Declaration(FakeCallableDescriptorForObject(classDescriptor)), emptyMap() + ) generateInstructions(entryOrObject) } } @@ -1431,7 +1402,8 @@ class ControlFlowProcessor(private val trace: BindingTrace) { } override fun visitSecondaryConstructor(constructor: KtSecondaryConstructor) { - val classOrObject = PsiTreeUtil.getParentOfType(constructor, KtClassOrObject::class.java) ?: error("Guaranteed by parsing contract") + val classOrObject = + PsiTreeUtil.getParentOfType(constructor, KtClassOrObject::class.java) ?: error("Guaranteed by parsing contract") processParameters(constructor.valueParameters) generateCallOrMarkUnresolved(constructor.getDelegationCall()) @@ -1493,8 +1465,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) { trace.bindingContext.get(BindingContext.DOUBLE_COLON_LHS, receiverExpression) is DoubleColonLHS.Expression) { generateInstructions(receiverExpression) createNonSyntheticValue(expression, MagicKind.BOUND_CALLABLE_REFERENCE, receiverExpression) - } - else { + } else { createNonSyntheticValue(expression, MagicKind.UNBOUND_CALLABLE_REFERENCE) } } @@ -1541,8 +1512,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) { val argumentExpression = argument.getArgumentExpression() if (argumentMapping is ArgumentMatch) { parameterValues = generateValueArgument(argument, argumentMapping.valueParameter, parameterValues) - } - else if (argumentExpression != null) { + } else if (argumentExpression != null) { generateInstructions(argumentExpression) createSyntheticValue(argumentExpression, MagicKind.VALUE_CONSUMER, argumentExpression) } @@ -1551,7 +1521,8 @@ class ControlFlowProcessor(private val trace: BindingTrace) { if (resolvedCall.resultingDescriptor is VariableDescriptor) { // If a callee of the call is just a variable (without 'invoke'), 'read variable' is generated. // todo : process arguments for such a case (KT-5387) - val callExpression = callElement as? KtExpression ?: error("Variable-based call without callee expression: " + callElement.text) + val callExpression = + callElement as? KtExpression ?: error("Variable-based call without callee expression: " + callElement.text) assert(parameterValues.isEmpty()) { "Variable-based call with non-empty argument list: " + callElement.text } return builder.readVariable(callExpression, resolvedCall, receivers) } @@ -1589,9 +1560,9 @@ class ControlFlowProcessor(private val trace: BindingTrace) { } private fun getReceiverValues( - callElement: KtElement, - receiver: ReceiverValue?, - receiverValuesArg: SmartFMap + callElement: KtElement, + receiver: ReceiverValue?, + receiverValuesArg: SmartFMap ): SmartFMap { var receiverValues = receiverValuesArg if (receiver == null || receiverValues.containsValue(receiver)) return receiverValues @@ -1633,9 +1604,9 @@ class ControlFlowProcessor(private val trace: BindingTrace) { } private fun generateValueArgument( - valueArgument: ValueArgument, - parameterDescriptor: ValueParameterDescriptor, - parameterValuesArg: SmartFMap + valueArgument: ValueArgument, + parameterDescriptor: ValueParameterDescriptor, + parameterValuesArg: SmartFMap ): SmartFMap { var parameterValues = parameterValuesArg val expression = valueArgument.getArgumentExpression() @@ -1652,4 +1623,4 @@ class ControlFlowProcessor(private val trace: BindingTrace) { return parameterValues } } -} +} \ No newline at end of file diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/LoopInfo.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/LoopInfo.kt index de3f1ca789a..78c55b2dc02 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/LoopInfo.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/LoopInfo.kt @@ -19,12 +19,12 @@ package org.jetbrains.kotlin.cfg import org.jetbrains.kotlin.psi.KtLoopExpression class LoopInfo( - override val element: KtLoopExpression, - entryPoint: Label, - exitPoint: Label, - val bodyEntryPoint: Label, - val bodyExitPoint: Label, - val conditionEntryPoint: Label + override val element: KtLoopExpression, + entryPoint: Label, + exitPoint: Label, + val bodyEntryPoint: Label, + val bodyExitPoint: Label, + val conditionEntryPoint: Label ) : BreakableBlockInfo(element, entryPoint, exitPoint) { init { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/PseudocodeTraverser.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/PseudocodeTraverser.kt index 5d066880518..536656a2ecc 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/PseudocodeTraverser.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/PseudocodeTraverser.kt @@ -27,8 +27,8 @@ import org.jetbrains.kotlin.cfg.pseudocodeTraverser.TraversalOrder.FORWARD import java.util.* fun Pseudocode.traverse( - traversalOrder: TraversalOrder, - analyzeInstruction: (Instruction) -> Unit + traversalOrder: TraversalOrder, + analyzeInstruction: (Instruction) -> Unit ) { val instructions = getInstructions(traversalOrder) for (instruction in instructions) { @@ -40,9 +40,9 @@ fun Pseudocode.traverse( } fun Pseudocode.traverse( - traversalOrder: TraversalOrder, - edgesMap: Map>, - analyzeInstruction: (Instruction, D, D) -> Unit + traversalOrder: TraversalOrder, + edgesMap: Map>, + analyzeInstruction: (Instruction, D, D) -> Unit ) { val instructions = getInstructions(traversalOrder) for (instruction in instructions) { @@ -57,10 +57,10 @@ fun Pseudocode.traverse( } fun > Pseudocode.collectData( - traversalOrder: TraversalOrder, - mergeEdges: (Instruction, Collection) -> Edges, - updateEdge: (Instruction, Instruction, I) -> I, - initialInfo: I + traversalOrder: TraversalOrder, + mergeEdges: (Instruction, Collection) -> Edges, + updateEdge: (Instruction, Instruction, I) -> I, + initialInfo: I ): Map> { val edgesMap = LinkedHashMap>() edgesMap.put(getStartInstruction(traversalOrder), Edges(initialInfo, initialInfo)) @@ -68,21 +68,22 @@ fun > Pseudocode.collectData( val changed = mutableMapOf() do { collectDataFromSubgraph( - traversalOrder, edgesMap, - mergeEdges, updateEdge, Collections.emptyList(), changed, false) + traversalOrder, edgesMap, + mergeEdges, updateEdge, Collections.emptyList(), changed, false + ) } while (changed.any { it.value }) return edgesMap } private fun > Pseudocode.collectDataFromSubgraph( - traversalOrder: TraversalOrder, - edgesMap: MutableMap>, - mergeEdges: (Instruction, Collection) -> Edges, - updateEdge: (Instruction, Instruction, I) -> I, - previousSubGraphInstructions: Collection, - changed: MutableMap, - isLocal: Boolean + traversalOrder: TraversalOrder, + edgesMap: MutableMap>, + mergeEdges: (Instruction, Collection) -> Edges, + updateEdge: (Instruction, Instruction, I) -> I, + previousSubGraphInstructions: Collection, + changed: MutableMap, + isLocal: Boolean ) { val instructions = getInstructions(traversalOrder) val startInstruction = getStartInstruction(traversalOrder) @@ -92,12 +93,13 @@ private fun > Pseudocode.collectDataFromSubgraph( if (!isLocal && isStart) continue - val previousInstructions = getPreviousIncludingSubGraphInstructions(instruction, traversalOrder, startInstruction, previousSubGraphInstructions) + val previousInstructions = + getPreviousIncludingSubGraphInstructions(instruction, traversalOrder, startInstruction, previousSubGraphInstructions) if (instruction is LocalFunctionDeclarationInstruction) { val subroutinePseudocode = instruction.body subroutinePseudocode.collectDataFromSubgraph( - traversalOrder, edgesMap, mergeEdges, updateEdge, previousInstructions, changed, true + traversalOrder, edgesMap, mergeEdges, updateEdge, previousInstructions, changed, true ) // Special case for inlined functions: take flow from EXIT instructions (it contains flow which exits declaration normally) val lastInstruction = if (instruction is InlinedLocalFunctionDeclarationInstruction && traversalOrder == FORWARD) @@ -125,8 +127,11 @@ private fun > Pseudocode.collectDataFromSubgraph( for (previousInstruction in previousInstructions) { val previousData = edgesMap[previousInstruction] if (previousData != null) { - incomingEdgesData.add(updateEdge( - previousInstruction, instruction, previousData.outgoing)) + incomingEdgesData.add( + updateEdge( + previousInstruction, instruction, previousData.outgoing + ) + ) } } val mergedData = mergeEdges(instruction, incomingEdgesData) @@ -135,10 +140,10 @@ private fun > Pseudocode.collectDataFromSubgraph( } private fun getPreviousIncludingSubGraphInstructions( - instruction: Instruction, - traversalOrder: TraversalOrder, - startInstruction: Instruction, - previousSubGraphInstructions: Collection + instruction: Instruction, + traversalOrder: TraversalOrder, + startInstruction: Instruction, + previousSubGraphInstructions: Collection ): Collection { val previous = instruction.getPreviousInstructions(traversalOrder) if (instruction != startInstruction || previousSubGraphInstructions.isEmpty()) { @@ -150,17 +155,16 @@ private fun getPreviousIncludingSubGraphInstructions( } private fun > updateEdgeDataForInstruction( - instruction: Instruction, - previousValue: Edges?, - newValue: Edges?, - edgesMap: MutableMap>, - changed: MutableMap + instruction: Instruction, + previousValue: Edges?, + newValue: Edges?, + edgesMap: MutableMap>, + changed: MutableMap ) { if (previousValue != newValue && newValue != null) { changed[instruction] = true edgesMap.put(instruction, newValue) - } - else { + } else { changed[instruction] = false } } @@ -175,11 +179,11 @@ enum class TraverseInstructionResult { // returns false when interrupted by handler fun traverseFollowingInstructions( - rootInstruction: Instruction, - visited: MutableSet = HashSet(), - order: TraversalOrder = FORWARD, - // true to continue traversal - handler: ((Instruction) -> TraverseInstructionResult)? + rootInstruction: Instruction, + visited: MutableSet = HashSet(), + order: TraversalOrder = FORWARD, + // true to continue traversal + handler: ((Instruction) -> TraverseInstructionResult)? ): Boolean { val stack = ArrayDeque() stack.push(rootInstruction) @@ -189,7 +193,8 @@ fun traverseFollowingInstructions( if (!visited.add(instruction)) continue when (handler?.let { it(instruction) } ?: TraverseInstructionResult.CONTINUE) { TraverseInstructionResult.CONTINUE -> instruction.getNextInstructions(order).forEach { stack.push(it) } - TraverseInstructionResult.SKIP -> {} + TraverseInstructionResult.SKIP -> { + } TraverseInstructionResult.HALT -> return false } } @@ -202,19 +207,19 @@ enum class TraversalOrder { } fun Pseudocode.getStartInstruction(traversalOrder: TraversalOrder): Instruction = - if (traversalOrder == FORWARD) enterInstruction else sinkInstruction + if (traversalOrder == FORWARD) enterInstruction else sinkInstruction fun Pseudocode.getLastInstruction(traversalOrder: TraversalOrder): Instruction = - if (traversalOrder == FORWARD) sinkInstruction else enterInstruction + if (traversalOrder == FORWARD) sinkInstruction else enterInstruction fun Pseudocode.getInstructions(traversalOrder: TraversalOrder): List = - if (traversalOrder == FORWARD) instructions else reversedInstructions + if (traversalOrder == FORWARD) instructions else reversedInstructions fun Instruction.getNextInstructions(traversalOrder: TraversalOrder): Collection = - if (traversalOrder == FORWARD) nextInstructions else previousInstructions + if (traversalOrder == FORWARD) nextInstructions else previousInstructions fun Instruction.getPreviousInstructions(traversalOrder: TraversalOrder): Collection = - if (traversalOrder == FORWARD) previousInstructions else nextInstructions + if (traversalOrder == FORWARD) previousInstructions else nextInstructions fun Instruction.isStartInstruction(traversalOrder: TraversalOrder): Boolean = - if (traversalOrder == FORWARD) this is SubroutineEnterInstruction else this is SubroutineSinkInstruction + if (traversalOrder == FORWARD) this is SubroutineEnterInstruction else this is SubroutineSinkInstruction diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/PseudoValueImpl.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/PseudoValueImpl.kt index 6b095cf3292..e29dd9b3f08 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/PseudoValueImpl.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/PseudoValueImpl.kt @@ -20,14 +20,14 @@ import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.cfg.pseudocode.instructions.eval.InstructionWithValue class PseudoValueImpl( - override val debugName: String, - override val element: KtElement?, - override val createdAt: InstructionWithValue? + override val debugName: String, + override val element: KtElement?, + override val createdAt: InstructionWithValue? ) : PseudoValue { override fun toString(): String = debugName } -open class PseudoValueFactoryImpl: PseudoValueFactory { +open class PseudoValueFactoryImpl : PseudoValueFactory { private var lastIndex: Int = 0 override fun newValue(element: KtElement?, instruction: InstructionWithValue?): PseudoValue { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/PseudocodeImpl.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/PseudocodeImpl.kt index 82647f1afaf..e90d62d4d18 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/PseudocodeImpl.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/PseudocodeImpl.kt @@ -109,7 +109,12 @@ class PseudocodeImpl(override val correspondingElement: KtElement, override val override val reversedInstructions: List get() { val traversedInstructions = linkedSetOf() - traverseFollowingInstructions(if (this.isInlined) instructions.last() else sinkInstruction, traversedInstructions, BACKWARD, null) + traverseFollowingInstructions( + if (this.isInlined) instructions.last() else sinkInstruction, + traversedInstructions, + BACKWARD, + null + ) if (traversedInstructions.size < instructions.size) { val simplyReversedInstructions = instructions.reversed() for (instruction in simplyReversedInstructions) { @@ -194,8 +199,8 @@ class PseudocodeImpl(override val correspondingElement: KtElement, override val fun bindLabel(label: PseudocodeLabel) { assert(this == label.pseudocode) { "Attempt to bind label $label to instruction from different pseudocode: " + - "\nowner pseudocode = ${label.pseudocode.mutableInstructionList}, " + - "\nbound pseudocode = ${this.mutableInstructionList}" + "\nowner pseudocode = ${label.pseudocode.mutableInstructionList}, " + + "\nbound pseudocode = ${this.mutableInstructionList}" } label.targetInstructionIndex = mutableInstructionList.size } @@ -214,7 +219,7 @@ class PseudocodeImpl(override val correspondingElement: KtElement, override val private fun addValueUsage(value: PseudoValue, usage: Instruction) { if (usage is MergeInstruction) return valueUsages.getOrPut( - value + value ) { arrayListOf() }.add(usage) } @@ -266,8 +271,7 @@ class PseudocodeImpl(override val correspondingElement: KtElement, override val if (instruction.onTrue) { instruction.nextOnFalse = nextInstruction instruction.nextOnTrue = jumpTarget - } - else { + } else { instruction.nextOnFalse = jumpTarget instruction.nextOnTrue = nextInstruction } @@ -286,7 +290,8 @@ class PseudocodeImpl(override val correspondingElement: KtElement, override val body.parent = this@PseudocodeImpl body.postProcess() // Don't add edge to next instruction if flow can't reach exit of inlined declaration - instruction.next = if (body.instructions.contains(body.exitInstruction)) getNextPosition(currentPosition) else sinkInstruction + instruction.next = + if (body.instructions.contains(body.exitInstruction)) getNextPosition(currentPosition) else sinkInstruction } override fun visitSubroutineExit(instruction: SubroutineExitInstruction) { @@ -305,7 +310,8 @@ class PseudocodeImpl(override val correspondingElement: KtElement, override val private fun collectReachableInstructions() { val reachableFromThisPseudocode = hashSetOf() - traverseFollowingInstructions(enterInstruction, reachableFromThisPseudocode, FORWARD + traverseFollowingInstructions( + enterInstruction, reachableFromThisPseudocode, FORWARD ) { instruction -> if (instruction is MagicInstruction && instruction.kind === MagicKind.EXHAUSTIVE_WHEN_ELSE) { return@traverseFollowingInstructions TraverseInstructionResult.SKIP @@ -358,12 +364,13 @@ class PseudocodeImpl(override val correspondingElement: KtElement, override val } fun repeatPart(startLabel: Label, finishLabel: Label, labelCount: Int): Int = - repeatInternal(startLabel.pseudocode as PseudocodeImpl, startLabel, finishLabel, labelCount) + repeatInternal(startLabel.pseudocode as PseudocodeImpl, startLabel, finishLabel, labelCount) private fun repeatInternal( - originalPseudocode: PseudocodeImpl, - startLabel: Label?, finishLabel: Label?, - labelCountArg: Int): Int { + originalPseudocode: PseudocodeImpl, + startLabel: Label?, finishLabel: Label?, + labelCountArg: Int + ): Int { var labelCount = labelCountArg val startIndex = startLabel?.targetInstructionIndex ?: 0 val finishIndex = finishLabel?.targetInstructionIndex ?: originalPseudocode.mutableInstructionList.size @@ -401,17 +408,20 @@ class PseudocodeImpl(override val correspondingElement: KtElement, override val } } if (finishIndex < originalPseudocode.mutableInstructionList.size) { - repeatLabelsBindingForInstruction(originalPseudocode.mutableInstructionList[finishIndex], - originalToCopy, - originalLabelsForInstruction) + repeatLabelsBindingForInstruction( + originalPseudocode.mutableInstructionList[finishIndex], + originalToCopy, + originalLabelsForInstruction + ) } return labelCount } private fun repeatLabelsBindingForInstruction( - originalInstruction: Instruction, - originalToCopy: Map, - originalLabelsForInstruction: Multimap) { + originalInstruction: Instruction, + originalToCopy: Map, + originalLabelsForInstruction: Multimap + ) { for (originalLabel in originalLabelsForInstruction.get(originalInstruction)) { bindLabel(originalToCopy[originalLabel]!!) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/PseudocodeLabel.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/PseudocodeLabel.kt index bab6e53952d..44a356cc29e 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/PseudocodeLabel.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/PseudocodeLabel.kt @@ -21,7 +21,7 @@ import org.jetbrains.kotlin.cfg.pseudocode.instructions.Instruction import org.jetbrains.kotlin.psi.KtElement class PseudocodeLabel internal constructor( - override val pseudocode: PseudocodeImpl, override val name: String, private val comment: String? + override val pseudocode: PseudocodeImpl, override val name: String, private val comment: String? ) : Label { private val instructionList: List get() = pseudocode.mutableInstructionList @@ -36,16 +36,20 @@ class PseudocodeLabel internal constructor( val index = targetInstructionIndex when { index < 0 -> - error("resolveToInstruction: unbound label $name " + - "in subroutine ${correspondingElement.text} with instructions $instructionList") + error( + "resolveToInstruction: unbound label $name " + + "in subroutine ${correspondingElement.text} with instructions $instructionList" + ) index >= instructionList.size -> - error("resolveToInstruction: incorrect index $index for label $name " + - "in subroutine ${correspondingElement.text} with instructions $instructionList") + error( + "resolveToInstruction: incorrect index $index for label $name " + + "in subroutine ${correspondingElement.text} with instructions $instructionList" + ) else -> return instructionList[index] } } fun copy(newPseudocode: PseudocodeImpl, newLabelIndex: Int): PseudocodeLabel = - PseudocodeLabel(newPseudocode, "L" + newLabelIndex, "copy of $name, $comment") + PseudocodeLabel(newPseudocode, "L" + newLabelIndex, "copy of $name, $comment") } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/InstructionImpl.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/InstructionImpl.kt index a002e4f8573..b6ae3789d8d 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/InstructionImpl.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/InstructionImpl.kt @@ -21,7 +21,7 @@ import java.util.LinkedHashSet import org.jetbrains.kotlin.cfg.pseudocode.Pseudocode import org.jetbrains.kotlin.cfg.pseudocode.PseudoValue -abstract class InstructionImpl(override val blockScope: BlockScope): Instruction { +abstract class InstructionImpl(override val blockScope: BlockScope) : Instruction { private var _owner: Pseudocode? = null override var owner: Pseudocode diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/InstructionVisitorWithResult.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/InstructionVisitorWithResult.kt index a5b9b96f947..e05c26802ea 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/InstructionVisitorWithResult.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/InstructionVisitorWithResult.kt @@ -28,10 +28,10 @@ abstract class InstructionVisitorWithResult { open fun visitReadValue(instruction: ReadValueInstruction): R = visitAccessInstruction(instruction) open fun visitLocalFunctionDeclarationInstruction(instruction: LocalFunctionDeclarationInstruction): R = - visitInstructionWithNext(instruction) + visitInstructionWithNext(instruction) open fun visitInlinedFunctionDeclarationInstruction(instruction: InlinedLocalFunctionDeclarationInstruction): R = - visitLocalFunctionDeclarationInstruction(instruction) + visitLocalFunctionDeclarationInstruction(instruction) open fun visitVariableDeclarationInstruction(instruction: VariableDeclarationInstruction): R = visitInstructionWithNext(instruction) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/InstructionWithNext.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/InstructionWithNext.kt index a1b55a822fc..1bdfe6a7fad 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/InstructionWithNext.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/InstructionWithNext.kt @@ -19,8 +19,8 @@ package org.jetbrains.kotlin.cfg.pseudocode.instructions import org.jetbrains.kotlin.psi.KtElement abstract class InstructionWithNext( - element: KtElement, - blockScope: BlockScope + element: KtElement, + blockScope: BlockScope ) : KtElementInstructionImpl(element, blockScope) { var next: Instruction? = null set(value) { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/KtElementInstructionImpl.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/KtElementInstructionImpl.kt index 776f0aaf638..20cba34fe18 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/KtElementInstructionImpl.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/KtElementInstructionImpl.kt @@ -20,9 +20,9 @@ import com.intellij.psi.PsiElement import org.jetbrains.kotlin.psi.KtElement abstract class KtElementInstructionImpl( - override val element: KtElement, - blockScope: BlockScope + override val element: KtElement, + blockScope: BlockScope ) : InstructionImpl(blockScope), KtElementInstruction { protected fun render(element: PsiElement): String = - element.text?.replace("\\s+".toRegex(), " ") ?: "" + element.text?.replace("\\s+".toRegex(), " ") ?: "" } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/eval/InstructionWithReceivers.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/eval/InstructionWithReceivers.kt index da5145dcdfc..c2320012ffe 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/eval/InstructionWithReceivers.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/eval/InstructionWithReceivers.kt @@ -20,6 +20,6 @@ import org.jetbrains.kotlin.cfg.pseudocode.PseudoValue import org.jetbrains.kotlin.cfg.pseudocode.instructions.Instruction import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue -interface InstructionWithReceivers: Instruction { +interface InstructionWithReceivers : Instruction { val receiverValues: Map } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/eval/LoadUnitValueInstruction.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/eval/LoadUnitValueInstruction.kt index 1dbe370ff82..bac9a8009e6 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/eval/LoadUnitValueInstruction.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/eval/LoadUnitValueInstruction.kt @@ -24,8 +24,8 @@ import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionImpl import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionVisitorWithResult class LoadUnitValueInstruction( - expression: KtExpression, - blockScope: BlockScope + expression: KtExpression, + blockScope: BlockScope ) : InstructionWithNext(expression, blockScope) { override fun accept(visitor: InstructionVisitor) { visitor.visitLoadUnitValue(this) @@ -36,8 +36,8 @@ class LoadUnitValueInstruction( } override fun toString(): String = - "read (Unit)" + "read (Unit)" override fun createCopy(): InstructionImpl = - LoadUnitValueInstruction(element as KtExpression, blockScope) + LoadUnitValueInstruction(element as KtExpression, blockScope) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/eval/accessInstructions.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/eval/accessInstructions.kt index e5d9cc3fdcd..9a74ccd8326 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/eval/accessInstructions.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/eval/accessInstructions.kt @@ -27,17 +27,19 @@ import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue sealed class AccessTarget { - class Declaration(val descriptor: VariableDescriptor): AccessTarget() { + class Declaration(val descriptor: VariableDescriptor) : AccessTarget() { override fun equals(other: Any?) = other is Declaration && descriptor == other.descriptor override fun hashCode() = descriptor.hashCode() } - class Call(val resolvedCall: ResolvedCall<*>): AccessTarget() { + + class Call(val resolvedCall: ResolvedCall<*>) : AccessTarget() { override fun equals(other: Any?) = other is Call && resolvedCall == other.resolvedCall override fun hashCode() = resolvedCall.hashCode() } - object BlackBox: AccessTarget() + + object BlackBox : AccessTarget() } val AccessTarget.accessedDescriptor: CallableDescriptor? @@ -48,26 +50,26 @@ val AccessTarget.accessedDescriptor: CallableDescriptor? } abstract class AccessValueInstruction protected constructor( - element: KtElement, - blockScope: BlockScope, - val target: AccessTarget, - override val receiverValues: Map + element: KtElement, + blockScope: BlockScope, + val target: AccessTarget, + override val receiverValues: Map ) : InstructionWithNext(element, blockScope), InstructionWithReceivers class ReadValueInstruction private constructor( + element: KtElement, + blockScope: BlockScope, + target: AccessTarget, + receiverValues: Map, + private var _outputValue: PseudoValue? +) : AccessValueInstruction(element, blockScope, target, receiverValues), InstructionWithValue { + constructor( element: KtElement, blockScope: BlockScope, target: AccessTarget, receiverValues: Map, - private var _outputValue: PseudoValue? -) : AccessValueInstruction(element, blockScope, target, receiverValues), InstructionWithValue { - constructor( - element: KtElement, - blockScope: BlockScope, - target: AccessTarget, - receiverValues: Map, - factory: PseudoValueFactory - ): this(element, blockScope, target, receiverValues, null) { + factory: PseudoValueFactory + ) : this(element, blockScope, target, receiverValues, null) { _outputValue = factory.newValue(element, this) } @@ -97,16 +99,16 @@ class ReadValueInstruction private constructor( } override fun createCopy(): InstructionImpl = - ReadValueInstruction(element, blockScope, target, receiverValues, outputValue) + ReadValueInstruction(element, blockScope, target, receiverValues, outputValue) } class WriteValueInstruction( - assignment: KtElement, - blockScope: BlockScope, - target: AccessTarget, - receiverValues: Map, - val lValue: KtElement, - private val rValue: PseudoValue + assignment: KtElement, + blockScope: BlockScope, + target: AccessTarget, + receiverValues: Map, + val lValue: KtElement, + private val rValue: PseudoValue ) : AccessValueInstruction(assignment, blockScope, target, receiverValues) { override val inputValues: List get() = (receiverValues.keys as Collection) + rValue @@ -123,5 +125,5 @@ class WriteValueInstruction( } override fun createCopy(): InstructionImpl = - WriteValueInstruction(element, blockScope, target, receiverValues, lValue, rValue) + WriteValueInstruction(element, blockScope, target, receiverValues, lValue, rValue) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/eval/operationInstructions.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/eval/operationInstructions.kt index efdbee85095..b0899fdfb65 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/eval/operationInstructions.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/eval/operationInstructions.kt @@ -28,9 +28,9 @@ import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue abstract class OperationInstruction protected constructor( - element: KtElement, - blockScope: BlockScope, - override val inputValues: List + element: KtElement, + blockScope: BlockScope, + override val inputValues: List ) : InstructionWithNext(element, blockScope), InstructionWithValue { protected var resultValue: PseudoValue? = null @@ -38,9 +38,9 @@ abstract class OperationInstruction protected constructor( get() = resultValue protected fun renderInstruction(name: String, desc: String): String = - "$name($desc" + - (if (inputValues.isNotEmpty()) "|${inputValues.joinToString(", ")})" else ")") + - (if (resultValue != null) " -> $resultValue" else "") + "$name($desc" + + (if (inputValues.isNotEmpty()) "|${inputValues.joinToString(", ")})" else ")") + + (if (resultValue != null) " -> $resultValue" else "") protected fun setResult(value: PseudoValue?): OperationInstruction { this.resultValue = value @@ -48,25 +48,25 @@ abstract class OperationInstruction protected constructor( } protected fun setResult(factory: PseudoValueFactory?, valueElement: KtElement? = element): OperationInstruction = - setResult(factory?.newValue(valueElement, this)) + setResult(factory?.newValue(valueElement, this)) } class CallInstruction private constructor( - element: KtElement, - blockScope: BlockScope, - val resolvedCall: ResolvedCall<*>, - override val receiverValues: Map, - val arguments: Map + element: KtElement, + blockScope: BlockScope, + val resolvedCall: ResolvedCall<*>, + override val receiverValues: Map, + val arguments: Map ) : OperationInstruction(element, blockScope, (receiverValues.keys as Collection) + arguments.keys), InstructionWithReceivers { constructor ( - element: KtElement, - blockScope: BlockScope, - resolvedCall: ResolvedCall<*>, - receiverValues: Map, - arguments: Map, - factory: PseudoValueFactory? - ): this(element, blockScope, resolvedCall, receiverValues, arguments) { + element: KtElement, + blockScope: BlockScope, + resolvedCall: ResolvedCall<*>, + receiverValues: Map, + arguments: Map, + factory: PseudoValueFactory? + ) : this(element, blockScope, resolvedCall, receiverValues, arguments) { setResult(factory) } @@ -77,10 +77,10 @@ class CallInstruction private constructor( override fun accept(visitor: InstructionVisitorWithResult): R = visitor.visitCallInstruction(this) override fun createCopy() = - CallInstruction(element, blockScope, resolvedCall, receiverValues, arguments).setResult(resultValue) + CallInstruction(element, blockScope, resolvedCall, receiverValues, arguments).setResult(resultValue) override fun toString() = - renderInstruction("call", "${render(element)}, ${resolvedCall.resultingDescriptor!!.name}") + renderInstruction("call", "${render(element)}, ${resolvedCall.resultingDescriptor!!.name}") } // Introduces black-box operation @@ -89,19 +89,19 @@ class CallInstruction private constructor( // denote value transformation which can't be expressed by other instructions (such as call or read) // pass more than one value to instruction which formally requires only one (e.g. jump) class MagicInstruction( - element: KtElement, - blockScope: BlockScope, - inputValues: List, - val kind: MagicKind + element: KtElement, + blockScope: BlockScope, + inputValues: List, + val kind: MagicKind ) : OperationInstruction(element, blockScope, inputValues) { constructor ( - element: KtElement, - valueElement: KtElement?, - blockScope: BlockScope, - inputValues: List, - kind: MagicKind, - factory: PseudoValueFactory - ): this(element, blockScope, inputValues, kind) { + element: KtElement, + valueElement: KtElement?, + blockScope: BlockScope, + inputValues: List, + kind: MagicKind, + factory: PseudoValueFactory + ) : this(element, blockScope, inputValues, kind) { setResult(factory, valueElement) } @@ -115,7 +115,7 @@ class MagicInstruction( override fun accept(visitor: InstructionVisitorWithResult): R = visitor.visitMagic(this) override fun createCopy() = - MagicInstruction(element, blockScope, inputValues, kind).setResult(resultValue) + MagicInstruction(element, blockScope, inputValues, kind).setResult(resultValue) override fun toString() = renderInstruction("magic[$kind]", render(element)) } @@ -145,16 +145,16 @@ enum class MagicKind(val sideEffectFree: Boolean = false) { // Merges values produced by alternative control-flow paths (such as 'if' branches) class MergeInstruction private constructor( + element: KtElement, + blockScope: BlockScope, + inputValues: List +) : OperationInstruction(element, blockScope, inputValues) { + constructor ( element: KtElement, blockScope: BlockScope, - inputValues: List -): OperationInstruction(element, blockScope, inputValues) { - constructor ( - element: KtElement, - blockScope: BlockScope, - inputValues: List, - factory: PseudoValueFactory - ): this(element, blockScope, inputValues) { + inputValues: List, + factory: PseudoValueFactory + ) : this(element, blockScope, inputValues) { setResult(factory) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/ConditionalJumpInstruction.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/ConditionalJumpInstruction.kt index 94f087f32bb..b609c6e80d8 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/ConditionalJumpInstruction.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/ConditionalJumpInstruction.kt @@ -26,11 +26,12 @@ import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionVisitorWithRe import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionVisitor class ConditionalJumpInstruction( - element: KtElement, - val onTrue: Boolean, - blockScope: BlockScope, - targetLabel: Label, - private val conditionValue: PseudoValue?) : AbstractJumpInstruction(element, targetLabel, blockScope) { + element: KtElement, + val onTrue: Boolean, + blockScope: BlockScope, + targetLabel: Label, + private val conditionValue: PseudoValue? +) : AbstractJumpInstruction(element, targetLabel, blockScope) { private var _nextOnTrue: Instruction? = null private var _nextOnFalse: Instruction? = null @@ -67,5 +68,5 @@ class ConditionalJumpInstruction( } override fun createCopy(newLabel: Label, blockScope: BlockScope): AbstractJumpInstruction = - ConditionalJumpInstruction(element, onTrue, blockScope, newLabel, conditionValue) + ConditionalJumpInstruction(element, onTrue, blockScope, newLabel, conditionValue) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/ReturnNoValueInstruction.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/ReturnNoValueInstruction.kt index a68bd747a44..13e645f6688 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/ReturnNoValueInstruction.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/ReturnNoValueInstruction.kt @@ -23,10 +23,10 @@ import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionVisitor import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionVisitorWithResult class ReturnNoValueInstruction( - element: KtElement, - blockScope: BlockScope, - targetLabel: Label, - val subroutine: KtElement + element: KtElement, + blockScope: BlockScope, + targetLabel: Label, + val subroutine: KtElement ) : AbstractJumpInstruction(element, targetLabel, blockScope) { override fun accept(visitor: InstructionVisitor) { visitor.visitReturnNoValue(this) @@ -37,5 +37,5 @@ class ReturnNoValueInstruction( override fun toString(): String = "ret $targetLabel" override fun createCopy(newLabel: Label, blockScope: BlockScope): AbstractJumpInstruction = - ReturnNoValueInstruction(element, blockScope, newLabel, subroutine) + ReturnNoValueInstruction(element, blockScope, newLabel, subroutine) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/ReturnValueInstruction.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/ReturnValueInstruction.kt index 262f6570ad0..92f212208a1 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/ReturnValueInstruction.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/ReturnValueInstruction.kt @@ -27,11 +27,11 @@ import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtReturnExpression class ReturnValueInstruction( - returnExpression: KtExpression, - blockScope: BlockScope, - targetLabel: Label, - val returnedValue: PseudoValue, - val subroutine: KtElement + returnExpression: KtExpression, + blockScope: BlockScope, + targetLabel: Label, + val returnedValue: PseudoValue, + val subroutine: KtElement ) : AbstractJumpInstruction(returnExpression, targetLabel, blockScope) { override val inputValues: List get() = Collections.singletonList(returnedValue) @@ -44,7 +44,7 @@ class ReturnValueInstruction( override fun toString(): String = "ret(*|$returnedValue) $targetLabel" override fun createCopy(newLabel: Label, blockScope: BlockScope): AbstractJumpInstruction = - ReturnValueInstruction((element as KtExpression), blockScope, newLabel, returnedValue, subroutine) + ReturnValueInstruction((element as KtExpression), blockScope, newLabel, returnedValue, subroutine) val returnExpressionIfAny: KtReturnExpression? = element as? KtReturnExpression } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/ThrowExceptionInstruction.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/ThrowExceptionInstruction.kt index c836be91c30..08c044b3895 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/ThrowExceptionInstruction.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/ThrowExceptionInstruction.kt @@ -25,10 +25,10 @@ import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionVisitor import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionVisitorWithResult class ThrowExceptionInstruction( - expression: KtThrowExpression, - blockScope: BlockScope, - errorLabel: Label, - private val thrownValue: PseudoValue + expression: KtThrowExpression, + blockScope: BlockScope, + errorLabel: Label, + private val thrownValue: PseudoValue ) : AbstractJumpInstruction(expression, errorLabel, blockScope) { override val inputValues: List get() = Collections.singletonList(thrownValue) @@ -41,5 +41,5 @@ class ThrowExceptionInstruction( override fun toString(): String = "throw (${element.text}|$thrownValue)" override fun createCopy(newLabel: Label, blockScope: BlockScope): AbstractJumpInstruction = - ThrowExceptionInstruction((element as KtThrowExpression), blockScope, newLabel, thrownValue) + ThrowExceptionInstruction((element as KtThrowExpression), blockScope, newLabel, thrownValue) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/UnconditionalJumpInstruction.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/UnconditionalJumpInstruction.kt index f859d0e0084..eef0a42376f 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/UnconditionalJumpInstruction.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/UnconditionalJumpInstruction.kt @@ -21,9 +21,9 @@ import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.cfg.Label class UnconditionalJumpInstruction( - element: KtElement, - targetLabel: Label, - blockScope: BlockScope + element: KtElement, + targetLabel: Label, + blockScope: BlockScope ) : AbstractJumpInstruction(element, targetLabel, blockScope) { override fun accept(visitor: InstructionVisitor) { visitor.visitUnconditionalJump(this) @@ -34,5 +34,5 @@ class UnconditionalJumpInstruction( override fun toString(): String = "jmp(${targetLabel.name})" override fun createCopy(newLabel: Label, blockScope: BlockScope): AbstractJumpInstruction = - UnconditionalJumpInstruction(element, newLabel, blockScope) + UnconditionalJumpInstruction(element, newLabel, blockScope) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/InlinedLocalFunctionDeclarationInstruction.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/InlinedLocalFunctionDeclarationInstruction.kt index ce3b645e207..dd5708f8f7d 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/InlinedLocalFunctionDeclarationInstruction.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/InlinedLocalFunctionDeclarationInstruction.kt @@ -25,10 +25,10 @@ import org.jetbrains.kotlin.contracts.description.InvocationKind import org.jetbrains.kotlin.psi.KtElement class InlinedLocalFunctionDeclarationInstruction( - element: KtElement, - body: Pseudocode, - blockScope: BlockScope, - val kind: InvocationKind + element: KtElement, + body: Pseudocode, + blockScope: BlockScope, + val kind: InvocationKind ) : LocalFunctionDeclarationInstruction(element, body, blockScope) { override fun createCopy(): InstructionImpl = InlinedLocalFunctionDeclarationInstruction(element, body, blockScope, kind) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/LocalFunctionDeclarationInstruction.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/LocalFunctionDeclarationInstruction.kt index 88e1d5f3062..389b1f4c02c 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/LocalFunctionDeclarationInstruction.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/LocalFunctionDeclarationInstruction.kt @@ -26,9 +26,9 @@ import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionVisitorWithRe import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionImpl open class LocalFunctionDeclarationInstruction( - element: KtElement, - val body: Pseudocode, - blockScope: BlockScope + element: KtElement, + val body: Pseudocode, + blockScope: BlockScope ) : InstructionWithNext(element, blockScope) { var sink: SubroutineSinkInstruction? = null set(value) { @@ -54,5 +54,5 @@ open class LocalFunctionDeclarationInstruction( override fun toString(): String = "d(${render(element)})" override fun createCopy(): InstructionImpl = - LocalFunctionDeclarationInstruction(element, body.copy(), blockScope) + LocalFunctionDeclarationInstruction(element, body.copy(), blockScope) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/MarkInstruction.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/MarkInstruction.kt index a425f5aeeff..d4c44734673 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/MarkInstruction.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/MarkInstruction.kt @@ -23,8 +23,8 @@ import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionVisitor import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionVisitorWithResult class MarkInstruction( - element: KtElement, - blockScope: BlockScope + element: KtElement, + blockScope: BlockScope ) : InstructionWithNext(element, blockScope) { override fun accept(visitor: InstructionVisitor) { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/SubroutineEnterInstruction.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/SubroutineEnterInstruction.kt index 0ed30e72b43..a3c7e2d88f9 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/SubroutineEnterInstruction.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/SubroutineEnterInstruction.kt @@ -24,8 +24,8 @@ import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionVisitorWithRe import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionImpl class SubroutineEnterInstruction( - val subroutine: KtElement, - blockScope: BlockScope + val subroutine: KtElement, + blockScope: BlockScope ) : InstructionWithNext(subroutine, blockScope) { override fun accept(visitor: InstructionVisitor) { visitor.visitSubroutineEnter(this) @@ -36,5 +36,5 @@ class SubroutineEnterInstruction( override fun toString(): String = "" override fun createCopy(): InstructionImpl = - SubroutineEnterInstruction(subroutine, blockScope) + SubroutineEnterInstruction(subroutine, blockScope) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/SubroutineExitInstruction.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/SubroutineExitInstruction.kt index 6091b4cc1da..39a4163615c 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/SubroutineExitInstruction.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/SubroutineExitInstruction.kt @@ -21,9 +21,9 @@ import org.jetbrains.kotlin.psi.KtElement import java.util.* class SubroutineExitInstruction( - val subroutine: KtElement, - blockScope: BlockScope, - val isError: Boolean + val subroutine: KtElement, + blockScope: BlockScope, + val isError: Boolean ) : InstructionImpl(blockScope) { private var _sink: SubroutineSinkInstruction? = null @@ -45,5 +45,5 @@ class SubroutineExitInstruction( override fun toString(): String = if (isError) "" else "" override fun createCopy(): InstructionImpl = - SubroutineExitInstruction(subroutine, blockScope, isError) + SubroutineExitInstruction(subroutine, blockScope, isError) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/SubroutineSinkInstruction.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/SubroutineSinkInstruction.kt index 6e01856d55a..4ae9481c412 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/SubroutineSinkInstruction.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/SubroutineSinkInstruction.kt @@ -25,9 +25,10 @@ import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionVisitor import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionVisitorWithResult class SubroutineSinkInstruction( - val subroutine: KtElement, - blockScope: BlockScope, - private val debugLabel: String) : InstructionImpl(blockScope) { + val subroutine: KtElement, + blockScope: BlockScope, + private val debugLabel: String +) : InstructionImpl(blockScope) { override val nextInstructions: Collection get() = Collections.emptyList() @@ -40,5 +41,5 @@ class SubroutineSinkInstruction( override fun toString(): String = debugLabel override fun createCopy(): InstructionImpl = - SubroutineSinkInstruction(subroutine, blockScope, debugLabel) + SubroutineSinkInstruction(subroutine, blockScope, debugLabel) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/VariableDeclarationInstruction.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/VariableDeclarationInstruction.kt index 481d758326a..1c4f8435ce9 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/VariableDeclarationInstruction.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/special/VariableDeclarationInstruction.kt @@ -24,8 +24,8 @@ import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionImpl import org.jetbrains.kotlin.psi.* class VariableDeclarationInstruction( - element: KtDeclaration, - blockScope: BlockScope + element: KtDeclaration, + blockScope: BlockScope ) : InstructionWithNext(element, blockScope) { init { assert(element is KtVariableDeclaration || element is KtParameter || element is KtEnumEntry || element is KtObjectDeclaration) { @@ -45,5 +45,5 @@ class VariableDeclarationInstruction( override fun toString(): String = "v(${render(element)})" override fun createCopy(): InstructionImpl = - VariableDeclarationInstruction(variableDeclarationElement, blockScope) + VariableDeclarationInstruction(variableDeclarationElement, blockScope) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/context/context.kt b/compiler/frontend/src/org/jetbrains/kotlin/context/context.kt index c5bbc5c4487..d8386072cbf 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/context/context.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/context/context.kt @@ -40,7 +40,7 @@ interface ModuleContext : ProjectContext { val module: ModuleDescriptor } -interface MutableModuleContext: ModuleContext { +interface MutableModuleContext : ModuleContext { override val module: ModuleDescriptorImpl fun setDependencies(vararg dependencies: ModuleDescriptorImpl) { @@ -57,30 +57,30 @@ interface MutableModuleContext: ModuleContext { } open class SimpleGlobalContext( - override val storageManager: StorageManager, - override val exceptionTracker: ExceptionTracker + override val storageManager: StorageManager, + override val exceptionTracker: ExceptionTracker ) : GlobalContext open class GlobalContextImpl( - storageManager: LockBasedStorageManager, - exceptionTracker: ExceptionTracker + storageManager: LockBasedStorageManager, + exceptionTracker: ExceptionTracker ) : SimpleGlobalContext(storageManager, exceptionTracker) { override val storageManager: LockBasedStorageManager = super.storageManager as LockBasedStorageManager } class ProjectContextImpl( - override val project: Project, - private val globalContext: GlobalContext + override val project: Project, + private val globalContext: GlobalContext ) : ProjectContext, GlobalContext by globalContext class ModuleContextImpl( - override val module: ModuleDescriptor, - projectContext: ProjectContext + override val module: ModuleDescriptor, + projectContext: ProjectContext ) : ModuleContext, ProjectContext by projectContext class MutableModuleContextImpl( - override val module: ModuleDescriptorImpl, - projectContext: ProjectContext + override val module: ModuleDescriptorImpl, + projectContext: ProjectContext ) : MutableModuleContext, ProjectContext by projectContext fun GlobalContext(): GlobalContextImpl { @@ -90,16 +90,16 @@ fun GlobalContext(): GlobalContextImpl { fun ProjectContext(project: Project): ProjectContext = ProjectContextImpl(project, GlobalContext()) fun ModuleContext(module: ModuleDescriptor, project: Project): ModuleContext = - ModuleContextImpl(module, ProjectContext(project)) + ModuleContextImpl(module, ProjectContext(project)) fun GlobalContext.withProject(project: Project): ProjectContext = ProjectContextImpl(project, this) fun ProjectContext.withModule(module: ModuleDescriptor): ModuleContext = ModuleContextImpl(module, this) fun ContextForNewModule( - projectContext: ProjectContext, - moduleName: Name, - builtIns: KotlinBuiltIns, - multiTargetPlatform: MultiTargetPlatform? + projectContext: ProjectContext, + moduleName: Name, + builtIns: KotlinBuiltIns, + multiTargetPlatform: MultiTargetPlatform? ): MutableModuleContext { val module = ModuleDescriptorImpl(moduleName, projectContext.storageManager, builtIns, multiTargetPlatform) return MutableModuleContextImpl(module, projectContext) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/contracts/ContractDeserializerImpl.kt b/compiler/frontend/src/org/jetbrains/kotlin/contracts/ContractDeserializerImpl.kt index 68596539c8f..3f02d3a5479 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/contracts/ContractDeserializerImpl.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/contracts/ContractDeserializerImpl.kt @@ -31,10 +31,10 @@ import org.jetbrains.kotlin.utils.addIfNotNull class ContractDeserializerImpl(private val configuration: DeserializationConfiguration) : ContractDeserializer { override fun deserializeContractFromFunction( - proto: ProtoBuf.Function, - ownerFunction: FunctionDescriptor, - typeTable: TypeTable, - typeDeserializer: TypeDeserializer + proto: ProtoBuf.Function, + ownerFunction: FunctionDescriptor, + typeTable: TypeTable, + typeDeserializer: TypeDeserializer ): Pair, LazyContractProvider>? { if (!proto.hasContract()) return null @@ -46,9 +46,9 @@ class ContractDeserializerImpl(private val configuration: DeserializationConfigu } private class ContractDeserializationWorker( - private val typeTable: TypeTable, - private val typeDeserializer: TypeDeserializer, - private val ownerFunction: FunctionDescriptor + private val typeTable: TypeTable, + private val typeDeserializer: TypeDeserializer, + private val ownerFunction: FunctionDescriptor ) { fun deserializeContract(proto: ProtoBuf.Contract): ContractDescription? { @@ -71,7 +71,9 @@ class ContractDeserializerImpl(private val configuration: DeserializationConfigu return when (type!!) { ProtoBuf.Effect.EffectType.RETURNS_CONSTANT -> { val argument = proto.effectConstructorArgumentList.getOrNull(0) - val returnValue = if (argument == null) ConstantReference.WILDCARD else deserializeExpression(argument) as? ConstantReference ?: return null + val returnValue = + if (argument == null) ConstantReference.WILDCARD else deserializeExpression(argument) as? ConstantReference + ?: return null ReturnsEffectDeclaration(returnValue) } @@ -225,7 +227,7 @@ class ContractDeserializerImpl(private val configuration: DeserializationConfigu private fun ProtoBuf.Expression.hasType(): Boolean = this.hasIsInstanceType() || this.hasIsInstanceTypeId() private fun ProtoBuf.Expression.hasFlag(flag: Flags.BooleanFlagField) = - this.hasFlags() && flag.get(this.flags) + this.hasFlags() && flag.get(this.flags) // Arguments of expressions with such types are never other expressions private enum class PrimitiveExpressionType { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/contracts/EffectSystem.kt b/compiler/frontend/src/org/jetbrains/kotlin/contracts/EffectSystem.kt index 740410b8bfc..d07d176d52c 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/contracts/EffectSystem.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/contracts/EffectSystem.kt @@ -41,9 +41,9 @@ import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo class EffectSystem(val languageVersionSettings: LanguageVersionSettings) { fun getDataFlowInfoForFinishedCall( - resolvedCall: ResolvedCall<*>, - bindingTrace: BindingTrace, - moduleDescriptor: ModuleDescriptor + resolvedCall: ResolvedCall<*>, + bindingTrace: BindingTrace, + moduleDescriptor: ModuleDescriptor ): DataFlowInfo { if (!languageVersionSettings.supportsFeature(LanguageFeature.ReturnsEffect)) return DataFlowInfo.EMPTY @@ -57,16 +57,18 @@ class EffectSystem(val languageVersionSettings: LanguageVersionSettings) { } fun getDataFlowInfoWhenEquals( - leftExpression: KtExpression?, - rightExpression: KtExpression?, - bindingTrace: BindingTrace, - moduleDescriptor: ModuleDescriptor + leftExpression: KtExpression?, + rightExpression: KtExpression?, + bindingTrace: BindingTrace, + moduleDescriptor: ModuleDescriptor ): ConditionalDataFlowInfo { if (!languageVersionSettings.supportsFeature(LanguageFeature.ReturnsEffect)) return ConditionalDataFlowInfo.EMPTY if (leftExpression == null || rightExpression == null) return ConditionalDataFlowInfo.EMPTY - val leftComputation = getNonTrivialComputation(leftExpression, bindingTrace, moduleDescriptor) ?: return ConditionalDataFlowInfo.EMPTY - val rightComputation = getNonTrivialComputation(rightExpression, bindingTrace, moduleDescriptor) ?: return ConditionalDataFlowInfo.EMPTY + val leftComputation = + getNonTrivialComputation(leftExpression, bindingTrace, moduleDescriptor) ?: return ConditionalDataFlowInfo.EMPTY + val rightComputation = + getNonTrivialComputation(rightExpression, bindingTrace, moduleDescriptor) ?: return ConditionalDataFlowInfo.EMPTY val effects = EqualsFunctor(false).invokeWithArguments(leftComputation, rightComputation) @@ -74,8 +76,8 @@ class EffectSystem(val languageVersionSettings: LanguageVersionSettings) { val notEqualsContextInfo = InfoCollector(ESReturns(false.lift())).collectFromSchema(effects) return ConditionalDataFlowInfo( - equalsContextInfo.toDataFlowInfo(languageVersionSettings), - notEqualsContextInfo.toDataFlowInfo(languageVersionSettings) + equalsContextInfo.toDataFlowInfo(languageVersionSettings), + notEqualsContextInfo.toDataFlowInfo(languageVersionSettings) ) } @@ -95,23 +97,23 @@ class EffectSystem(val languageVersionSettings: LanguageVersionSettings) { } fun extractDataFlowInfoFromCondition( - condition: KtExpression?, - value: Boolean, - bindingTrace: BindingTrace, - moduleDescriptor: ModuleDescriptor + condition: KtExpression?, + value: Boolean, + bindingTrace: BindingTrace, + moduleDescriptor: ModuleDescriptor ): DataFlowInfo { if (!languageVersionSettings.supportsFeature(LanguageFeature.ReturnsEffect)) return DataFlowInfo.EMPTY if (condition == null) return DataFlowInfo.EMPTY return getContextInfoWhen(ESReturns(value.lift()), condition, bindingTrace, moduleDescriptor) - .toDataFlowInfo(languageVersionSettings) + .toDataFlowInfo(languageVersionSettings) } private fun getContextInfoWhen( - observedEffect: ESEffect, - expression: KtExpression, - bindingTrace: BindingTrace, - moduleDescriptor: ModuleDescriptor + observedEffect: ESEffect, + expression: KtExpression, + bindingTrace: BindingTrace, + moduleDescriptor: ModuleDescriptor ): MutableContextInfo { val computation = getNonTrivialComputation(expression, bindingTrace, moduleDescriptor) ?: return MutableContextInfo.EMPTY return InfoCollector(observedEffect).collectFromSchema(computation.effects) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/contracts/EffectsExtractingVisitor.kt b/compiler/frontend/src/org/jetbrains/kotlin/contracts/EffectsExtractingVisitor.kt index 43d70efbe9a..6c6fb0dd1f0 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/contracts/EffectsExtractingVisitor.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/contracts/EffectsExtractingVisitor.kt @@ -50,8 +50,8 @@ import org.jetbrains.kotlin.utils.addIfNotNull * about effects of that call. */ class EffectsExtractingVisitor( - private val trace: BindingTrace, - private val moduleDescriptor: ModuleDescriptor + private val trace: BindingTrace, + private val moduleDescriptor: ModuleDescriptor ) : KtVisitor() { fun extractOrGetCached(element: KtElement): Computation { trace[BindingContext.EXPRESSION_EFFECTS, element]?.let { return it } @@ -66,9 +66,18 @@ class EffectsExtractingVisitor( val descriptor = resolvedCall.resultingDescriptor return when { - descriptor.isEqualsDescriptor() -> CallComputation(DefaultBuiltIns.Instance.booleanType, EqualsFunctor(false).invokeWithArguments(arguments)) - descriptor is ValueDescriptor -> ESDataFlowValue(descriptor, (element as KtExpression).createDataFlowValue() ?: return UNKNOWN_COMPUTATION) - descriptor is FunctionDescriptor -> CallComputation(descriptor.returnType, descriptor.getFunctor()?.invokeWithArguments(arguments) ?: emptyList()) + descriptor.isEqualsDescriptor() -> CallComputation( + DefaultBuiltIns.Instance.booleanType, + EqualsFunctor(false).invokeWithArguments(arguments) + ) + descriptor is ValueDescriptor -> ESDataFlowValue( + descriptor, + (element as KtExpression).createDataFlowValue() ?: return UNKNOWN_COMPUTATION + ) + descriptor is FunctionDescriptor -> CallComputation( + descriptor.returnType, + descriptor.getFunctor()?.invokeWithArguments(arguments) ?: emptyList() + ) else -> UNKNOWN_COMPUTATION } } @@ -78,15 +87,15 @@ class EffectsExtractingVisitor( override fun visitLambdaExpression(expression: KtLambdaExpression, data: Unit?): Computation = UNKNOWN_COMPUTATION override fun visitParenthesizedExpression(expression: KtParenthesizedExpression, data: Unit): Computation = - KtPsiUtil.deparenthesize(expression)?.accept(this, data) ?: UNKNOWN_COMPUTATION + KtPsiUtil.deparenthesize(expression)?.accept(this, data) ?: UNKNOWN_COMPUTATION override fun visitConstantExpression(expression: KtConstantExpression, data: Unit): Computation { val bindingContext = trace.bindingContext val type: KotlinType = bindingContext.getType(expression) ?: return UNKNOWN_COMPUTATION - val compileTimeConstant: CompileTimeConstant<*> - = bindingContext.get(BindingContext.COMPILE_TIME_VALUE, expression) ?: return UNKNOWN_COMPUTATION + val compileTimeConstant: CompileTimeConstant<*> = + bindingContext.get(BindingContext.COMPILE_TIME_VALUE, expression) ?: return UNKNOWN_COMPUTATION val value: Any? = compileTimeConstant.getValue(type) return when (value) { @@ -99,7 +108,10 @@ class EffectsExtractingVisitor( override fun visitIsExpression(expression: KtIsExpression, data: Unit): Computation { val rightType: KotlinType = trace[BindingContext.TYPE, expression.typeReference] ?: return UNKNOWN_COMPUTATION val arg = extractOrGetCached(expression.leftHandSide) - return CallComputation(DefaultBuiltIns.Instance.booleanType, IsFunctor(rightType, expression.isNegated).invokeWithArguments(listOf(arg))) + return CallComputation( + DefaultBuiltIns.Instance.booleanType, + IsFunctor(rightType, expression.isNegated).invokeWithArguments(listOf(arg)) + ) } override fun visitBinaryExpression(expression: KtBinaryExpression, data: Unit): Computation { @@ -132,10 +144,10 @@ class EffectsExtractingVisitor( private fun KtExpression.createDataFlowValue(): DataFlowValue? { return DataFlowValueFactory.createDataFlowValue( - expression = this, - type = trace.getType(this) ?: return null, - bindingContext = trace.bindingContext, - containingDeclarationOrModule = moduleDescriptor + expression = this, + type = trace.getType(this) ?: return null, + bindingContext = trace.bindingContext, + containingDeclarationOrModule = moduleDescriptor ) } @@ -148,9 +160,9 @@ class EffectsExtractingVisitor( } private fun ResolvedCall<*>.isCallWithUnsupportedReceiver(): Boolean = - (extensionReceiver as? ExpressionReceiver)?.expression?.getResolvedCall(trace.bindingContext) == this || - (dispatchReceiver as? ExpressionReceiver)?.expression?.getResolvedCall(trace.bindingContext) == this || - (explicitReceiverKind == ExplicitReceiverKind.BOTH_RECEIVERS) + (extensionReceiver as? ExpressionReceiver)?.expression?.getResolvedCall(trace.bindingContext) == this || + (dispatchReceiver as? ExpressionReceiver)?.expression?.getResolvedCall(trace.bindingContext) == this || + (explicitReceiverKind == ExplicitReceiverKind.BOTH_RECEIVERS) private fun ResolvedCall<*>.getCallArgumentsAsComputations(): List? { val arguments = mutableListOf() diff --git a/compiler/frontend/src/org/jetbrains/kotlin/contracts/parsing/PsiConstantParser.kt b/compiler/frontend/src/org/jetbrains/kotlin/contracts/parsing/PsiConstantParser.kt index 0b95c480c28..48f3bd2b048 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/contracts/parsing/PsiConstantParser.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/contracts/parsing/PsiConstantParser.kt @@ -32,8 +32,7 @@ internal class PsiConstantParser(val trace: BindingTrace) : KtVisitor - = trace.get(BindingContext.COMPILE_TIME_VALUE, expression) ?: return null + val compileTimeConstant: CompileTimeConstant<*> = trace.get(BindingContext.COMPILE_TIME_VALUE, expression) ?: return null val value: Any? = compileTimeConstant.getValue(type) return when (value) { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/contracts/parsing/PsiContractParserDispatcher.kt b/compiler/frontend/src/org/jetbrains/kotlin/contracts/parsing/PsiContractParserDispatcher.kt index d979375cedb..4b95ef40d0b 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/contracts/parsing/PsiContractParserDispatcher.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/contracts/parsing/PsiContractParserDispatcher.kt @@ -46,10 +46,10 @@ internal class PsiContractParserDispatcher(val trace: BindingTrace, val contract private val conditionParser = PsiConditionParser(trace, this) private val constantParser = PsiConstantParser(trace) private val effectsParsers: Map = mapOf( - RETURNS_EFFECT to PsiReturnsEffectParser(trace, this), - RETURNS_NOT_NULL_EFFECT to PsiReturnsEffectParser(trace, this), - CALLS_IN_PLACE_EFFECT to PsiCallsEffectParser(trace, this), - CONDITIONAL_EFFECT to PsiConditionalEffectParser(trace, this) + RETURNS_EFFECT to PsiReturnsEffectParser(trace, this), + RETURNS_NOT_NULL_EFFECT to PsiReturnsEffectParser(trace, this), + CALLS_IN_PLACE_EFFECT to PsiCallsEffectParser(trace, this), + CONDITIONAL_EFFECT to PsiConditionalEffectParser(trace, this) ) fun parseContract(expression: KtExpression?, ownerDescriptor: FunctionDescriptor): ContractDescription? { @@ -89,12 +89,22 @@ internal class PsiContractParserDispatcher(val trace: BindingTrace, val contract if (expression == null) return null val descriptor = expression.getResolvedCall(trace.bindingContext)?.resultingDescriptor ?: return null if (descriptor !is ParameterDescriptor) { - trace.report(Errors.ERROR_IN_CONTRACT_DESCRIPTION.on(expression, "only references to parameters are allowed in contract description")) + trace.report( + Errors.ERROR_IN_CONTRACT_DESCRIPTION.on( + expression, + "only references to parameters are allowed in contract description" + ) + ) return null } if (descriptor is ReceiverParameterDescriptor && descriptor.type.constructor.declarationDescriptor?.isFromContractDsl() == true) { - trace.report(Errors.ERROR_IN_CONTRACT_DESCRIPTION.on(expression, "only references to parameters are allowed. Did you miss label on ?")) + trace.report( + Errors.ERROR_IN_CONTRACT_DESCRIPTION.on( + expression, + "only references to parameters are allowed. Did you miss label on ?" + ) + ) } return if (KotlinBuiltIns.isBoolean(descriptor.type)) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/contracts/parsing/PsiContractsUtils.kt b/compiler/frontend/src/org/jetbrains/kotlin/contracts/parsing/PsiContractsUtils.kt index f15de4823a8..9556a42364b 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/contracts/parsing/PsiContractsUtils.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/contracts/parsing/PsiContractsUtils.kt @@ -83,10 +83,10 @@ fun DeclarationDescriptor.isCallsInPlaceEffectDescriptor(): Boolean = equalsDslD fun DeclarationDescriptor.isInvocationKindEnum(): Boolean = equalsDslDescriptor(INVOCATION_KIND_ENUM) fun DeclarationDescriptor.isEqualsDescriptor(): Boolean = - this is FunctionDescriptor && this.name == Name.identifier("equals") && // fast checks - this.returnType?.isBoolean() == true && this.valueParameters.singleOrNull()?.type?.isNullableAny() == true // signature matches + this is FunctionDescriptor && this.name == Name.identifier("equals") && // fast checks + this.returnType?.isBoolean() == true && this.valueParameters.singleOrNull()?.type?.isNullableAny() == true // signature matches internal fun ResolvedCall<*>.firstArgumentAsExpressionOrNull(): KtExpression? = - this.valueArgumentsByIndex?.firstOrNull()?.safeAs()?.valueArgument?.getArgumentExpression() + this.valueArgumentsByIndex?.firstOrNull()?.safeAs()?.valueArgument?.getArgumentExpression() private fun DeclarationDescriptor.equalsDslDescriptor(dslName: Name): Boolean = this.name == dslName && this.isFromContractDsl() \ No newline at end of file diff --git a/compiler/frontend/src/org/jetbrains/kotlin/contracts/parsing/effects/PsiCallsEffectParser.kt b/compiler/frontend/src/org/jetbrains/kotlin/contracts/parsing/effects/PsiCallsEffectParser.kt index 06813e46737..a9c93d23757 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/contracts/parsing/effects/PsiCallsEffectParser.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/contracts/parsing/effects/PsiCallsEffectParser.kt @@ -29,8 +29,8 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.descriptorUtil.parents internal class PsiCallsEffectParser( - trace: BindingTrace, - contractParserDispatcher: PsiContractParserDispatcher + trace: BindingTrace, + contractParserDispatcher: PsiContractParserDispatcher ) : AbstractPsiEffectParser(trace, contractParserDispatcher) { override fun tryParseEffect(expression: KtExpression): EffectDeclaration? { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/contracts/parsing/effects/PsiConditionalEffectParser.kt b/compiler/frontend/src/org/jetbrains/kotlin/contracts/parsing/effects/PsiConditionalEffectParser.kt index f0856d95921..bb4a8f00e20 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/contracts/parsing/effects/PsiConditionalEffectParser.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/contracts/parsing/effects/PsiConditionalEffectParser.kt @@ -29,8 +29,8 @@ import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver import org.jetbrains.kotlin.utils.addToStdlib.safeAs internal class PsiConditionalEffectParser( - trace: BindingTrace, - dispatcher: PsiContractParserDispatcher + trace: BindingTrace, + dispatcher: PsiContractParserDispatcher ) : AbstractPsiEffectParser(trace, dispatcher) { override fun tryParseEffect(expression: KtExpression): EffectDeclaration? { val resolvedCall = expression.getResolvedCall(trace.bindingContext) ?: return null @@ -38,9 +38,9 @@ internal class PsiConditionalEffectParser( if (!resolvedCall.resultingDescriptor.isImpliesCallDescriptor()) return null val effect = contractParserDispatcher.parseEffect(resolvedCall.dispatchReceiver.safeAs()?.expression) - ?: return null + ?: return null val condition = contractParserDispatcher.parseCondition(resolvedCall.firstArgumentAsExpressionOrNull()) - ?: return null + ?: return null return ConditionalEffectDeclaration(effect, condition) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/contracts/parsing/effects/PsiReturnsEffectParser.kt b/compiler/frontend/src/org/jetbrains/kotlin/contracts/parsing/effects/PsiReturnsEffectParser.kt index 5066acf883a..bcc9de261a7 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/contracts/parsing/effects/PsiReturnsEffectParser.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/contracts/parsing/effects/PsiReturnsEffectParser.kt @@ -26,8 +26,8 @@ import org.jetbrains.kotlin.resolve.BindingTrace import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall internal class PsiReturnsEffectParser( - trace: BindingTrace, - contractParserDispatcher: PsiContractParserDispatcher + trace: BindingTrace, + contractParserDispatcher: PsiContractParserDispatcher ) : AbstractPsiEffectParser(trace, contractParserDispatcher) { override fun tryParseEffect(expression: KtExpression): EffectDeclaration? { val resolvedCall = expression.getResolvedCall(trace.bindingContext) ?: return null @@ -39,13 +39,18 @@ internal class PsiReturnsEffectParser( if (!descriptor.isReturnsEffectDescriptor()) return null val argumentExpression = resolvedCall.firstArgumentAsExpressionOrNull() - val constantValue = if (argumentExpression == null) + val constantValue = if (argumentExpression == null) { ConstantReference.WILDCARD - else { + } else { // Note that we distinguish absence of an argument and unparsed argument val constant = contractParserDispatcher.parseConstant(argumentExpression) if (constant == null) { - trace.report(Errors.ERROR_IN_CONTRACT_DESCRIPTION.on(argumentExpression, "only true/false/null constants in Returns-effect are currently supported")) + trace.report( + Errors.ERROR_IN_CONTRACT_DESCRIPTION.on( + argumentExpression, + "only true/false/null constants in Returns-effect are currently supported" + ) + ) return null } constant diff --git a/compiler/frontend/src/org/jetbrains/kotlin/descriptors/annotations/AnnotationSplitter.kt b/compiler/frontend/src/org/jetbrains/kotlin/descriptors/annotations/AnnotationSplitter.kt index 10c0db85b8e..66b83a0b967 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/descriptors/annotations/AnnotationSplitter.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/descriptors/annotations/AnnotationSplitter.kt @@ -40,22 +40,24 @@ import org.jetbrains.kotlin.storage.getValue */ class AnnotationSplitter( - val storageManager: StorageManager, - allAnnotations: Annotations, - applicableTargetsLazy: () -> Set + val storageManager: StorageManager, + allAnnotations: Annotations, + applicableTargetsLazy: () -> Set ) { companion object { private val TARGET_PRIORITIES = setOf(CONSTRUCTOR_PARAMETER, PROPERTY, FIELD) - @JvmStatic fun create( - storageManager: StorageManager, - annotations: Annotations, - targets: Set + @JvmStatic + fun create( + storageManager: StorageManager, + annotations: Annotations, + targets: Set ): AnnotationSplitter { return AnnotationSplitter(storageManager, annotations, { targets }) } - @JvmStatic fun getTargetSet(parameter: Boolean, context: BindingContext, wrapper: PropertyWrapper): Set { + @JvmStatic + fun getTargetSet(parameter: Boolean, context: BindingContext, wrapper: PropertyWrapper): Set { val descriptor = wrapper.descriptor assert(descriptor != null) val hasBackingField = context[BindingContext.BACKING_FIELD_REQUIRED, descriptor] ?: false @@ -63,8 +65,9 @@ class AnnotationSplitter( return getTargetSet(parameter, descriptor!!.isVar, hasBackingField, hasDelegate) } - @JvmStatic fun getTargetSet( - parameter: Boolean, isVar: Boolean, hasBackingField: Boolean, hasDelegate: Boolean + @JvmStatic + fun getTargetSet( + parameter: Boolean, isVar: Boolean, hasBackingField: Boolean, hasDelegate: Boolean ): Set = hashSetOf(PROPERTY, PROPERTY_GETTER).apply { if (parameter) add(CONSTRUCTOR_PARAMETER) if (hasBackingField) add(FIELD) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/descriptors/impl/LocalVariableAccessorDescriptor.kt b/compiler/frontend/src/org/jetbrains/kotlin/descriptors/impl/LocalVariableAccessorDescriptor.kt index 0d1513859e9..fc8db16d1ff 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/descriptors/impl/LocalVariableAccessorDescriptor.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/descriptors/impl/LocalVariableAccessorDescriptor.kt @@ -23,31 +23,33 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import org.jetbrains.kotlin.types.KotlinType sealed class LocalVariableAccessorDescriptor( - final override val correspondingVariable: LocalVariableDescriptor, - isGetter: Boolean + final override val correspondingVariable: LocalVariableDescriptor, + isGetter: Boolean ) : SimpleFunctionDescriptorImpl( - correspondingVariable.containingDeclaration, - null, - Annotations.EMPTY, - Name.special((if (isGetter) ""), - CallableMemberDescriptor.Kind.SYNTHESIZED, - SourceElement.NO_SOURCE + correspondingVariable.containingDeclaration, + null, + Annotations.EMPTY, + Name.special((if (isGetter) ""), + CallableMemberDescriptor.Kind.SYNTHESIZED, + SourceElement.NO_SOURCE ), VariableAccessorDescriptor { class Getter(correspondingVariable: LocalVariableDescriptor) : LocalVariableAccessorDescriptor(correspondingVariable, true) class Setter(correspondingVariable: LocalVariableDescriptor) : LocalVariableAccessorDescriptor(correspondingVariable, false) init { val valueParameters = - if (isGetter) emptyList() else listOf(createValueParameter(Name.identifier("value"), correspondingVariable.type)) + if (isGetter) emptyList() else listOf(createValueParameter(Name.identifier("value"), correspondingVariable.type)) val returnType = - if (isGetter) correspondingVariable.type else correspondingVariable.builtIns.unitType + if (isGetter) correspondingVariable.type else correspondingVariable.builtIns.unitType @Suppress("LeakingThis") initialize(null, null, emptyList(), valueParameters, returnType, Modality.FINAL, Visibilities.LOCAL) } private fun createValueParameter(name: Name, type: KotlinType): ValueParameterDescriptorImpl { - return ValueParameterDescriptorImpl(this, null, 0, Annotations.EMPTY, name, type, - false, false, false, null, SourceElement.NO_SOURCE) + return ValueParameterDescriptorImpl( + this, null, 0, Annotations.EMPTY, name, type, + false, false, false, null, SourceElement.NO_SOURCE + ) } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/descriptors/impl/SyntheticFieldDescriptor.kt b/compiler/frontend/src/org/jetbrains/kotlin/descriptors/impl/SyntheticFieldDescriptor.kt index bff25f7a188..2b17932bc24 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/descriptors/impl/SyntheticFieldDescriptor.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/descriptors/impl/SyntheticFieldDescriptor.kt @@ -25,15 +25,19 @@ import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.resolve.source.toSourceElement class SyntheticFieldDescriptor private constructor( - val propertyDescriptor: PropertyDescriptor, + val propertyDescriptor: PropertyDescriptor, + accessorDescriptor: PropertyAccessorDescriptor, + property: KtProperty +) : LocalVariableDescriptor( + accessorDescriptor, Annotations.EMPTY, SyntheticFieldDescriptor.NAME, + propertyDescriptor.type, propertyDescriptor.isVar, false, false, + property.toSourceElement() +) { + + constructor( accessorDescriptor: PropertyAccessorDescriptor, property: KtProperty -): LocalVariableDescriptor(accessorDescriptor, Annotations.EMPTY, SyntheticFieldDescriptor.NAME, - propertyDescriptor.type, propertyDescriptor.isVar, false, false, - property.toSourceElement()) { - - constructor(accessorDescriptor: PropertyAccessorDescriptor, - property: KtProperty): this(accessorDescriptor.correspondingProperty, accessorDescriptor, property) + ) : this(accessorDescriptor.correspondingProperty, accessorDescriptor, property) override fun getDispatchReceiverParameter() = null diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/RenderedDiagnostic.kt b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/RenderedDiagnostic.kt index 976ed7223c8..b2c9409fe2a 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/RenderedDiagnostic.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/RenderedDiagnostic.kt @@ -19,8 +19,8 @@ package org.jetbrains.kotlin.diagnostics import org.jetbrains.kotlin.diagnostics.rendering.DiagnosticRenderer class RenderedDiagnostic( - val diagnostic: D, - val renderer: DiagnosticRenderer + val diagnostic: D, + val renderer: DiagnosticRenderer ) { val text = renderer.render(diagnostic) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/diagnosticUtils.kt b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/diagnosticUtils.kt index a3e4052cd91..f79a496e0fa 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/diagnosticUtils.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/diagnosticUtils.kt @@ -44,42 +44,39 @@ import org.jetbrains.kotlin.types.typeUtil.isNothing import org.jetbrains.kotlin.types.typeUtil.isNullableNothing fun ResolutionContext<*>.reportTypeMismatchDueToTypeProjection( - expression: KtElement, - expectedType: KotlinType, - expressionType: KotlinType? + expression: KtElement, + expectedType: KotlinType, + expressionType: KotlinType? ): Boolean { if (!TypeUtils.contains(expectedType) { it.isAnyOrNullableAny() || it.isNothing() || it.isNullableNothing() }) return false val callPosition = this.callPosition val (resolvedCall, correspondingNotApproximatedTypeByDescriptor: (CallableDescriptor) -> KotlinType?) = when (callPosition) { is CallPosition.ValueArgumentPosition -> Pair( - callPosition.resolvedCall, { - f: CallableDescriptor -> - getEffectiveExpectedType(f.valueParameters[callPosition.valueParameter.index], callPosition.valueArgument, this) - }) + callPosition.resolvedCall, { f: CallableDescriptor -> + getEffectiveExpectedType(f.valueParameters[callPosition.valueParameter.index], callPosition.valueArgument, this) + }) is CallPosition.ExtensionReceiverPosition -> Pair( - callPosition.resolvedCall, { - f: CallableDescriptor -> - f.extensionReceiverParameter?.type - }) + callPosition.resolvedCall, { f: CallableDescriptor -> + f.extensionReceiverParameter?.type + }) is CallPosition.PropertyAssignment -> Pair( - callPosition.leftPart.getResolvedCall(trace.bindingContext) ?: return false, { - f: CallableDescriptor -> - (f as? PropertyDescriptor)?.setter?.valueParameters?.get(0)?.type - }) + callPosition.leftPart.getResolvedCall(trace.bindingContext) ?: return false, { f: CallableDescriptor -> + (f as? PropertyDescriptor)?.setter?.valueParameters?.get(0)?.type + }) is CallPosition.Unknown -> return false } val receiverType = resolvedCall.smartCastDispatchReceiverType - ?: (resolvedCall.dispatchReceiver ?: return false).type + ?: (resolvedCall.dispatchReceiver ?: return false).type val callableDescriptor = resolvedCall.resultingDescriptor.original val substitutedDescriptor = - TypeConstructorSubstitution - .create(receiverType) - .wrapWithCapturingSubstitution(needApproximation = false) - .buildSubstitutor().let { callableDescriptor.substitute(it) } ?: return false + TypeConstructorSubstitution + .create(receiverType) + .wrapWithCapturingSubstitution(needApproximation = false) + .buildSubstitutor().let { callableDescriptor.substitute(it) } ?: return false val nonApproximatedExpectedType = correspondingNotApproximatedTypeByDescriptor(substitutedDescriptor) ?: return false if (!TypeUtils.contains(nonApproximatedExpectedType) { it.isCaptured() }) return false @@ -87,25 +84,26 @@ fun ResolutionContext<*>.reportTypeMismatchDueToTypeProjection( if (expectedType.isNothing()) { if (callPosition is CallPosition.PropertyAssignment) { trace.report(Errors.SETTER_PROJECTED_OUT.on(callPosition.leftPart ?: return false, resolvedCall.resultingDescriptor)) - } - else { + } else { val call = resolvedCall.call val reportOn = - if (resolvedCall is VariableAsFunctionResolvedCall) - resolvedCall.variableCall.call.calleeExpression - else - call.calleeExpression + if (resolvedCall is VariableAsFunctionResolvedCall) + resolvedCall.variableCall.call.calleeExpression + else + call.calleeExpression trace.reportDiagnosticOnce(Errors.MEMBER_PROJECTED_OUT.on(reportOn ?: call.callElement, callableDescriptor, receiverType)) } - } - else { + } else { // expressionType can be null when reporting CONSTANT_EXPECTED_TYPE_MISMATCH (see addAll.kt test) expressionType ?: return false trace.report( - Errors.TYPE_MISMATCH_DUE_TO_TYPE_PROJECTIONS.on( - expression, TypeMismatchDueToTypeProjectionsData( - expectedType, expressionType, receiverType, callableDescriptor))) + Errors.TYPE_MISMATCH_DUE_TO_TYPE_PROJECTIONS.on( + expression, TypeMismatchDueToTypeProjectionsData( + expectedType, expressionType, receiverType, callableDescriptor + ) + ) + ) } @@ -119,16 +117,16 @@ fun BindingTrace.reportDiagnosticOnce(diagnostic: Diagnostic) { } class TypeMismatchDueToTypeProjectionsData( - val expectedType: KotlinType, - val expressionType: KotlinType, - val receiverType: KotlinType, - val callableDescriptor: CallableDescriptor + val expectedType: KotlinType, + val expressionType: KotlinType, + val receiverType: KotlinType, + val callableDescriptor: CallableDescriptor ) fun ResolutionContext<*>.reportTypeMismatchDueToScalaLikeNamedFunctionSyntax( - expression: KtElement, - expectedType: KotlinType, - expressionType: KotlinType? + expression: KtElement, + expectedType: KotlinType, + expressionType: KotlinType? ): Boolean { if (expressionType == null) return false @@ -141,21 +139,26 @@ fun ResolutionContext<*>.reportTypeMismatchDueToScalaLikeNamedFunctionSyntax( } private fun isScalaLikeEqualsBlock(expression: KtElement): Boolean = - expression is KtLambdaExpression && - expression.parent.let { it is KtNamedFunction && it.equalsToken != null } + expression is KtLambdaExpression && + expression.parent.let { it is KtNamedFunction && it.equalsToken != null } inline fun reportOnDeclaration(trace: BindingTrace, descriptor: DeclarationDescriptor, what: (PsiElement) -> Diagnostic) { DescriptorToSourceUtils.descriptorToDeclaration(descriptor)?.let { psiElement -> trace.report(what(psiElement)) } } + inline fun reportOnDeclarationOrFail(trace: BindingTrace, descriptor: DeclarationDescriptor, what: (PsiElement) -> Diagnostic) { DescriptorToSourceUtils.descriptorToDeclaration(descriptor)?.let { psiElement -> trace.report(what(psiElement)) } ?: throw AssertionError("No declaration for $descriptor") } -inline fun reportOnDeclarationAs(trace: BindingTrace, descriptor: DeclarationDescriptor, what: (T) -> Diagnostic) { +inline fun reportOnDeclarationAs( + trace: BindingTrace, + descriptor: DeclarationDescriptor, + what: (T) -> Diagnostic +) { DescriptorToSourceUtils.descriptorToDeclaration(descriptor)?.let { psiElement -> (psiElement as? T)?.let { trace.report(what(it)) @@ -166,7 +169,7 @@ inline fun reportOnDeclarationAs(trace: BindingTrace fun DiagnosticSink.reportFromPlugin(diagnostic: D, ext: DefaultErrorMessages.Extension) { @Suppress("UNCHECKED_CAST") val renderer = ext.map[diagnostic.factory] as? DiagnosticRenderer - ?: error("Renderer not found for diagnostic ${diagnostic.factory.name}") + ?: error("Renderer not found for diagnostic ${diagnostic.factory.name}") val renderedDiagnostic = RenderedDiagnostic(diagnostic, renderer) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/LanguageFeatureMessageRenderer.kt b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/LanguageFeatureMessageRenderer.kt index 7ea505c7d7d..285467ef842 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/LanguageFeatureMessageRenderer.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/LanguageFeatureMessageRenderer.kt @@ -20,9 +20,9 @@ import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.config.LanguageVersionSettings class LanguageFeatureMessageRenderer @JvmOverloads constructor( - private val type: Type, - private val useHtml: Boolean = false -): DiagnosticParameterRenderer> { + private val type: Type, + private val useHtml: Boolean = false +) : DiagnosticParameterRenderer> { enum class Type { UNSUPPORTED, @@ -58,8 +58,7 @@ class LanguageFeatureMessageRenderer @JvmOverloads constructor( if (hintUrl != null) { if (useHtml) { sb.append(" (").append("see more here)") - } - else { + } else { sb.append(" (see: ").append(hintUrl).append(")") } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/PlatformIncompatibilityDiagnosticRenderer.kt b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/PlatformIncompatibilityDiagnosticRenderer.kt index 76f4f9fa43a..65a9a334979 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/PlatformIncompatibilityDiagnosticRenderer.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/PlatformIncompatibilityDiagnosticRenderer.kt @@ -21,11 +21,11 @@ import org.jetbrains.kotlin.descriptors.MemberDescriptor import org.jetbrains.kotlin.resolve.checkers.ExpectedActualDeclarationChecker.Compatibility.Incompatible class PlatformIncompatibilityDiagnosticRenderer( - private val mode: MultiplatformDiagnosticRenderingMode + private val mode: MultiplatformDiagnosticRenderingMode ) : DiagnosticParameterRenderer>> { override fun render( - obj: Map>, - renderingContext: RenderingContext + obj: Map>, + renderingContext: RenderingContext ): String { if (obj.isEmpty()) return "" @@ -42,11 +42,11 @@ class PlatformIncompatibilityDiagnosticRenderer( } class IncompatibleExpectedActualClassScopesRenderer( - private val mode: MultiplatformDiagnosticRenderingMode + private val mode: MultiplatformDiagnosticRenderingMode ) : DiagnosticParameterRenderer>>>> { override fun render( - obj: List>>>, - renderingContext: RenderingContext + obj: List>>>, + renderingContext: RenderingContext ): String { if (obj.isEmpty()) return "" @@ -82,10 +82,10 @@ open class MultiplatformDiagnosticRenderingMode { } private fun StringBuilder.renderIncompatibilityInformation( - map: Map>, - indent: String, - context: RenderingContext, - mode: MultiplatformDiagnosticRenderingMode + map: Map>, + indent: String, + context: RenderingContext, + mode: MultiplatformDiagnosticRenderingMode ) { for ((incompatibility, descriptors) in map) { append(indent) @@ -109,10 +109,10 @@ private fun StringBuilder.renderIncompatibilityInformation( } private fun StringBuilder.renderIncompatibleClassScopes( - unfulfilled: List>>>, - indent: String, - context: RenderingContext, - mode: MultiplatformDiagnosticRenderingMode + unfulfilled: List>>>, + indent: String, + context: RenderingContext, + mode: MultiplatformDiagnosticRenderingMode ) { mode.renderList(this, unfulfilled.indices.map { index -> { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/diagnosticsWithParameterRenderers.kt b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/diagnosticsWithParameterRenderers.kt index b897d8e5956..3dcac178b75 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/diagnosticsWithParameterRenderers.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/diagnosticsWithParameterRenderers.kt @@ -33,8 +33,8 @@ abstract class AbstractDiagnosticWithParametersRenderer protecte class DiagnosticWithParameters1Renderer( - message: String, - private val rendererForA: DiagnosticParameterRenderer? + message: String, + private val rendererForA: DiagnosticParameterRenderer? ) : AbstractDiagnosticWithParametersRenderer>(message) { override fun renderParameters(diagnostic: DiagnosticWithParameters1<*, A>): Array { @@ -44,40 +44,40 @@ class DiagnosticWithParameters1Renderer( } class DiagnosticWithParameters2Renderer( - message: String, - private val rendererForA: DiagnosticParameterRenderer?, - private val rendererForB: DiagnosticParameterRenderer? + message: String, + private val rendererForA: DiagnosticParameterRenderer?, + private val rendererForB: DiagnosticParameterRenderer? ) : AbstractDiagnosticWithParametersRenderer>(message) { override fun renderParameters(diagnostic: DiagnosticWithParameters2<*, A, B>): Array { val context = RenderingContext.of(diagnostic.a, diagnostic.b) return arrayOf( - renderParameter(diagnostic.a, rendererForA, context), - renderParameter(diagnostic.b, rendererForB, context) + renderParameter(diagnostic.a, rendererForA, context), + renderParameter(diagnostic.b, rendererForB, context) ) } } class DiagnosticWithParameters3Renderer( - message: String, - private val rendererForA: DiagnosticParameterRenderer?, - private val rendererForB: DiagnosticParameterRenderer?, - private val rendererForC: DiagnosticParameterRenderer? + message: String, + private val rendererForA: DiagnosticParameterRenderer?, + private val rendererForB: DiagnosticParameterRenderer?, + private val rendererForC: DiagnosticParameterRenderer? ) : AbstractDiagnosticWithParametersRenderer>(message) { override fun renderParameters(diagnostic: DiagnosticWithParameters3<*, A, B, C>): Array { val context = RenderingContext.of(diagnostic.a, diagnostic.b, diagnostic.c) return arrayOf( - renderParameter(diagnostic.a, rendererForA, context), - renderParameter(diagnostic.b, rendererForB, context), - renderParameter(diagnostic.c, rendererForC, context) + renderParameter(diagnostic.a, rendererForA, context), + renderParameter(diagnostic.b, rendererForB, context), + renderParameter(diagnostic.c, rendererForC, context) ) } } class DiagnosticWithParametersMultiRenderer( - message: String, - private val renderer: MultiRenderer + message: String, + private val renderer: MultiRenderer ) : AbstractDiagnosticWithParametersRenderer>(message) { override fun renderParameters(diagnostic: DiagnosticWithParameters1<*, A>): Array { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/extensions/AnnotationBasedExtension.kt b/compiler/frontend/src/org/jetbrains/kotlin/extensions/AnnotationBasedExtension.kt index 5a15b313b93..587c0127699 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/extensions/AnnotationBasedExtension.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/extensions/AnnotationBasedExtension.kt @@ -42,9 +42,9 @@ interface AnnotationBasedExtension { } private fun AnnotationDescriptor.isASpecialAnnotation( - specialAnnotations: List, - visitedAnnotations: MutableSet = hashSetOf(), - allowMetaAnnotations: Boolean = true + specialAnnotations: List, + visitedAnnotations: MutableSet = hashSetOf(), + allowMetaAnnotations: Boolean = true ): Boolean { val annotationFqName = fqName?.asString() ?: return false if (annotationFqName in visitedAnnotations) return false // Prevent infinite recursion diff --git a/compiler/frontend/src/org/jetbrains/kotlin/extensions/DeclarationAttributeAltererExtension.kt b/compiler/frontend/src/org/jetbrains/kotlin/extensions/DeclarationAttributeAltererExtension.kt index 7a245ed40dc..3df5d1f853c 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/extensions/DeclarationAttributeAltererExtension.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/extensions/DeclarationAttributeAltererExtension.kt @@ -24,21 +24,21 @@ import org.jetbrains.kotlin.resolve.BindingContext interface DeclarationAttributeAltererExtension { companion object : ProjectExtensionDescriptor( - "org.jetbrains.kotlin.declarationAttributeAltererExtension", - DeclarationAttributeAltererExtension::class.java + "org.jetbrains.kotlin.declarationAttributeAltererExtension", + DeclarationAttributeAltererExtension::class.java ) /** * Returns the new modality for the [declaration], or null if the [currentModality] is good enough. */ fun refineDeclarationModality( - modifierListOwner: KtModifierListOwner, - declaration: DeclarationDescriptor?, - containingDeclaration: DeclarationDescriptor?, - currentModality: Modality, - bindingContext: BindingContext, - isImplicitModality: Boolean + modifierListOwner: KtModifierListOwner, + declaration: DeclarationDescriptor?, + containingDeclaration: DeclarationDescriptor?, + currentModality: Modality, + bindingContext: BindingContext, + isImplicitModality: Boolean ): Modality? = null - fun shouldConvertFirstSAMParameterToReceiver(function: FunctionDescriptor) : Boolean = false + fun shouldConvertFirstSAMParameterToReceiver(function: FunctionDescriptor): Boolean = false } \ No newline at end of file diff --git a/compiler/frontend/src/org/jetbrains/kotlin/extensions/PreprocessedVirtualFileFactoryExtension.kt b/compiler/frontend/src/org/jetbrains/kotlin/extensions/PreprocessedVirtualFileFactoryExtension.kt index 091c4cfe1ea..822bdc8cfb1 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/extensions/PreprocessedVirtualFileFactoryExtension.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/extensions/PreprocessedVirtualFileFactoryExtension.kt @@ -27,9 +27,10 @@ import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult */ interface PreprocessedVirtualFileFactoryExtension { companion object : ProjectExtensionDescriptor( - "org.jetbrains.kotlin.preprocessedVirtualFileFactoryExtension", - PreprocessedVirtualFileFactoryExtension::class.java + "org.jetbrains.kotlin.preprocessedVirtualFileFactoryExtension", + PreprocessedVirtualFileFactoryExtension::class.java ) + fun isPassThrough(): Boolean fun createPreprocessedFile(file: VirtualFile?): VirtualFile? @@ -45,6 +46,7 @@ class PreprocessedFileCreator(val project: Project) { fun create(file: VirtualFile): VirtualFile = validExts.firstNotNullResult { it.createPreprocessedFile(file) } ?: file // unused now, but could be used in the IDE at some point - fun createLight(file: LightVirtualFile): LightVirtualFile = validExts.firstNotNullResult { it.createPreprocessedLightFile(file) } ?: file + fun createLight(file: LightVirtualFile): LightVirtualFile = + validExts.firstNotNullResult { it.createPreprocessedLightFile(file) } ?: file } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/extensions/ProjectExtensionDescriptor.kt b/compiler/frontend/src/org/jetbrains/kotlin/extensions/ProjectExtensionDescriptor.kt index a9fb1123f93..4a183874216 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/extensions/ProjectExtensionDescriptor.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/extensions/ProjectExtensionDescriptor.kt @@ -26,9 +26,9 @@ open class ProjectExtensionDescriptor(name: String, private val extensionClas fun registerExtensionPoint(project: Project) { Extensions.getArea(project).registerExtensionPoint( - extensionPointName.name, - extensionClass.name, - ExtensionPoint.Kind.INTERFACE + extensionPointName.name, + extensionClass.name, + ExtensionPoint.Kind.INTERFACE ) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/extensions/StorageComponentContainerContributor.kt b/compiler/frontend/src/org/jetbrains/kotlin/extensions/StorageComponentContainerContributor.kt index ca84a579c79..a54ffa094c9 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/extensions/StorageComponentContainerContributor.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/extensions/StorageComponentContainerContributor.kt @@ -22,7 +22,7 @@ import org.jetbrains.kotlin.resolve.TargetPlatform interface StorageComponentContainerContributor { companion object : ProjectExtensionDescriptor( - "org.jetbrains.kotlin.storageComponentContainerContributor", StorageComponentContainerContributor::class.java + "org.jetbrains.kotlin.storageComponentContainerContributor", StorageComponentContainerContributor::class.java ) fun registerModuleComponents(container: StorageComponentContainer, platform: TargetPlatform, moduleDescriptor: ModuleDescriptor) {} diff --git a/compiler/frontend/src/org/jetbrains/kotlin/kdoc/parser/KDocKnownTag.kt b/compiler/frontend/src/org/jetbrains/kotlin/kdoc/parser/KDocKnownTag.kt index 137af4a022b..3cba98eeb71 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/kdoc/parser/KDocKnownTag.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/kdoc/parser/KDocKnownTag.kt @@ -41,8 +41,7 @@ enum class KDocKnownTag private constructor(val isReferenceRequired: Boolean, va } try { return valueOf(tagName.toString().toUpperCase()) - } - catch (ignored: IllegalArgumentException) { + } catch (ignored: IllegalArgumentException) { } return null diff --git a/compiler/frontend/src/org/jetbrains/kotlin/kdoc/psi/impl/KDocName.kt b/compiler/frontend/src/org/jetbrains/kotlin/kdoc/psi/impl/KDocName.kt index 7860f0ac12c..13b559dc8fb 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/kdoc/psi/impl/KDocName.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/kdoc/psi/impl/KDocName.kt @@ -27,7 +27,7 @@ import org.jetbrains.kotlin.psi.psiUtil.getChildOfType /** * A single part of a qualified name in the tag subject or link. */ -class KDocName(node: ASTNode): KtElementImpl(node) { +class KDocName(node: ASTNode) : KtElementImpl(node) { fun getContainingDoc(): KDoc { val kdoc = getStrictParentOfType() return kdoc ?: throw IllegalStateException("KDocName must be inside a KDoc") diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/DebugTextUtil.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/DebugTextUtil.kt index 5d2d1f07271..0436643a06a 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/DebugTextUtil.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/DebugTextUtil.kt @@ -292,9 +292,11 @@ private object DebugTextBuildingVisitor : KtVisitor() { private fun StringBuilder.appendInn(target: Any?, prefix: String = "", suffix: String = "") { if (target == null) return append(prefix) - append(when (target) { - is KtElement -> target.getDebugText() - else -> target.toString() - }) + append( + when (target) { + is KtElement -> target.getDebugText() + else -> target.toString() + } + ) append(suffix) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/EditCommaSeparatedListHelper.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/EditCommaSeparatedListHelper.kt index 24120f60bf0..dcecc2cbf6a 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/EditCommaSeparatedListHelper.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/EditCommaSeparatedListHelper.kt @@ -24,28 +24,31 @@ import org.jetbrains.kotlin.psi.psiUtil.siblings object EditCommaSeparatedListHelper { @JvmOverloads - fun addItem(list: KtElement, allItems: List, item: TItem, prefix: KtToken = KtTokens.LPAR): TItem { + fun addItem(list: KtElement, allItems: List, item: TItem, prefix: KtToken = KtTokens.LPAR): TItem { return addItemBefore(list, allItems, item, null, prefix) } @JvmOverloads - fun addItemAfter(list: KtElement, allItems: List, item: TItem, anchor: TItem?, prefix: KtToken = KtTokens.LPAR): TItem { + fun addItemAfter( + list: KtElement, + allItems: List, + item: TItem, + anchor: TItem?, + prefix: KtToken = KtTokens.LPAR + ): TItem { assert(anchor == null || anchor.parent == list) if (allItems.isEmpty()) { return if (list.firstChild?.node?.elementType == prefix) { list.addAfter(item, list.firstChild) as TItem - } - else { + } else { list.add(item) as TItem } - } - else { + } else { var comma = KtPsiFactory(list).createComma() return if (anchor != null) { comma = list.addAfter(comma, anchor) list.addAfter(item, comma) as TItem - } - else { + } else { comma = list.addBefore(comma, allItems.first()) list.addBefore(item, comma) as TItem } @@ -53,26 +56,30 @@ object EditCommaSeparatedListHelper { } @JvmOverloads - fun addItemBefore(list: KtElement, allItems: List, item: TItem, anchor: TItem?, prefix: KtToken = KtTokens.LPAR): TItem { + fun addItemBefore( + list: KtElement, + allItems: List, + item: TItem, + anchor: TItem?, + prefix: KtToken = KtTokens.LPAR + ): TItem { val anchorAfter: TItem? anchorAfter = if (allItems.isEmpty()) { assert(anchor == null) null - } - else { + } else { if (anchor != null) { val index = allItems.indexOf(anchor) assert(index >= 0) if (index > 0) allItems[index - 1] else null - } - else { + } else { allItems[allItems.size - 1] } } return addItemAfter(list, allItems, item, anchorAfter, prefix) } - fun removeItem(item: TItem) { + fun removeItem(item: TItem) { var comma = item.siblings(withItself = false).firstOrNull { it !is PsiWhiteSpace && it !is PsiComment } if (comma?.node?.elementType != KtTokens.COMMA) { comma = item.siblings(forward = false, withItself = false).firstOrNull { it !is PsiWhiteSpace && it !is PsiComment } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/FindDocComment.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/FindDocComment.kt index af625260d81..03e5c01b6f8 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/FindDocComment.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/FindDocComment.kt @@ -23,12 +23,12 @@ import org.jetbrains.kotlin.psi.psiUtil.allChildren fun findDocComment(declaration: KtDeclaration): KDoc? { return declaration.allChildren - .flatMap { - if (it is KtDeclarationModifierList) { - return@flatMap it.children.asSequence() - } - sequenceOf(it) + .flatMap { + if (it is KtDeclarationModifierList) { + return@flatMap it.children.asSequence() } - .dropWhile { it !is KDoc } - .firstOrNull() as? KDoc + sequenceOf(it) + } + .dropWhile { it !is KDoc } + .firstOrNull() as? KDoc } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtBlockCodeFragment.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtBlockCodeFragment.kt index 48ed8989657..f4507df2595 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtBlockCodeFragment.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtBlockCodeFragment.kt @@ -21,13 +21,13 @@ import com.intellij.psi.PsiElement import org.jetbrains.kotlin.KtNodeTypes class KtBlockCodeFragment( - project: Project, - name: String, - text: CharSequence, - imports: String?, - context: PsiElement? + project: Project, + name: String, + text: CharSequence, + imports: String?, + context: PsiElement? ) : KtCodeFragment(project, name, text, imports, KtNodeTypes.BLOCK_CODE_FRAGMENT, context) { override fun getContentElement() = findChildByClass(KtBlockExpression::class.java) - ?: throw IllegalStateException("Block expression should be parsed for BlockCodeFragment") + ?: throw IllegalStateException("Block expression should be parsed for BlockCodeFragment") } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtClassOrObject.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtClassOrObject.kt index 4474e7350db..359e1d2b943 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtClassOrObject.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtClassOrObject.kt @@ -30,7 +30,8 @@ import org.jetbrains.kotlin.psi.stubs.KotlinClassOrObjectStub import org.jetbrains.kotlin.psi.stubs.elements.KtStubElementTypes abstract class KtClassOrObject : - KtTypeParameterListOwnerStub>, KtDeclarationContainer, KtNamedDeclaration, KtPureClassOrObject { + KtTypeParameterListOwnerStub>, KtDeclarationContainer, KtNamedDeclaration, + KtPureClassOrObject { constructor(node: ASTNode) : super(node) constructor(stub: KotlinClassOrObjectStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType) @@ -59,8 +60,7 @@ abstract class KtClassOrObject : if (specifierList.entries.size > 1) { EditCommaSeparatedListHelper.removeItem(superTypeListEntry) - } - else { + } else { deleteChildRange(findChildByType(KtTokens.COLON) ?: specifierList, specifierList) } } @@ -69,18 +69,18 @@ abstract class KtClassOrObject : fun getBody(): KtClassBody? = getStubOrPsiChild(KtStubElementTypes.CLASS_BODY) - inline fun addDeclaration(declaration: T): T { + inline fun addDeclaration(declaration: T): T { val body = getOrCreateBody() val anchor = PsiTreeUtil.skipSiblingsBackward(body.rBrace ?: body.lastChild!!, PsiWhiteSpace::class.java) return body.addAfter(declaration, anchor) as T } - inline fun addDeclarationAfter(declaration: T, anchor: PsiElement?): T { + inline fun addDeclarationAfter(declaration: T, anchor: PsiElement?): T { val anchorBefore = anchor ?: declarations.lastOrNull() ?: return addDeclaration(declaration) return getOrCreateBody().addAfter(declaration, anchorBefore) as T } - inline fun addDeclarationBefore(declaration: T, anchor: PsiElement?): T { + inline fun addDeclarationBefore(declaration: T, anchor: PsiElement?): T { val anchorAfter = anchor ?: declarations.firstOrNull() ?: return addDeclaration(declaration) return getOrCreateBody().addBefore(declaration, anchorAfter) as T } @@ -112,9 +112,11 @@ abstract class KtClassOrObject : fun isAnnotation(): Boolean = hasModifier(KtTokens.ANNOTATION_KEYWORD) fun getDeclarationKeyword(): PsiElement? = - findChildByType(TokenSet.create( - KtTokens.CLASS_KEYWORD, KtTokens.INTERFACE_KEYWORD, KtTokens.OBJECT_KEYWORD - )) + findChildByType( + TokenSet.create( + KtTokens.CLASS_KEYWORD, KtTokens.INTERFACE_KEYWORD, KtTokens.OBJECT_KEYWORD + ) + ) override fun delete() { CheckUtil.checkWritable(this) @@ -122,8 +124,7 @@ abstract class KtClassOrObject : val file = containingKtFile if (!isTopLevel() || file.declarations.size > 1) { super.delete() - } - else { + } else { file.delete() } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtCodeFragment.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtCodeFragment.kt index 5a0da935d42..3e499e9bdf1 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtCodeFragment.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtCodeFragment.kt @@ -31,13 +31,21 @@ import org.jetbrains.kotlin.types.KotlinType import java.util.* abstract class KtCodeFragment( - private val _project: Project, - name: String, - text: CharSequence, - imports: String?, // Should be separated by JetCodeFragment.IMPORT_SEPARATOR - elementType: IElementType, - private val context: PsiElement? -): KtFile((PsiManager.getInstance(_project) as PsiManagerEx).fileManager.createFileViewProvider(LightVirtualFile(name, KotlinFileType.INSTANCE, text), true), false), JavaCodeFragment { + private val _project: Project, + name: String, + text: CharSequence, + imports: String?, // Should be separated by JetCodeFragment.IMPORT_SEPARATOR + elementType: IElementType, + private val context: PsiElement? +) : KtFile( + (PsiManager.getInstance(_project) as PsiManagerEx).fileManager.createFileViewProvider( + LightVirtualFile( + name, + KotlinFileType.INSTANCE, + text + ), true + ), false +), JavaCodeFragment { private var viewProvider = super.getViewProvider() as SingleRootFileViewProvider private var imports = LinkedHashSet() @@ -93,7 +101,8 @@ abstract class KtCodeFragment( clone.isPhysical = false clone.originalFile = this clone.imports = imports - clone.viewProvider = SingleRootFileViewProvider(PsiManager.getInstance(_project), LightVirtualFile(name, KotlinFileType.INSTANCE, text), false) + clone.viewProvider = + SingleRootFileViewProvider(PsiManager.getInstance(_project), LightVirtualFile(name, KotlinFileType.INSTANCE, text), false) clone.viewProvider.forceCachedPsi(clone) return clone } @@ -147,7 +156,7 @@ abstract class KtCodeFragment( override val importDirectives: List get() = importsAsImportList()?.imports ?: emptyList() - override fun setVisibilityChecker(checker: JavaCodeFragment.VisibilityChecker?) { } + override fun setVisibilityChecker(checker: JavaCodeFragment.VisibilityChecker?) {} override fun getVisibilityChecker() = JavaCodeFragment.VisibilityChecker.EVERYTHING_VISIBLE diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtConstructor.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtConstructor.kt index 9e5a310bd50..b25faf11ea6 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtConstructor.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtConstructor.kt @@ -86,8 +86,8 @@ abstract class KtConstructor> : KtDeclarationStub): Array? { if (stub.getParentStubOfType(KtImportDirective::class.java) == null && stub.getParentStubOfType(KtPackageDirective::class.java) == null) { - LOG.error("KtDotQualifiedExpression should only have stubs inside import or package directives.\n" + - "Stubs were created for:\n$text\nFile text:\n${containingFile.text}") + LOG.error( + "KtDotQualifiedExpression should only have stubs inside import or package directives.\n" + + "Stubs were created for:\n$text\nFile text:\n${containingFile.text}" + ) return null - } - else { + } else { val expressions = stub.getChildrenByType(INSIDE_DIRECTIVE_EXPRESSIONS, KtExpression.ARRAY_FACTORY) if (expressions.size !in 1..2) { - LOG.error("Invalid stub structure. DOT_QUALIFIED_EXPRESSION must have one or two children. Was: ${expressions.size}\n" + - "File text:\n${containingFile.text}") + LOG.error( + "Invalid stub structure. DOT_QUALIFIED_EXPRESSION must have one or two children. Was: ${expressions.size}\n" + + "File text:\n${containingFile.text}" + ) return null } return expressions diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtExpressionCodeFragment.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtExpressionCodeFragment.kt index bb164b2afb3..3754cfee883 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtExpressionCodeFragment.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtExpressionCodeFragment.kt @@ -21,11 +21,11 @@ import com.intellij.psi.PsiElement import org.jetbrains.kotlin.KtNodeTypes class KtExpressionCodeFragment( - project: Project, - name: String, - text: CharSequence, - imports: String?, - context: PsiElement? + project: Project, + name: String, + text: CharSequence, + imports: String?, + context: PsiElement? ) : KtCodeFragment(project, name, text, imports, KtNodeTypes.EXPRESSION_CODE_FRAGMENT, context) { override fun getContentElement() = findChildByClass(KtExpression::class.java) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtExpressionWithLabel.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtExpressionWithLabel.kt index 2806e4a68c0..c0e79519b0e 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtExpressionWithLabel.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtExpressionWithLabel.kt @@ -23,7 +23,7 @@ import org.jetbrains.kotlin.name.Name open class KtExpressionWithLabel(node: ASTNode) : KtExpressionImpl(node) { fun getTargetLabel(): KtSimpleNameExpression? = - labelQualifier?.findChildByType(KtNodeTypes.LABEL) as? KtSimpleNameExpression + labelQualifier?.findChildByType(KtNodeTypes.LABEL) as? KtSimpleNameExpression val labelQualifier: KtContainerNode? get() = findChildByType(KtNodeTypes.LABEL_QUALIFIER) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtFile.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtFile.kt index a60d0a59236..be41eb3c0fe 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtFile.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtFile.kt @@ -36,13 +36,13 @@ import org.jetbrains.kotlin.psi.stubs.elements.KtPlaceHolderStubElementType import org.jetbrains.kotlin.psi.stubs.elements.KtStubElementTypes open class KtFile(viewProvider: FileViewProvider, val isCompiled: Boolean) : - PsiFileBase(viewProvider, KotlinLanguage.INSTANCE), - KtDeclarationContainer, - KtAnnotated, - KtElement, - PsiClassOwner, - PsiNamedElement, - PsiModifiableCodeBlock { + PsiFileBase(viewProvider, KotlinLanguage.INSTANCE), + KtDeclarationContainer, + KtAnnotated, + KtElement, + PsiClassOwner, + PsiNamedElement, + PsiModifiableCodeBlock { @Volatile private var isScript: Boolean? = null @@ -85,8 +85,7 @@ open class KtFile(viewProvider: FileViewProvider, val isCompiled: Boolean) : val packageDirective = packageDirective if (packageDirective != null) { packageDirective.fqName = value - } - else { + } else { val newPackageDirective = KtPsiFactory(this).createPackageDirectiveIfNeeded(value) ?: return addAfter(newPackageDirective, null) } @@ -126,8 +125,8 @@ open class KtFile(viewProvider: FileViewProvider, val isCompiled: Boolean) : get() { val stub = stub val danglingModifierLists = stub?.getChildrenByType( - KtStubElementTypes.MODIFIER_LIST, - KtStubElementTypes.MODIFIER_LIST.arrayFactory + KtStubElementTypes.MODIFIER_LIST, + KtStubElementTypes.MODIFIER_LIST.arrayFactory ) ?: findChildrenByClass(KtModifierList::class.java) return danglingModifierLists.flatMap { obj: KtModifierList -> obj.annotationEntries } } @@ -139,12 +138,12 @@ open class KtFile(viewProvider: FileViewProvider, val isCompiled: Boolean) : override fun getDeclarations(): List { val stub = stub return stub?.getChildrenByType(KtStubElementTypes.DECLARATION_TYPES, KtDeclaration.ARRAY_FACTORY)?.toList() - ?: PsiTreeUtil.getChildrenOfTypeAsList(this, KtDeclaration::class.java) + ?: PsiTreeUtil.getChildrenOfTypeAsList(this, KtDeclaration::class.java) } fun >> findChildByTypeOrClass( - elementType: KtPlaceHolderStubElementType, - elementClass: Class + elementType: KtPlaceHolderStubElementType, + elementClass: Class ): T? { val stub = stub if (stub != null) { @@ -155,7 +154,7 @@ open class KtFile(viewProvider: FileViewProvider, val isCompiled: Boolean) : } fun findImportByAlias(name: String): KtImportDirective? = - importDirectives.firstOrNull { name == it.aliasName } + importDirectives.firstOrNull { name == it.aliasName } @Deprecated("") // getPackageFqName should be used instead override fun getPackageName(): String { @@ -188,9 +187,9 @@ open class KtFile(viewProvider: FileViewProvider, val isCompiled: Boolean) : val result = declarations.any { (it is KtProperty || - it is KtNamedFunction || - it is KtScript || - it is KtTypeAlias) && !it.hasExpectModifier() + it is KtNamedFunction || + it is KtScript || + it is KtTypeAlias) && !it.hasExpectModifier() } hasTopLeveCallables = result @@ -201,8 +200,7 @@ open class KtFile(viewProvider: FileViewProvider, val isCompiled: Boolean) : if (visitor is KtVisitor<*, *>) { @Suppress("UNCHECKED_CAST") accept(visitor as KtVisitor, null) - } - else { + } else { visitor.visitFile(this) } } @@ -218,10 +216,10 @@ open class KtFile(viewProvider: FileViewProvider, val isCompiled: Boolean) : } override fun getAnnotations(): List = - fileAnnotationList?.annotations ?: emptyList() + fileAnnotationList?.annotations ?: emptyList() override fun getAnnotationEntries(): List = - fileAnnotationList?.annotationEntries ?: emptyList() + fileAnnotationList?.annotationEntries ?: emptyList() @Throws(IncorrectOperationException::class) override fun setName(name: String): PsiElement { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtLabelReferenceExpression.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtLabelReferenceExpression.kt index 60e09f4dc5a..8642df38072 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtLabelReferenceExpression.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtLabelReferenceExpression.kt @@ -19,5 +19,5 @@ package org.jetbrains.kotlin.psi import com.intellij.lang.ASTNode class KtLabelReferenceExpression(node: ASTNode) : KtSimpleNameExpressionImpl(node) { - override fun getReferencedNameElement() = getIdentifier() ?: this + override fun getReferencedNameElement() = getIdentifier() ?: this } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtObjectDeclaration.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtObjectDeclaration.kt index 351ced03640..66e7bba9096 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtObjectDeclaration.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtObjectDeclaration.kt @@ -49,8 +49,7 @@ class KtObjectDeclaration : KtClassOrObject { addAfter(psiFactory.createWhiteSpace(), getObjectKeyword()!!) result - } - else { + } else { super.setName(name) } } @@ -58,7 +57,7 @@ class KtObjectDeclaration : KtClassOrObject { fun isCompanion(): Boolean = _stub?.isCompanion() ?: hasModifier(KtTokens.COMPANION_KEYWORD) override fun getTextOffset(): Int = nameIdentifier?.textRange?.startOffset - ?: getObjectKeyword()!!.textRange.startOffset + ?: getObjectKeyword()!!.textRange.startOffset override fun accept(visitor: KtVisitor, data: D): R { return visitor.visitObjectDeclaration(this, data) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtTypeReference.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtTypeReference.kt index a0a7def9179..7c30423cfcc 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtTypeReference.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtTypeReference.kt @@ -28,7 +28,7 @@ import org.jetbrains.kotlin.psi.stubs.elements.KtStubElementTypes * Underlying token is [org.jetbrains.kotlin.KtNodeTypes.TYPE_REFERENCE] */ class KtTypeReference : KtModifierListOwnerStub>, - KtAnnotated, KtAnnotationsContainer { + KtAnnotated, KtAnnotationsContainer { constructor(node: ASTNode) : super(node) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/TypeRefHelpers.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/TypeRefHelpers.kt index 4d1bf58960d..b597c58046c 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/TypeRefHelpers.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/TypeRefHelpers.kt @@ -27,8 +27,8 @@ import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull fun getTypeReference(declaration: KtCallableDeclaration): KtTypeReference? { return declaration.firstChild!!.siblings(forward = true) - .dropWhile { it.node!!.elementType != KtTokens.COLON } - .firstIsInstanceOrNull() + .dropWhile { it.node!!.elementType != KtTokens.COLON } + .firstIsInstanceOrNull() } fun setTypeReference(declaration: KtCallableDeclaration, addAfter: PsiElement?, typeRef: KtTypeReference?): KtTypeReference? { @@ -36,17 +36,15 @@ fun setTypeReference(declaration: KtCallableDeclaration, addAfter: PsiElement?, if (typeRef != null) { return if (oldTypeRef != null) { oldTypeRef.replace(typeRef) as KtTypeReference - } - else { + } else { val anchor = addAfter - ?: declaration.nameIdentifier?.siblings(forward = true)?.firstOrNull { it is PsiErrorElement } - ?: (declaration as? KtParameter)?.destructuringDeclaration + ?: declaration.nameIdentifier?.siblings(forward = true)?.firstOrNull { it is PsiErrorElement } + ?: (declaration as? KtParameter)?.destructuringDeclaration val newTypeRef = declaration.addAfter(typeRef, anchor) as KtTypeReference declaration.addAfter(KtPsiFactory(declaration.project).createColon(), anchor) newTypeRef } - } - else { + } else { if (oldTypeRef != null) { val colon = declaration.colon!! val removeFrom = colon.prevSibling as? PsiWhiteSpace ?: colon @@ -57,30 +55,28 @@ fun setTypeReference(declaration: KtCallableDeclaration, addAfter: PsiElement?, } private inline fun T.doSetReceiverTypeReference( - typeRef: KtTypeReference?, - getReceiverTypeReference: T.() -> KtTypeReference?, - addReceiverTypeReference: T.(typeRef: KtTypeReference) -> KtTypeReference + typeRef: KtTypeReference?, + getReceiverTypeReference: T.() -> KtTypeReference?, + addReceiverTypeReference: T.(typeRef: KtTypeReference) -> KtTypeReference ): KtTypeReference? { val needParentheses = typeRef != null && typeRef.typeElement is KtFunctionType && !typeRef.hasParentheses() val oldTypeRef = getReceiverTypeReference() if (typeRef != null) { val newTypeRef = - if (oldTypeRef != null) { - oldTypeRef.replace(typeRef) as KtTypeReference - } - else { - val newTypeRef = addReceiverTypeReference(typeRef) - addAfter(KtPsiFactory(project).createDot(), newTypeRef.parentsWithSelf.first { it.parent == this }) - newTypeRef - } + if (oldTypeRef != null) { + oldTypeRef.replace(typeRef) as KtTypeReference + } else { + val newTypeRef = addReceiverTypeReference(typeRef) + addAfter(KtPsiFactory(project).createDot(), newTypeRef.parentsWithSelf.first { it.parent == this }) + newTypeRef + } if (needParentheses) { val argList = KtPsiFactory(project).createCallArguments("()") newTypeRef.addBefore(argList.leftParenthesis!!, newTypeRef.firstChild) newTypeRef.add(argList.rightParenthesis!!) } return newTypeRef - } - else { + } else { if (oldTypeRef != null) { val dotSibling = oldTypeRef.parent as? KtFunctionTypeReceiver ?: oldTypeRef val dot = dotSibling.siblings(forward = true).firstOrNull { it.node.elementType == KtTokens.DOT } @@ -91,18 +87,20 @@ private inline fun T.doSetReceiverTypeReference( } fun KtCallableDeclaration.setReceiverTypeReference(typeRef: KtTypeReference?) = - doSetReceiverTypeReference( - typeRef, - { receiverTypeReference }, - { this.addBefore(it, nameIdentifier ?: valueParameterList) as KtTypeReference } - ) + doSetReceiverTypeReference( + typeRef, + { receiverTypeReference }, + { this.addBefore(it, nameIdentifier ?: valueParameterList) as KtTypeReference } + ) fun KtFunctionType.setReceiverTypeReference(typeRef: KtTypeReference?) = - doSetReceiverTypeReference( - typeRef, - { receiverTypeReference }, - { - (addBefore(KtPsiFactory(project).createFunctionTypeReceiver(it), - parameterList ?: firstChild) as KtFunctionTypeReceiver).typeReference - } - ) \ No newline at end of file + doSetReceiverTypeReference( + typeRef, + { receiverTypeReference }, + { + (addBefore( + KtPsiFactory(project).createFunctionTypeReceiver(it), + parameterList ?: firstChild + ) as KtFunctionTypeReceiver).typeReference + } + ) \ No newline at end of file diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/ValueArgument.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/ValueArgument.kt index f4d59648f71..8e5203415cc 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/ValueArgument.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/ValueArgument.kt @@ -20,7 +20,8 @@ import com.intellij.psi.impl.source.tree.LeafPsiElement import org.jetbrains.kotlin.name.Name interface ValueArgument { - @IfNotParsed fun getArgumentExpression(): KtExpression? + @IfNotParsed + fun getArgumentExpression(): KtExpression? fun getArgumentName(): ValueArgumentName? diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/psiUtil/KtStringTemplateExpressionManipulator.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/psiUtil/KtStringTemplateExpressionManipulator.kt index 554c3b25230..2085afa19f6 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/psiUtil/KtStringTemplateExpressionManipulator.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/psiUtil/KtStringTemplateExpressionManipulator.kt @@ -23,7 +23,11 @@ import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtStringTemplateExpression class KtStringTemplateExpressionManipulator : AbstractElementManipulator() { - override fun handleContentChange(element: KtStringTemplateExpression, range: TextRange, newContent: String): KtStringTemplateExpression? { + override fun handleContentChange( + element: KtStringTemplateExpression, + range: TextRange, + newContent: String + ): KtStringTemplateExpression? { val node = element.node val content = if (element.isSingleQuoted()) StringUtil.escapeStringCharacters(newContent) else newContent val oldText = node.text diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/psiUtil/PsiChildRange.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/psiUtil/PsiChildRange.kt index 14cf128d79a..4ec363bc7f0 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/psiUtil/PsiChildRange.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/psiUtil/PsiChildRange.kt @@ -22,8 +22,7 @@ data class PsiChildRange(val first: PsiElement?, val last: PsiElement?) : Sequen init { if (first == null) { assert(last == null) - } - else { + } else { assert(first.parent == last!!.parent) } } @@ -34,8 +33,7 @@ data class PsiChildRange(val first: PsiElement?, val last: PsiElement?) : Sequen override fun iterator(): Iterator { val sequence = if (first == null) { emptySequence() - } - else { + } else { val afterLast = last!!.nextSibling first.siblings().takeWhile { it != afterLast } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/psiUtil/StringTemplateExpressionManipulator.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/psiUtil/StringTemplateExpressionManipulator.kt index e2bc26c6d5e..0621025481c 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/psiUtil/StringTemplateExpressionManipulator.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/psiUtil/StringTemplateExpressionManipulator.kt @@ -22,8 +22,12 @@ import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.psi.KtPsiFactory import com.intellij.openapi.util.text.StringUtil -class StringTemplateExpressionManipulator: AbstractElementManipulator() { - override fun handleContentChange(element: KtStringTemplateExpression, range: TextRange, newContent: String): KtStringTemplateExpression? { +class StringTemplateExpressionManipulator : AbstractElementManipulator() { + override fun handleContentChange( + element: KtStringTemplateExpression, + range: TextRange, + newContent: String + ): KtStringTemplateExpression? { val node = element.node val content = if (node.firstChildNode.textLength == 1) StringUtil.escapeStringCharacters(newContent) else newContent val oldText = node.text diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/elements/KtScriptElementType.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/elements/KtScriptElementType.kt index 9dd89658ee0..7b772301258 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/elements/KtScriptElementType.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/elements/KtScriptElementType.kt @@ -27,7 +27,7 @@ import org.jetbrains.kotlin.psi.stubs.KotlinScriptStub import org.jetbrains.kotlin.psi.stubs.impl.KotlinScriptStubImpl class KtScriptElementType(debugName: String) : KtStubElementType( - debugName, KtScript::class.java, KotlinScriptStub::class.java + debugName, KtScript::class.java, KotlinScriptStub::class.java ) { override fun createStub(psi: KtScript, parentStub: StubElement): KotlinScriptStub { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/elements/KtTypeAliasElementType.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/elements/KtTypeAliasElementType.kt index ede75ae37bd..1765fc90a29 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/elements/KtTypeAliasElementType.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/elements/KtTypeAliasElementType.kt @@ -27,7 +27,7 @@ import org.jetbrains.kotlin.psi.stubs.impl.KotlinTypeAliasStubImpl import org.jetbrains.kotlin.resolve.lazy.ResolveSessionUtils class KtTypeAliasElementType(debugName: String) : - KtStubElementType(debugName, KtTypeAlias::class.java, KotlinTypeAliasStub::class.java) { + KtStubElementType(debugName, KtTypeAlias::class.java, KotlinTypeAliasStub::class.java) { override fun createStub(psi: KtTypeAlias, parentStub: StubElement<*>?): KotlinTypeAliasStub { val name = StringRef.fromString(psi.name) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/elements/StubIndexService.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/elements/StubIndexService.kt index 8104842c759..64315cfa257 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/elements/StubIndexService.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/elements/StubIndexService.kt @@ -71,7 +71,8 @@ open class StubIndexService protected constructor() { } companion object { - @JvmStatic fun getInstance(): StubIndexService { + @JvmStatic + fun getInstance(): StubIndexService { return ServiceManager.getService(StubIndexService::class.java) ?: NO_INDEX } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinClassStubImpl.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinClassStubImpl.kt index 8b080b9e7af..d2f0154c290 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinClassStubImpl.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinClassStubImpl.kt @@ -26,15 +26,15 @@ import org.jetbrains.kotlin.psi.stubs.elements.KtClassElementType import java.util.* class KotlinClassStubImpl( - type: KtClassElementType, - parent: StubElement?, - private val qualifiedName: StringRef?, - private val name: StringRef?, - private val superNames: Array, - private val isInterface: Boolean, - private val isEnumEntry: Boolean, - private val isLocal: Boolean, - private val isTopLevel: Boolean + type: KtClassElementType, + parent: StubElement?, + private val qualifiedName: StringRef?, + private val name: StringRef?, + private val superNames: Array, + private val isInterface: Boolean, + private val isEnumEntry: Boolean, + private val isLocal: Boolean, + private val isTopLevel: Boolean ) : KotlinStubBaseImpl(parent, type), KotlinClassStub { override fun getFqName(): FqName? { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinEnumEntrySuperclassReferenceExpressionStubImpl.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinEnumEntrySuperclassReferenceExpressionStubImpl.kt index 20e66edc945..fe2065a4242 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinEnumEntrySuperclassReferenceExpressionStubImpl.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinEnumEntrySuperclassReferenceExpressionStubImpl.kt @@ -22,8 +22,9 @@ import org.jetbrains.kotlin.psi.KtEnumEntrySuperclassReferenceExpression import org.jetbrains.kotlin.psi.stubs.KotlinEnumEntrySuperclassReferenceExpressionStub import org.jetbrains.kotlin.psi.stubs.elements.KtStubElementTypes -class KotlinEnumEntrySuperclassReferenceExpressionStubImpl(parent: StubElement<*>, private val referencedName: StringRef) - : KotlinStubBaseImpl(parent, KtStubElementTypes.ENUM_ENTRY_SUPERCLASS_REFERENCE_EXPRESSION), KotlinEnumEntrySuperclassReferenceExpressionStub { +class KotlinEnumEntrySuperclassReferenceExpressionStubImpl(parent: StubElement<*>, private val referencedName: StringRef) : + KotlinStubBaseImpl(parent, KtStubElementTypes.ENUM_ENTRY_SUPERCLASS_REFERENCE_EXPRESSION), + KotlinEnumEntrySuperclassReferenceExpressionStub { override fun getReferencedName() = referencedName.string } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinFileStubImpl.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinFileStubImpl.kt index 0f9e24916c9..1a93db8ed15 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinFileStubImpl.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinFileStubImpl.kt @@ -32,13 +32,13 @@ import org.jetbrains.kotlin.psi.stubs.elements.KtStubElementTypes.IMPORT_LIST import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull open class KotlinFileStubImpl( - jetFile: KtFile?, - private val packageName: StringRef, - private val isScript: Boolean + jetFile: KtFile?, + private val packageName: StringRef, + private val isScript: Boolean ) : PsiFileStubImpl(jetFile), KotlinFileStub, PsiClassHolderFileStub { constructor(jetFile: KtFile?, packageName: String, isScript: Boolean) - : this(jetFile, StringRef.fromString(packageName)!!, isScript) + : this(jetFile, StringRef.fromString(packageName)!!, isScript) override fun getPackageFqName(): FqName = FqName(StringRef.toString(packageName)!!) override fun isScript(): Boolean = isScript diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinImportAliasStubImpl.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinImportAliasStubImpl.kt index d0edfbe987c..637350f81c6 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinImportAliasStubImpl.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinImportAliasStubImpl.kt @@ -24,8 +24,8 @@ import org.jetbrains.kotlin.psi.stubs.KotlinImportAliasStub import org.jetbrains.kotlin.psi.stubs.elements.KtStubElementTypes class KotlinImportAliasStubImpl( - parent: StubElement?, - private val name: StringRef? + parent: StubElement?, + private val name: StringRef? ) : KotlinStubBaseImpl(parent, KtStubElementTypes.IMPORT_ALIAS), KotlinImportAliasStub { override fun getName(): String? = StringRef.toString(name) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinImportDirectiveStubImpl.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinImportDirectiveStubImpl.kt index 1a6db306794..021c262377c 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinImportDirectiveStubImpl.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinImportDirectiveStubImpl.kt @@ -25,10 +25,10 @@ import org.jetbrains.kotlin.psi.stubs.KotlinImportDirectiveStub import org.jetbrains.kotlin.psi.stubs.elements.KtStubElementTypes class KotlinImportDirectiveStubImpl( - parent: StubElement, - private val isAllUnder: Boolean, - private val importedFqName: StringRef?, - private val isValid: Boolean + parent: StubElement, + private val isAllUnder: Boolean, + private val importedFqName: StringRef?, + private val isValid: Boolean ) : KotlinStubBaseImpl(parent, KtStubElementTypes.IMPORT_DIRECTIVE), KotlinImportDirectiveStub { override fun isAllUnder(): Boolean = isAllUnder diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinObjectStubImpl.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinObjectStubImpl.kt index 01949a3e8ee..07b0057caca 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinObjectStubImpl.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinObjectStubImpl.kt @@ -26,14 +26,14 @@ import org.jetbrains.kotlin.name.FqName import com.intellij.psi.PsiElement class KotlinObjectStubImpl( - parent: StubElement?, - private val name: StringRef?, - private val fqName: FqName?, - private val superNames: Array, - private val isTopLevel: Boolean, - private val isDefault: Boolean, - private val isLocal: Boolean, - private val isObjectLiteral: Boolean + parent: StubElement?, + private val name: StringRef?, + private val fqName: FqName?, + private val superNames: Array, + private val isTopLevel: Boolean, + private val isDefault: Boolean, + private val isLocal: Boolean, + private val isObjectLiteral: Boolean ) : KotlinStubBaseImpl(parent, KtStubElementTypes.OBJECT_DECLARATION), KotlinObjectStub { override fun getFqName() = fqName override fun getName() = StringRef.toString(name) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinPropertyStubImpl.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinPropertyStubImpl.kt index ac56b293240..5cbdd0ec1f7 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinPropertyStubImpl.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinPropertyStubImpl.kt @@ -25,16 +25,16 @@ import org.jetbrains.kotlin.name.FqName import com.intellij.psi.PsiElement class KotlinPropertyStubImpl( - parent: StubElement?, - private val name: StringRef?, - private val isVar: Boolean, - private val isTopLevel: Boolean, - private val hasDelegate: Boolean, - private val hasDelegateExpression: Boolean, - private val hasInitializer: Boolean, - private val isExtension: Boolean, - private val hasReturnTypeRef: Boolean, - private val fqName: FqName? + parent: StubElement?, + private val name: StringRef?, + private val isVar: Boolean, + private val isTopLevel: Boolean, + private val hasDelegate: Boolean, + private val hasDelegateExpression: Boolean, + private val hasInitializer: Boolean, + private val isExtension: Boolean, + private val hasReturnTypeRef: Boolean, + private val fqName: FqName? ) : KotlinStubBaseImpl(parent, KtStubElementTypes.PROPERTY), KotlinPropertyStub { init { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinScriptStubImpl.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinScriptStubImpl.kt index 99518df13ea..049ce44d1ef 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinScriptStubImpl.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinScriptStubImpl.kt @@ -25,8 +25,8 @@ import org.jetbrains.kotlin.psi.stubs.KotlinScriptStub import org.jetbrains.kotlin.psi.stubs.elements.KtStubElementTypes class KotlinScriptStubImpl( - parent: StubElement?, - private val _fqName: StringRef? + parent: StubElement?, + private val _fqName: StringRef? ) : KotlinStubBaseImpl(parent, KtStubElementTypes.SCRIPT), KotlinScriptStub { override fun getName(): String = getFqName().shortName().asString() diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinTypeAliasStubImpl.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinTypeAliasStubImpl.kt index 93ec9779696..282662c3485 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinTypeAliasStubImpl.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinTypeAliasStubImpl.kt @@ -25,17 +25,17 @@ import org.jetbrains.kotlin.psi.stubs.KotlinTypeAliasStub import org.jetbrains.kotlin.psi.stubs.elements.KtStubElementTypes class KotlinTypeAliasStubImpl( - parent: StubElement?, - private val name: StringRef?, - private val qualifiedName: StringRef?, - private val isTopLevel: Boolean + parent: StubElement?, + private val name: StringRef?, + private val qualifiedName: StringRef?, + private val isTopLevel: Boolean ) : KotlinStubBaseImpl(parent, KtStubElementTypes.TYPEALIAS), KotlinTypeAliasStub { override fun getName(): String? = - StringRef.toString(name) + StringRef.toString(name) override fun getFqName(): FqName? = - StringRef.toString(qualifiedName)?.let(::FqName) + StringRef.toString(qualifiedName)?.let(::FqName) override fun isTopLevel(): Boolean = isTopLevel } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinTypeParameterStubImpl.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinTypeParameterStubImpl.kt index ee728c2f5e8..4a46145a6db 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinTypeParameterStubImpl.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/KotlinTypeParameterStubImpl.kt @@ -24,10 +24,10 @@ import org.jetbrains.kotlin.psi.stubs.elements.KtStubElementTypes import com.intellij.psi.PsiElement class KotlinTypeParameterStubImpl( - parent: StubElement?, - private val name: StringRef?, - private val isInVariance: Boolean, - private val isOutVariance: Boolean + parent: StubElement?, + private val name: StringRef?, + private val isInVariance: Boolean, + private val isOutVariance: Boolean ) : KotlinStubBaseImpl(parent, KtStubElementTypes.TYPE_PARAMETER), KotlinTypeParameterStub { override fun isInVariance() = isInVariance override fun isOutVariance() = isOutVariance diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/ModifierMaskUtils.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/ModifierMaskUtils.kt index 64cef741458..3e5bdb59d14 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/ModifierMaskUtils.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/stubs/impl/ModifierMaskUtils.kt @@ -26,9 +26,11 @@ object ModifierMaskUtils { assert(MODIFIER_KEYWORDS_ARRAY.size <= 32) { "Current implementation depends on the ability to represent modifier list as bit mask" } } - @JvmStatic fun computeMaskFromModifierList(modifierList: KtModifierList): Int = computeMask { modifierList.hasModifier(it) } + @JvmStatic + fun computeMaskFromModifierList(modifierList: KtModifierList): Int = computeMask { modifierList.hasModifier(it) } - @JvmStatic fun computeMask(hasModifier: (KtModifierKeywordToken) -> Boolean): Int { + @JvmStatic + fun computeMask(hasModifier: (KtModifierKeywordToken) -> Boolean): Int { var mask = 0 for ((index, modifierKeywordToken) in MODIFIER_KEYWORDS_ARRAY.withIndex()) { if (hasModifier(modifierKeywordToken)) { @@ -38,13 +40,15 @@ object ModifierMaskUtils { return mask } - @JvmStatic fun maskHasModifier(mask: Int, modifierToken: KtModifierKeywordToken): Boolean { + @JvmStatic + fun maskHasModifier(mask: Int, modifierToken: KtModifierKeywordToken): Boolean { val index = MODIFIER_KEYWORDS_ARRAY.indexOf(modifierToken) assert(index >= 0) { "All JetModifierKeywordTokens should be present in MODIFIER_KEYWORDS_ARRAY" } return (mask and (1 shl index)) != 0 } - @JvmStatic fun maskToString(mask: Int): String { + @JvmStatic + fun maskToString(mask: Int): String { val sb = StringBuilder() sb.append("[") var first = true diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/AbstractFilteringTrace.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/AbstractFilteringTrace.kt index 72bbfdf2178..d8b01f6a917 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/AbstractFilteringTrace.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/AbstractFilteringTrace.kt @@ -27,8 +27,8 @@ import org.jetbrains.kotlin.util.slicedMap.WritableSlice * (like storing them in the local map, later re-committing into parent's, etc.) */ abstract class AbstractFilteringTrace( - private val parentTrace: BindingTrace, - name: String + private val parentTrace: BindingTrace, + name: String ) : DelegatingBindingTrace(parentTrace.bindingContext, name, true, BindingTraceFilter.ACCEPT_ALL, false) { abstract protected fun shouldBeHiddenFromParent(slice: WritableSlice, key: K): Boolean diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationChecker.kt index ee128781bae..67d2769b708 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationChecker.kt @@ -41,8 +41,8 @@ import org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils import org.jetbrains.kotlin.types.isError class AnnotationChecker( - private val additionalCheckers: Iterable, - private val languageVersionSettings: LanguageVersionSettings + private val additionalCheckers: Iterable, + private val languageVersionSettings: LanguageVersionSettings ) { fun check(annotated: KtAnnotated, trace: BindingTrace, descriptor: DeclarationDescriptor? = null) { @@ -86,25 +86,25 @@ class AnnotationChecker( private fun KtAnnotated?.getImplicitUseSiteTargetList(): List = when (this) { is KtParameter -> - if (ownerFunction is KtPrimaryConstructor) UseSiteTargetsList.T_CONSTRUCTOR_PARAMETER else emptyList() + if (ownerFunction is KtPrimaryConstructor) UseSiteTargetsList.T_CONSTRUCTOR_PARAMETER else emptyList() is KtProperty -> - if (!isLocal) UseSiteTargetsList.T_PROPERTY else emptyList() + if (!isLocal) UseSiteTargetsList.T_PROPERTY else emptyList() is KtPropertyAccessor -> - if (isGetter) listOf(AnnotationUseSiteTarget.PROPERTY_GETTER) else listOf(AnnotationUseSiteTarget.PROPERTY_SETTER) + if (isGetter) listOf(AnnotationUseSiteTarget.PROPERTY_GETTER) else listOf(AnnotationUseSiteTarget.PROPERTY_SETTER) else -> - emptyList() + emptyList() } private fun KtAnnotated?.getDefaultUseSiteTarget(descriptor: AnnotationDescriptor) = - getImplicitUseSiteTargetList().firstOrNull { - KotlinTarget.USE_SITE_MAPPING[it] in AnnotationChecker.applicableTargetSet(descriptor) - } + getImplicitUseSiteTargetList().firstOrNull { + KotlinTarget.USE_SITE_MAPPING[it] in AnnotationChecker.applicableTargetSet(descriptor) + } private fun checkEntries( - entries: List, - actualTargets: TargetList, - trace: BindingTrace, - annotated: KtAnnotated? = null + entries: List, + actualTargets: TargetList, + trace: BindingTrace, + annotated: KtAnnotated? = null ) { val entryTypesWithAnnotations = hashMapOf>() @@ -116,7 +116,7 @@ class AnnotationChecker( val useSiteTarget = entry.useSiteTarget?.getAnnotationUseSiteTarget() ?: annotated.getDefaultUseSiteTarget(descriptor) val existingTargetsForAnnotation = entryTypesWithAnnotations.getOrPut(descriptor.type) { arrayListOf() } val duplicateAnnotation = useSiteTarget in existingTargetsForAnnotation - || (existingTargetsForAnnotation.any { (it == null) != (useSiteTarget == null) }) + || (existingTargetsForAnnotation.any { (it == null) != (useSiteTarget == null) }) if (duplicateAnnotation && !classDescriptor.isRepeatableAnnotation()) { trace.report(Errors.REPEATED_ANNOTATION.on(entry)) @@ -174,12 +174,17 @@ class AnnotationChecker( } if (useSiteTarget != null) { - trace.report(Errors.WRONG_ANNOTATION_TARGET_WITH_USE_SITE_TARGET.on( - entry, actualTargets.defaultTargets.firstOrNull()?.description ?: "unidentified target", useSiteTarget.renderName)) - } - else { - trace.report(Errors.WRONG_ANNOTATION_TARGET.on( - entry, actualTargets.defaultTargets.firstOrNull()?.description ?: "unidentified target")) + trace.report( + Errors.WRONG_ANNOTATION_TARGET_WITH_USE_SITE_TARGET.on( + entry, actualTargets.defaultTargets.firstOrNull()?.description ?: "unidentified target", useSiteTarget.renderName + ) + ) + } else { + trace.report( + Errors.WRONG_ANNOTATION_TARGET.on( + entry, actualTargets.defaultTargets.firstOrNull()?.description ?: "unidentified target" + ) + ) } } @@ -191,14 +196,15 @@ class AnnotationChecker( return descriptor.annotationClass?.let(this::applicableTargetSet) ?: KotlinTarget.DEFAULT_TARGET_SET } - @JvmStatic fun applicableTargetSet(descriptor: AnnotationDescriptor): Set { + @JvmStatic + fun applicableTargetSet(descriptor: AnnotationDescriptor): Set { val classDescriptor = descriptor.annotationClass ?: return emptySet() return applicableTargetSet(classDescriptor) ?: KotlinTarget.DEFAULT_TARGET_SET } fun applicableTargetSet(classDescriptor: ClassDescriptor): Set? { val targetEntryDescriptor = classDescriptor.annotations.findAnnotation(KotlinBuiltIns.FQ_NAMES.target) - ?: return null + ?: return null val valueArguments = targetEntryDescriptor.allValueArguments val valueArgument = valueArguments.entries.firstOrNull()?.value as? ArrayValue ?: return null return valueArgument.value.filterIsInstance().mapNotNull { @@ -211,8 +217,8 @@ class AnnotationChecker( return getActualTargetList(annotated, descriptor, trace).defaultTargets } - private fun DeclarationDescriptor?.hasBackingField(bindingTrace: BindingTrace) - = (this as? PropertyDescriptor)?.let { bindingTrace.get(BindingContext.BACKING_FIELD_REQUIRED, it) } ?: false + private fun DeclarationDescriptor?.hasBackingField(bindingTrace: BindingTrace) = + (this as? PropertyDescriptor)?.let { bindingTrace.get(BindingContext.BACKING_FIELD_REQUIRED, it) } ?: false private fun getActualTargetList(annotated: KtElement, descriptor: DeclarationDescriptor?, trace: BindingTrace): TargetList { return when (annotated) { @@ -273,29 +279,32 @@ class AnnotationChecker( if (backingField) extraTargets(FIELD) if (delegate) { onlyWithUseSiteTarget(VALUE_PARAMETER, PROPERTY_GETTER, PROPERTY_SETTER, FIELD) - } - else { + } else { onlyWithUseSiteTarget(VALUE_PARAMETER, PROPERTY_GETTER, PROPERTY_SETTER) } } fun T_MEMBER_PROPERTY(backingField: Boolean, delegate: Boolean) = - targetList(when { + targetList( + when { backingField -> MEMBER_PROPERTY_WITH_BACKING_FIELD delegate -> MEMBER_PROPERTY_WITH_DELEGATE else -> MEMBER_PROPERTY_WITHOUT_FIELD_OR_DELEGATE - }, MEMBER_PROPERTY, PROPERTY) { - propertyTargets(backingField, delegate) - } + }, MEMBER_PROPERTY, PROPERTY + ) { + propertyTargets(backingField, delegate) + } fun T_TOP_LEVEL_PROPERTY(backingField: Boolean, delegate: Boolean) = - targetList(when { + targetList( + when { backingField -> TOP_LEVEL_PROPERTY_WITH_BACKING_FIELD delegate -> TOP_LEVEL_PROPERTY_WITH_DELEGATE else -> TOP_LEVEL_PROPERTY_WITHOUT_FIELD_OR_DELEGATE - }, TOP_LEVEL_PROPERTY, PROPERTY) { - propertyTargets(backingField, delegate) - } + }, TOP_LEVEL_PROPERTY, PROPERTY + ) { + propertyTargets(backingField, delegate) + } val T_PROPERTY_GETTER = targetList(PROPERTY_GETTER) val T_PROPERTY_SETTER = targetList(PROPERTY_SETTER) @@ -368,17 +377,22 @@ class AnnotationChecker( } private class TargetList( - val defaultTargets: List, - val canBeSubstituted: List = emptyList(), - val onlyWithUseSiteTarget: List = emptyList()) + val defaultTargets: List, + val canBeSubstituted: List = emptyList(), + val onlyWithUseSiteTarget: List = emptyList() + ) private object UseSiteTargetsList { - val T_CONSTRUCTOR_PARAMETER = listOf(AnnotationUseSiteTarget.CONSTRUCTOR_PARAMETER, - AnnotationUseSiteTarget.PROPERTY, - AnnotationUseSiteTarget.FIELD) + val T_CONSTRUCTOR_PARAMETER = listOf( + AnnotationUseSiteTarget.CONSTRUCTOR_PARAMETER, + AnnotationUseSiteTarget.PROPERTY, + AnnotationUseSiteTarget.FIELD + ) - val T_PROPERTY = listOf(AnnotationUseSiteTarget.PROPERTY, - AnnotationUseSiteTarget.FIELD) + val T_PROPERTY = listOf( + AnnotationUseSiteTarget.PROPERTY, + AnnotationUseSiteTarget.FIELD + ) } } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationResolver.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationResolver.kt index 43cbb3a8343..fcee136f3e5 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationResolver.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationResolver.kt @@ -29,23 +29,23 @@ import org.jetbrains.kotlin.types.KotlinType abstract class AnnotationResolver { fun resolveAnnotationsWithoutArguments( - scope: LexicalScope, - modifierList: KtModifierList?, - trace: BindingTrace + scope: LexicalScope, + modifierList: KtModifierList?, + trace: BindingTrace ): Annotations = resolveAnnotationsFromModifierList(scope, modifierList, trace, false) fun resolveAnnotationsWithArguments( - scope: LexicalScope, - modifierList: KtModifierList?, - trace: BindingTrace + scope: LexicalScope, + modifierList: KtModifierList?, + trace: BindingTrace ): Annotations = resolveAnnotationsFromModifierList(scope, modifierList, trace, true) private fun resolveAnnotationsFromModifierList( - scope: LexicalScope, - modifierList: KtModifierList?, - trace: BindingTrace, - shouldResolveArguments: Boolean + scope: LexicalScope, + modifierList: KtModifierList?, + trace: BindingTrace, + shouldResolveArguments: Boolean ): Annotations { if (modifierList == null) { return Annotations.EMPTY @@ -55,36 +55,36 @@ abstract class AnnotationResolver { } fun resolveAnnotationsWithoutArguments( - scope: LexicalScope, - annotationEntries: @JvmSuppressWildcards List, - trace: BindingTrace + scope: LexicalScope, + annotationEntries: @JvmSuppressWildcards List, + trace: BindingTrace ): Annotations = resolveAnnotationEntries(scope, annotationEntries, trace, false) fun resolveAnnotationsWithArguments( - scope: LexicalScope, - annotationEntries: @JvmSuppressWildcards List, - trace: BindingTrace + scope: LexicalScope, + annotationEntries: @JvmSuppressWildcards List, + trace: BindingTrace ): Annotations = resolveAnnotationEntries(scope, annotationEntries, trace, true) protected abstract fun resolveAnnotationEntries( - scope: LexicalScope, - annotationEntries: @JvmSuppressWildcards List, - trace: BindingTrace, - shouldResolveArguments: Boolean + scope: LexicalScope, + annotationEntries: @JvmSuppressWildcards List, + trace: BindingTrace, + shouldResolveArguments: Boolean ): Annotations abstract fun resolveAnnotationType(scope: LexicalScope, entryElement: KtAnnotationEntry, trace: BindingTrace): KotlinType abstract fun resolveAnnotationCall( - annotationEntry: KtAnnotationEntry, - scope: LexicalScope, - trace: BindingTrace + annotationEntry: KtAnnotationEntry, + scope: LexicalScope, + trace: BindingTrace ): OverloadResolutionResults abstract fun getAnnotationArgumentValue( - trace: BindingTrace, - valueParameter: ValueParameterDescriptor, - resolvedArgument: ResolvedValueArgument + trace: BindingTrace, + valueParameter: ValueParameterDescriptor, + resolvedArgument: ResolvedValueArgument ): ConstantValue<*>? } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationUseSiteTargetChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationUseSiteTargetChecker.kt index 1eb4b6b5d71..64b4c6b9c1e 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationUseSiteTargetChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationUseSiteTargetChecker.kt @@ -46,26 +46,26 @@ object AnnotationUseSiteTargetChecker { when (target) { AnnotationUseSiteTarget.FIELD -> checkIfHasBackingField(annotated, descriptor, annotation) AnnotationUseSiteTarget.PROPERTY, - AnnotationUseSiteTarget.PROPERTY_GETTER -> {} + AnnotationUseSiteTarget.PROPERTY_GETTER -> { + } AnnotationUseSiteTarget.PROPERTY_DELEGATE_FIELD -> checkIfDelegatedProperty(annotated, annotation) AnnotationUseSiteTarget.PROPERTY_SETTER -> checkIfMutableProperty(annotated, annotation) AnnotationUseSiteTarget.CONSTRUCTOR_PARAMETER -> { if (annotated !is KtParameter) { report(INAPPLICABLE_PARAM_TARGET.on(annotation)) - } - else { + } else { val containingDeclaration = bindingContext[BindingContext.VALUE_PARAMETER, annotated]?.containingDeclaration if (containingDeclaration !is ConstructorDescriptor || !containingDeclaration.isPrimary) { report(INAPPLICABLE_PARAM_TARGET.on(annotation)) - } - else if (!annotated.hasValOrVar()) { + } else if (!annotated.hasValOrVar()) { report(REDUNDANT_ANNOTATION_TARGET.on(annotation, target.renderName)) } } } AnnotationUseSiteTarget.SETTER_PARAMETER -> checkIfMutableProperty(annotated, annotation) AnnotationUseSiteTarget.FILE -> reportDiagnosticOnce(INAPPLICABLE_FILE_TARGET.on(useSiteTarget)) - AnnotationUseSiteTarget.RECEIVER -> {} + AnnotationUseSiteTarget.RECEIVER -> { + } } } } @@ -76,7 +76,11 @@ object AnnotationUseSiteTargetChecker { } } - private fun BindingTrace.checkIfHasBackingField(annotated: KtAnnotated, descriptor: DeclarationDescriptor, annotation: KtAnnotationEntry) { + private fun BindingTrace.checkIfHasBackingField( + annotated: KtAnnotated, + descriptor: DeclarationDescriptor, + annotation: KtAnnotationEntry + ) { if (annotated is KtProperty && annotated.hasDelegate() && descriptor is PropertyDescriptor && get(BindingContext.BACKING_FIELD_REQUIRED, descriptor) != true) { report(INAPPLICABLE_TARGET_PROPERTY_HAS_NO_BACKING_FIELD.on(annotation)) @@ -84,7 +88,7 @@ object AnnotationUseSiteTargetChecker { } private fun KtAnnotationEntry.useSiteDescription() = - useSiteTarget?.getAnnotationUseSiteTarget()?.renderName ?: "unknown target" // should not happen + useSiteTarget?.getAnnotationUseSiteTarget()?.renderName ?: "unknown target" // should not happen private fun BindingTrace.checkIfMutableProperty(annotated: KtAnnotated, annotation: KtAnnotationEntry) { if (!checkIfProperty(annotated, annotation)) return diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationUtil.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationUtil.kt index f1640cbef90..f2bb40c799a 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationUtil.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationUtil.kt @@ -36,12 +36,12 @@ private val JVM_SYNTHETIC_ANNOTATION_FQ_NAME = FqName("kotlin.jvm.JvmSynthetic") fun DeclarationDescriptor.hasJvmSyntheticAnnotation() = findJvmSyntheticAnnotation() != null fun DeclarationDescriptor.findJvmSyntheticAnnotation() = - DescriptorUtils.getAnnotationByFqName(annotations, JVM_SYNTHETIC_ANNOTATION_FQ_NAME) + DescriptorUtils.getAnnotationByFqName(annotations, JVM_SYNTHETIC_ANNOTATION_FQ_NAME) private val STRICTFP_ANNOTATION_FQ_NAME = FqName("kotlin.jvm.Strictfp") fun DeclarationDescriptor.findStrictfpAnnotation() = - DescriptorUtils.getAnnotationByFqName(annotations, STRICTFP_ANNOTATION_FQ_NAME) + DescriptorUtils.getAnnotationByFqName(annotations, STRICTFP_ANNOTATION_FQ_NAME) fun AnnotationDescriptor.argumentValue(parameterName: String): Any? { return allValueArguments[Name.identifier(parameterName)].takeUnless { it is ErrorValue }?.value diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/BindingContextUtils.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/BindingContextUtils.kt index 9792763b6b7..dbcd16ebd65 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/BindingContextUtils.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/BindingContextUtils.kt @@ -46,8 +46,8 @@ fun KtReturnExpression.getTargetFunctionDescriptor(context: BindingContext): Fun if (containingFunctionDescriptor == null) return null return generateSequence(containingFunctionDescriptor) { DescriptorUtils.getParentOfType(it, FunctionDescriptor::class.java) } - .dropWhile { it is AnonymousFunctionDescriptor } - .firstOrNull() + .dropWhile { it is AnonymousFunctionDescriptor } + .firstOrNull() } fun KtReturnExpression.getTargetFunction(context: BindingContext): KtCallableDeclaration? { @@ -65,8 +65,7 @@ fun > ResolutionContext.recordDataFlowInfo(expressio val typeInfo = trace.get(BindingContext.EXPRESSION_TYPE_INFO, expression) if (typeInfo != null) { trace.record(BindingContext.EXPRESSION_TYPE_INFO, expression, typeInfo.replaceDataFlowInfo(dataFlowInfo)) - } - else if (dataFlowInfo != DataFlowInfo.EMPTY) { + } else if (dataFlowInfo != DataFlowInfo.EMPTY) { // Don't store anything in BindingTrace if it's simply an empty DataFlowInfo trace.record(BindingContext.EXPRESSION_TYPE_INFO, expression, noTypeInfo(dataFlowInfo)) } @@ -93,8 +92,8 @@ fun BindingContext.getDataFlowInfoAfter(position: PsiElement): DataFlowInfo { fun BindingContext.getDataFlowInfoBefore(position: PsiElement): DataFlowInfo { for (element in position.parentsWithSelf) { (element as? KtExpression) - ?.let { this[BindingContext.DATA_FLOW_INFO_BEFORE, it] } - ?.let { return it } + ?.let { this[BindingContext.DATA_FLOW_INFO_BEFORE, it] } + ?.let { return it } } return DataFlowInfo.EMPTY } @@ -107,7 +106,7 @@ fun KtExpression.getReferenceTargets(context: BindingContext): Collection(project, CodeAnalyzerInitializer::class.java)!! + ServiceManager.getService(project, CodeAnalyzerInitializer::class.java)!! } } -class DummyCodeAnalyzerInitializer: CodeAnalyzerInitializer { +class DummyCodeAnalyzerInitializer : CodeAnalyzerInitializer { override fun initialize(trace: BindingTrace, module: ModuleDescriptor, codeAnalyzer: KotlinCodeAnalyzer) { // Do nothing } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/CollectionLiteralResolver.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/CollectionLiteralResolver.kt index 5bdeb355f45..232bc6d8780 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/CollectionLiteralResolver.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/CollectionLiteralResolver.kt @@ -39,25 +39,29 @@ import org.jetbrains.kotlin.types.expressions.KotlinTypeInfo import org.jetbrains.kotlin.types.expressions.typeInfoFactory.createTypeInfo import org.jetbrains.kotlin.types.expressions.typeInfoFactory.noTypeInfo -class CollectionLiteralResolver(val module: ModuleDescriptor, val callResolver: CallResolver, val languageVersionSettings: LanguageVersionSettings) { +class CollectionLiteralResolver( + val module: ModuleDescriptor, + val callResolver: CallResolver, + val languageVersionSettings: LanguageVersionSettings +) { companion object { val PRIMITIVE_TYPE_TO_ARRAY: Map = hashMapOf( - PrimitiveType.BOOLEAN to Name.identifier("booleanArrayOf"), - PrimitiveType.CHAR to Name.identifier("charArrayOf"), - PrimitiveType.INT to Name.identifier("intArrayOf"), - PrimitiveType.BYTE to Name.identifier("byteArrayOf"), - PrimitiveType.SHORT to Name.identifier("shortArrayOf"), - PrimitiveType.FLOAT to Name.identifier("floatArrayOf"), - PrimitiveType.LONG to Name.identifier("longArrayOf"), - PrimitiveType.DOUBLE to Name.identifier("doubleArrayOf") + PrimitiveType.BOOLEAN to Name.identifier("booleanArrayOf"), + PrimitiveType.CHAR to Name.identifier("charArrayOf"), + PrimitiveType.INT to Name.identifier("intArrayOf"), + PrimitiveType.BYTE to Name.identifier("byteArrayOf"), + PrimitiveType.SHORT to Name.identifier("shortArrayOf"), + PrimitiveType.FLOAT to Name.identifier("floatArrayOf"), + PrimitiveType.LONG to Name.identifier("longArrayOf"), + PrimitiveType.DOUBLE to Name.identifier("doubleArrayOf") ) val ARRAY_OF_FUNCTION = Name.identifier("arrayOf") } fun resolveCollectionLiteral( - collectionLiteralExpression: KtCollectionLiteralExpression, - context: ExpressionTypingContext + collectionLiteralExpression: KtCollectionLiteralExpression, + context: ExpressionTypingContext ): KotlinTypeInfo { if (!isInsideAnnotationEntryOrClass(collectionLiteralExpression)) { context.trace.report(UNSUPPORTED.on(collectionLiteralExpression, "Collection literals outside of annotations")) @@ -69,15 +73,18 @@ class CollectionLiteralResolver(val module: ModuleDescriptor, val callResolver: } private fun resolveCollectionLiteralSpecialMethod( - expression: KtCollectionLiteralExpression, - context: ExpressionTypingContext + expression: KtCollectionLiteralExpression, + context: ExpressionTypingContext ): KotlinTypeInfo { val call = CallMaker.makeCallForCollectionLiteral(expression) val callName = getArrayFunctionCallName(context.expectedType) val functionDescriptors = getFunctionDescriptorForCollectionLiteral(expression, callName) if (functionDescriptors.isEmpty()) { - context.trace.report(MISSING_STDLIB.on( - expression, "Collection literal call '$callName()' is unresolved")) + context.trace.report( + MISSING_STDLIB.on( + expression, "Collection literal call '$callName()' is unresolved" + ) + ) return noTypeInfo(context) } @@ -92,8 +99,8 @@ class CollectionLiteralResolver(val module: ModuleDescriptor, val callResolver: } private fun getFunctionDescriptorForCollectionLiteral( - expression: KtCollectionLiteralExpression, - callName: Name + expression: KtCollectionLiteralExpression, + callName: Name ): Collection { val memberScopeOfKotlinPackage = module.getPackage(KotlinBuiltIns.BUILT_INS_PACKAGE_FQ_NAME).memberScope return memberScopeOfKotlinPackage.getContributedFunctions(callName, KotlinLookupLocation(expression)) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/DeclarationReturnTypeSanitizer.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/DeclarationReturnTypeSanitizer.kt index 4100dcbd4f8..ff8df4d8262 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/DeclarationReturnTypeSanitizer.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/DeclarationReturnTypeSanitizer.kt @@ -23,18 +23,18 @@ import org.jetbrains.kotlin.types.WrappedTypeFactory interface DeclarationReturnTypeSanitizer { fun sanitizeReturnType( - inferred: UnwrappedType, - wrappedTypeFactory: WrappedTypeFactory, - trace: BindingTrace, - languageVersionSettings: LanguageVersionSettings + inferred: UnwrappedType, + wrappedTypeFactory: WrappedTypeFactory, + trace: BindingTrace, + languageVersionSettings: LanguageVersionSettings ): UnwrappedType object Default : DeclarationReturnTypeSanitizer { override fun sanitizeReturnType( - inferred: UnwrappedType, - wrappedTypeFactory: WrappedTypeFactory, - trace: BindingTrace, - languageVersionSettings: LanguageVersionSettings + inferred: UnwrappedType, + wrappedTypeFactory: WrappedTypeFactory, + trace: BindingTrace, + languageVersionSettings: LanguageVersionSettings ) = inferred } } \ No newline at end of file diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/DelegatedPropertyResolver.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/DelegatedPropertyResolver.kt index 575bb5c99e1..e0ed66b400a 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/DelegatedPropertyResolver.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/DelegatedPropertyResolver.kt @@ -60,19 +60,19 @@ import org.jetbrains.kotlin.util.OperatorNameConventions //TODO: check for 'operator' modifier! class DelegatedPropertyResolver( - private val builtIns: KotlinBuiltIns, - private val fakeCallResolver: FakeCallResolver, - private val expressionTypingServices: ExpressionTypingServices, - private val languageVersionSettings: LanguageVersionSettings + private val builtIns: KotlinBuiltIns, + private val fakeCallResolver: FakeCallResolver, + private val expressionTypingServices: ExpressionTypingServices, + private val languageVersionSettings: LanguageVersionSettings ) { fun resolvePropertyDelegate( - outerDataFlowInfo: DataFlowInfo, - property: KtProperty, - variableDescriptor: VariableDescriptorWithAccessors, - delegateExpression: KtExpression, - propertyHeaderScope: LexicalScope, - trace: BindingTrace + outerDataFlowInfo: DataFlowInfo, + property: KtProperty, + variableDescriptor: VariableDescriptorWithAccessors, + delegateExpression: KtExpression, + propertyHeaderScope: LexicalScope, + trace: BindingTrace ) { property.getter?.let { getter -> if (getter.hasBody()) trace.report(ACCESSOR_FOR_DELEGATED_PROPERTY.on(getter)) @@ -82,11 +82,12 @@ class DelegatedPropertyResolver( } val initializerScope: LexicalScope = - if (variableDescriptor is PropertyDescriptor) - ScopeUtils.makeScopeForPropertyInitializer(propertyHeaderScope, variableDescriptor) - else propertyHeaderScope + if (variableDescriptor is PropertyDescriptor) + ScopeUtils.makeScopeForPropertyInitializer(propertyHeaderScope, variableDescriptor) + else propertyHeaderScope - val byExpressionType = resolveDelegateExpression(delegateExpression, property, variableDescriptor, initializerScope, trace, outerDataFlowInfo) + val byExpressionType = + resolveDelegateExpression(delegateExpression, property, variableDescriptor, initializerScope, trace, outerDataFlowInfo) resolveProvideDelegateMethod(variableDescriptor, delegateExpression, byExpressionType, trace, initializerScope, outerDataFlowInfo) val delegateType = getResolvedDelegateType(variableDescriptor, delegateExpression, byExpressionType, trace) @@ -98,26 +99,26 @@ class DelegatedPropertyResolver( } private fun getResolvedDelegateType( - variableDescriptor: VariableDescriptorWithAccessors, - delegateExpression: KtExpression, - byExpressionType: KotlinType, - trace: BindingTrace + variableDescriptor: VariableDescriptorWithAccessors, + delegateExpression: KtExpression, + byExpressionType: KotlinType, + trace: BindingTrace ): KotlinType { val provideDelegateResolvedCall = trace.bindingContext.get(PROVIDE_DELEGATE_RESOLVED_CALL, variableDescriptor) if (provideDelegateResolvedCall != null) { return provideDelegateResolvedCall.resultingDescriptor.returnType - ?: throw AssertionError("No return type fore 'provideDelegate' of ${delegateExpression.text}") + ?: throw AssertionError("No return type fore 'provideDelegate' of ${delegateExpression.text}") } return byExpressionType } fun getGetValueMethodReturnType( - variableDescriptor: VariableDescriptorWithAccessors, - delegateExpression: KtExpression, - byExpressionType: KotlinType, - trace: BindingTrace, - initializerScope: LexicalScope, - dataFlowInfo: DataFlowInfo + variableDescriptor: VariableDescriptorWithAccessors, + delegateExpression: KtExpression, + byExpressionType: KotlinType, + trace: BindingTrace, + initializerScope: LexicalScope, + dataFlowInfo: DataFlowInfo ): KotlinType? { resolveProvideDelegateMethod(variableDescriptor, delegateExpression, byExpressionType, trace, initializerScope, dataFlowInfo) val delegateType = getResolvedDelegateType(variableDescriptor, delegateExpression, byExpressionType, trace) @@ -131,35 +132,41 @@ class DelegatedPropertyResolver( get() = languageVersionSettings.supportsFeature(LanguageFeature.OperatorProvideDelegate) private fun resolveGetValueMethod( - variableDescriptor: VariableDescriptorWithAccessors, - delegateExpression: KtExpression, - delegateType: KotlinType, - trace: BindingTrace, - initializerScope: LexicalScope, - dataFlowInfo: DataFlowInfo + variableDescriptor: VariableDescriptorWithAccessors, + delegateExpression: KtExpression, + delegateType: KotlinType, + trace: BindingTrace, + initializerScope: LexicalScope, + dataFlowInfo: DataFlowInfo ) { - val returnType = getGetValueMethodReturnType(variableDescriptor, delegateExpression, delegateType, trace, initializerScope, dataFlowInfo) + val returnType = + getGetValueMethodReturnType(variableDescriptor, delegateExpression, delegateType, trace, initializerScope, dataFlowInfo) val propertyType = variableDescriptor.type /* Do not check return type of get() method of delegate for properties with DeferredType because property type is taken from it */ if (propertyType !is DeferredType && returnType != null && !KotlinTypeChecker.DEFAULT.isSubtypeOf(returnType, propertyType)) { val call = trace.bindingContext.get(DELEGATED_PROPERTY_CALL, variableDescriptor.getter) - ?: throw AssertionError("Call should exists for ${variableDescriptor.getter}") - trace.report(DELEGATE_SPECIAL_FUNCTION_RETURN_TYPE_MISMATCH.on( - delegateExpression, renderCall(call, trace.bindingContext), variableDescriptor.type, returnType)) + ?: throw AssertionError("Call should exists for ${variableDescriptor.getter}") + trace.report( + DELEGATE_SPECIAL_FUNCTION_RETURN_TYPE_MISMATCH.on( + delegateExpression, renderCall(call, trace.bindingContext), variableDescriptor.type, returnType + ) + ) } } private fun resolveSetValueMethod( - variableDescriptor: VariableDescriptorWithAccessors, - delegateExpression: KtExpression, - delegateType: KotlinType, - trace: BindingTrace, - initializerScope: LexicalScope, - dataFlowInfo: DataFlowInfo + variableDescriptor: VariableDescriptorWithAccessors, + delegateExpression: KtExpression, + delegateType: KotlinType, + trace: BindingTrace, + initializerScope: LexicalScope, + dataFlowInfo: DataFlowInfo ) { - resolveGetSetValueMethod(variableDescriptor, delegateExpression, delegateType, trace, - initializerScope, dataFlowInfo, false) + resolveGetSetValueMethod( + variableDescriptor, delegateExpression, delegateType, trace, + initializerScope, dataFlowInfo, false + ) } private fun KtPsiFactory.createExpressionForProperty(): KtExpression { @@ -168,27 +175,27 @@ class DelegatedPropertyResolver( /* Resolve getValue() or setValue() methods from delegate */ private fun resolveGetSetValueMethod( - propertyDescriptor: VariableDescriptorWithAccessors, - delegateExpression: KtExpression, - delegateType: KotlinType, - trace: BindingTrace, - initializerScope: LexicalScope, - dataFlowInfo: DataFlowInfo, - isGet: Boolean + propertyDescriptor: VariableDescriptorWithAccessors, + delegateExpression: KtExpression, + delegateType: KotlinType, + trace: BindingTrace, + initializerScope: LexicalScope, + dataFlowInfo: DataFlowInfo, + isGet: Boolean ) { val accessor = (if (isGet) propertyDescriptor.getter else propertyDescriptor.setter) - ?: throw AssertionError("Delegated property should have getter/setter $propertyDescriptor ${delegateExpression.text}") + ?: throw AssertionError("Delegated property should have getter/setter $propertyDescriptor ${delegateExpression.text}") if (trace.bindingContext.get(DELEGATED_PROPERTY_CALL, accessor) != null) return val functionResults = getGetSetValueMethod( - propertyDescriptor, delegateExpression, delegateType, trace, initializerScope, dataFlowInfo, - isGet = isGet, isComplete = true + propertyDescriptor, delegateExpression, delegateType, trace, initializerScope, dataFlowInfo, + isGet = isGet, isComplete = true ) if (!functionResults.isSuccess) { val call = trace.bindingContext.get(DELEGATED_PROPERTY_CALL, accessor) - ?: throw AssertionError("'getDelegatedPropertyConventionMethod' didn't record a call") + ?: throw AssertionError("'getDelegatedPropertyConventionMethod' didn't record a call") reportDelegateOperatorResolutionError(trace, call, functionResults, delegateExpression, delegateType) return } @@ -211,19 +218,19 @@ class DelegatedPropertyResolver( } private fun reportDelegateOperatorResolutionError( - trace: BindingTrace, - delegateOperatorCall: Call, - delegateOperatorResults: OverloadResolutionResults, - delegateExpression: KtExpression, - delegateType: KotlinType, - operatorRequired: Boolean = true + trace: BindingTrace, + delegateOperatorCall: Call, + delegateOperatorResults: OverloadResolutionResults, + delegateExpression: KtExpression, + delegateType: KotlinType, + operatorRequired: Boolean = true ): Boolean { val expectedFunction = renderCall(delegateOperatorCall, trace.bindingContext) val resolutionErrorFactory = when { delegateOperatorResults.isSingleResult || - delegateOperatorResults.isIncomplete || - delegateOperatorResults.resultCode == OverloadResolutionResults.Code.MANY_FAILED_CANDIDATES -> DELEGATE_SPECIAL_FUNCTION_NONE_APPLICABLE + delegateOperatorResults.isIncomplete || + delegateOperatorResults.resultCode == OverloadResolutionResults.Code.MANY_FAILED_CANDIDATES -> DELEGATE_SPECIAL_FUNCTION_NONE_APPLICABLE delegateOperatorResults.isAmbiguity -> DELEGATE_SPECIAL_FUNCTION_AMBIGUITY @@ -244,25 +251,28 @@ class DelegatedPropertyResolver( } private fun resolveProvideDelegateMethod( - propertyDescriptor: VariableDescriptorWithAccessors, - byExpression: KtExpression, - byExpressionType: KotlinType, - trace: BindingTrace, - initializerScope: LexicalScope, - dataFlowInfo: DataFlowInfo + propertyDescriptor: VariableDescriptorWithAccessors, + byExpression: KtExpression, + byExpressionType: KotlinType, + trace: BindingTrace, + initializerScope: LexicalScope, + dataFlowInfo: DataFlowInfo ) { if (!isOperatorProvideDelegateSupported) return if (trace.bindingContext.get(BindingContext.PROVIDE_DELEGATE_CALL, propertyDescriptor) != null) return val traceForProvideDelegate = TemporaryBindingTrace.create(trace, "trace to resolve provideDelegate method") - val provideDelegateResults = getProvideDelegateMethod(propertyDescriptor, byExpression, byExpressionType, - traceForProvideDelegate, initializerScope, dataFlowInfo) + val provideDelegateResults = getProvideDelegateMethod( + propertyDescriptor, byExpression, byExpressionType, + traceForProvideDelegate, initializerScope, dataFlowInfo + ) if (!provideDelegateResults.isSuccess) { val call = traceForProvideDelegate.bindingContext.get(BindingContext.PROVIDE_DELEGATE_CALL, propertyDescriptor) - ?: throw AssertionError("'getDelegatedPropertyConventionMethod' didn't record a call") + ?: throw AssertionError("'getDelegatedPropertyConventionMethod' didn't record a call") val shouldCommitTrace = reportDelegateOperatorResolutionError( - traceForProvideDelegate, call, provideDelegateResults, byExpression, byExpressionType, operatorRequired = false) + traceForProvideDelegate, call, provideDelegateResults, byExpression, byExpressionType, operatorRequired = false + ) if (shouldCommitTrace) { traceForProvideDelegate.commit() @@ -285,19 +295,19 @@ class DelegatedPropertyResolver( /* Resolve getValue() or setValue() methods from delegate */ private fun getGetSetValueMethod( - propertyDescriptor: VariableDescriptorWithAccessors, - delegateExpression: KtExpression, - delegateType: KotlinType, - trace: BindingTrace, - scopeForDelegate: LexicalScope, - dataFlowInfo: DataFlowInfo, - isGet: Boolean, - isComplete: Boolean + propertyDescriptor: VariableDescriptorWithAccessors, + delegateExpression: KtExpression, + delegateType: KotlinType, + trace: BindingTrace, + scopeForDelegate: LexicalScope, + dataFlowInfo: DataFlowInfo, + isGet: Boolean, + isComplete: Boolean ): OverloadResolutionResults { val delegateFunctionsScope = ScopeUtils.makeScopeForDelegateConventionFunctions(scopeForDelegate, propertyDescriptor) val accessor = (if (isGet) propertyDescriptor.getter else propertyDescriptor.setter) - ?: throw AssertionError("Delegated property should have getter/setter $propertyDescriptor ${delegateExpression.text}") + ?: throw AssertionError("Delegated property should have getter/setter $propertyDescriptor ${delegateExpression.text}") val expectedType = if (isComplete && isGet && propertyDescriptor.type !is DeferredType) propertyDescriptor.type @@ -314,9 +324,11 @@ class DelegatedPropertyResolver( arguments.add(psiFactory.createExpressionForProperty()) if (!isGet) { - val fakeArgument = createFakeExpressionOfType(delegateExpression.project, trace, - "fakeArgument${arguments.size}", - propertyDescriptor.type) as KtReferenceExpression + val fakeArgument = createFakeExpressionOfType( + delegateExpression.project, trace, + "fakeArgument${arguments.size}", + propertyDescriptor.type + ) as KtReferenceExpression arguments.add(fakeArgument) val valueParameters = accessor.valueParameters trace.record(REFERENCE_TARGET, fakeArgument, valueParameters[0]) @@ -325,35 +337,36 @@ class DelegatedPropertyResolver( val functionName = if (isGet) OperatorNameConventions.GET_VALUE else OperatorNameConventions.SET_VALUE val receiver = ExpressionReceiver.create(delegateExpression, delegateType, trace.bindingContext) - val resolutionResult = fakeCallResolver.makeAndResolveFakeCallInContext(receiver, context, arguments, functionName, delegateExpression) + val resolutionResult = + fakeCallResolver.makeAndResolveFakeCallInContext(receiver, context, arguments, functionName, delegateExpression) trace.record(BindingContext.DELEGATED_PROPERTY_CALL, accessor, resolutionResult.first) return resolutionResult.second } private fun getProvideDelegateMethod( - propertyDescriptor: VariableDescriptorWithAccessors, - delegateExpression: KtExpression, - delegateExpressionType: KotlinType, - trace: BindingTrace, - initializerScope: LexicalScope, - dataFlowInfo: DataFlowInfo + propertyDescriptor: VariableDescriptorWithAccessors, + delegateExpression: KtExpression, + delegateExpressionType: KotlinType, + trace: BindingTrace, + initializerScope: LexicalScope, + dataFlowInfo: DataFlowInfo ): OverloadResolutionResults { val context = ExpressionTypingContext.newContext(trace, initializerScope, dataFlowInfo, NO_EXPECTED_TYPE, languageVersionSettings) return getProvideDelegateMethod(propertyDescriptor, delegateExpression, delegateExpressionType, context) } private fun getProvideDelegateMethod( - propertyDescriptor: VariableDescriptorWithAccessors, - delegateExpression: KtExpression, - delegateExpressionType: KotlinType, - context: ExpressionTypingContext + propertyDescriptor: VariableDescriptorWithAccessors, + delegateExpression: KtExpression, + delegateExpressionType: KotlinType, + context: ExpressionTypingContext ): OverloadResolutionResults { val propertyHasReceiver = propertyDescriptor.dispatchReceiverParameter != null val arguments = KtPsiFactory(delegateExpression, markGenerated = false).run { listOf( - createExpression(if (propertyHasReceiver) "this" else "null"), - createExpressionForProperty() + createExpression(if (propertyHasReceiver) "this" else "null"), + createExpressionForProperty() ) } val functionName = OperatorNameConventions.PROVIDE_DELEGATE @@ -373,38 +386,53 @@ class DelegatedPropertyResolver( //TODO: diagnostics rendering does not belong here private fun renderCall(call: Call, context: BindingContext): String { val calleeExpression = call.calleeExpression - ?: throw AssertionError("CalleeExpression should exists for fake call of convention method") + ?: throw AssertionError("CalleeExpression should exists for fake call of convention method") return call.valueArguments.joinToString( - prefix = "${calleeExpression.text}(", - postfix = ")", - separator = ", ", - transform = { argument -> - val type = context.getType(argument.getArgumentExpression()!!)!! - DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(type) - } + prefix = "${calleeExpression.text}(", + postfix = ")", + separator = ", ", + transform = { argument -> + val type = context.getType(argument.getArgumentExpression()!!)!! + DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(type) + } ) } fun resolveDelegateExpression( - delegateExpression: KtExpression, - property: KtProperty, - variableDescriptor: VariableDescriptorWithAccessors, - scopeForDelegate: LexicalScope, - trace: BindingTrace, - dataFlowInfo: DataFlowInfo + delegateExpression: KtExpression, + property: KtProperty, + variableDescriptor: VariableDescriptorWithAccessors, + scopeForDelegate: LexicalScope, + trace: BindingTrace, + dataFlowInfo: DataFlowInfo ): KotlinType { val traceToResolveDelegatedProperty = TemporaryBindingTrace.create(trace, "Trace to resolve delegated property") val propertyExpectedType = if (property.typeReference != null) variableDescriptor.type else NO_EXPECTED_TYPE - val completer = ConstraintSystemCompleterImpl(property, propertyExpectedType, variableDescriptor, delegateExpression, scopeForDelegate, trace, dataFlowInfo) + val completer = ConstraintSystemCompleterImpl( + property, + propertyExpectedType, + variableDescriptor, + delegateExpression, + scopeForDelegate, + trace, + dataFlowInfo + ) delegateExpression.getCalleeExpressionIfAny()?.let { traceToResolveDelegatedProperty.record(CONSTRAINT_SYSTEM_COMPLETER, it, completer) } - val expectedTypeByNewInference = completer.resolveViaNewInference(delegateExpression, variableDescriptor, scopeForDelegate, trace, dataFlowInfo) - val delegateType = expressionTypingServices.safeGetType(scopeForDelegate, delegateExpression, expectedTypeByNewInference ?: NO_EXPECTED_TYPE, dataFlowInfo, traceToResolveDelegatedProperty) + val expectedTypeByNewInference = + completer.resolveViaNewInference(delegateExpression, variableDescriptor, scopeForDelegate, trace, dataFlowInfo) + val delegateType = expressionTypingServices.safeGetType( + scopeForDelegate, + delegateExpression, + expectedTypeByNewInference ?: NO_EXPECTED_TYPE, + dataFlowInfo, + traceToResolveDelegatedProperty + ) traceToResolveDelegatedProperty.commit({ slice, _ -> slice !== CONSTRAINT_SYSTEM_COMPLETER }, true) @@ -412,27 +440,28 @@ class DelegatedPropertyResolver( } inner class ConstraintSystemCompleterImpl( - val property: KtProperty, - val expectedType: KotlinType, - val variableDescriptor: VariableDescriptorWithAccessors, - val delegateExpression: KtExpression, - val scopeForDelegate: LexicalScope, - val trace: BindingTrace, - val dataFlowInfo: DataFlowInfo - ): ConstraintSystemCompleter { + val property: KtProperty, + val expectedType: KotlinType, + val variableDescriptor: VariableDescriptorWithAccessors, + val delegateExpression: KtExpression, + val scopeForDelegate: LexicalScope, + val trace: BindingTrace, + val dataFlowInfo: DataFlowInfo + ) : ConstraintSystemCompleter { override fun completeConstraintSystem(constraintSystem: ConstraintSystem.Builder, resolvedCall: ResolvedCall<*>) { val returnType = resolvedCall.candidateDescriptor.returnType ?: return val typeVariableSubstitutor = constraintSystem.typeVariableSubstitutors[resolvedCall.call.toHandle()] - ?: throw AssertionError("No substitutor in the system for call: " + resolvedCall.call) + ?: throw AssertionError("No substitutor in the system for call: " + resolvedCall.call) - val traceToResolveConventionMethods = TemporaryBindingTrace.create(trace, "Trace to resolve delegated property convention methods") + val traceToResolveConventionMethods = + TemporaryBindingTrace.create(trace, "Trace to resolve delegated property convention methods") val delegateType = getDelegateType(returnType, constraintSystem, typeVariableSubstitutor, traceToResolveConventionMethods) val getValueResults = getGetSetValueMethod( - variableDescriptor, delegateExpression, delegateType, traceToResolveConventionMethods, scopeForDelegate, dataFlowInfo, - isGet = true, isComplete = false + variableDescriptor, delegateExpression, delegateType, traceToResolveConventionMethods, scopeForDelegate, dataFlowInfo, + isGet = true, isComplete = false ) if (conventionMethodFound(getValueResults)) { val getValueDescriptor = getValueResults.resultingDescriptor @@ -453,8 +482,8 @@ class DelegatedPropertyResolver( if (variableDescriptor.returnType is DeferredType) return val setValueResults = getGetSetValueMethod( - variableDescriptor, delegateExpression, delegateType, traceToResolveConventionMethods, scopeForDelegate, dataFlowInfo, - isGet = false, isComplete = false + variableDescriptor, delegateExpression, delegateType, traceToResolveConventionMethods, scopeForDelegate, dataFlowInfo, + isGet = false, isComplete = false ) if (conventionMethodFound(setValueResults)) { val setValueDescriptor = setValueResults.resultingDescriptor @@ -471,24 +500,26 @@ class DelegatedPropertyResolver( } private fun getDelegateType( - byExpressionType: KotlinType, - constraintSystem: ConstraintSystem.Builder, - typeVariableSubstitutor: TypeSubstitutor, - traceToResolveConventionMethods: TemporaryBindingTrace + byExpressionType: KotlinType, + constraintSystem: ConstraintSystem.Builder, + typeVariableSubstitutor: TypeSubstitutor, + traceToResolveConventionMethods: TemporaryBindingTrace ): KotlinType { if (isOperatorProvideDelegateSupported) { val provideDelegateResults = getProvideDelegateMethod( - variableDescriptor, delegateExpression, byExpressionType, - traceToResolveConventionMethods, scopeForDelegate, dataFlowInfo + variableDescriptor, delegateExpression, byExpressionType, + traceToResolveConventionMethods, scopeForDelegate, dataFlowInfo ) if (conventionMethodFound(provideDelegateResults)) { val provideDelegateDescriptor = provideDelegateResults.resultingDescriptor val provideDelegateReturnType = provideDelegateDescriptor.returnType if (provideDelegateDescriptor.isOperator) { - addConstraintForThisValue(constraintSystem, typeVariableSubstitutor, provideDelegateDescriptor, - dispatchReceiverOnly = true) + addConstraintForThisValue( + constraintSystem, typeVariableSubstitutor, provideDelegateDescriptor, + dispatchReceiverOnly = true + ) return provideDelegateReturnType - ?: throw AssertionError("No return type fore 'provideDelegate' of ${delegateExpression.text}") + ?: throw AssertionError("No return type fore 'provideDelegate' of ${delegateExpression.text}") } } } @@ -497,48 +528,53 @@ class DelegatedPropertyResolver( } private fun conventionMethodFound(results: OverloadResolutionResults): Boolean = - results.isSuccess || - results.isSingleResult && results.resultCode == OverloadResolutionResults.Code.SINGLE_CANDIDATE_ARGUMENT_MISMATCH + results.isSuccess || + results.isSingleResult && results.resultCode == OverloadResolutionResults.Code.SINGLE_CANDIDATE_ARGUMENT_MISMATCH private fun addConstraintForThisValue( - constraintSystem: ConstraintSystem.Builder, - typeVariableSubstitutor: TypeSubstitutor, - resultingDescriptor: FunctionDescriptor, - dispatchReceiverOnly: Boolean = false + constraintSystem: ConstraintSystem.Builder, + typeVariableSubstitutor: TypeSubstitutor, + resultingDescriptor: FunctionDescriptor, + dispatchReceiverOnly: Boolean = false ) { val extensionReceiver = variableDescriptor.extensionReceiverParameter val dispatchReceiver = variableDescriptor.dispatchReceiverParameter val typeOfThis = (if (dispatchReceiverOnly) dispatchReceiver?.type else (extensionReceiver?.type ?: dispatchReceiver?.type)) - ?: builtIns.nullableNothingType + ?: builtIns.nullableNothingType val valueParameters = resultingDescriptor.valueParameters if (valueParameters.isEmpty()) return val valueParameterForThis = valueParameters[0] constraintSystem.addSubtypeConstraint( - typeOfThis, - typeVariableSubstitutor.substitute(valueParameterForThis.type, Variance.INVARIANT), - FROM_COMPLETER.position() + typeOfThis, + typeVariableSubstitutor.substitute(valueParameterForThis.type, Variance.INVARIANT), + FROM_COMPLETER.position() ) } fun resolveViaNewInference( - delegateExpression: KtExpression, - variableDescriptor: VariableDescriptorWithAccessors, - scopeForDelegate: LexicalScope, - trace: BindingTrace, - dataFlowInfo: DataFlowInfo + delegateExpression: KtExpression, + variableDescriptor: VariableDescriptorWithAccessors, + scopeForDelegate: LexicalScope, + trace: BindingTrace, + dataFlowInfo: DataFlowInfo ): KotlinType? { if (!languageVersionSettings.supportsFeature(LanguageFeature.NewInference)) return null - val traceToResolveConventionMethods = TemporaryBindingTrace.create(trace, "Trace to resolve delegated property convention methods") + val traceToResolveConventionMethods = + TemporaryBindingTrace.create(trace, "Trace to resolve delegated property convention methods") - val delegateTypeInfo = expressionTypingServices.getTypeInfo(scopeForDelegate, delegateExpression, NO_EXPECTED_TYPE, dataFlowInfo, - traceToResolveConventionMethods, false, delegateExpression, ContextDependency.DEPENDENT) + val delegateTypeInfo = expressionTypingServices.getTypeInfo( + scopeForDelegate, delegateExpression, NO_EXPECTED_TYPE, dataFlowInfo, + traceToResolveConventionMethods, false, delegateExpression, ContextDependency.DEPENDENT + ) - val contextForProvideDelegate = ExpressionTypingContext.newContext(traceToResolveConventionMethods, scopeForDelegate, delegateTypeInfo.dataFlowInfo, - NO_EXPECTED_TYPE, ContextDependency.DEPENDENT, StatementFilter.NONE, - languageVersionSettings) + val contextForProvideDelegate = ExpressionTypingContext.newContext( + traceToResolveConventionMethods, scopeForDelegate, delegateTypeInfo.dataFlowInfo, + NO_EXPECTED_TYPE, ContextDependency.DEPENDENT, StatementFilter.NONE, + languageVersionSettings + ) val delegateTypeConstructor = delegateTypeInfo.type?.constructor @@ -549,29 +585,31 @@ class DelegatedPropertyResolver( delegateTypeInfo.type val provideDelegateResults = getProvideDelegateMethod( - variableDescriptor, delegateExpression, delegateType ?: return null, contextForProvideDelegate + variableDescriptor, delegateExpression, delegateType ?: return null, contextForProvideDelegate ) var typeInfoForGetValueReceiver = KotlinTypeInfo(delegateType, delegateTypeInfo.dataFlowInfo) if (conventionMethodFound(provideDelegateResults)) { val provideDelegateDescriptor = provideDelegateResults.resultingDescriptor if (provideDelegateDescriptor.isOperator) { - typeInfoForGetValueReceiver = KotlinTypeInfo(provideDelegateDescriptor.returnType, - provideDelegateResults.resultingCall.dataFlowInfoForArguments.resultInfo) + typeInfoForGetValueReceiver = KotlinTypeInfo( + provideDelegateDescriptor.returnType, + provideDelegateResults.resultingCall.dataFlowInfoForArguments.resultInfo + ) } } getGetSetValueMethod( - variableDescriptor, delegateExpression, typeInfoForGetValueReceiver.type ?: return null, - traceToResolveConventionMethods, scopeForDelegate, typeInfoForGetValueReceiver.dataFlowInfo, - isGet = true, isComplete = true + variableDescriptor, delegateExpression, typeInfoForGetValueReceiver.type ?: return null, + traceToResolveConventionMethods, scopeForDelegate, typeInfoForGetValueReceiver.dataFlowInfo, + isGet = true, isComplete = true ) if (variableDescriptor.isVar && variableDescriptor.returnType !is DeferredType) { getGetSetValueMethod( - variableDescriptor, delegateExpression, typeInfoForGetValueReceiver.type ?: return null, - traceToResolveConventionMethods, scopeForDelegate, typeInfoForGetValueReceiver.dataFlowInfo, - isGet = false, isComplete = true + variableDescriptor, delegateExpression, typeInfoForGetValueReceiver.type ?: return null, + traceToResolveConventionMethods, scopeForDelegate, typeInfoForGetValueReceiver.dataFlowInfo, + isGet = false, isComplete = true ) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/DelegatingBindingTrace.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/DelegatingBindingTrace.kt index 30836400cb7..6e6c63d562d 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/DelegatingBindingTrace.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/DelegatingBindingTrace.kt @@ -27,13 +27,13 @@ import org.jetbrains.kotlin.types.expressions.typeInfoFactory.createTypeInfo import org.jetbrains.kotlin.util.slicedMap.* open class DelegatingBindingTrace( - private val parentContext: BindingContext, - private val name: String, - withParentDiagnostics: Boolean = true, - private val filter: BindingTraceFilter = BindingTraceFilter.ACCEPT_ALL, - allowSliceRewrite: Boolean = false + private val parentContext: BindingContext, + private val name: String, + withParentDiagnostics: Boolean = true, + private val filter: BindingTraceFilter = BindingTraceFilter.ACCEPT_ALL, + allowSliceRewrite: Boolean = false ) : BindingTrace { - + private val map = if (BindingTraceContext.TRACK_REWRITES && !allowSliceRewrite) TrackingSlicedMap(BindingTraceContext.TRACK_WITH_STACK_TRACES) else @@ -76,15 +76,18 @@ open class DelegatingBindingTrace( } } - constructor(parentContext: BindingContext, - debugName: String, - resolutionSubjectForMessage: Any?, - filter: BindingTraceFilter = BindingTraceFilter.ACCEPT_ALL, - allowSliceRewrite: Boolean = false - ) : this(parentContext, - AnalyzingUtils.formDebugNameForBindingTrace(debugName, resolutionSubjectForMessage), - filter = filter, - allowSliceRewrite = allowSliceRewrite) + constructor( + parentContext: BindingContext, + debugName: String, + resolutionSubjectForMessage: Any?, + filter: BindingTraceFilter = BindingTraceFilter.ACCEPT_ALL, + allowSliceRewrite: Boolean = false + ) : this( + parentContext, + AnalyzingUtils.formDebugNameForBindingTrace(debugName, resolutionSubjectForMessage), + filter = filter, + allowSliceRewrite = allowSliceRewrite + ) override fun getBindingContext(): BindingContext = bindingContext @@ -101,8 +104,7 @@ open class DelegatingBindingTrace( if (slice is SetSlice<*>) { assert(value != null) if (value != SetSlice.DEFAULT) return value - } - else if (value != null) { + } else if (value != null) { return value } @@ -127,8 +129,7 @@ open class DelegatingBindingTrace( var typeInfo = get(BindingContext.EXPRESSION_TYPE_INFO, expression) if (typeInfo == null) { typeInfo = createTypeInfo(type) - } - else { + } else { typeInfo = typeInfo.replaceType(type) } record(BindingContext.EXPRESSION_TYPE_INFO, expression, typeInfo) @@ -139,7 +140,8 @@ open class DelegatingBindingTrace( clear() } - @JvmOverloads fun addOwnDataTo(trace: BindingTrace, filter: TraceEntryFilter? = null, commitDiagnostics: Boolean = true) { + @JvmOverloads + fun addOwnDataTo(trace: BindingTrace, filter: TraceEntryFilter? = null, commitDiagnostics: Boolean = true) { BindingContextUtils.addOwnDataTo(trace, filter, commitDiagnostics, map, mutableDiagnostics) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/ExceptionWrappingKtVisitorVoid.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/ExceptionWrappingKtVisitorVoid.kt index 355bc4ae1a9..15f1b54a5c7 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/ExceptionWrappingKtVisitorVoid.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/ExceptionWrappingKtVisitorVoid.kt @@ -30,18 +30,14 @@ class ExceptionWrappingKtVisitorVoid(private val delegate: KtVisitorVoid) : KtVi override fun visitDeclaration(dcl: KtDeclaration) { try { dcl.accept(delegate) - } - catch (e: ProcessCanceledException) { + } catch (e: ProcessCanceledException) { throw e - } - catch (e: KotlinFrontEndException) { + } catch (e: KotlinFrontEndException) { throw e - } - catch (t: Throwable) { + } catch (t: Throwable) { val name = try { dcl.name - } - catch (e: Throwable) { + } catch (e: Throwable) { "- error: ${e.message}" } throw KotlinFrontEndException("Failed to analyze declaration $name", t, dcl) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/FiniteBoundRestrictionChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/FiniteBoundRestrictionChecker.kt index 86c9f32aa25..fbffce85275 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/FiniteBoundRestrictionChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/FiniteBoundRestrictionChecker.kt @@ -32,9 +32,9 @@ import org.jetbrains.kotlin.utils.DFS object FiniteBoundRestrictionChecker { @JvmStatic fun check( - declaration: KtClass, - classDescriptor: ClassDescriptor, - diagnosticHolder: DiagnosticSink + declaration: KtClass, + classDescriptor: ClassDescriptor, + diagnosticHolder: DiagnosticSink ) { val typeConstructor = classDescriptor.typeConstructor if (typeConstructor.parameters.isEmpty()) return @@ -102,7 +102,7 @@ object FiniteBoundRestrictionChecker { } } - private interface Graph { + private interface Graph { val nodes: Set fun getNeighbors(node: T): List } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/FunctionDescriptorResolver.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/FunctionDescriptorResolver.kt index c165fdbdd42..bbbb8ee7505 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/FunctionDescriptorResolver.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/FunctionDescriptorResolver.kt @@ -67,72 +67,83 @@ import org.jetbrains.kotlin.types.typeUtil.replaceAnnotations import java.util.* class FunctionDescriptorResolver( - private val typeResolver: TypeResolver, - private val descriptorResolver: DescriptorResolver, - private val annotationResolver: AnnotationResolver, - private val builtIns: KotlinBuiltIns, - private val modifiersChecker: ModifiersChecker, - private val overloadChecker: OverloadChecker, - private val contractParsingServices: ContractParsingServices, - private val expressionTypingServices: ExpressionTypingServices, - private val languageVersionSettings: LanguageVersionSettings + private val typeResolver: TypeResolver, + private val descriptorResolver: DescriptorResolver, + private val annotationResolver: AnnotationResolver, + private val builtIns: KotlinBuiltIns, + private val modifiersChecker: ModifiersChecker, + private val overloadChecker: OverloadChecker, + private val contractParsingServices: ContractParsingServices, + private val expressionTypingServices: ExpressionTypingServices, + private val languageVersionSettings: LanguageVersionSettings ) { fun resolveFunctionDescriptor( - containingDescriptor: DeclarationDescriptor, - scope: LexicalScope, - function: KtNamedFunction, - trace: BindingTrace, - dataFlowInfo: DataFlowInfo + containingDescriptor: DeclarationDescriptor, + scope: LexicalScope, + function: KtNamedFunction, + trace: BindingTrace, + dataFlowInfo: DataFlowInfo ): SimpleFunctionDescriptor { if (function.name == null) trace.report(FUNCTION_DECLARATION_WITH_NO_NAME.on(function)) return resolveFunctionDescriptor( - SimpleFunctionDescriptorImpl::create, containingDescriptor, scope, function, trace, dataFlowInfo, TypeUtils.NO_EXPECTED_TYPE) + SimpleFunctionDescriptorImpl::create, containingDescriptor, scope, function, trace, dataFlowInfo, TypeUtils.NO_EXPECTED_TYPE + ) } fun resolveFunctionExpressionDescriptor( - containingDescriptor: DeclarationDescriptor, - scope: LexicalScope, - function: KtNamedFunction, - trace: BindingTrace, - dataFlowInfo: DataFlowInfo, - expectedFunctionType: KotlinType + containingDescriptor: DeclarationDescriptor, + scope: LexicalScope, + function: KtNamedFunction, + trace: BindingTrace, + dataFlowInfo: DataFlowInfo, + expectedFunctionType: KotlinType ): SimpleFunctionDescriptor = resolveFunctionDescriptor( - ::FunctionExpressionDescriptor, containingDescriptor, scope, function, trace, dataFlowInfo, expectedFunctionType) + ::FunctionExpressionDescriptor, containingDescriptor, scope, function, trace, dataFlowInfo, expectedFunctionType + ) private fun resolveFunctionDescriptor( - functionConstructor: (DeclarationDescriptor, Annotations, Name, CallableMemberDescriptor.Kind, SourceElement) -> SimpleFunctionDescriptorImpl, - containingDescriptor: DeclarationDescriptor, - scope: LexicalScope, - function: KtNamedFunction, - trace: BindingTrace, - dataFlowInfo: DataFlowInfo, - expectedFunctionType: KotlinType + functionConstructor: (DeclarationDescriptor, Annotations, Name, CallableMemberDescriptor.Kind, SourceElement) -> SimpleFunctionDescriptorImpl, + containingDescriptor: DeclarationDescriptor, + scope: LexicalScope, + function: KtNamedFunction, + trace: BindingTrace, + dataFlowInfo: DataFlowInfo, + expectedFunctionType: KotlinType ): SimpleFunctionDescriptor { val functionDescriptor = functionConstructor( - containingDescriptor, - annotationResolver.resolveAnnotationsWithoutArguments(scope, function.modifierList, trace), - function.nameAsSafeName, - CallableMemberDescriptor.Kind.DECLARATION, - function.toSourceElement() + containingDescriptor, + annotationResolver.resolveAnnotationsWithoutArguments(scope, function.modifierList, trace), + function.nameAsSafeName, + CallableMemberDescriptor.Kind.DECLARATION, + function.toSourceElement() + ) + initializeFunctionDescriptorAndExplicitReturnType( + containingDescriptor, + scope, + function, + functionDescriptor, + trace, + expectedFunctionType, + dataFlowInfo ) - initializeFunctionDescriptorAndExplicitReturnType(containingDescriptor, scope, function, functionDescriptor, trace, expectedFunctionType, dataFlowInfo) initializeFunctionReturnTypeBasedOnFunctionBody(scope, function, functionDescriptor, trace, dataFlowInfo) BindingContextUtils.recordFunctionDeclarationToDescriptor(trace, function, functionDescriptor) return functionDescriptor } private fun initializeFunctionReturnTypeBasedOnFunctionBody( - scope: LexicalScope, - function: KtNamedFunction, - functionDescriptor: SimpleFunctionDescriptorImpl, - trace: BindingTrace, - dataFlowInfo: DataFlowInfo + scope: LexicalScope, + function: KtNamedFunction, + functionDescriptor: SimpleFunctionDescriptorImpl, + trace: BindingTrace, + dataFlowInfo: DataFlowInfo ) { if (functionDescriptor.returnType != null) return assert(function.typeReference == null) { - "Return type must be initialized early for function: " + function.text + ", at: " + DiagnosticUtils.atLocation(function) } + "Return type must be initialized early for function: " + function.text + ", at: " + DiagnosticUtils.atLocation(function) + } val inferredReturnType = when { function.hasBlockBody() -> @@ -146,51 +157,55 @@ class FunctionDescriptorResolver( } fun initializeFunctionDescriptorAndExplicitReturnType( - container: DeclarationDescriptor, - scope: LexicalScope, - function: KtFunction, - functionDescriptor: SimpleFunctionDescriptorImpl, - trace: BindingTrace, - expectedFunctionType: KotlinType, - dataFlowInfo: DataFlowInfo + container: DeclarationDescriptor, + scope: LexicalScope, + function: KtFunction, + functionDescriptor: SimpleFunctionDescriptorImpl, + trace: BindingTrace, + expectedFunctionType: KotlinType, + dataFlowInfo: DataFlowInfo ) { - val headerScope = LexicalWritableScope(scope, functionDescriptor, true, - TraceBasedLocalRedeclarationChecker(trace, overloadChecker), LexicalScopeKind.FUNCTION_HEADER) + val headerScope = LexicalWritableScope( + scope, functionDescriptor, true, + TraceBasedLocalRedeclarationChecker(trace, overloadChecker), LexicalScopeKind.FUNCTION_HEADER + ) - val typeParameterDescriptors = descriptorResolver. - resolveTypeParametersForDescriptor(functionDescriptor, headerScope, scope, function.typeParameters, trace) + val typeParameterDescriptors = + descriptorResolver.resolveTypeParametersForDescriptor(functionDescriptor, headerScope, scope, function.typeParameters, trace) descriptorResolver.resolveGenericBounds(function, functionDescriptor, headerScope, typeParameterDescriptors, trace) val receiverTypeRef = function.receiverTypeReference val receiverType = - if (receiverTypeRef != null) { - typeResolver.resolveType(headerScope, receiverTypeRef, trace, true) - } - else { - if (function is KtFunctionLiteral) expectedFunctionType.getReceiverType() else null - } + if (receiverTypeRef != null) { + typeResolver.resolveType(headerScope, receiverTypeRef, trace, true) + } else { + if (function is KtFunctionLiteral) expectedFunctionType.getReceiverType() else null + } - val valueParameterDescriptors = createValueParameterDescriptors(function, functionDescriptor, headerScope, trace, expectedFunctionType) + val valueParameterDescriptors = + createValueParameterDescriptors(function, functionDescriptor, headerScope, trace, expectedFunctionType) headerScope.freeze() val returnType = function.typeReference?.let { typeResolver.resolveType(headerScope, it, trace, true) } val visibility = resolveVisibilityFromModifiers(function, getDefaultVisibility(function, container)) - val modality = resolveMemberModalityFromModifiers(function, getDefaultModality(container, visibility, function.hasBody()), - trace.bindingContext, container) + val modality = resolveMemberModalityFromModifiers( + function, getDefaultModality(container, visibility, function.hasBody()), + trace.bindingContext, container + ) val contractProvider = getContractProvider(functionDescriptor, trace, scope, dataFlowInfo, function) functionDescriptor.initialize( - receiverType, - getDispatchReceiverParameterIfNeeded(container), - typeParameterDescriptors, - valueParameterDescriptors, - returnType, - modality, - visibility, - mapOf(ContractProviderKey to contractProvider) + receiverType, + getDispatchReceiverParameterIfNeeded(container), + typeParameterDescriptors, + valueParameterDescriptors, + returnType, + modality, + visibility, + mapOf(ContractProviderKey to contractProvider) ) functionDescriptor.isOperator = function.hasModifier(KtTokens.OPERATOR_KEYWORD) functionDescriptor.isInfix = function.hasModifier(KtTokens.INFIX_KEYWORD) @@ -199,7 +214,7 @@ class FunctionDescriptorResolver( functionDescriptor.isTailrec = function.hasModifier(KtTokens.TAILREC_KEYWORD) functionDescriptor.isSuspend = function.hasModifier(KtTokens.SUSPEND_KEYWORD) functionDescriptor.isExpect = container is PackageFragmentDescriptor && function.hasExpectModifier() || - container is ClassDescriptor && container.isExpect + container is ClassDescriptor && container.isExpect functionDescriptor.isActual = function.hasActualModifier() receiverType?.let { ForceResolveUtil.forceResolveAllContents(it.annotations) } @@ -209,11 +224,11 @@ class FunctionDescriptorResolver( } private fun getContractProvider( - functionDescriptor: SimpleFunctionDescriptorImpl, - trace: BindingTrace, - scope: LexicalScope, - dataFlowInfo: DataFlowInfo, - function: KtFunction + functionDescriptor: SimpleFunctionDescriptorImpl, + trace: BindingTrace, + scope: LexicalScope, + dataFlowInfo: DataFlowInfo, + function: KtFunction ): LazyContractProvider { val provideByDeferredForceResolve = LazyContractProvider { expressionTypingServices.getBodyExpressionType(trace, scope, dataFlowInfo, function, functionDescriptor) @@ -221,9 +236,9 @@ class FunctionDescriptorResolver( val emptyContract = LazyContractProvider.createInitialized(null) val isContractsEnabled = languageVersionSettings.supportsFeature(LanguageFeature.CallsInPlaceEffect) || - languageVersionSettings.supportsFeature(LanguageFeature.ReturnsEffect) || - // We need to enable contracts if we're compiling "kotlin"-package to be able to ship contracts in stdlib in 1.2 - languageVersionSettings.getFlag(AnalysisFlag.allowKotlinPackage) + languageVersionSettings.supportsFeature(LanguageFeature.ReturnsEffect) || + // We need to enable contracts if we're compiling "kotlin"-package to be able to ship contracts in stdlib in 1.2 + languageVersionSettings.getFlag(AnalysisFlag.allowKotlinPackage) if (!isContractsEnabled || !contractParsingServices.fastCheckIfContractPresent(function)) return emptyContract @@ -231,11 +246,11 @@ class FunctionDescriptorResolver( } private fun createValueParameterDescriptors( - function: KtFunction, - functionDescriptor: SimpleFunctionDescriptorImpl, - innerScope: LexicalWritableScope, - trace: BindingTrace, - expectedFunctionType: KotlinType + function: KtFunction, + functionDescriptor: SimpleFunctionDescriptorImpl, + innerScope: LexicalWritableScope, + trace: BindingTrace, + expectedFunctionType: KotlinType ): List { val expectedValueParameters = expectedFunctionType.getValueParameters(functionDescriptor) val expectedParameterTypes = expectedValueParameters?.map { it.type.removeParameterNameAnnotation() } @@ -243,10 +258,12 @@ class FunctionDescriptorResolver( if (expectedValueParameters.size == 1 && function is KtFunctionLiteral && function.getValueParameterList() == null) { // it parameter for lambda val valueParameterDescriptor = expectedValueParameters.single() - val it = ValueParameterDescriptorImpl(functionDescriptor, null, 0, Annotations.EMPTY, Name.identifier("it"), - expectedParameterTypes!!.single(), valueParameterDescriptor.declaresDefaultValue(), - valueParameterDescriptor.isCrossinline, valueParameterDescriptor.isNoinline, - valueParameterDescriptor.varargElementType, SourceElement.NO_SOURCE) + val it = ValueParameterDescriptorImpl( + functionDescriptor, null, 0, Annotations.EMPTY, Name.identifier("it"), + expectedParameterTypes!!.single(), valueParameterDescriptor.declaresDefaultValue(), + valueParameterDescriptor.isCrossinline, valueParameterDescriptor.isNoinline, + valueParameterDescriptor.varargElementType, SourceElement.NO_SOURCE + ) trace.record(BindingContext.AUTO_CREATED_IT, it) return listOf(it) } @@ -258,11 +275,11 @@ class FunctionDescriptorResolver( trace.recordScope(innerScope, function.valueParameterList) return resolveValueParameters( - functionDescriptor, - innerScope, - function.valueParameters, - trace, - expectedParameterTypes + functionDescriptor, + innerScope, + function.valueParameters, + trace, + expectedParameterTypes ) } @@ -274,63 +291,62 @@ class FunctionDescriptorResolver( private fun KotlinType.functionTypeExpected() = !TypeUtils.noExpectedType(this) && isBuiltinFunctionalType private fun KotlinType.getReceiverType(): KotlinType? = - if (functionTypeExpected()) this.getReceiverTypeFromFunctionType() else null + if (functionTypeExpected()) this.getReceiverTypeFromFunctionType() else null private fun KotlinType.getValueParameters(owner: FunctionDescriptor): List? = - if (functionTypeExpected()) { - createValueParametersForInvokeInFunctionType(owner, this.getValueParameterTypesFromFunctionType()) - } - else null + if (functionTypeExpected()) { + createValueParametersForInvokeInFunctionType(owner, this.getValueParameterTypesFromFunctionType()) + } else null fun resolvePrimaryConstructorDescriptor( - scope: LexicalScope, - classDescriptor: ClassDescriptor, - classElement: KtPureClassOrObject, - trace: BindingTrace + scope: LexicalScope, + classDescriptor: ClassDescriptor, + classElement: KtPureClassOrObject, + trace: BindingTrace ): ClassConstructorDescriptorImpl? { if (classDescriptor.kind == ClassKind.ENUM_ENTRY || !classElement.hasPrimaryConstructor()) return null return createConstructorDescriptor( - scope, - classDescriptor, - true, - classElement.primaryConstructorModifierList, - classElement.primaryConstructor ?: classElement, - classElement.primaryConstructorParameters, - trace + scope, + classDescriptor, + true, + classElement.primaryConstructorModifierList, + classElement.primaryConstructor ?: classElement, + classElement.primaryConstructorParameters, + trace ) } fun resolveSecondaryConstructorDescriptor( - scope: LexicalScope, - classDescriptor: ClassDescriptor, - constructor: KtSecondaryConstructor, - trace: BindingTrace + scope: LexicalScope, + classDescriptor: ClassDescriptor, + constructor: KtSecondaryConstructor, + trace: BindingTrace ): ClassConstructorDescriptorImpl { return createConstructorDescriptor( - scope, - classDescriptor, - false, - constructor.modifierList, - constructor, - constructor.valueParameters, - trace + scope, + classDescriptor, + false, + constructor.modifierList, + constructor, + constructor.valueParameters, + trace ) } private fun createConstructorDescriptor( - scope: LexicalScope, - classDescriptor: ClassDescriptor, - isPrimary: Boolean, - modifierList: KtModifierList?, - declarationToTrace: KtPureElement, - valueParameters: List, - trace: BindingTrace + scope: LexicalScope, + classDescriptor: ClassDescriptor, + isPrimary: Boolean, + modifierList: KtModifierList?, + declarationToTrace: KtPureElement, + valueParameters: List, + trace: BindingTrace ): ClassConstructorDescriptorImpl { val constructorDescriptor = ClassConstructorDescriptorImpl.create( - classDescriptor, - annotationResolver.resolveAnnotationsWithoutArguments(scope, modifierList, trace), - isPrimary, - declarationToTrace.toSourceElement() + classDescriptor, + annotationResolver.resolveAnnotationsWithoutArguments(scope, modifierList, trace), + isPrimary, + declarationToTrace.toSourceElement() ) if (classDescriptor.isExpect) { constructorDescriptor.isExpect = true @@ -341,18 +357,18 @@ class FunctionDescriptorResolver( if (declarationToTrace is PsiElement) trace.record(BindingContext.CONSTRUCTOR, declarationToTrace, constructorDescriptor) val parameterScope = LexicalWritableScope( - scope, - constructorDescriptor, - false, - TraceBasedLocalRedeclarationChecker(trace, overloadChecker), - LexicalScopeKind.CONSTRUCTOR_HEADER + scope, + constructorDescriptor, + false, + TraceBasedLocalRedeclarationChecker(trace, overloadChecker), + LexicalScopeKind.CONSTRUCTOR_HEADER ) val constructor = constructorDescriptor.initialize( - resolveValueParameters(constructorDescriptor, parameterScope, valueParameters, trace, null), - resolveVisibilityFromModifiers( - modifierList, - DescriptorUtils.getDefaultConstructorVisibility(classDescriptor) - ) + resolveValueParameters(constructorDescriptor, parameterScope, valueParameters, trace, null), + resolveVisibilityFromModifiers( + modifierList, + DescriptorUtils.getDefaultConstructorVisibility(classDescriptor) + ) ) constructor.returnType = classDescriptor.defaultType if (DescriptorUtils.isAnnotationClass(classDescriptor)) { @@ -362,11 +378,11 @@ class FunctionDescriptorResolver( } private fun resolveValueParameters( - functionDescriptor: FunctionDescriptor, - parameterScope: LexicalWritableScope, - valueParameters: List, - trace: BindingTrace, - expectedParameterTypes: List? + functionDescriptor: FunctionDescriptor, + parameterScope: LexicalWritableScope, + valueParameters: List, + trace: BindingTrace, + expectedParameterTypes: List? ): List { val result = ArrayList() @@ -383,8 +399,7 @@ class FunctionDescriptorResolver( trace.report(EXPECTED_PARAMETER_TYPE_MISMATCH.on(valueParameter, expectedType)) } } - } - else { + } else { type = if (isFunctionLiteral(functionDescriptor) || isFunctionExpression(functionDescriptor)) { val containsUninferredParameter = TypeUtils.contains(expectedType) { TypeUtils.isDontCarePlaceholder(it) || ErrorUtils.isUninferredParameter(it) @@ -394,8 +409,7 @@ class FunctionDescriptorResolver( } expectedType ?: TypeUtils.CANT_INFER_FUNCTION_PARAM_TYPE - } - else { + } else { trace.report(VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION.on(valueParameter)) ErrorUtils.createErrorType("Type annotation was missing for parameter ${valueParameter.nameAsSafeName}") } @@ -403,16 +417,18 @@ class FunctionDescriptorResolver( if (functionDescriptor !is ConstructorDescriptor || !functionDescriptor.isPrimary) { val isConstructor = functionDescriptor is ConstructorDescriptor - with (modifiersChecker.withTrace(trace)) { + with(modifiersChecker.withTrace(trace)) { checkParameterHasNoValOrVar( - valueParameter, - if (isConstructor) VAL_OR_VAR_ON_SECONDARY_CONSTRUCTOR_PARAMETER else VAL_OR_VAR_ON_FUN_PARAMETER + valueParameter, + if (isConstructor) VAL_OR_VAR_ON_SECONDARY_CONSTRUCTOR_PARAMETER else VAL_OR_VAR_ON_FUN_PARAMETER ) } } - val valueParameterDescriptor = descriptorResolver.resolveValueParameterDescriptor(parameterScope, functionDescriptor, - valueParameter, i, type, trace) + val valueParameterDescriptor = descriptorResolver.resolveValueParameterDescriptor( + parameterScope, functionDescriptor, + valueParameter, i, type, trace + ) // Do not report NAME_SHADOWING for lambda destructured parameters as they may be not fully resolved at this time ExpressionTypingUtils.checkVariableShadowing(parameterScope, trace, valueParameterDescriptor) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/ImportPath.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/ImportPath.kt index 78ba9f6613a..47964e6d312 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/ImportPath.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/ImportPath.kt @@ -43,11 +43,11 @@ data class ImportPath @JvmOverloads constructor(val fqName: FqName, val isAllUnd } companion object { - @JvmStatic fun fromString(pathStr: String): ImportPath { + @JvmStatic + fun fromString(pathStr: String): ImportPath { return if (pathStr.endsWith(".*")) { ImportPath(FqName(pathStr.substring(0, pathStr.length - 2)), isAllUnder = true) - } - else { + } else { ImportPath(FqName(pathStr), isAllUnder = false) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/LateinitModifierApplicabilityChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/LateinitModifierApplicabilityChecker.kt index 04164a4174a..9e56ec46fce 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/LateinitModifierApplicabilityChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/LateinitModifierApplicabilityChecker.kt @@ -47,9 +47,13 @@ object LateinitModifierApplicabilityChecker { if (type.isMarkedNullable) { trace.report(Errors.INAPPLICABLE_LATEINIT_MODIFIER.on(modifier, "is not allowed on $variables of nullable types")) - } - else if (TypeUtils.isNullableType(type)) { - trace.report(Errors.INAPPLICABLE_LATEINIT_MODIFIER.on(modifier, "is not allowed on $variables of a type with nullable upper bound")) + } else if (TypeUtils.isNullableType(type)) { + trace.report( + Errors.INAPPLICABLE_LATEINIT_MODIFIER.on( + modifier, + "is not allowed on $variables of a type with nullable upper bound" + ) + ) } if (KotlinBuiltIns.isPrimitiveType(type)) { @@ -59,8 +63,7 @@ object LateinitModifierApplicabilityChecker { if (ktDeclaration is KtProperty) { if (ktDeclaration.hasDelegateExpression()) { trace.report(Errors.INAPPLICABLE_LATEINIT_MODIFIER.on(modifier, "is not allowed on delegated properties")) - } - else if (ktDeclaration.hasInitializer()) { + } else if (ktDeclaration.hasInitializer()) { trace.report(Errors.INAPPLICABLE_LATEINIT_MODIFIER.on(modifier, "is not allowed on $variables with initializer")) } } @@ -81,9 +84,13 @@ object LateinitModifierApplicabilityChecker { if (!hasDelegateExpressionOrInitializer) { if (hasAccessorImplementation) { - trace.report(Errors.INAPPLICABLE_LATEINIT_MODIFIER.on(modifier, "is not allowed on properties with a custom getter or setter")) - } - else if (!isAbstract && !hasBackingField) { + trace.report( + Errors.INAPPLICABLE_LATEINIT_MODIFIER.on( + modifier, + "is not allowed on properties with a custom getter or setter" + ) + ) + } else if (!isAbstract && !hasBackingField) { trace.report(Errors.INAPPLICABLE_LATEINIT_MODIFIER.on(modifier, "is not allowed on properties without backing field")) } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/LazyExplicitImportScope.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/LazyExplicitImportScope.kt index e2f62db0519..bed75f8ec57 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/LazyExplicitImportScope.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/LazyExplicitImportScope.kt @@ -28,12 +28,12 @@ import org.jetbrains.kotlin.utils.Printer import org.jetbrains.kotlin.utils.addIfNotNull class LazyExplicitImportScope( - private val packageOrClassDescriptor: DeclarationDescriptor, - private val packageFragmentForVisibilityCheck: PackageFragmentDescriptor?, - private val declaredName: Name, - private val aliasName: Name, - private val storeReferences: (Collection) -> Unit -): BaseImportingScope(null) { + private val packageOrClassDescriptor: DeclarationDescriptor, + private val packageFragmentForVisibilityCheck: PackageFragmentDescriptor?, + private val declaredName: Name, + private val aliasName: Name, + private val storeReferences: (Collection) -> Unit +) : BaseImportingScope(null) { override fun getContributedClassifier(name: Name, location: LookupLocation): ClassifierDescriptor? { if (name != aliasName) return null @@ -58,9 +58,9 @@ class LazyExplicitImportScope( } override fun getContributedDescriptors( - kindFilter: DescriptorKindFilter, - nameFilter: (Name) -> Boolean, - changeNamesForAliased: Boolean + kindFilter: DescriptorKindFilter, + nameFilter: (Name) -> Boolean, + changeNamesForAliased: Boolean ): Collection { val descriptors = SmartList() @@ -86,10 +86,10 @@ class LazyExplicitImportScope( is CallableMemberDescriptor -> { descriptor - .newCopyBuilder() - .setName(aliasName) - .setOriginal(descriptor) - .build()!! + .newCopyBuilder() + .setName(aliasName) + .setOriginal(descriptor) + .build()!! } else -> error("Unknown kind of descriptor in import alias: $descriptor") @@ -111,8 +111,8 @@ class LazyExplicitImportScope( internal fun storeReferencesToDescriptors() = getContributedDescriptors().apply(storeReferences) private fun collectCallableMemberDescriptors( - location: LookupLocation, - getDescriptors: MemberScope.(Name, LookupLocation) -> Collection + location: LookupLocation, + getDescriptors: MemberScope.(Name, LookupLocation) -> Collection ): Collection { val descriptors = SmartList() @@ -128,8 +128,8 @@ class LazyExplicitImportScope( if (packageOrClassDescriptor.kind == ClassKind.OBJECT) { descriptors.addAll( - packageOrClassDescriptor.unsubstitutedMemberScope.getDescriptors(declaredName, location) - .mapNotNull { it.asImportedFromObjectIfPossible() } + packageOrClassDescriptor.unsubstitutedMemberScope.getDescriptors(declaredName, location) + .mapNotNull { it.asImportedFromObjectIfPossible() } ) } } @@ -148,6 +148,5 @@ class LazyExplicitImportScope( } private fun Collection.choseOnlyVisibleOrAll() = - filter { isVisible(it, packageFragmentForVisibilityCheck, position = QualifierPosition.IMPORT) }. - takeIf { it.isNotEmpty() } ?: this + filter { isVisible(it, packageFragmentForVisibilityCheck, position = QualifierPosition.IMPORT) }.takeIf { it.isNotEmpty() } ?: this } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/LocalVariableResolver.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/LocalVariableResolver.kt index a2ea5c46512..540cb070286 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/LocalVariableResolver.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/LocalVariableResolver.kt @@ -42,20 +42,20 @@ import org.jetbrains.kotlin.types.expressions.* import org.jetbrains.kotlin.types.expressions.typeInfoFactory.noTypeInfo class LocalVariableResolver( - private val modifiersChecker: ModifiersChecker, - private val identifierChecker: IdentifierChecker, - private val dataFlowAnalyzer: DataFlowAnalyzer, - private val annotationResolver: AnnotationResolver, - private val variableTypeAndInitializerResolver: VariableTypeAndInitializerResolver, - private val delegatedPropertyResolver: DelegatedPropertyResolver, - private val languageVersionSettings: LanguageVersionSettings + private val modifiersChecker: ModifiersChecker, + private val identifierChecker: IdentifierChecker, + private val dataFlowAnalyzer: DataFlowAnalyzer, + private val annotationResolver: AnnotationResolver, + private val variableTypeAndInitializerResolver: VariableTypeAndInitializerResolver, + private val delegatedPropertyResolver: DelegatedPropertyResolver, + private val languageVersionSettings: LanguageVersionSettings ) { fun process( - property: KtProperty, - typingContext: ExpressionTypingContext, - scope: LexicalScope, - facade: ExpressionTypingFacade + property: KtProperty, + typingContext: ExpressionTypingContext, + scope: LexicalScope, + facade: ExpressionTypingFacade ): Pair { val context = typingContext.replaceContextDependency(ContextDependency.INDEPENDENT).replaceScope(scope) val receiverTypeRef = property.receiverTypeReference @@ -78,16 +78,23 @@ class LocalVariableResolver( val delegateExpression = property.delegateExpression if (delegateExpression != null) { if (!languageVersionSettings.supportsFeature(LanguageFeature.LocalDelegatedProperties)) { - context.trace.report(UNSUPPORTED_FEATURE.on(property.delegate!!, LanguageFeature.LocalDelegatedProperties to languageVersionSettings)) + context.trace.report( + UNSUPPORTED_FEATURE.on( + property.delegate!!, + LanguageFeature.LocalDelegatedProperties to languageVersionSettings + ) + ) } if (propertyDescriptor is VariableDescriptorWithAccessors) { - delegatedPropertyResolver.resolvePropertyDelegate(typingContext.dataFlowInfo, - property, - propertyDescriptor, - delegateExpression, - typingContext.scope, - typingContext.trace) + delegatedPropertyResolver.resolvePropertyDelegate( + typingContext.dataFlowInfo, + property, + propertyDescriptor, + delegateExpression, + typingContext.scope, + typingContext.trace + ) propertyDescriptor.getter?.updateAccessorFlagsFromResolvedCallForDelegatedProperty(typingContext.trace) propertyDescriptor.setter?.updateAccessorFlagsFromResolvedCallForDelegatedProperty(typingContext.trace) } @@ -110,16 +117,20 @@ class LocalVariableResolver( // In this case s will be not-nullable until it is changed if (property.typeReference == null) { val variableDataFlowValue = DataFlowValueFactory.createDataFlowValueForProperty( - property, propertyDescriptor, context.trace.bindingContext, - DescriptorUtils.getContainingModuleOrNull(scope.ownerDescriptor)) + property, propertyDescriptor, context.trace.bindingContext, + DescriptorUtils.getContainingModuleOrNull(scope.ownerDescriptor) + ) // We cannot say here anything new about initializerDataFlowValue // except it has the same value as variableDataFlowValue - typeInfo = typeInfo.replaceDataFlowInfo(dataFlowInfo.assign(variableDataFlowValue, initializerDataFlowValue, - languageVersionSettings)) + typeInfo = typeInfo.replaceDataFlowInfo( + dataFlowInfo.assign( + variableDataFlowValue, initializerDataFlowValue, + languageVersionSettings + ) + ) } } - } - else { + } else { typeInfo = noTypeInfo(context) } @@ -138,30 +149,30 @@ class LocalVariableResolver( } private fun resolveLocalVariableDescriptor( - scope: LexicalScope, - variable: KtVariableDeclaration, - dataFlowInfo: DataFlowInfo, - trace: BindingTrace + scope: LexicalScope, + variable: KtVariableDeclaration, + dataFlowInfo: DataFlowInfo, + trace: BindingTrace ): VariableDescriptor { val containingDeclaration = scope.ownerDescriptor val result: VariableDescriptorWithInitializerImpl val type: KotlinType if (KtPsiUtil.isScriptDeclaration(variable)) { val propertyDescriptor = PropertyDescriptorImpl.create( - containingDeclaration, - annotationResolver.resolveAnnotationsWithArguments(scope, variable.modifierList, trace), - Modality.FINAL, - Visibilities.INTERNAL, - variable.isVar, - KtPsiUtil.safeName(variable.name), - CallableMemberDescriptor.Kind.DECLARATION, - variable.toSourceElement(), - /* lateInit = */ false, - /* isConst = */ false, - /* isExpect = */ false, - /* isActual = */ false, - /* isExternal = */ false, - variable is KtProperty && variable.hasDelegate() + containingDeclaration, + annotationResolver.resolveAnnotationsWithArguments(scope, variable.modifierList, trace), + Modality.FINAL, + Visibilities.INTERNAL, + variable.isVar, + KtPsiUtil.safeName(variable.name), + CallableMemberDescriptor.Kind.DECLARATION, + variable.toSourceElement(), + /* lateInit = */ false, + /* isConst = */ false, + /* isExpect = */ false, + /* isActual = */ false, + /* isExternal = */ false, + variable is KtProperty && variable.hasDelegate() ) // For a local variable the type must not be deferred type = variableTypeAndInitializerResolver.resolveType(propertyDescriptor, scope, variable, dataFlowInfo, trace, local = true) @@ -171,8 +182,7 @@ class LocalVariableResolver( initializeWithDefaultGetterSetter(propertyDescriptor) trace.record(BindingContext.VARIABLE, variable, propertyDescriptor) result = propertyDescriptor - } - else { + } else { val variableDescriptor = resolveLocalVariableDescriptorWithType(scope, variable, null, trace) // For a local variable the type must not be deferred type = variableTypeAndInitializerResolver.resolveType(variableDescriptor, scope, variable, dataFlowInfo, trace, local = true) @@ -200,27 +210,27 @@ class LocalVariableResolver( } internal fun resolveLocalVariableDescriptorWithType( - scope: LexicalScope, - variable: KtVariableDeclaration, - type: KotlinType?, - trace: BindingTrace + scope: LexicalScope, + variable: KtVariableDeclaration, + type: KotlinType?, + trace: BindingTrace ): LocalVariableDescriptor { val hasDelegate = variable is KtProperty && variable.hasDelegate() val hasLateinit = variable.hasModifier(KtTokens.LATEINIT_KEYWORD) val variableDescriptor = LocalVariableDescriptor( - scope.ownerDescriptor, - annotationResolver.resolveAnnotationsWithArguments(scope, variable.modifierList, trace), - // Note, that the same code works both for common local vars and for destructuring declarations, - // but since the first case is illegal error must be reported somewhere else - if (variable.isSingleUnderscore) - Name.special("") - else - KtPsiUtil.safeName(variable.name), - type, - variable.isVar, - hasDelegate, - hasLateinit, - variable.toSourceElement() + scope.ownerDescriptor, + annotationResolver.resolveAnnotationsWithArguments(scope, variable.modifierList, trace), + // Note, that the same code works both for common local vars and for destructuring declarations, + // but since the first case is illegal error must be reported somewhere else + if (variable.isSingleUnderscore) + Name.special("") + else + KtPsiUtil.safeName(variable.name), + type, + variable.isVar, + hasDelegate, + hasLateinit, + variable.toSourceElement() ) trace.record(BindingContext.VARIABLE, variable, variableDescriptor) return variableDescriptor diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/OperatorModifierChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/OperatorModifierChecker.kt index 420a2f375be..531db90bd83 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/OperatorModifierChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/OperatorModifierChecker.kt @@ -32,10 +32,10 @@ import org.jetbrains.kotlin.util.OperatorNameConventions object OperatorModifierChecker { fun check( - declaration: KtDeclaration, - descriptor: DeclarationDescriptor, - diagnosticHolder: DiagnosticSink, - languageVersionSettings: LanguageVersionSettings + declaration: KtDeclaration, + descriptor: DeclarationDescriptor, + diagnosticHolder: DiagnosticSink, + languageVersionSettings: LanguageVersionSettings ) { val functionDescriptor = descriptor as? FunctionDescriptor ?: return if (!functionDescriptor.isOperator) return @@ -64,7 +64,12 @@ object OperatorModifierChecker { diagnosticHolder.report(Errors.INAPPLICABLE_OPERATOR_MODIFIER.on(modifier, errorDescription)) } - private fun checkSupportsFeature(feature: LanguageFeature, languageVersionSettings: LanguageVersionSettings, diagnosticHolder: DiagnosticSink, modifier: PsiElement) { + private fun checkSupportsFeature( + feature: LanguageFeature, + languageVersionSettings: LanguageVersionSettings, + diagnosticHolder: DiagnosticSink, + modifier: PsiElement + ) { if (!languageVersionSettings.supportsFeature(feature)) { diagnosticHolder.report(Errors.UNSUPPORTED_FEATURE.on(modifier, feature to languageVersionSettings)) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/OverloadChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/OverloadChecker.kt index a8c414bfeb8..eb0a4381d4f 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/OverloadChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/OverloadChecker.kt @@ -30,7 +30,7 @@ import org.jetbrains.kotlin.types.KotlinType object OverloadabilitySpecificityCallbacks : SpecificityComparisonCallbacks { override fun isNonSubtypeNotLessSpecific(specific: KotlinType, general: KotlinType): Boolean = - false + false } class OverloadChecker(val specificityComparator: TypeSpecificityComparator) { @@ -61,8 +61,10 @@ class OverloadChecker(val specificityComparator: TypeSpecificityComparator) { val aSignature = FlatSignature.createFromCallableDescriptor(a) val bSignature = FlatSignature.createFromCallableDescriptor(b) - val aIsNotLessSpecificThanB = ConstraintSystemBuilderImpl.forSpecificity().isSignatureNotLessSpecific(aSignature, bSignature, OverloadabilitySpecificityCallbacks, specificityComparator) - val bIsNotLessSpecificThanA = ConstraintSystemBuilderImpl.forSpecificity().isSignatureNotLessSpecific(bSignature, aSignature, OverloadabilitySpecificityCallbacks, specificityComparator) + val aIsNotLessSpecificThanB = ConstraintSystemBuilderImpl.forSpecificity() + .isSignatureNotLessSpecific(aSignature, bSignature, OverloadabilitySpecificityCallbacks, specificityComparator) + val bIsNotLessSpecificThanA = ConstraintSystemBuilderImpl.forSpecificity() + .isSignatureNotLessSpecific(bSignature, aSignature, OverloadabilitySpecificityCallbacks, specificityComparator) return !(aIsNotLessSpecificThanB && bIsNotLessSpecificThanA) } @@ -74,18 +76,18 @@ class OverloadChecker(val specificityComparator: TypeSpecificityComparator) { } private fun getDeclarationCategory(a: DeclarationDescriptor): DeclarationCategory = - when (a) { - is PropertyDescriptor -> - if (a.isExtensionProperty) - DeclarationCategory.EXTENSION_PROPERTY - else - DeclarationCategory.TYPE_OR_VALUE - is FunctionDescriptor -> - DeclarationCategory.FUNCTION - is ClassifierDescriptor -> + when (a) { + is PropertyDescriptor -> + if (a.isExtensionProperty) + DeclarationCategory.EXTENSION_PROPERTY + else DeclarationCategory.TYPE_OR_VALUE - else -> - error("Unexpected declaration kind: $a") - } + is FunctionDescriptor -> + DeclarationCategory.FUNCTION + is ClassifierDescriptor -> + DeclarationCategory.TYPE_OR_VALUE + else -> + error("Unexpected declaration kind: $a") + } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/OverloadFilter.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/OverloadFilter.kt index b02281c7f26..b763df2ef4a 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/OverloadFilter.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/OverloadFilter.kt @@ -24,6 +24,6 @@ interface OverloadFilter { object Default : OverloadFilter { override fun filterPackageMemberOverloads(overloads: Collection): Collection = - overloads + overloads } } \ No newline at end of file diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/OverloadResolver.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/OverloadResolver.kt index e4d57ac0d98..570a95fc4f3 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/OverloadResolver.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/OverloadResolver.kt @@ -29,9 +29,9 @@ import org.jetbrains.kotlin.resolve.scopes.MemberScope import java.util.* class OverloadResolver( - private val trace: BindingTrace, - private val overloadFilter: OverloadFilter, - private val overloadChecker: OverloadChecker + private val trace: BindingTrace, + private val overloadFilter: OverloadFilter, + private val overloadChecker: OverloadChecker ) { fun checkOverloads(c: BodiesResolveContext) { @@ -54,13 +54,11 @@ class OverloadResolver( val containingDeclaration = klass.containingDeclaration if (containingDeclaration is ScriptDescriptor) { // TODO: check overload conflicts of functions with constructors in scripts - } - else if (containingDeclaration is ClassDescriptor) { + } else if (containingDeclaration is ClassDescriptor) { constructorsByOuterClass.putValues(containingDeclaration, klass.constructors) - } - else if (!(containingDeclaration is FunctionDescriptor || - containingDeclaration is PropertyDescriptor || - containingDeclaration is PackageFragmentDescriptor)) { + } else if (!(containingDeclaration is FunctionDescriptor || + containingDeclaration is PropertyDescriptor || + containingDeclaration is PackageFragmentDescriptor)) { throw IllegalStateException("Illegal class container: " + containingDeclaration) } } @@ -84,17 +82,16 @@ class OverloadResolver( } private fun groupModulePackageMembersByFqName( - c: BodiesResolveContext, - overloadFilter: OverloadFilter + c: BodiesResolveContext, + overloadFilter: OverloadFilter ): MultiMap { val packageMembersByName = MultiMap() collectModulePackageMembersWithSameName( - packageMembersByName, - (c.functions.values as Collection) + c.declaredClasses.values + c.typeAliases.values, - overloadFilter - ) { - scope, name -> + packageMembersByName, + (c.functions.values as Collection) + c.declaredClasses.values + c.typeAliases.values, + overloadFilter + ) { scope, name -> val functions = scope.getContributedFunctions(name, NoLookupLocation.WHEN_CHECK_DECLARATION_CONFLICTS) val classifier = scope.getContributedClassifier(name, NoLookupLocation.WHEN_CHECK_DECLARATION_CONFLICTS) when (classifier) { @@ -110,8 +107,7 @@ class OverloadResolver( } } - collectModulePackageMembersWithSameName(packageMembersByName, c.properties.values, overloadFilter) { - scope, name -> + collectModulePackageMembersWithSameName(packageMembersByName, c.properties.values, overloadFilter) { scope, name -> val variables = scope.getContributedVariables(name, NoLookupLocation.WHEN_CHECK_DECLARATION_CONFLICTS) val classifier = scope.getContributedClassifier(name, NoLookupLocation.WHEN_CHECK_DECLARATION_CONFLICTS) variables + listOfNotNull(classifier) @@ -121,10 +117,10 @@ class OverloadResolver( } private inline fun collectModulePackageMembersWithSameName( - packageMembersByName: MultiMap, - interestingDescriptors: Collection, - overloadFilter: OverloadFilter, - getMembersByName: (MemberScope, Name) -> Collection + packageMembersByName: MultiMap, + interestingDescriptors: Collection, + overloadFilter: OverloadFilter, + getMembersByName: (MemberScope, Name) -> Collection ) { val observedFQNs = hashSetOf() for (descriptor in interestingDescriptors) { @@ -140,35 +136,34 @@ class OverloadResolver( } private inline fun getModulePackageMembersWithSameName( - descriptor: DeclarationDescriptor, - overloadFilter: OverloadFilter, - getMembersByName: (MemberScope, Name) -> Collection + descriptor: DeclarationDescriptor, + overloadFilter: OverloadFilter, + getMembersByName: (MemberScope, Name) -> Collection ): Collection { val containingPackage = descriptor.containingDeclaration if (containingPackage !is PackageFragmentDescriptor) { throw AssertionError("$descriptor is not a top-level package member") } - val containingModule = DescriptorUtils.getContainingModuleOrNull(descriptor) ?: - return when (descriptor) { - is CallableMemberDescriptor -> listOf(descriptor) - is ClassDescriptor -> descriptor.constructors - else -> throw AssertionError("Unexpected descriptor kind: $descriptor") - } + val containingModule = DescriptorUtils.getContainingModuleOrNull(descriptor) ?: return when (descriptor) { + is CallableMemberDescriptor -> listOf(descriptor) + is ClassDescriptor -> descriptor.constructors + else -> throw AssertionError("Unexpected descriptor kind: $descriptor") + } val containingPackageScope = containingModule.getPackage(containingPackage.fqName).memberScope val possibleOverloads = - getMembersByName(containingPackageScope, descriptor.name).filter { - // NB memberScope for PackageViewDescriptor includes module dependencies - DescriptorUtils.getContainingModule(it) == containingModule - } + getMembersByName(containingPackageScope, descriptor.name).filter { + // NB memberScope for PackageViewDescriptor includes module dependencies + DescriptorUtils.getContainingModule(it) == containingModule + } return overloadFilter.filterPackageMemberOverloads(possibleOverloads) } private fun checkOverloadsInClass( - classDescriptor: ClassDescriptorWithResolutionScopes, - nestedClassConstructors: Collection + classDescriptor: ClassDescriptorWithResolutionScopes, + nestedClassConstructors: Collection ) { val functionsByName = MultiMap.create() @@ -231,8 +226,8 @@ class OverloadResolver( } private fun DeclarationDescriptor.isPrivate() = - this is DeclarationDescriptorWithVisibility && - Visibilities.isPrivate(this.visibility) + this is DeclarationDescriptorWithVisibility && + Visibilities.isPrivate(this.visibility) private fun checkOverloadsInClass(members: Collection) { if (members.size == 1) return @@ -240,7 +235,7 @@ class OverloadResolver( } private fun DeclarationDescriptor.isSynthesized() = - this is CallableMemberDescriptor && kind == CallableMemberDescriptor.Kind.SYNTHESIZED + this is CallableMemberDescriptor && kind == CallableMemberDescriptor.Kind.SYNTHESIZED private fun findRedeclarations(members: Collection): Collection { val redeclarations = linkedSetOf() @@ -284,14 +279,14 @@ class OverloadResolver( private fun isExpectDeclarationAndDefinition(declaration: DeclarationDescriptor, definition: DeclarationDescriptor): Boolean { return declaration is MemberDescriptor && declaration.isExpect && - definition is MemberDescriptor && !definition.isExpect + definition is MemberDescriptor && !definition.isExpect } private fun isDefinitionsForDifferentPlatforms(member1: DeclarationDescriptorNonRoot, member2: DeclarationDescriptorNonRoot): Boolean { if (member1 !is MemberDescriptor || member2 !is MemberDescriptor) return false return member1.isActual && member2.isActual && - member1.getMultiTargetPlatform() != member2.getMultiTargetPlatform() + member1.getMultiTargetPlatform() != member2.getMultiTargetPlatform() } private fun reportRedeclarations(redeclarations: Collection) { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/OverridesBackwardCompatibilityHelper.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/OverridesBackwardCompatibilityHelper.kt index 8204d2b5fec..faf0f25deda 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/OverridesBackwardCompatibilityHelper.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/OverridesBackwardCompatibilityHelper.kt @@ -23,6 +23,6 @@ interface OverridesBackwardCompatibilityHelper { object Default : OverridesBackwardCompatibilityHelper { override fun overrideCanBeOmitted(overridingDescriptor: CallableMemberDescriptor): Boolean = - false + false } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/QualifiedExpressionResolveUtil.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/QualifiedExpressionResolveUtil.kt index 048a952637d..6d9f8e7d5ba 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/QualifiedExpressionResolveUtil.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/QualifiedExpressionResolveUtil.kt @@ -25,7 +25,7 @@ import org.jetbrains.kotlin.resolve.scopes.receivers.* import org.jetbrains.kotlin.types.expressions.ExpressionTypingContext fun resolveQualifierAsReceiverInExpression( - qualifier: Qualifier, selector: DeclarationDescriptor?, context: ExpressionTypingContext + qualifier: Qualifier, selector: DeclarationDescriptor?, context: ExpressionTypingContext ): DeclarationDescriptor { val referenceTarget = resolveQualifierReferenceTarget(qualifier, selector, context) @@ -37,7 +37,7 @@ fun resolveQualifierAsReceiverInExpression( } fun resolveQualifierAsStandaloneExpression( - qualifier: Qualifier, context: ExpressionTypingContext + qualifier: Qualifier, context: ExpressionTypingContext ): DeclarationDescriptor { val referenceTarget = resolveQualifierReferenceTarget(qualifier, null, context) @@ -66,9 +66,9 @@ fun resolveQualifierAsStandaloneExpression( } private fun resolveQualifierReferenceTarget( - qualifier: Qualifier, - selector: DeclarationDescriptor?, - context: ExpressionTypingContext + qualifier: Qualifier, + selector: DeclarationDescriptor?, + context: ExpressionTypingContext ): DeclarationDescriptor { if (qualifier is TypeParameterQualifier) { return qualifier.descriptor @@ -92,7 +92,7 @@ private fun resolveQualifierReferenceTarget( if (qualifier is ClassifierQualifier) { val classifier = qualifier.descriptor val selectorIsCallable = selector is CallableDescriptor && - (selector.dispatchReceiverParameter != null || selector.extensionReceiverParameter != null) + (selector.dispatchReceiverParameter != null || selector.extensionReceiverParameter != null) // TODO simplify this code. // Given a class qualifier in expression position, // it should provide a proper REFERENCE_TARGET (with type), diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/QualifiedExpressionResolver.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/QualifiedExpressionResolver.kt index 07cbcc361de..49381f51d5c 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/QualifiedExpressionResolver.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/QualifiedExpressionResolver.kt @@ -41,30 +41,32 @@ import org.jetbrains.kotlin.types.expressions.isWithoutValueArguments class QualifiedExpressionResolver { fun resolvePackageHeader( - packageDirective: KtPackageDirective, - module: ModuleDescriptor, - trace: BindingTrace + packageDirective: KtPackageDirective, + module: ModuleDescriptor, + trace: BindingTrace ) { val packageNames = packageDirective.packageNames for ((index, nameExpression) in packageNames.withIndex()) { - storeResult(trace, nameExpression, module.getPackage(packageDirective.getFqName(nameExpression)), - shouldBeVisibleFrom = null, position = QualifierPosition.PACKAGE_HEADER, isQualifier = index != packageNames.lastIndex) + storeResult( + trace, nameExpression, module.getPackage(packageDirective.getFqName(nameExpression)), + shouldBeVisibleFrom = null, position = QualifierPosition.PACKAGE_HEADER, isQualifier = index != packageNames.lastIndex + ) } } data class TypeQualifierResolutionResult( - val qualifierParts: List, - val classifierDescriptor: ClassifierDescriptor? = null + val qualifierParts: List, + val classifierDescriptor: ClassifierDescriptor? = null ) { val allProjections: List get() = qualifierParts.flatMap { it.typeArguments?.arguments.orEmpty() } } fun resolveDescriptorForType( - userType: KtUserType, - scope: LexicalScope, - trace: BindingTrace, - isDebuggerContext: Boolean + userType: KtUserType, + scope: LexicalScope, + trace: BindingTrace, + isDebuggerContext: Boolean ): TypeQualifierResolutionResult { val ownerDescriptor = if (!isDebuggerContext) scope.ownerDescriptor else null if (userType.qualifier == null) { @@ -81,7 +83,7 @@ class QualifiedExpressionResolver { val (qualifierPartList, hasError) = userType.asQualifierPartList() if (hasError) { val descriptor = resolveToPackageOrClass( - qualifierPartList, scope.ownerDescriptor.module, trace, ownerDescriptor, scope, position = QualifierPosition.TYPE + qualifierPartList, scope.ownerDescriptor.module, trace, ownerDescriptor, scope, position = QualifierPosition.TYPE ) as? ClassifierDescriptor return TypeQualifierResolutionResult(qualifierPartList, descriptor) } @@ -90,18 +92,18 @@ class QualifiedExpressionResolver { } private fun resolveQualifierPartListForType( - qualifierPartList: List, - ownerDescriptor: DeclarationDescriptor?, - scope: LexicalScope, - trace: BindingTrace, - isQualifier: Boolean + qualifierPartList: List, + ownerDescriptor: DeclarationDescriptor?, + scope: LexicalScope, + trace: BindingTrace, + isQualifier: Boolean ): TypeQualifierResolutionResult { assert(qualifierPartList.isNotEmpty()) { "Qualifier list should not be empty" } val qualifier = resolveToPackageOrClass( - qualifierPartList.subList(0, qualifierPartList.size - 1), - scope.ownerDescriptor.module, trace, ownerDescriptor, scope, - position = QualifierPosition.TYPE + qualifierPartList.subList(0, qualifierPartList.size - 1), + scope.ownerDescriptor.module, trace, ownerDescriptor, scope, + position = QualifierPosition.TYPE ) ?: return TypeQualifierResolutionResult(qualifierPartList, null) val lastPart = qualifierPartList.last() @@ -128,10 +130,10 @@ class QualifiedExpressionResolver { } fun resolveDescriptorForDoubleColonLHS( - expression: KtExpression, - scope: LexicalScope, - trace: BindingTrace, - isDebuggerContext: Boolean + expression: KtExpression, + scope: LexicalScope, + trace: BindingTrace, + isDebuggerContext: Boolean ): TypeQualifierResolutionResult { val ownerDescriptor = if (!isDebuggerContext) scope.ownerDescriptor else null @@ -158,8 +160,7 @@ class QualifiedExpressionResolver { val referenceExpression = userType.referenceExpression if (referenceExpression != null) { result.add(QualifierPart(referenceExpression.getReferencedNameAsName(), referenceExpression, userType.typeArgumentList)) - } - else { + } else { hasError = true } userType = userType.qualifier @@ -168,79 +169,106 @@ class QualifiedExpressionResolver { } fun processImportReference( - importDirective: KtImportDirective, - moduleDescriptor: ModuleDescriptor, - trace: BindingTrace, - excludedImportNames: Collection, - packageFragmentForVisibilityCheck: PackageFragmentDescriptor? + importDirective: KtImportDirective, + moduleDescriptor: ModuleDescriptor, + trace: BindingTrace, + excludedImportNames: Collection, + packageFragmentForVisibilityCheck: PackageFragmentDescriptor? ): ImportingScope? { // null if some error happened val importedReference = importDirective.importedReference ?: return null val path = importedReference.asQualifierPartList() val lastPart = path.lastOrNull() ?: return null val packageFragmentForCheck = - when { - importDirective.suppressDiagnosticsInDebugMode() -> null - packageFragmentForVisibilityCheck is DeclarationDescriptorWithSource && packageFragmentForVisibilityCheck.source == SourceElement.NO_SOURCE -> { - PackageFragmentWithCustomSource(packageFragmentForVisibilityCheck, KotlinSourceElement(importDirective.containingKtFile)) - } - else -> packageFragmentForVisibilityCheck + when { + importDirective.suppressDiagnosticsInDebugMode() -> null + packageFragmentForVisibilityCheck is DeclarationDescriptorWithSource && packageFragmentForVisibilityCheck.source == SourceElement.NO_SOURCE -> { + PackageFragmentWithCustomSource( + packageFragmentForVisibilityCheck, + KotlinSourceElement(importDirective.containingKtFile) + ) } + else -> packageFragmentForVisibilityCheck + } if (importDirective.isAllUnder) { - val packageOrClassDescriptor = resolveToPackageOrClass(path, moduleDescriptor, trace, packageFragmentForCheck, - scopeForFirstPart = null, position = QualifierPosition.IMPORT) ?: return null + val packageOrClassDescriptor = resolveToPackageOrClass( + path, moduleDescriptor, trace, packageFragmentForCheck, + scopeForFirstPart = null, position = QualifierPosition.IMPORT + ) ?: return null if (packageOrClassDescriptor is ClassDescriptor && packageOrClassDescriptor.kind.isSingleton) { - trace.report(Errors.CANNOT_ALL_UNDER_IMPORT_FROM_SINGLETON.on(lastPart.expression, packageOrClassDescriptor)) // todo report on star + trace.report( + Errors.CANNOT_ALL_UNDER_IMPORT_FROM_SINGLETON.on( + lastPart.expression, + packageOrClassDescriptor + ) + ) // todo report on star return null } return AllUnderImportScope(packageOrClassDescriptor, excludedImportNames) - } - else { + } else { return processSingleImport(moduleDescriptor, trace, importDirective, path, lastPart, packageFragmentForCheck) } } private fun processSingleImport( - moduleDescriptor: ModuleDescriptor, - trace: BindingTrace, - importDirective: KtImportDirective, - path: List, - lastPart: QualifierPart, - packageFragmentForVisibilityCheck: PackageFragmentDescriptor? + moduleDescriptor: ModuleDescriptor, + trace: BindingTrace, + importDirective: KtImportDirective, + path: List, + lastPart: QualifierPart, + packageFragmentForVisibilityCheck: PackageFragmentDescriptor? ): ImportingScope? { val aliasName = KtPsiUtil.getAliasName(importDirective) if (aliasName == null) { // import kotlin. - resolveToPackageOrClass(path, moduleDescriptor, trace, packageFragmentForVisibilityCheck, scopeForFirstPart = null, position = QualifierPosition.IMPORT) + resolveToPackageOrClass( + path, + moduleDescriptor, + trace, + packageFragmentForVisibilityCheck, + scopeForFirstPart = null, + position = QualifierPosition.IMPORT + ) return null } val resolvedDescriptor = resolveToPackageOrClass( - path.subList(0, path.size - 1), moduleDescriptor, trace, - packageFragmentForVisibilityCheck, scopeForFirstPart = null, position = QualifierPosition.IMPORT + path.subList(0, path.size - 1), moduleDescriptor, trace, + packageFragmentForVisibilityCheck, scopeForFirstPart = null, position = QualifierPosition.IMPORT ) ?: return null - val packageOrClassDescriptor = (resolvedDescriptor as? TypeAliasDescriptor)?.let { it.classDescriptor ?: return null } ?: resolvedDescriptor + val packageOrClassDescriptor = + (resolvedDescriptor as? TypeAliasDescriptor)?.let { it.classDescriptor ?: return null } ?: resolvedDescriptor - return LazyExplicitImportScope(packageOrClassDescriptor, packageFragmentForVisibilityCheck, lastPart.name, aliasName) { - candidates -> + return LazyExplicitImportScope( + packageOrClassDescriptor, + packageFragmentForVisibilityCheck, + lastPart.name, + aliasName + ) { candidates -> if (candidates.isNotEmpty()) { - storeResult(trace, lastPart.expression, candidates, packageFragmentForVisibilityCheck, position = QualifierPosition.IMPORT, isQualifier = false) - } - else { + storeResult( + trace, + lastPart.expression, + candidates, + packageFragmentForVisibilityCheck, + position = QualifierPosition.IMPORT, + isQualifier = false + ) + } else { tryResolveDescriptorsWhichCannotBeImported(trace, moduleDescriptor, packageOrClassDescriptor, lastPart) } } } private fun tryResolveDescriptorsWhichCannotBeImported( - trace: BindingTrace, - moduleDescriptor: ModuleDescriptor, - packageOrClassDescriptor: DeclarationDescriptor, - lastPart: QualifierPart + trace: BindingTrace, + moduleDescriptor: ModuleDescriptor, + packageOrClassDescriptor: DeclarationDescriptor, + lastPart: QualifierPart ) { val descriptors = SmartList() val lastName = lastPart.name @@ -264,7 +292,14 @@ class QualifiedExpressionResolver { else -> throw IllegalStateException("Should be class or package: $packageOrClassDescriptor") } - storeResult(trace, lastPart.expression, descriptors, shouldBeVisibleFrom = null, position = QualifierPosition.IMPORT, isQualifier = false) + storeResult( + trace, + lastPart.expression, + descriptors, + shouldBeVisibleFrom = null, + position = QualifierPosition.IMPORT, + isQualifier = false + ) } private fun KtExpression.asQualifierPartList(doubleColonLHS: Boolean = false): List { @@ -299,9 +334,9 @@ class QualifiedExpressionResolver { } data class QualifierPart( - val name: Name, - val expression: KtSimpleNameExpression, - val typeArguments: KtTypeArgumentList? = null + val name: Name, + val expression: KtSimpleNameExpression, + val typeArguments: KtTypeArgumentList? = null ) { constructor (expression: KtSimpleNameExpression) : this(expression.getReferencedNameAsName(), expression) @@ -310,12 +345,12 @@ class QualifiedExpressionResolver { private fun resolveToPackageOrClass( - path: List, - moduleDescriptor: ModuleDescriptor, - trace: BindingTrace, - shouldBeVisibleFrom: DeclarationDescriptor?, - scopeForFirstPart: LexicalScope?, - position: QualifierPosition + path: List, + moduleDescriptor: ModuleDescriptor, + trace: BindingTrace, + shouldBeVisibleFrom: DeclarationDescriptor?, + scopeForFirstPart: LexicalScope?, + position: QualifierPosition ): DeclarationDescriptor? { val (packageOrClassDescriptor, endIndex) = resolveToPackageOrClassPrefix(path, moduleDescriptor, trace, shouldBeVisibleFrom, scopeForFirstPart, position) @@ -328,13 +363,13 @@ class QualifiedExpressionResolver { } private fun resolveToPackageOrClassPrefix( - path: List, - moduleDescriptor: ModuleDescriptor, - trace: BindingTrace, - shouldBeVisibleFrom: DeclarationDescriptor?, - scopeForFirstPart: LexicalScope?, - position: QualifierPosition, - isValue: ((KtSimpleNameExpression) -> Boolean)? = null + path: List, + moduleDescriptor: ModuleDescriptor, + trace: BindingTrace, + shouldBeVisibleFrom: DeclarationDescriptor?, + scopeForFirstPart: LexicalScope?, + position: QualifierPosition, + isValue: ((KtSimpleNameExpression) -> Boolean)? = null ): Pair { if (path.isEmpty()) { return Pair(moduleDescriptor.getPackage(FqName.ROOT), 0) @@ -368,27 +403,25 @@ class QualifiedExpressionResolver { val qualifierPart = path[qualifierPartIndex] val nextPackageOrClassDescriptor = - when (currentDescriptor) { - is TypeAliasDescriptor -> // TODO type aliases as qualifiers? (would break some assumptions in TypeResolver) - null - is ClassDescriptor -> - currentDescriptor.getContributedClassifier(qualifierPart) - is PackageViewDescriptor -> { - val packageView = - if (qualifierPart.typeArguments == null) { - moduleDescriptor.getPackage(currentDescriptor.fqName.child(qualifierPart.name)) - } - else null - if (packageView != null && !packageView.isEmpty()) { - packageView - } - else { - currentDescriptor.memberScope.getContributedClassifier(qualifierPart.name, qualifierPart.location) - } + when (currentDescriptor) { + is TypeAliasDescriptor -> // TODO type aliases as qualifiers? (would break some assumptions in TypeResolver) + null + is ClassDescriptor -> + currentDescriptor.getContributedClassifier(qualifierPart) + is PackageViewDescriptor -> { + val packageView = + if (qualifierPart.typeArguments == null) { + moduleDescriptor.getPackage(currentDescriptor.fqName.child(qualifierPart.name)) + } else null + if (packageView != null && !packageView.isEmpty()) { + packageView + } else { + currentDescriptor.memberScope.getContributedClassifier(qualifierPart.name, qualifierPart.location) } - else -> - null } + else -> + null + } // If we are in expression, this name can denote a value (not a package or class). if (!(position == QualifierPosition.EXPRESSION && nextPackageOrClassDescriptor == null)) { @@ -406,12 +439,12 @@ class QualifiedExpressionResolver { } fun ClassDescriptor.getContributedClassifier(qualifierPart: QualifierPart) = - unsubstitutedInnerClassesScope.getContributedClassifier(qualifierPart.name, qualifierPart.location) + unsubstitutedInnerClassesScope.getContributedClassifier(qualifierPart.name, qualifierPart.location) fun resolveNameExpressionAsQualifierForDiagnostics( - expression: KtSimpleNameExpression, - receiver: Receiver?, - context: ExpressionTypingContext + expression: KtSimpleNameExpression, + receiver: Receiver?, + context: ExpressionTypingContext ): Qualifier? { val name = expression.getReferencedNameAsName() @@ -419,12 +452,12 @@ class QualifiedExpressionResolver { val qualifierDescriptor = when (receiver) { is PackageQualifier -> { val childPackageFQN = receiver.descriptor.fqName.child(name) - receiver.descriptor.module.getPackage(childPackageFQN).takeUnless { it.isEmpty() } ?: - receiver.descriptor.memberScope.getContributedClassifier(name, location) + receiver.descriptor.module.getPackage(childPackageFQN).takeUnless { it.isEmpty() } + ?: receiver.descriptor.memberScope.getContributedClassifier(name, location) } is ClassQualifier -> receiver.staticScope.getContributedClassifier(name, location) - null -> context.scope.findClassifier(name, location) ?: - context.scope.ownerDescriptor.module.getPackage(FqName.ROOT.child(name)).takeUnless { it.isEmpty() } + null -> context.scope.findClassifier(name, location) + ?: context.scope.ownerDescriptor.module.getPackage(FqName.ROOT.child(name)).takeUnless { it.isEmpty() } is ReceiverValue -> receiver.type.memberScope.memberScopeAsImportingScope().findClassifier(name, location) else -> null } @@ -436,27 +469,31 @@ class QualifiedExpressionResolver { return null } - data class QualifiedExpressionResolveResult(val classOrPackage: DeclarationDescriptor?, - val memberName: Name?) { + data class QualifiedExpressionResolveResult( + val classOrPackage: DeclarationDescriptor?, + val memberName: Name? + ) { companion object { val UNRESOLVED = QualifiedExpressionResolveResult(null, null) } } - fun resolveClassOrPackageInQualifiedExpression(expression: KtQualifiedExpression, - scope: LexicalScope, - context: BindingContext): QualifiedExpressionResolveResult { + fun resolveClassOrPackageInQualifiedExpression( + expression: KtQualifiedExpression, + scope: LexicalScope, + context: BindingContext + ): QualifiedExpressionResolveResult { val qualifiedExpressions = unrollToLeftMostQualifiedExpression(expression) val path = mapToQualifierParts(qualifiedExpressions, 0) val trace = DelegatingBindingTrace(context, "Temp trace for resolving qualified expression") val (result, index) = resolveToPackageOrClassPrefix( - path = path, - moduleDescriptor = scope.ownerDescriptor.module, - trace = trace, - shouldBeVisibleFrom = scope.ownerDescriptor, - scopeForFirstPart = scope, - position = QualifierPosition.EXPRESSION + path = path, + moduleDescriptor = scope.ownerDescriptor.module, + trace = trace, + shouldBeVisibleFrom = scope.ownerDescriptor, + scopeForFirstPart = scope, + position = QualifierPosition.EXPRESSION ) if (result == null) return QualifiedExpressionResolveResult.UNRESOLVED @@ -468,33 +505,35 @@ class QualifiedExpressionResolver { } fun resolveQualifierInExpressionAndUnroll( - expression: KtQualifiedExpression, - context: ExpressionTypingContext, - isValue: (KtSimpleNameExpression) -> Boolean + expression: KtQualifiedExpression, + context: ExpressionTypingContext, + isValue: (KtSimpleNameExpression) -> Boolean ): List { val qualifiedExpressions = unrollToLeftMostQualifiedExpression(expression) val maxPossibleQualifierPrefix = mapToQualifierParts(qualifiedExpressions, 1) val nextIndexAfterPrefix = resolveToPackageOrClassPrefix( - path = maxPossibleQualifierPrefix, - moduleDescriptor = context.scope.ownerDescriptor.module, - trace = context.trace, - shouldBeVisibleFrom = context.scope.ownerDescriptor, - scopeForFirstPart = context.scope, - position = QualifierPosition.EXPRESSION, - isValue = isValue + path = maxPossibleQualifierPrefix, + moduleDescriptor = context.scope.ownerDescriptor.module, + trace = context.trace, + shouldBeVisibleFrom = context.scope.ownerDescriptor, + scopeForFirstPart = context.scope, + position = QualifierPosition.EXPRESSION, + isValue = isValue ).second val nextExpressionIndexAfterQualifier = - if (nextIndexAfterPrefix == 0) 0 else nextIndexAfterPrefix - 1 + if (nextIndexAfterPrefix == 0) 0 else nextIndexAfterPrefix - 1 return qualifiedExpressions - .subList(nextExpressionIndexAfterQualifier, qualifiedExpressions.size) - .map(::CallExpressionElement) + .subList(nextExpressionIndexAfterQualifier, qualifiedExpressions.size) + .map(::CallExpressionElement) } - private fun mapToQualifierParts(qualifiedExpressions: List, - skipLast: Int): List { + private fun mapToQualifierParts( + qualifiedExpressions: List, + skipLast: Int + ): List { if (qualifiedExpressions.isEmpty()) return emptyList() val first = qualifiedExpressions.first() @@ -524,9 +563,9 @@ class QualifiedExpressionResolver { } private fun ModuleDescriptor.quickResolveToPackage( - path: List, - trace: BindingTrace, - position: QualifierPosition + path: List, + trace: BindingTrace, + position: QualifierPosition ): Pair { val possiblePackagePrefixSize = path.indexOfFirst { it.typeArguments != null }.let { if (it == -1) path.size else it + 1 } var fqName = FqName.fromSegments(path.subList(0, possiblePackagePrefixSize).map { it.name.asString() }) @@ -545,26 +584,28 @@ class QualifiedExpressionResolver { } private fun recordPackageViews( - path: List, - packageView: PackageViewDescriptor, - trace: BindingTrace, - position: QualifierPosition + path: List, + packageView: PackageViewDescriptor, + trace: BindingTrace, + position: QualifierPosition ) { path.foldRight(packageView) { (_, expression), currentView -> storeResult(trace, expression, currentView, shouldBeVisibleFrom = null, position = position) currentView.containingDeclaration - ?: error("Containing Declaration must be not null for package with fqName: ${currentView.fqName}, " + - "path: ${path.joinToString()}, packageView fqName: ${packageView.fqName}") + ?: error( + "Containing Declaration must be not null for package with fqName: ${currentView.fqName}, " + + "path: ${path.joinToString()}, packageView fqName: ${packageView.fqName}" + ) } } private fun storeResult( - trace: BindingTrace, - referenceExpression: KtSimpleNameExpression, - descriptors: Collection, - shouldBeVisibleFrom: DeclarationDescriptor?, - position: QualifierPosition, - isQualifier: Boolean = true + trace: BindingTrace, + referenceExpression: KtSimpleNameExpression, + descriptors: Collection, + shouldBeVisibleFrom: DeclarationDescriptor?, + position: QualifierPosition, + isQualifier: Boolean = true ) { if (descriptors.size > 1) { val visibleDescriptors = descriptors.filter { isVisible(it, shouldBeVisibleFrom, position) } @@ -580,19 +621,18 @@ class QualifiedExpressionResolver { storeResult(trace, referenceExpression, visibleDescriptors.single(), null, position, isQualifier) } } - } - else { + } else { storeResult(trace, referenceExpression, descriptors.singleOrNull(), shouldBeVisibleFrom, position, isQualifier) } } private fun storeResult( - trace: BindingTrace, - referenceExpression: KtSimpleNameExpression, - descriptor: DeclarationDescriptor?, - shouldBeVisibleFrom: DeclarationDescriptor?, - position: QualifierPosition, - isQualifier: Boolean = true + trace: BindingTrace, + referenceExpression: KtSimpleNameExpression, + descriptor: DeclarationDescriptor?, + shouldBeVisibleFrom: DeclarationDescriptor?, + position: QualifierPosition, + isQualifier: Boolean = true ): Qualifier? { if (descriptor == null) { trace.report(Errors.UNRESOLVED_REFERENCE.on(referenceExpression, referenceExpression)) @@ -605,12 +645,11 @@ class QualifiedExpressionResolver { if (descriptor is DeclarationDescriptorWithVisibility) { val fromToCheck = - if (shouldBeVisibleFrom is PackageFragmentDescriptor && shouldBeVisibleFrom.source == SourceElement.NO_SOURCE && referenceExpression.containingFile !is DummyHolder) { - PackageFragmentWithCustomSource(shouldBeVisibleFrom, KotlinSourceElement(referenceExpression.containingKtFile)) - } - else { - shouldBeVisibleFrom - } + if (shouldBeVisibleFrom is PackageFragmentDescriptor && shouldBeVisibleFrom.source == SourceElement.NO_SOURCE && referenceExpression.containingFile !is DummyHolder) { + PackageFragmentWithCustomSource(shouldBeVisibleFrom, KotlinSourceElement(referenceExpression.containingKtFile)) + } else { + shouldBeVisibleFrom + } if (!isVisible(descriptor, fromToCheck, position)) { trace.report(Errors.INVISIBLE_REFERENCE.on(referenceExpression, descriptor, descriptor.visibility, descriptor)) } @@ -619,18 +658,22 @@ class QualifiedExpressionResolver { return if (isQualifier) storeQualifier(trace, referenceExpression, descriptor) else null } - private fun storeQualifier(trace: BindingTrace, referenceExpression: KtSimpleNameExpression, descriptor: DeclarationDescriptor): Qualifier? { + private fun storeQualifier( + trace: BindingTrace, + referenceExpression: KtSimpleNameExpression, + descriptor: DeclarationDescriptor + ): Qualifier? { val qualifier = - when (descriptor) { - is PackageViewDescriptor -> PackageQualifier(referenceExpression, descriptor) - is ClassDescriptor -> ClassQualifier(referenceExpression, descriptor) - is TypeParameterDescriptor -> TypeParameterQualifier(referenceExpression, descriptor) - is TypeAliasDescriptor -> { - val classDescriptor = descriptor.classDescriptor ?: return null - TypeAliasQualifier(referenceExpression, descriptor, classDescriptor) - } - else -> return null + when (descriptor) { + is PackageViewDescriptor -> PackageQualifier(referenceExpression, descriptor) + is ClassDescriptor -> ClassQualifier(referenceExpression, descriptor) + is TypeParameterDescriptor -> TypeParameterQualifier(referenceExpression, descriptor) + is TypeAliasDescriptor -> { + val classDescriptor = descriptor.classDescriptor ?: return null + TypeAliasQualifier(referenceExpression, descriptor, classDescriptor) } + else -> return null + } trace.record(BindingContext.QUALIFIER, qualifier.expression, qualifier) @@ -639,9 +682,9 @@ class QualifiedExpressionResolver { } internal fun isVisible( - descriptor: DeclarationDescriptor, - shouldBeVisibleFrom: DeclarationDescriptor?, - position: QualifierPosition + descriptor: DeclarationDescriptor, + shouldBeVisibleFrom: DeclarationDescriptor?, + position: QualifierPosition ): Boolean { if (descriptor !is DeclarationDescriptorWithVisibility || shouldBeVisibleFrom == null) return true @@ -661,6 +704,7 @@ internal enum class QualifierPosition { This purpose of this class is to pass information about source file for current package fragment in order for check visibilities between modules (see ModuleVisibilityHelperImpl.isInFriendModule). */ -private class PackageFragmentWithCustomSource(private val original: PackageFragmentDescriptor, private val source: SourceElement) : PackageFragmentDescriptor by original { +private class PackageFragmentWithCustomSource(private val original: PackageFragmentDescriptor, private val source: SourceElement) : + PackageFragmentDescriptor by original { override fun getSource(): SourceElement = source } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/ShadowedExtensionChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/ShadowedExtensionChecker.kt index 91e2513bf74..d56341f190b 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/ShadowedExtensionChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/ShadowedExtensionChecker.kt @@ -51,7 +51,9 @@ class ShadowedExtensionChecker(val typeSpecificityComparator: TypeSpecificityCom private fun checkShadowedExtensionFunction(declaration: KtDeclaration, extensionFunction: FunctionDescriptor, trace: DiagnosticSink) { val memberScope = extensionFunction.extensionReceiverParameter?.type?.memberScope ?: return - for (memberFunction in memberScope.getContributedFunctions(extensionFunction.name, NoLookupLocation.WHEN_CHECK_DECLARATION_CONFLICTS)) { + val contributedFunctions = + memberScope.getContributedFunctions(extensionFunction.name, NoLookupLocation.WHEN_CHECK_DECLARATION_CONFLICTS) + for (memberFunction in contributedFunctions) { if (memberFunction.isPublic() && isExtensionFunctionShadowedByMemberFunction(extensionFunction, memberFunction)) { trace.report(Errors.EXTENSION_SHADOWED_BY_MEMBER.on(declaration, memberFunction)) return @@ -68,19 +70,27 @@ class ShadowedExtensionChecker(val typeSpecificityComparator: TypeSpecificityCom } } - for (memberProperty in memberScope.getContributedVariables(extensionFunction.name, NoLookupLocation.WHEN_CHECK_DECLARATION_CONFLICTS)) { + val contributedVariables = + memberScope.getContributedVariables(extensionFunction.name, NoLookupLocation.WHEN_CHECK_DECLARATION_CONFLICTS) + for (memberProperty in contributedVariables) { if (!memberProperty.isPublic()) continue val invokeOperator = getInvokeOperatorShadowingExtensionFunction(extensionFunction, memberProperty) if (invokeOperator != null) { - trace.report(Errors.EXTENSION_FUNCTION_SHADOWED_BY_MEMBER_PROPERTY_WITH_INVOKE.on(declaration, memberProperty, invokeOperator)) + trace.report( + Errors.EXTENSION_FUNCTION_SHADOWED_BY_MEMBER_PROPERTY_WITH_INVOKE.on( + declaration, + memberProperty, + invokeOperator + ) + ) return } } } private fun DeclarationDescriptorWithVisibility.isPublic() = - visibility.normalize() == Visibilities.PUBLIC + visibility.normalize() == Visibilities.PUBLIC private fun isExtensionFunctionShadowedByMemberFunction(extension: FunctionDescriptor, member: FunctionDescriptor): Boolean { // Permissive check: @@ -99,26 +109,32 @@ class ShadowedExtensionChecker(val typeSpecificityComparator: TypeSpecificityCom return isSignatureNotLessSpecific(extensionSignature, memberSignature) } - private fun getInvokeOperatorShadowingExtensionFunction(extension: FunctionDescriptor, member: PropertyDescriptor): FunctionDescriptor? = - member.type.memberScope.getContributedFunctions(OperatorNameConventions.INVOKE, NoLookupLocation.WHEN_CHECK_DECLARATION_CONFLICTS) - .firstOrNull { it.isPublic() && it.isOperator && isExtensionFunctionShadowedByMemberFunction(extension, it) } + private fun getInvokeOperatorShadowingExtensionFunction( + extension: FunctionDescriptor, + member: PropertyDescriptor + ): FunctionDescriptor? = + member.type.memberScope.getContributedFunctions(OperatorNameConventions.INVOKE, NoLookupLocation.WHEN_CHECK_DECLARATION_CONFLICTS) + .firstOrNull { it.isPublic() && it.isOperator && isExtensionFunctionShadowedByMemberFunction(extension, it) } - private fun isSignatureNotLessSpecific(extensionSignature: FlatSignature, memberSignature: FlatSignature): Boolean = - ConstraintSystemBuilderImpl.forSpecificity().isSignatureNotLessSpecific( - extensionSignature, - memberSignature, - OverloadabilitySpecificityCallbacks, - typeSpecificityComparator - ) + private fun isSignatureNotLessSpecific( + extensionSignature: FlatSignature, + memberSignature: FlatSignature + ): Boolean = + ConstraintSystemBuilderImpl.forSpecificity().isSignatureNotLessSpecific( + extensionSignature, + memberSignature, + OverloadabilitySpecificityCallbacks, + typeSpecificityComparator + ) private fun checkShadowedExtensionProperty(declaration: KtDeclaration, extensionProperty: PropertyDescriptor, trace: DiagnosticSink) { val memberScope = extensionProperty.extensionReceiverParameter?.type?.memberScope ?: return memberScope.getContributedVariables(extensionProperty.name, NoLookupLocation.WHEN_CHECK_DECLARATION_CONFLICTS) - .firstOrNull { it.isPublic() && !it.isExtension } - ?.let { memberProperty -> - trace.report(Errors.EXTENSION_SHADOWED_BY_MEMBER.on(declaration, memberProperty)) - } + .firstOrNull { it.isPublic() && !it.isExtension } + ?.let { memberProperty -> + trace.report(Errors.EXTENSION_SHADOWED_BY_MEMBER.on(declaration, memberProperty)) + } } } \ No newline at end of file diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/StatementFilter.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/StatementFilter.kt index a1ce24f6fb3..fa1df763e40 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/StatementFilter.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/StatementFilter.kt @@ -25,7 +25,8 @@ open class StatementFilter { get() = null companion object { - @JvmField val NONE = object : StatementFilter() { + @JvmField + val NONE = object : StatementFilter() { override fun toString() = "NONE" } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/TargetPlatform.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/TargetPlatform.kt index 29462efbe02..656434d5632 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/TargetPlatform.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/TargetPlatform.kt @@ -40,10 +40,10 @@ abstract class TargetPlatform(val platformName: String) { abstract val multiTargetPlatform: MultiTargetPlatform object Common : TargetPlatform("Default") { - private val defaultImports = LockBasedStorageManager().createMemoizedFunction> { - includeKotlinComparisons -> - ArrayList().apply { - listOf( + private val defaultImports = + LockBasedStorageManager().createMemoizedFunction> { includeKotlinComparisons -> + ArrayList().apply { + listOf( "kotlin.*", "kotlin.annotation.*", "kotlin.collections.*", @@ -51,28 +51,28 @@ abstract class TargetPlatform(val platformName: String) { "kotlin.sequences.*", "kotlin.text.*", "kotlin.io.*" - ).forEach { add(ImportPath.fromString(it)) } + ).forEach { add(ImportPath.fromString(it)) } - if (includeKotlinComparisons) { - add(ImportPath.fromString("kotlin.comparisons.*")) + if (includeKotlinComparisons) { + add(ImportPath.fromString("kotlin.comparisons.*")) + } } } - } override fun getDefaultImports(includeKotlinComparisons: Boolean): List = defaultImports(includeKotlinComparisons) override val platformConfigurator = - object : PlatformConfigurator( - DynamicTypesSettings(), listOf(), listOf(), listOf(), listOf(), listOf(), - IdentifierChecker.Default, OverloadFilter.Default, PlatformToKotlinClassMap.EMPTY, DelegationFilter.Default, - OverridesBackwardCompatibilityHelper.Default, - DeclarationReturnTypeSanitizer.Default - ) { - override fun configureModuleComponents(container: StorageComponentContainer) { - container.useInstance(SyntheticScopes.Empty) - container.useInstance(TypeSpecificityComparator.NONE) - } + object : PlatformConfigurator( + DynamicTypesSettings(), listOf(), listOf(), listOf(), listOf(), listOf(), + IdentifierChecker.Default, OverloadFilter.Default, PlatformToKotlinClassMap.EMPTY, DelegationFilter.Default, + OverridesBackwardCompatibilityHelper.Default, + DeclarationReturnTypeSanitizer.Default + ) { + override fun configureModuleComponents(container: StorageComponentContainer) { + container.useInstance(SyntheticScopes.Empty) + container.useInstance(TypeSpecificityComparator.NONE) } + } override val multiTargetPlatform: MultiTargetPlatform get() = MultiTargetPlatform.Common @@ -80,52 +80,53 @@ abstract class TargetPlatform(val platformName: String) { } private val DEFAULT_DECLARATION_CHECKERS = listOf( - DataClassDeclarationChecker(), - ConstModifierChecker, - UnderscoreChecker, - InlineParameterChecker, - InfixModifierChecker(), - SinceKotlinAnnotationValueChecker, - RequireKotlinAnnotationValueChecker, - ReifiedTypeParameterAnnotationChecker(), - DynamicReceiverChecker, - DelegationChecker(), - KClassWithIncorrectTypeArgumentChecker, - SuspendOperatorsCheckers + DataClassDeclarationChecker(), + ConstModifierChecker, + UnderscoreChecker, + InlineParameterChecker, + InfixModifierChecker(), + SinceKotlinAnnotationValueChecker, + RequireKotlinAnnotationValueChecker, + ReifiedTypeParameterAnnotationChecker(), + DynamicReceiverChecker, + DelegationChecker(), + KClassWithIncorrectTypeArgumentChecker, + SuspendOperatorsCheckers ) private val DEFAULT_CALL_CHECKERS = listOf( - CapturingInClosureChecker(), InlineCheckerWrapper(), SafeCallChecker(), - DeprecatedCallChecker, CallReturnsArrayOfNothingChecker(), InfixCallChecker(), OperatorCallChecker(), - ConstructorHeaderCallChecker, ProtectedConstructorCallChecker, ApiVersionCallChecker, - CoroutineSuspendCallChecker, BuilderFunctionsCallChecker, DslScopeViolationCallChecker, MissingDependencyClassChecker, - CallableReferenceCompatibilityChecker(), LateinitIntrinsicApplicabilityChecker, - UnderscoreUsageChecker, AssigningNamedArgumentToVarargChecker() + CapturingInClosureChecker(), InlineCheckerWrapper(), SafeCallChecker(), + DeprecatedCallChecker, CallReturnsArrayOfNothingChecker(), InfixCallChecker(), OperatorCallChecker(), + ConstructorHeaderCallChecker, ProtectedConstructorCallChecker, ApiVersionCallChecker, + CoroutineSuspendCallChecker, BuilderFunctionsCallChecker, DslScopeViolationCallChecker, MissingDependencyClassChecker, + CallableReferenceCompatibilityChecker(), LateinitIntrinsicApplicabilityChecker, + UnderscoreUsageChecker, AssigningNamedArgumentToVarargChecker() ) private val DEFAULT_TYPE_CHECKERS = emptyList() private val DEFAULT_CLASSIFIER_USAGE_CHECKERS = listOf( - DeprecatedClassifierUsageChecker(), ApiVersionClassifierUsageChecker, MissingDependencyClassChecker.ClassifierUsage + DeprecatedClassifierUsageChecker(), ApiVersionClassifierUsageChecker, MissingDependencyClassChecker.ClassifierUsage ) abstract class PlatformConfigurator( - private val dynamicTypesSettings: DynamicTypesSettings, - additionalDeclarationCheckers: List, - additionalCallCheckers: List, - additionalTypeCheckers: List, - additionalClassifierUsageCheckers: List, - private val additionalAnnotationCheckers: List, - private val identifierChecker: IdentifierChecker, - private val overloadFilter: OverloadFilter, - private val platformToKotlinClassMap: PlatformToKotlinClassMap, - private val delegationFilter: DelegationFilter, - private val overridesBackwardCompatibilityHelper: OverridesBackwardCompatibilityHelper, - private val declarationReturnTypeSanitizer: DeclarationReturnTypeSanitizer + private val dynamicTypesSettings: DynamicTypesSettings, + additionalDeclarationCheckers: List, + additionalCallCheckers: List, + additionalTypeCheckers: List, + additionalClassifierUsageCheckers: List, + private val additionalAnnotationCheckers: List, + private val identifierChecker: IdentifierChecker, + private val overloadFilter: OverloadFilter, + private val platformToKotlinClassMap: PlatformToKotlinClassMap, + private val delegationFilter: DelegationFilter, + private val overridesBackwardCompatibilityHelper: OverridesBackwardCompatibilityHelper, + private val declarationReturnTypeSanitizer: DeclarationReturnTypeSanitizer ) { private val declarationCheckers: List = DEFAULT_DECLARATION_CHECKERS + additionalDeclarationCheckers private val callCheckers: List = DEFAULT_CALL_CHECKERS + additionalCallCheckers private val typeCheckers: List = DEFAULT_TYPE_CHECKERS + additionalTypeCheckers - private val classifierUsageCheckers: List = DEFAULT_CLASSIFIER_USAGE_CHECKERS + additionalClassifierUsageCheckers + private val classifierUsageCheckers: List = + DEFAULT_CLASSIFIER_USAGE_CHECKERS + additionalClassifierUsageCheckers abstract fun configureModuleComponents(container: StorageComponentContainer) @@ -145,5 +146,5 @@ abstract class PlatformConfigurator( } } -fun createContainer(id: String, platform: TargetPlatform, init: StorageComponentContainer.() -> Unit) - = composeContainer(id, platform.platformConfigurator.platformSpecificContainer, init) +fun createContainer(id: String, platform: TargetPlatform, init: StorageComponentContainer.() -> Unit) = + composeContainer(id, platform.platformConfigurator.platformSpecificContainer, init) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/TypeAliasExpander.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/TypeAliasExpander.kt index 18fe73ca9d7..53e24a674d2 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/TypeAliasExpander.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/TypeAliasExpander.kt @@ -26,24 +26,28 @@ import org.jetbrains.kotlin.types.typeUtil.containsTypeAliasParameters import org.jetbrains.kotlin.types.typeUtil.requiresTypeAliasExpansion class TypeAliasExpander( - private val reportStrategy: TypeAliasExpansionReportStrategy, - private val shouldCheckBounds: Boolean + private val reportStrategy: TypeAliasExpansionReportStrategy, + private val shouldCheckBounds: Boolean ) { fun expand(typeAliasExpansion: TypeAliasExpansion, annotations: Annotations) = - expandRecursively(typeAliasExpansion, annotations, - isNullable = false, recursionDepth = 0, withAbbreviatedType = true) + expandRecursively( + typeAliasExpansion, annotations, + isNullable = false, recursionDepth = 0, withAbbreviatedType = true + ) fun expandWithoutAbbreviation(typeAliasExpansion: TypeAliasExpansion, annotations: Annotations) = - expandRecursively(typeAliasExpansion, annotations, - isNullable = false, recursionDepth = 0, withAbbreviatedType = false) + expandRecursively( + typeAliasExpansion, annotations, + isNullable = false, recursionDepth = 0, withAbbreviatedType = false + ) private fun expandRecursively( - typeAliasExpansion: TypeAliasExpansion, - annotations: Annotations, - isNullable: Boolean, - recursionDepth: Int, - withAbbreviatedType: Boolean + typeAliasExpansion: TypeAliasExpansion, + annotations: Annotations, + isNullable: Boolean, + recursionDepth: Int, + withAbbreviatedType: Boolean ): SimpleType { val underlyingProjection = TypeProjectionImpl(Variance.INVARIANT, typeAliasExpansion.descriptor.underlyingType) val expandedProjection = expandTypeProjection(underlyingProjection, typeAliasExpansion, null, recursionDepth) @@ -56,7 +60,8 @@ class TypeAliasExpander( } checkRepeatedAnnotations(expandedType.annotations, annotations) - val expandedTypeWithExtraAnnotations = expandedType.combineAnnotations(annotations).let { TypeUtils.makeNullableIfNeeded(it, isNullable) } + val expandedTypeWithExtraAnnotations = + expandedType.combineAnnotations(annotations).let { TypeUtils.makeNullableIfNeeded(it, isNullable) } return if (withAbbreviatedType) expandedTypeWithExtraAnnotations.withAbbreviation(typeAliasExpansion.createAbbreviation(annotations, isNullable)) @@ -65,19 +70,19 @@ class TypeAliasExpander( } private fun TypeAliasExpansion.createAbbreviation(annotations: Annotations, isNullable: Boolean) = - KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope( - annotations, - descriptor.typeConstructor, - arguments, - isNullable, - MemberScope.Empty - ) + KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope( + annotations, + descriptor.typeConstructor, + arguments, + isNullable, + MemberScope.Empty + ) private fun expandTypeProjection( - underlyingProjection: TypeProjection, - typeAliasExpansion: TypeAliasExpansion, - typeParameterDescriptor: TypeParameterDescriptor?, - recursionDepth: Int + underlyingProjection: TypeProjection, + typeAliasExpansion: TypeAliasExpansion, + typeParameterDescriptor: TypeParameterDescriptor?, + recursionDepth: Int ): TypeProjection { // TODO refactor TypeSubstitutor to introduce custom diagnostics assertRecursionDepth(recursionDepth, typeAliasExpansion.descriptor) @@ -85,8 +90,12 @@ class TypeAliasExpander( if (underlyingProjection.isStarProjection) return TypeUtils.makeStarProjection(typeParameterDescriptor!!) val underlyingType = underlyingProjection.type - val argument = typeAliasExpansion.getReplacement(underlyingType.constructor) ?: - return expandNonArgumentTypeProjection(underlyingProjection, typeAliasExpansion, recursionDepth) + val argument = typeAliasExpansion.getReplacement(underlyingType.constructor) + ?: return expandNonArgumentTypeProjection( + underlyingProjection, + typeAliasExpansion, + recursionDepth + ) if (argument.isStarProjection) return TypeUtils.makeStarProjection(typeParameterDescriptor!!) @@ -97,15 +106,15 @@ class TypeAliasExpander( val underlyingVariance = underlyingProjection.projectionKind val substitutionVariance = - when { - underlyingVariance == argumentVariance -> argumentVariance - underlyingVariance == Variance.INVARIANT -> argumentVariance - argumentVariance == Variance.INVARIANT -> underlyingVariance - else -> { - reportStrategy.conflictingProjection(typeAliasExpansion.descriptor, typeParameterDescriptor, argumentType) - argumentVariance - } + when { + underlyingVariance == argumentVariance -> argumentVariance + underlyingVariance == Variance.INVARIANT -> argumentVariance + argumentVariance == Variance.INVARIANT -> underlyingVariance + else -> { + reportStrategy.conflictingProjection(typeAliasExpansion.descriptor, typeParameterDescriptor, argumentType) + argumentVariance } + } val parameterVariance = typeParameterDescriptor?.variance ?: Variance.INVARIANT @@ -123,19 +132,19 @@ class TypeAliasExpander( checkRepeatedAnnotations(underlyingType.annotations, argumentType.annotations) val substitutedType = - if (argumentType is DynamicType) - argumentType.combineAnnotations(underlyingType.annotations) - else - argumentType.asSimpleType().combineNullabilityAndAnnotations(underlyingType) + if (argumentType is DynamicType) + argumentType.combineAnnotations(underlyingType.annotations) + else + argumentType.asSimpleType().combineNullabilityAndAnnotations(underlyingType) return TypeProjectionImpl(resultingVariance, substitutedType) } private fun DynamicType.combineAnnotations(newAnnotations: Annotations): DynamicType = - replaceAnnotations(createCombinedAnnotations(newAnnotations)) + replaceAnnotations(createCombinedAnnotations(newAnnotations)) private fun SimpleType.combineAnnotations(newAnnotations: Annotations): SimpleType = - if (isError) this else replace(newAnnotations = createCombinedAnnotations(newAnnotations)) + if (isError) this else replace(newAnnotations = createCombinedAnnotations(newAnnotations)) private fun KotlinType.createCombinedAnnotations(newAnnotations: Annotations): Annotations { if (isError) return annotations @@ -154,15 +163,15 @@ class TypeAliasExpander( } private fun SimpleType.combineNullability(fromType: KotlinType) = - TypeUtils.makeNullableIfNeeded(this, fromType.isMarkedNullable) + TypeUtils.makeNullableIfNeeded(this, fromType.isMarkedNullable) private fun SimpleType.combineNullabilityAndAnnotations(fromType: KotlinType) = - combineNullability(fromType).combineAnnotations(fromType.annotations) + combineNullability(fromType).combineAnnotations(fromType.annotations) private fun expandNonArgumentTypeProjection( - originalProjection: TypeProjection, - typeAliasExpansion: TypeAliasExpansion, - recursionDepth: Int + originalProjection: TypeProjection, + typeAliasExpansion: TypeAliasExpansion, + recursionDepth: Int ): TypeProjection { val originalType = originalProjection.type.unwrap() @@ -186,7 +195,10 @@ class TypeAliasExpander( is TypeAliasDescriptor -> { if (typeAliasExpansion.isRecursion(typeDescriptor)) { reportStrategy.recursiveTypeAlias(typeDescriptor) - return TypeProjectionImpl(Variance.INVARIANT, ErrorUtils.createErrorType("Recursive type alias: ${typeDescriptor.name}")) + return TypeProjectionImpl( + Variance.INVARIANT, + ErrorUtils.createErrorType("Recursive type alias: ${typeDescriptor.name}") + ) } val expandedArguments = type.arguments.mapIndexed { i, typeAliasArgument -> @@ -195,23 +207,29 @@ class TypeAliasExpander( val nestedExpansion = TypeAliasExpansion.create(typeAliasExpansion, typeDescriptor, expandedArguments) - val nestedExpandedType = expandRecursively(nestedExpansion, type.annotations, - isNullable = type.isMarkedNullable, - recursionDepth = recursionDepth + 1, - withAbbreviatedType = false) + val nestedExpandedType = expandRecursively( + nestedExpansion, type.annotations, + isNullable = type.isMarkedNullable, + recursionDepth = recursionDepth + 1, + withAbbreviatedType = false + ) // 'dynamic' type can't be abbreviated - will be reported separately - val typeWithAbbreviation = if (nestedExpandedType.isDynamic()) nestedExpandedType else nestedExpandedType.withAbbreviation(type) + val typeWithAbbreviation = + if (nestedExpandedType.isDynamic()) nestedExpandedType else nestedExpandedType.withAbbreviation(type) TypeProjectionImpl(originalProjection.projectionKind, typeWithAbbreviation) } else -> { val substitutedArguments = type.arguments.mapIndexed { i, originalArgument -> val projection = expandTypeProjection( - originalArgument, typeAliasExpansion, typeConstructor.parameters[i], recursionDepth + 1) + originalArgument, typeAliasExpansion, typeConstructor.parameters[i], recursionDepth + 1 + ) if (projection.isStarProjection) projection - else TypeProjectionImpl(projection.projectionKind, - TypeUtils.makeNullableIfNeeded(projection.type, originalArgument.type.isMarkedNullable)) + else TypeProjectionImpl( + projection.projectionKind, + TypeUtils.makeNullableIfNeeded(projection.type, originalArgument.type.isMarkedNullable) + ) } val substitutedType = type.replace(newArguments = substitutedArguments) @@ -231,7 +249,13 @@ class TypeAliasExpander( val unsubstitutedArgument = unsubstitutedType.arguments[i] val typeParameter = unsubstitutedType.constructor.parameters[i] if (shouldCheckBounds) { - DescriptorResolver.checkBoundsInTypeAlias(reportStrategy, unsubstitutedArgument.type, substitutedArgument.type, typeParameter, typeSubstitutor) + DescriptorResolver.checkBoundsInTypeAlias( + reportStrategy, + unsubstitutedArgument.type, + substitutedArgument.type, + typeParameter, + typeSubstitutor + ) } } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/TypeAliasExpansion.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/TypeAliasExpansion.kt index f97e893344a..f67a1ab2fbe 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/TypeAliasExpansion.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/TypeAliasExpansion.kt @@ -22,10 +22,10 @@ import org.jetbrains.kotlin.types.TypeConstructor import org.jetbrains.kotlin.types.TypeProjection class TypeAliasExpansion private constructor( - val parent: TypeAliasExpansion?, - val descriptor: TypeAliasDescriptor, - val arguments: List, - val mapping: Map + val parent: TypeAliasExpansion?, + val descriptor: TypeAliasDescriptor, + val arguments: List, + val mapping: Map ) { fun getReplacement(constructor: TypeConstructor): TypeProjection? { val descriptor = constructor.declarationDescriptor @@ -36,13 +36,13 @@ class TypeAliasExpansion private constructor( } fun isRecursion(descriptor: TypeAliasDescriptor): Boolean = - this.descriptor == descriptor || (parent?.isRecursion(descriptor) ?: false) + this.descriptor == descriptor || (parent?.isRecursion(descriptor) ?: false) companion object { fun create( - parent: TypeAliasExpansion?, - typeAliasDescriptor: TypeAliasDescriptor, - arguments: List + parent: TypeAliasExpansion?, + typeAliasDescriptor: TypeAliasDescriptor, + arguments: List ): TypeAliasExpansion { val typeParameters = typeAliasDescriptor.typeConstructor.parameters.map { it.original } val mappedArguments = typeParameters.zip(arguments).toMap() @@ -50,6 +50,6 @@ class TypeAliasExpansion private constructor( } fun createWithFormalArguments(typeAliasDescriptor: TypeAliasDescriptor) = - create(null, typeAliasDescriptor, emptyList()) + create(null, typeAliasDescriptor, emptyList()) } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/TypeAliasExpansionReportStrategy.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/TypeAliasExpansionReportStrategy.kt index e04c0f3e2d4..515e7fa4e6c 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/TypeAliasExpansionReportStrategy.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/TypeAliasExpansionReportStrategy.kt @@ -25,14 +25,33 @@ interface TypeAliasExpansionReportStrategy { fun wrongNumberOfTypeArguments(typeAlias: TypeAliasDescriptor, numberOfParameters: Int) fun conflictingProjection(typeAlias: TypeAliasDescriptor, typeParameter: TypeParameterDescriptor?, substitutedArgument: KotlinType) fun recursiveTypeAlias(typeAlias: TypeAliasDescriptor) - fun boundsViolationInSubstitution(bound: KotlinType, unsubstitutedArgument: KotlinType, argument: KotlinType, typeParameter: TypeParameterDescriptor) + fun boundsViolationInSubstitution( + bound: KotlinType, + unsubstitutedArgument: KotlinType, + argument: KotlinType, + typeParameter: TypeParameterDescriptor + ) + fun repeatedAnnotation(annotation: AnnotationDescriptor) object DO_NOTHING : TypeAliasExpansionReportStrategy { override fun wrongNumberOfTypeArguments(typeAlias: TypeAliasDescriptor, numberOfParameters: Int) {} - override fun conflictingProjection(typeAlias: TypeAliasDescriptor, typeParameter: TypeParameterDescriptor?, substitutedArgument: KotlinType) {} + override fun conflictingProjection( + typeAlias: TypeAliasDescriptor, + typeParameter: TypeParameterDescriptor?, + substitutedArgument: KotlinType + ) { + } + override fun recursiveTypeAlias(typeAlias: TypeAliasDescriptor) {} - override fun boundsViolationInSubstitution(bound: KotlinType, unsubstitutedArgument: KotlinType, argument: KotlinType, typeParameter: TypeParameterDescriptor) {} + override fun boundsViolationInSubstitution( + bound: KotlinType, + unsubstitutedArgument: KotlinType, + argument: KotlinType, + typeParameter: TypeParameterDescriptor + ) { + } + override fun repeatedAnnotation(annotation: AnnotationDescriptor) {} } } \ No newline at end of file diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/TypeResolver.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/TypeResolver.kt index 7dc39e05b12..1caf74be07d 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/TypeResolver.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/TypeResolver.kt @@ -59,15 +59,15 @@ import org.jetbrains.kotlin.types.typeUtil.isArrayOfNothing import org.jetbrains.kotlin.utils.addToStdlib.safeAs class TypeResolver( - private val annotationResolver: AnnotationResolver, - private val qualifiedExpressionResolver: QualifiedExpressionResolver, - private val moduleDescriptor: ModuleDescriptor, - private val typeTransformerForTests: TypeTransformerForTests, - private val dynamicTypesSettings: DynamicTypesSettings, - private val dynamicCallableDescriptors: DynamicCallableDescriptors, - private val identifierChecker: IdentifierChecker, - private val platformToKotlinClassMap: PlatformToKotlinClassMap, - private val languageVersionSettings: LanguageVersionSettings + private val annotationResolver: AnnotationResolver, + private val qualifiedExpressionResolver: QualifiedExpressionResolver, + private val moduleDescriptor: ModuleDescriptor, + private val typeTransformerForTests: TypeTransformerForTests, + private val dynamicTypesSettings: DynamicTypesSettings, + private val dynamicCallableDescriptors: DynamicCallableDescriptors, + private val identifierChecker: IdentifierChecker, + private val platformToKotlinClassMap: PlatformToKotlinClassMap, + private val languageVersionSettings: LanguageVersionSettings ) { open class TypeTransformerForTests { open fun transformType(kotlinType: KotlinType): KotlinType? = null @@ -75,12 +75,17 @@ class TypeResolver( fun resolveType(scope: LexicalScope, typeReference: KtTypeReference, trace: BindingTrace, checkBounds: Boolean): KotlinType { // bare types are not allowed - return resolveType(TypeResolutionContext(scope, trace, checkBounds, false, typeReference.suppressDiagnosticsInDebugMode(), false), typeReference) + return resolveType( + TypeResolutionContext(scope, trace, checkBounds, false, typeReference.suppressDiagnosticsInDebugMode(), false), + typeReference + ) } fun resolveAbbreviatedType(scope: LexicalScope, typeReference: KtTypeReference, trace: BindingTrace): SimpleType { - val resolvedType = resolveType(TypeResolutionContext(scope, trace, true, false, typeReference.suppressDiagnosticsInDebugMode(), true), - typeReference).unwrap() + val resolvedType = resolveType( + TypeResolutionContext(scope, trace, true, false, typeReference.suppressDiagnosticsInDebugMode(), true), + typeReference + ).unwrap() return when (resolvedType) { is DynamicType -> { trace.report(Errors.TYPEALIAS_SHOULD_EXPAND_TO_CLASS.on(typeReference, resolvedType)) @@ -128,7 +133,7 @@ class TypeResolver( } internal fun KtElementImplStub<*>.getAllModifierLists(): Array = - getStubOrPsiChildren(KtStubElementTypes.MODIFIER_LIST, KtStubElementTypes.MODIFIER_LIST.arrayFactory) + getStubOrPsiChildren(KtStubElementTypes.MODIFIER_LIST, KtStubElementTypes.MODIFIER_LIST.arrayFactory) private fun resolveTypeAnnotations(c: TypeResolutionContext, modifierListsOwner: KtElementImplStub<*>): Annotations { val modifierLists = modifierListsOwner.getAllModifierLists() @@ -168,8 +173,7 @@ class TypeResolver( if (type.isFlexible()) { forceResolveTypeContents(type.asFlexibleType().lowerBound) forceResolveTypeContents(type.asFlexibleType().upperBound) - } - else { + } else { type.constructor // force read type constructor for (projection in type.arguments) { if (!projection.isStarProjection) { @@ -179,15 +183,19 @@ class TypeResolver( } } - private fun resolveTypeElement(c: TypeResolutionContext, annotations: Annotations, outerModifierList: KtModifierList?, typeElement: KtTypeElement?): PossiblyBareType { + private fun resolveTypeElement( + c: TypeResolutionContext, + annotations: Annotations, + outerModifierList: KtModifierList?, + typeElement: KtTypeElement? + ): PossiblyBareType { var result: PossiblyBareType? = null val hasSuspendModifier = outerModifierList?.hasModifier(KtTokens.SUSPEND_KEYWORD) ?: false val suspendModifier = outerModifierList?.getModifier(KtTokens.SUSPEND_KEYWORD) if (hasSuspendModifier && !typeElement.canHaveFunctionTypeModifiers()) { c.trace.report(Errors.WRONG_MODIFIER_TARGET.on(suspendModifier!!, KtTokens.SUSPEND_KEYWORD, "non-functional type")) - } - else if (hasSuspendModifier) { + } else if (hasSuspendModifier) { checkCoroutinesFeature(languageVersionSettings, c.trace, suspendModifier!!) } @@ -198,7 +206,7 @@ class TypeResolver( if (classifier == null) { val arguments = resolveTypeProjections( - c, ErrorUtils.createErrorType("No type").constructor, qualifierResolutionResult.allProjections + c, ErrorUtils.createErrorType("No type").constructor, qualifierResolutionResult.allProjections ) result = type(ErrorUtils.createUnresolvedType(type.getDebugText(), arguments)) return @@ -237,15 +245,17 @@ class TypeResolver( val returnTypeRef = type.returnTypeReference val returnType = if (returnTypeRef != null) resolveType(c.noBareTypes(), returnTypeRef) - else moduleDescriptor.builtIns.unitType + else moduleDescriptor.builtIns.unitType - result = type(createFunctionType( + result = type( + createFunctionType( moduleDescriptor.builtIns, annotations, receiverType, parameterDescriptors.map { it.type }, parameterDescriptors.map { it.name }, returnType, suspendFunction = hasSuspendModifier - )) + ) + ) } private fun checkParametersOfFunctionType(parameterDescriptors: List) { @@ -261,11 +271,11 @@ class TypeResolver( private fun resolveParametersOfFunctionType(parameters: List): List { class ParameterOfFunctionTypeDescriptor( - containingDeclaration: DeclarationDescriptor, - annotations: Annotations, - name: Name, - type: KotlinType, - source: SourceElement + containingDeclaration: DeclarationDescriptor, + annotations: Annotations, + name: Name, + type: KotlinType, + source: SourceElement ) : VariableDescriptorImpl(containingDeclaration, annotations, name, type, source) { override fun getVisibility() = Visibilities.LOCAL @@ -291,11 +301,11 @@ class TypeResolver( return parameters.map { parameter -> val parameterType = resolveType(c.noBareTypes(), parameter.typeReference!!) val descriptor = ParameterOfFunctionTypeDescriptor( - c.scope.ownerDescriptor, - annotationResolver.resolveAnnotationsWithoutArguments(c.scope, parameter.modifierList, c.trace), - parameter.nameAsSafeName, - parameterType, - parameter.toSourceElement() + c.scope.ownerDescriptor, + annotationResolver.resolveAnnotationsWithoutArguments(c.scope, parameter.modifierList, c.trace), + parameter.nameAsSafeName, + parameterType, + parameter.toSourceElement() ) c.trace.record(BindingContext.VALUE_PARAMETER, parameter, descriptor) descriptor @@ -331,9 +341,10 @@ class TypeResolver( val modifierList = param.modifierList if (modifierList != null) { KtTokens.MODIFIER_KEYWORDS_ARRAY - .mapNotNull { modifierList.getModifier(it) } - .forEach { c.trace.report(Errors.UNSUPPORTED.on(it, "modifier on parameter in function type")) - } + .mapNotNull { modifierList.getModifier(it) } + .forEach { + c.trace.report(Errors.UNSUPPORTED.on(it, "modifier on parameter in function type")) + } } param.valOrVarKeyword?.let { @@ -346,13 +357,13 @@ class TypeResolver( } private fun KtTypeElement?.canHaveFunctionTypeModifiers(): Boolean = - this is KtFunctionType + this is KtFunctionType private fun resolveTypeForTypeParameter( - c: TypeResolutionContext, annotations: Annotations, - typeParameter: TypeParameterDescriptor, - referenceExpression: KtSimpleNameExpression, - typeArgumentList: KtTypeArgumentList? + c: TypeResolutionContext, annotations: Annotations, + typeParameter: TypeParameterDescriptor, + referenceExpression: KtSimpleNameExpression, + typeArgumentList: KtTypeArgumentList? ): KotlinType { val scopeForTypeParameter = getScopeForTypeParameter(c, typeParameter) @@ -369,11 +380,13 @@ class TypeResolver( return if (scopeForTypeParameter is ErrorUtils.ErrorScope) ErrorUtils.createErrorType("?") else - KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope(annotations, - typeParameter.typeConstructor, - listOf(), - false, - scopeForTypeParameter) + KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope( + annotations, + typeParameter.typeConstructor, + listOf(), + false, + scopeForTypeParameter + ) } private fun getScopeForTypeParameter(c: TypeResolutionContext, typeParameterDescriptor: TypeParameterDescriptor): MemberScope { @@ -386,11 +399,11 @@ class TypeResolver( } fun resolveTypeForClassifier( - c: TypeResolutionContext, - descriptor: ClassifierDescriptor, - qualifierResolutionResult: QualifiedExpressionResolver.TypeQualifierResolutionResult, - element: KtElement, - annotations: Annotations + c: TypeResolutionContext, + descriptor: ClassifierDescriptor, + qualifierResolutionResult: QualifiedExpressionResolver.TypeQualifierResolutionResult, + element: KtElement, + annotations: Annotations ): PossiblyBareType { val qualifierParts = qualifierResolutionResult.qualifierParts @@ -398,7 +411,7 @@ class TypeResolver( is TypeParameterDescriptor -> { assert(qualifierParts.size == 1) { "Type parameter can be resolved only by it's short name, but '${element.text}' is contradiction " + - "with ${qualifierParts.size} qualifier parts" + "with ${qualifierParts.size} qualifier parts" } val qualifierPart = qualifierParts.single() @@ -411,9 +424,9 @@ class TypeResolver( } private fun resolveTypeForClass( - c: TypeResolutionContext, annotations: Annotations, - classDescriptor: ClassDescriptor, element: KtElement, - qualifierResolutionResult: QualifiedExpressionResolver.TypeQualifierResolutionResult + c: TypeResolutionContext, annotations: Annotations, + classDescriptor: ClassDescriptor, element: KtElement, + qualifierResolutionResult: QualifiedExpressionResolver.TypeQualifierResolutionResult ): PossiblyBareType { val typeConstructor = classDescriptor.typeConstructor @@ -430,11 +443,11 @@ class TypeResolver( val (collectedArgumentAsTypeProjections, argumentsForOuterClass) = collectArgumentsForClassifierTypeConstructor(c, classDescriptor, qualifierResolutionResult.qualifierParts) - ?: return createErrorTypeForTypeConstructor(c, projectionFromAllQualifierParts, typeConstructor) + ?: return createErrorTypeForTypeConstructor(c, projectionFromAllQualifierParts, typeConstructor) assert(collectedArgumentAsTypeProjections.size <= parameters.size) { "Collected arguments count should be not greater then parameters count," + - " but ${collectedArgumentAsTypeProjections.size} instead of ${parameters.size} found in ${element.text}" + " but ${collectedArgumentAsTypeProjections.size} instead of ${parameters.size} found in ${element.text}" } val argumentsFromUserType = resolveTypeProjections(c, typeConstructor, collectedArgumentAsTypeProjections) @@ -442,7 +455,7 @@ class TypeResolver( assert(arguments.size == parameters.size) { "Collected arguments count should be equal to parameters count," + - " but ${collectedArgumentAsTypeProjections.size} instead of ${parameters.size} found in ${element.text}" + " but ${collectedArgumentAsTypeProjections.size} instead of ${parameters.size} found in ${element.text}" } val resultingType = KotlinTypeFactory.simpleNotNullType(annotations, classDescriptor, arguments) @@ -473,12 +486,12 @@ class TypeResolver( } private fun buildFinalArgumentList( - argumentsFromUserType: List, - argumentsForOuterClass: List?, - parameters: List + argumentsFromUserType: List, + argumentsForOuterClass: List?, + parameters: List ): List { return argumentsFromUserType + - (argumentsForOuterClass ?: appendDefaultArgumentsForLocalClassifier(argumentsFromUserType.size, parameters)) + (argumentsForOuterClass ?: appendDefaultArgumentsForLocalClassifier(argumentsFromUserType.size, parameters)) } private fun shouldCheckBounds(c: TypeResolutionContext, inType: KotlinType): Boolean { @@ -490,11 +503,11 @@ class TypeResolver( } private fun resolveTypeForTypeAlias( - c: TypeResolutionContext, - annotations: Annotations, - descriptor: TypeAliasDescriptor, - type: KtElement, - qualifierResolutionResult: QualifiedExpressionResolver.TypeQualifierResolutionResult + c: TypeResolutionContext, + annotations: Annotations, + descriptor: TypeAliasDescriptor, + type: KtElement, + qualifierResolutionResult: QualifiedExpressionResolver.TypeQualifierResolutionResult ): PossiblyBareType { val typeConstructor = descriptor.typeConstructor val projectionFromAllQualifierParts = qualifierResolutionResult.allProjections @@ -517,22 +530,22 @@ class TypeResolver( } val typeAliasQualifierPart = - qualifierResolutionResult.qualifierParts.lastOrNull() - ?: return createErrorTypeForTypeConstructor(c, projectionFromAllQualifierParts, typeConstructor) + qualifierResolutionResult.qualifierParts.lastOrNull() + ?: return createErrorTypeForTypeConstructor(c, projectionFromAllQualifierParts, typeConstructor) val (argumentElementsFromUserType, argumentsForOuterClass) = collectArgumentsForClassifierTypeConstructor(c, descriptor, qualifierResolutionResult.qualifierParts) - ?: return createErrorTypeForTypeConstructor(c, projectionFromAllQualifierParts, typeConstructor) + ?: return createErrorTypeForTypeConstructor(c, projectionFromAllQualifierParts, typeConstructor) val argumentsFromUserType = resolveTypeProjections(c, typeConstructor, argumentElementsFromUserType) val arguments = buildFinalArgumentList(argumentsFromUserType, argumentsForOuterClass, parameters) val reportStrategy = TracingTypeAliasExpansionReportStrategy( - c.trace, - type, typeAliasQualifierPart.typeArguments ?: typeAliasQualifierPart.expression, - descriptor, descriptor.declaredTypeParameters, - argumentElementsFromUserType // TODO arguments from inner scope + c.trace, + type, typeAliasQualifierPart.typeArguments ?: typeAliasQualifierPart.expression, + descriptor, descriptor.declaredTypeParameters, + argumentElementsFromUserType // TODO arguments from inner scope ) if (parameters.size != arguments.size) { @@ -543,8 +556,7 @@ class TypeResolver( return if (c.abbreviated) { val abbreviatedType = KotlinTypeFactory.simpleType(annotations, descriptor.typeConstructor, arguments, false) type(abbreviatedType) - } - else { + } else { val typeAliasExpansion = TypeAliasExpansion.create(null, descriptor, arguments) val expandedType = TypeAliasExpander(reportStrategy, c.checkBounds).expand(typeAliasExpansion, annotations) type(expandedType) @@ -590,12 +602,12 @@ class TypeResolver( } private class TracingTypeAliasExpansionReportStrategy( - val trace: BindingTrace, - val type: KtElement?, - val typeArgumentsOrTypeName: KtElement?, - val typeAliasDescriptor: TypeAliasDescriptor, - typeParameters: List, - typeArguments: List + val trace: BindingTrace, + val type: KtElement?, + val typeArgumentsOrTypeName: KtElement?, + val typeAliasDescriptor: TypeAliasDescriptor, + typeParameters: List, + typeArguments: List ) : TypeAliasExpansionReportStrategy { private val mappedArguments = typeParameters.zip(typeArguments).toMap() @@ -606,12 +618,15 @@ class TypeResolver( } } - override fun conflictingProjection(typeAlias: TypeAliasDescriptor, typeParameter: TypeParameterDescriptor?, substitutedArgument: KotlinType) { + override fun conflictingProjection( + typeAlias: TypeAliasDescriptor, + typeParameter: TypeParameterDescriptor?, + substitutedArgument: KotlinType + ) { val argumentElement = typeParameter?.let { mappedArguments[it] } if (argumentElement != null) { trace.report(CONFLICTING_PROJECTION.on(argumentElement, typeParameter)) - } - else if (type != null) { + } else if (type != null) { trace.report(CONFLICTING_PROJECTION_IN_TYPEALIAS_EXPANSION.on(type, typeAliasDescriptor.underlyingType)) } } @@ -622,14 +637,18 @@ class TypeResolver( } } - override fun boundsViolationInSubstitution(bound: KotlinType, unsubstitutedArgument: KotlinType, argument: KotlinType, typeParameter: TypeParameterDescriptor) { + override fun boundsViolationInSubstitution( + bound: KotlinType, + unsubstitutedArgument: KotlinType, + argument: KotlinType, + typeParameter: TypeParameterDescriptor + ) { val descriptorForUnsubstitutedArgument = unsubstitutedArgument.constructor.declarationDescriptor val argumentElement = mappedArguments[descriptorForUnsubstitutedArgument] val argumentTypeReferenceElement = argumentElement?.typeReference if (argumentTypeReferenceElement != null) { trace.report(UPPER_BOUND_VIOLATED.on(argumentTypeReferenceElement, bound, argument)) - } - else if (type != null) { + } else if (type != null) { trace.report(UPPER_BOUND_VIOLATED_IN_TYPEALIAS_EXPANSION.on(type, bound, argument, typeParameter)) } } @@ -641,14 +660,16 @@ class TypeResolver( } private fun createErrorTypeForTypeConstructor( - c: TypeResolutionContext, - arguments: List, - typeConstructor: TypeConstructor + c: TypeResolutionContext, + arguments: List, + typeConstructor: TypeConstructor ): PossiblyBareType = - type(ErrorUtils.createErrorTypeWithArguments( - typeConstructor.declarationDescriptor?.name?.asString() ?: typeConstructor.toString(), - resolveTypeProjectionsWithErrorConstructor(c, arguments) - )) + type( + ErrorUtils.createErrorTypeWithArguments( + typeConstructor.declarationDescriptor?.name?.asString() ?: typeConstructor.toString(), + resolveTypeProjectionsWithErrorConstructor(c, arguments) + ) + ) // Returns true in case when at least one argument for this class could be specified // It could be always equal to 'typeConstructor.parameters.isNotEmpty()' unless local classes could captured type parameters @@ -675,9 +696,9 @@ class TypeResolver( * If second component is null then rest of the arguments should be appended using default types of relevant parameters */ private fun collectArgumentsForClassifierTypeConstructor( - c: TypeResolutionContext, - classifierDescriptor: ClassifierDescriptorWithTypeParameters, - qualifierParts: List + c: TypeResolutionContext, + classifierDescriptor: ClassifierDescriptorWithTypeParameters, + qualifierParts: List ): Pair, List?>? { val classifierDescriptorChain = classifierDescriptor.classifierDescriptorsFromInnerToOuter() val reversedQualifierParts = qualifierParts.asReversed() @@ -700,10 +721,10 @@ class TypeResolver( if (currentArguments.size != currentParameters.size) { c.trace.report( - WRONG_NUMBER_OF_TYPE_ARGUMENTS.on( - qualifierPart.typeArguments ?: qualifierPart.expression, - currentParameters.size, classifierDescriptorChain[index] - ) + WRONG_NUMBER_OF_TYPE_ARGUMENTS.on( + qualifierPart.typeArguments ?: qualifierPart.expression, + currentParameters.size, classifierDescriptorChain[index] + ) ) return null } @@ -714,9 +735,10 @@ class TypeResolver( } val nonClassQualifierParts = - reversedQualifierParts.subList( - Math.min(classifierChainLastIndex + 1, reversedQualifierParts.size), - reversedQualifierParts.size) + reversedQualifierParts.subList( + Math.min(classifierChainLastIndex + 1, reversedQualifierParts.size), + reversedQualifierParts.size + ) for ((_, _, typeArguments) in nonClassQualifierParts) { if (typeArguments != null) { @@ -728,33 +750,32 @@ class TypeResolver( val parameters = classifierDescriptor.typeConstructor.parameters if (result.size < parameters.size) { val nextParameterOwner = - parameters[result.size].original.containingDeclaration as? ClassDescriptor - // If next parameter is captured from the enclosing function, default arguments must be used - // (see appendDefaultArgumentsForLocalClassifier) - ?: return Pair(result, null) + parameters[result.size].original.containingDeclaration as? ClassDescriptor + // If next parameter is captured from the enclosing function, default arguments must be used + // (see appendDefaultArgumentsForLocalClassifier) + ?: return Pair(result, null) val restArguments = c.scope.findImplicitOuterClassArguments(nextParameterOwner) val restParameters = parameters.subList(result.size, parameters.size) val typeArgumentsCanBeSpecifiedCount = - classifierDescriptor.classifierDescriptorsFromInnerToOuter().sumBy { it.declaredTypeParameters.size } + classifierDescriptor.classifierDescriptorsFromInnerToOuter().sumBy { it.declaredTypeParameters.size } if (restArguments == null && typeArgumentsCanBeSpecifiedCount > result.size) { c.trace.report( - OUTER_CLASS_ARGUMENTS_REQUIRED.on(qualifierParts.first().expression, nextParameterOwner)) + OUTER_CLASS_ARGUMENTS_REQUIRED.on(qualifierParts.first().expression, nextParameterOwner) + ) return null - } - else if (restArguments == null) { + } else if (restArguments == null) { assert(typeArgumentsCanBeSpecifiedCount == result.size) { "Number of type arguments that can be specified ($typeArgumentsCanBeSpecifiedCount) " + - "should be equal to actual arguments number ${result.size}, (classifier: $classifierDescriptor)" + "should be equal to actual arguments number ${result.size}, (classifier: $classifierDescriptor)" } return Pair(result, null) - } - else { + } else { assert(restParameters.size == restArguments.size) { "Number of type of restParameters should be equal to ${restArguments.size}, " + - "but ${restArguments.size} were found for $classifierDescriptor/$nextParameterOwner" + "but ${restArguments.size} were found for $classifierDescriptor/$nextParameterOwner" } return Pair(result, restArguments) @@ -765,15 +786,15 @@ class TypeResolver( } private fun ClassifierDescriptor?.classifierDescriptorsFromInnerToOuter(): List = - generateSequence( - { this as? ClassifierDescriptorWithTypeParameters }, - { it.containingDeclaration as? ClassifierDescriptorWithTypeParameters } - ).toList() + generateSequence( + { this as? ClassifierDescriptorWithTypeParameters }, + { it.containingDeclaration as? ClassifierDescriptorWithTypeParameters } + ).toList() private fun resolveTypeProjectionsWithErrorConstructor( - c: TypeResolutionContext, - argumentElements: List, - message: String = "Error type for resolving type projections" + c: TypeResolutionContext, + argumentElements: List, + message: String = "Error type for resolving type projections" ) = resolveTypeProjections(c, ErrorUtils.createErrorTypeConstructor(message), argumentElements) /** @@ -784,18 +805,18 @@ class TypeResolver( * } * * type constructor for `Local` captures type parameter E from containing outer function - */ + */ private fun appendDefaultArgumentsForLocalClassifier( - fromIndex: Int, - constructorParameters: List + fromIndex: Int, + constructorParameters: List ) = constructorParameters.subList(fromIndex, constructorParameters.size).map { TypeProjectionImpl(it.original.defaultType) } fun resolveTypeProjections( - c: TypeResolutionContext, - constructor: TypeConstructor, - argumentElements: List + c: TypeResolutionContext, + constructor: TypeConstructor, + argumentElements: List ): List { return argumentElements.mapIndexed { i, argumentElement -> val projectionKind = argumentElement.projectionKind @@ -805,12 +826,10 @@ class TypeResolver( if (parameters.size > i) { val parameterDescriptor = parameters[i] TypeUtils.makeStarProjection(parameterDescriptor) - } - else { + } else { TypeProjectionImpl(OUT_VARIANCE, ErrorUtils.createErrorType("*")) } - } - else { + } else { val type = resolveType(c.noBareTypes(), argumentElement.typeReference!!) val kind = resolveProjectionKind(projectionKind) if (constructor.parameters.size > i) { @@ -818,8 +837,7 @@ class TypeResolver( if (kind != INVARIANT && parameterDescriptor.variance != INVARIANT) { if (kind == parameterDescriptor.variance) { c.trace.report(REDUNDANT_PROJECTION.on(argumentElement, constructor.declarationDescriptor!!)) - } - else { + } else { c.trace.report(CONFLICTING_PROJECTION.on(argumentElement, constructor.declarationDescriptor!!)) } } @@ -831,7 +849,7 @@ class TypeResolver( } private fun LexicalScope.findImplicitOuterClassArguments( - outerClass: ClassDescriptor + outerClass: ClassDescriptor ): List? { val enclosingClass = findFirstFromMeAndParent { scope -> if (scope is LexicalScope && scope.kind == LexicalScopeKind.CLASS_MEMBER_SCOPE) @@ -844,11 +862,11 @@ class TypeResolver( } fun resolveClass( - scope: LexicalScope, userType: KtUserType, trace: BindingTrace, isDebuggerContext: Boolean + scope: LexicalScope, userType: KtUserType, trace: BindingTrace, isDebuggerContext: Boolean ): ClassifierDescriptor? = resolveDescriptorForType(scope, userType, trace, isDebuggerContext).classifierDescriptor fun resolveDescriptorForType( - scope: LexicalScope, userType: KtUserType, trace: BindingTrace, isDebuggerContext: Boolean + scope: LexicalScope, userType: KtUserType, trace: BindingTrace, isDebuggerContext: Boolean ): QualifiedExpressionResolver.TypeQualifierResolutionResult { if (userType.qualifier != null) { // we must resolve all type references in arguments of qualifier type for (typeArgument in userType.qualifier!!.typeArguments) { @@ -862,7 +880,7 @@ class TypeResolver( return qualifiedExpressionResolver.resolveDescriptorForType(userType, scope, trace, isDebuggerContext).apply { if (classifierDescriptor != null) { PlatformClassesMappedToKotlinChecker.reportPlatformClassMappedToKotlin( - platformToKotlinClassMap, trace, userType, classifierDescriptor + platformToKotlinClassMap, trace, userType, classifierDescriptor ) } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/VariableTypeAndInitializerResolver.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/VariableTypeAndInitializerResolver.kt index dfd41fcbce2..9ec84c6edaf 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/VariableTypeAndInitializerResolver.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/VariableTypeAndInitializerResolver.kt @@ -34,15 +34,15 @@ import org.jetbrains.kotlin.types.expressions.ExpressionTypingServices import org.jetbrains.kotlin.types.expressions.PreliminaryDeclarationVisitor class VariableTypeAndInitializerResolver( - private val storageManager: StorageManager, - private val expressionTypingServices: ExpressionTypingServices, - private val typeResolver: TypeResolver, - private val constantExpressionEvaluator: ConstantExpressionEvaluator, - private val delegatedPropertyResolver: DelegatedPropertyResolver, - private val wrappedTypeFactory: WrappedTypeFactory, - private val typeApproximator: TypeApproximator, - private val declarationReturnTypeSanitizer: DeclarationReturnTypeSanitizer, - private val languageVersionSettings: LanguageVersionSettings + private val storageManager: StorageManager, + private val expressionTypingServices: ExpressionTypingServices, + private val typeResolver: TypeResolver, + private val constantExpressionEvaluator: ConstantExpressionEvaluator, + private val delegatedPropertyResolver: DelegatedPropertyResolver, + private val wrappedTypeFactory: WrappedTypeFactory, + private val typeApproximator: TypeApproximator, + private val declarationReturnTypeSanitizer: DeclarationReturnTypeSanitizer, + private val languageVersionSettings: LanguageVersionSettings ) { companion object { @JvmField @@ -50,12 +50,12 @@ class VariableTypeAndInitializerResolver( } fun resolveType( - variableDescriptor: VariableDescriptorWithInitializerImpl, - scopeForInitializer: LexicalScope, - variable: KtVariableDeclaration, - dataFlowInfo: DataFlowInfo, - trace: BindingTrace, - local: Boolean + variableDescriptor: VariableDescriptorWithInitializerImpl, + scopeForInitializer: LexicalScope, + variable: KtVariableDeclaration, + dataFlowInfo: DataFlowInfo, + trace: BindingTrace, + local: Boolean ): KotlinType { resolveTypeNullable(variableDescriptor, scopeForInitializer, variable, dataFlowInfo, trace, local)?.let { return it } @@ -67,29 +67,32 @@ class VariableTypeAndInitializerResolver( } fun resolveTypeNullable( - variableDescriptor: VariableDescriptorWithInitializerImpl, - scopeForInitializer: LexicalScope, - variable: KtVariableDeclaration, - dataFlowInfo: DataFlowInfo, - trace: BindingTrace, - local: Boolean + variableDescriptor: VariableDescriptorWithInitializerImpl, + scopeForInitializer: LexicalScope, + variable: KtVariableDeclaration, + dataFlowInfo: DataFlowInfo, + trace: BindingTrace, + local: Boolean ): KotlinType? { val propertyTypeRef = variable.typeReference return when { propertyTypeRef != null -> typeResolver.resolveType(scopeForInitializer, propertyTypeRef, trace, true) !variable.hasInitializer() && variable is KtProperty && variableDescriptor is VariableDescriptorWithAccessors && - variable.hasDelegateExpression() -> - resolveDelegatedPropertyType(variable, variableDescriptor, scopeForInitializer, dataFlowInfo, trace, local) + variable.hasDelegateExpression() -> + resolveDelegatedPropertyType(variable, variableDescriptor, scopeForInitializer, dataFlowInfo, trace, local) variable.hasInitializer() -> when { !local -> wrappedTypeFactory.createRecursionIntolerantDeferredType( - trace + trace ) { - PreliminaryDeclarationVisitor.createForDeclaration(variable, trace, - expressionTypingServices.languageVersionSettings) - val initializerType = resolveInitializerType(scopeForInitializer, variable.initializer!!, dataFlowInfo, trace, local) + PreliminaryDeclarationVisitor.createForDeclaration( + variable, trace, + expressionTypingServices.languageVersionSettings + ) + val initializerType = + resolveInitializerType(scopeForInitializer, variable.initializer!!, dataFlowInfo, trace, local) transformAnonymousTypeIfNeeded(variableDescriptor, variable, initializerType, trace) } @@ -101,60 +104,64 @@ class VariableTypeAndInitializerResolver( } fun setConstantForVariableIfNeeded( - variableDescriptor: VariableDescriptorWithInitializerImpl, - scope: LexicalScope, - variable: KtVariableDeclaration, - dataFlowInfo: DataFlowInfo, - variableType: KotlinType, - trace: BindingTrace + variableDescriptor: VariableDescriptorWithInitializerImpl, + scope: LexicalScope, + variable: KtVariableDeclaration, + dataFlowInfo: DataFlowInfo, + variableType: KotlinType, + trace: BindingTrace ) { if (!variable.hasInitializer() || variable.isVar) return variableDescriptor.setCompileTimeInitializer( - storageManager.createRecursionTolerantNullableLazyValue( - computeInitializer@{ - if (!DescriptorUtils.shouldRecordInitializerForProperty(variableDescriptor, variableType)) return@computeInitializer null + storageManager.createRecursionTolerantNullableLazyValue( + computeInitializer@{ + if (!DescriptorUtils.shouldRecordInitializerForProperty( + variableDescriptor, + variableType + )) return@computeInitializer null - val initializer = variable.initializer - val initializerType = expressionTypingServices.safeGetType(scope, initializer!!, variableType, dataFlowInfo, trace) - val constant = constantExpressionEvaluator.evaluateExpression(initializer, trace, initializerType) - ?: return@computeInitializer null + val initializer = variable.initializer + val initializerType = expressionTypingServices.safeGetType(scope, initializer!!, variableType, dataFlowInfo, trace) + val constant = constantExpressionEvaluator.evaluateExpression(initializer, trace, initializerType) + ?: return@computeInitializer null - if (constant.usesNonConstValAsConstant && variableDescriptor.isConst) { - trace.report(Errors.NON_CONST_VAL_USED_IN_CONSTANT_EXPRESSION.on(initializer)) - } + if (constant.usesNonConstValAsConstant && variableDescriptor.isConst) { + trace.report(Errors.NON_CONST_VAL_USED_IN_CONSTANT_EXPRESSION.on(initializer)) + } - constant.toConstantValue(initializerType) - }, - null - ) + constant.toConstantValue(initializerType) + }, + null + ) ) } private fun resolveDelegatedPropertyType( - property: KtProperty, - variableDescriptor: VariableDescriptorWithAccessors, - scopeForInitializer: LexicalScope, - dataFlowInfo: DataFlowInfo, - trace: BindingTrace, - local: Boolean + property: KtProperty, + variableDescriptor: VariableDescriptorWithAccessors, + scopeForInitializer: LexicalScope, + dataFlowInfo: DataFlowInfo, + trace: BindingTrace, + local: Boolean ) = wrappedTypeFactory.createRecursionIntolerantDeferredType(trace) { val delegateExpression = property.delegateExpression!! val type = delegatedPropertyResolver.resolveDelegateExpression( - delegateExpression, property, variableDescriptor, scopeForInitializer, trace, dataFlowInfo) + delegateExpression, property, variableDescriptor, scopeForInitializer, trace, dataFlowInfo + ) val getterReturnType = delegatedPropertyResolver.getGetValueMethodReturnType( - variableDescriptor, delegateExpression, type, trace, scopeForInitializer, dataFlowInfo + variableDescriptor, delegateExpression, type, trace, scopeForInitializer, dataFlowInfo ) getterReturnType?.let { approximateType(it, local) } ?: ErrorUtils.createErrorType("Type from delegate") } private fun resolveInitializerType( - scope: LexicalScope, - initializer: KtExpression, - dataFlowInfo: DataFlowInfo, - trace: BindingTrace, - local: Boolean + scope: LexicalScope, + initializer: KtExpression, + dataFlowInfo: DataFlowInfo, + trace: BindingTrace, + local: Boolean ): KotlinType { val inferredType = expressionTypingServices.safeGetType(scope, initializer, TypeUtils.NO_EXPECTED_TYPE, dataFlowInfo, trace) val approximatedType = approximateType(inferredType, local) @@ -162,5 +169,5 @@ class VariableTypeAndInitializerResolver( } private fun approximateType(type: KotlinType, local: Boolean): UnwrappedType = - typeApproximator.approximateDeclarationType(type, local, expressionTypingServices.languageVersionSettings) + typeApproximator.approximateDeclarationType(type, local, expressionTypingServices.languageVersionSettings) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/VarianceChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/VarianceChecker.kt index c8b47387cf5..d22e953e12d 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/VarianceChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/VarianceChecker.kt @@ -47,15 +47,15 @@ class VarianceChecker(trace: BindingTrace) { } class VarianceConflictDiagnosticData( - val containingType: KotlinType, - val typeParameter: TypeParameterDescriptor, - val occurrencePosition: Variance + val containingType: KotlinType, + val typeParameter: TypeParameterDescriptor, + val occurrencePosition: Variance ) class VarianceCheckerCore( - val context: BindingContext, - private val diagnosticSink: DiagnosticSink, - private val manualVariance: ManualVariance? = null + val context: BindingContext, + private val diagnosticSink: DiagnosticSink, + private val manualVariance: ManualVariance? = null ) { fun check(c: TopDownAnalysisContext) { @@ -86,10 +86,10 @@ class VarianceCheckerCore( } fun checkMember(member: KtCallableDeclaration, descriptor: CallableMemberDescriptor) = - Visibilities.isPrivate(descriptor.visibility) || checkCallableDeclaration(context, member, descriptor) + Visibilities.isPrivate(descriptor.visibility) || checkCallableDeclaration(context, member, descriptor) private fun TypeParameterDescriptor.varianceWithManual() = - if (manualVariance != null && this.original == manualVariance.descriptor) manualVariance.variance else variance + if (manualVariance != null && this.original == manualVariance.descriptor) manualVariance.variance else variance fun recordPrivateToThisIfNeeded(descriptor: CallableMemberDescriptor) { if (isIrrelevant(descriptor) || descriptor.visibility != Visibilities.PRIVATE) return @@ -102,9 +102,9 @@ class VarianceCheckerCore( } private fun checkCallableDeclaration( - trace: BindingContext, - declaration: KtCallableDeclaration, - descriptor: CallableDescriptor + trace: BindingContext, + declaration: KtCallableDeclaration, + descriptor: CallableDescriptor ): Boolean { if (isIrrelevant(descriptor)) return true var noError = true @@ -124,8 +124,8 @@ class VarianceCheckerCore( } private fun KtTypeParameterListOwner.checkTypeParameters( - trace: BindingContext, - typePosition: Variance + trace: BindingContext, + typePosition: Variance ): Boolean { var noError = true for (typeParameter in typeParameters) { @@ -137,20 +137,21 @@ class VarianceCheckerCore( return noError } - private fun KtTypeReference.checkTypePosition(trace: BindingContext, position: Variance) - = createTypeBinding(trace)?.checkTypePosition(position) + private fun KtTypeReference.checkTypePosition(trace: BindingContext, position: Variance) = + createTypeBinding(trace)?.checkTypePosition(position) private fun TypeBinding.checkTypePosition(position: Variance) = checkTypePosition(type, position) private fun TypeBinding.checkTypePosition(containingType: KotlinType, position: Variance): Boolean = checkTypePosition( - position, - { typeParameterDescriptor, typeBinding, errorPosition -> - val varianceConflictDiagnosticData = VarianceConflictDiagnosticData(containingType, typeParameterDescriptor, errorPosition) - val diagnostic = if (typeBinding.isInAbbreviation) Errors.TYPE_VARIANCE_CONFLICT_IN_EXPANDED_TYPE else Errors.TYPE_VARIANCE_CONFLICT - diagnosticSink.report(diagnostic.on(typeBinding.psiElement, varianceConflictDiagnosticData)) - }, - customVariance = { it.varianceWithManual() } + position, + { typeParameterDescriptor, typeBinding, errorPosition -> + val varianceConflictDiagnosticData = VarianceConflictDiagnosticData(containingType, typeParameterDescriptor, errorPosition) + val diagnostic = + if (typeBinding.isInAbbreviation) Errors.TYPE_VARIANCE_CONFLICT_IN_EXPANDED_TYPE else Errors.TYPE_VARIANCE_CONFLICT + diagnosticSink.report(diagnostic.on(typeBinding.psiElement, varianceConflictDiagnosticData)) + }, + customVariance = { it.varianceWithManual() } ) private fun isIrrelevant(descriptor: CallableDescriptor): Boolean { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/CallExpressionUnroller.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/CallExpressionUnroller.kt index cd86816c6cc..4de054c21bc 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/CallExpressionUnroller.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/CallExpressionUnroller.kt @@ -38,7 +38,7 @@ fun unrollToLeftMostQualifiedExpression(expression: KtQualifiedExpression): List return unrolled.asReversed() } -data class CallExpressionElement internal constructor (val qualified: KtQualifiedExpression) { +data class CallExpressionElement internal constructor(val qualified: KtQualifiedExpression) { val receiver: KtExpression get() = qualified.receiverExpression diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/DiagnosticReporterImpl.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/DiagnosticReporterImpl.kt index f03129fac64..81d4679790f 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/DiagnosticReporterImpl.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/DiagnosticReporterImpl.kt @@ -30,27 +30,36 @@ import java.util.* object CallDiagnosticToDiagnostic { - private val diagnosticMap: MutableMap, KotlinCallDiagnostic.(PsiElement) -> ParametrizedDiagnostic<*>> = HashMap() + private val diagnosticMap: MutableMap, KotlinCallDiagnostic.(PsiElement) -> ParametrizedDiagnostic<*>> = + HashMap() - private fun checkPut(klass: Class, factory: C.(PsiElement) -> ParametrizedDiagnostic?) { + private fun checkPut( + klass: Class, + factory: C.(PsiElement) -> ParametrizedDiagnostic? + ) { @Suppress("UNCHECKED_CAST") diagnosticMap.put(klass, factory as KotlinCallDiagnostic.(PsiElement) -> ParametrizedDiagnostic<*>) } - private inline fun put(factory0: DiagnosticFactory0, klass: Class) { + private inline fun put(factory0: DiagnosticFactory0, klass: Class) { checkPut(klass) { (it as? E)?.let { factory0.on(it) } } } - private inline fun put(factory1: DiagnosticFactory1, klass: Class, crossinline getA: C.() -> A) { + private inline fun put( + factory1: DiagnosticFactory1, + klass: Class, + crossinline getA: C.() -> A + ) { checkPut(klass) { (it as? E)?.let { factory1.on(it, getA()) } } } - private inline fun put( - factory2: DiagnosticFactory2, klass: Class, crossinline getA: C.() -> A, crossinline getB: C.() -> B) { + private inline fun put( + factory2: DiagnosticFactory2, klass: Class, crossinline getA: C.() -> A, crossinline getB: C.() -> B + ) { checkPut(klass) { (it as? E)?.let { factory2.on(it, getA(), getB()) } } @@ -58,7 +67,12 @@ object CallDiagnosticToDiagnostic { init { // put(Errors.UNSAFE_CALL, UnsafeCallDiagnostic::class.java, UnsafeCallDiagnostic::receiverType) - put(Errors.TYPE_MISMATCH, TypeMismatchDiagnostic::class.java, TypeMismatchDiagnostic::expectedType, TypeMismatchDiagnostic::actualType) + put( + Errors.TYPE_MISMATCH, + TypeMismatchDiagnostic::class.java, + TypeMismatchDiagnostic::expectedType, + TypeMismatchDiagnostic::actualType + ) } @@ -85,9 +99,9 @@ abstract class DiagnosticReporterImpl(private val bindingTrace: BindingTrace, pr } class TypeMismatchDiagnostic( - val callArgument: KotlinCallArgument, - val expectedType: KotlinType, - val actualType: KotlinType + val callArgument: KotlinCallArgument, + val expectedType: KotlinType, + val actualType: KotlinType ) : KotlinCallDiagnostic(ResolutionCandidateApplicability.INAPPLICABLE) { override fun report(reporter: DiagnosticReporter) = reporter.onCallArgument(callArgument, this) } \ No newline at end of file diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/AbstractReflectionApiCallChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/AbstractReflectionApiCallChecker.kt index adb805b6527..b3dbdfe6cb5 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/AbstractReflectionApiCallChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/AbstractReflectionApiCallChecker.kt @@ -36,9 +36,9 @@ private val ANY_MEMBER_NAMES = setOf("equals", "hashCode", "toString") * Checks that there are no usages of reflection API which will fail at runtime. */ abstract class AbstractReflectionApiCallChecker( - private val module: ModuleDescriptor, - private val notFoundClasses: NotFoundClasses, - storageManager: StorageManager + private val module: ModuleDescriptor, + private val notFoundClasses: NotFoundClasses, + storageManager: StorageManager ) : CallChecker { protected abstract val isWholeReflectionApiAvailable: Boolean protected abstract fun report(element: PsiElement, context: CallCheckerContext) @@ -66,9 +66,9 @@ abstract class AbstractReflectionApiCallChecker( protected open fun isAllowedReflectionApi(descriptor: CallableDescriptor, containingClass: ClassDescriptor): Boolean { val name = descriptor.name return name.asString() in ANY_MEMBER_NAMES || - name == OperatorNameConventions.INVOKE || - name.asString() == "name" || - (name.asString() == "get" || name.asString() == "set") && containingClass.isKPropertyClass() + name == OperatorNameConventions.INVOKE || + name.asString() == "name" || + (name.asString() == "get" || name.asString() == "set") && containingClass.isKPropertyClass() } private fun ClassDescriptor.isKPropertyClass() = kPropertyClasses.any { kProperty -> DescriptorUtils.isSubclass(this, kProperty) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/AdditionalTypeChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/AdditionalTypeChecker.kt index b1cf59aa2aa..238ec69ae0d 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/AdditionalTypeChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/AdditionalTypeChecker.kt @@ -25,17 +25,18 @@ import org.jetbrains.kotlin.types.KotlinType interface AdditionalTypeChecker { fun checkType( - expression: KtExpression, - expressionType: KotlinType, - expressionTypeWithSmartCast: KotlinType, - c: ResolutionContext<*> + expression: KtExpression, + expressionType: KotlinType, + expressionTypeWithSmartCast: KotlinType, + c: ResolutionContext<*> ) fun checkReceiver( - receiverParameter: ReceiverParameterDescriptor, - receiverArgument: ReceiverValue, - safeAccess: Boolean, - c: CallResolutionContext<*> - ) { } + receiverParameter: ReceiverParameterDescriptor, + receiverArgument: ReceiverValue, + safeAccess: Boolean, + c: CallResolutionContext<*> + ) { + } } \ No newline at end of file diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/ApiVersionCallChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/ApiVersionCallChecker.kt index 20d9000c340..c5f85eacabe 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/ApiVersionCallChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/ApiVersionCallChecker.kt @@ -36,7 +36,7 @@ object ApiVersionCallChecker : CallChecker { val accessible = targetDescriptor.checkSinceKotlinVersionAccessibility(context.languageVersionSettings) { version -> context.trace.report( - API_NOT_AVAILABLE.on(element, version.versionString, context.languageVersionSettings.apiVersion.versionString) + API_NOT_AVAILABLE.on(element, version.versionString, context.languageVersionSettings.apiVersion.versionString) ) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/AssigningNamedArgumentToVarargChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/AssigningNamedArgumentToVarargChecker.kt index a7b95dd095f..59f33e821a1 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/AssigningNamedArgumentToVarargChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/AssigningNamedArgumentToVarargChecker.kt @@ -38,9 +38,9 @@ class AssigningNamedArgumentToVarargChecker : CallChecker { } private fun checkAssignmentOfSingleElementToVararg( - argument: ValueArgument, - parameterDescriptor: ValueParameterDescriptor, - context: ResolutionContext<*> + argument: ValueArgument, + parameterDescriptor: ValueParameterDescriptor, + context: ResolutionContext<*> ) { if (!context.languageVersionSettings.supportsFeature(LanguageFeature.AssigningArraysToVarargsInNamedFormInAnnotations)) return @@ -51,35 +51,38 @@ class AssigningNamedArgumentToVarargChecker : CallChecker { if (isParameterOfAnnotation(parameterDescriptor)) { checkAssignmentOfSingleElementInAnnotation(argument, argumentExpression, context) - } - else { + } else { checkAssignmentOfSingleElementInFunction(argument, argumentExpression, context, parameterDescriptor) } } private fun checkAssignmentOfSingleElementInAnnotation( - argument: ValueArgument, - argumentExpression: KtExpression, - context: ResolutionContext<*> + argument: ValueArgument, + argumentExpression: KtExpression, + context: ResolutionContext<*> ) { if (isArrayOrArrayLiteral(argument, context)) { if (argument.hasSpread()) { context.trace.report(Errors.ASSIGNING_SINGLE_ELEMENT_TO_VARARG_IN_NAMED_FORM_ANNOTATION.on(argumentExpression)) } - } - else { + } else { context.trace.report(Errors.ASSIGNING_SINGLE_ELEMENT_TO_VARARG_IN_NAMED_FORM_ANNOTATION.on(argumentExpression)) } } private fun checkAssignmentOfSingleElementInFunction( - argument: ValueArgument, - argumentExpression: KtExpression, - context: ResolutionContext<*>, - parameterDescriptor: ValueParameterDescriptor + argument: ValueArgument, + argumentExpression: KtExpression, + context: ResolutionContext<*>, + parameterDescriptor: ValueParameterDescriptor ) { if (!argument.hasSpread()) { - context.trace.report(Errors.ASSIGNING_SINGLE_ELEMENT_TO_VARARG_IN_NAMED_FORM_FUNCTION.on(argumentExpression, parameterDescriptor.type)) + context.trace.report( + Errors.ASSIGNING_SINGLE_ELEMENT_TO_VARARG_IN_NAMED_FORM_FUNCTION.on( + argumentExpression, + parameterDescriptor.type + ) + ) } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/CallChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/CallChecker.kt index 076b58d72cc..1dcdb5f81c9 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/CallChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/CallChecker.kt @@ -36,10 +36,10 @@ interface CallChecker { } class CallCheckerContext( - val resolutionContext: ResolutionContext<*>, - val trace: BindingTrace, - val languageVersionSettings: LanguageVersionSettings, - val deprecationResolver: DeprecationResolver + val resolutionContext: ResolutionContext<*>, + val trace: BindingTrace, + val languageVersionSettings: LanguageVersionSettings, + val deprecationResolver: DeprecationResolver ) { val scope: LexicalScope get() = resolutionContext.scope @@ -51,9 +51,9 @@ class CallCheckerContext( get() = resolutionContext.isAnnotationContext constructor( - c: ResolutionContext<*>, - languageVersionSettings: LanguageVersionSettings, - deprecationResolver: DeprecationResolver + c: ResolutionContext<*>, + languageVersionSettings: LanguageVersionSettings, + deprecationResolver: DeprecationResolver ) : this(c, c.trace, languageVersionSettings, deprecationResolver) } @@ -62,4 +62,4 @@ class CallCheckerContext( // Receiver parameter is present to emphasize that this function should ideally be only used from call checkers. @Suppress("unused") fun CallChecker.isComputingDeferredType(type: KotlinType) = - type is DeferredType && type.isComputing + type is DeferredType && type.isComputing diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/ConstructorHeaderCallChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/ConstructorHeaderCallChecker.kt index 406396f51f0..6cdeada5d7f 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/ConstructorHeaderCallChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/ConstructorHeaderCallChecker.kt @@ -37,19 +37,18 @@ object ConstructorHeaderCallChecker : CallChecker { val callElement = resolvedCall.call.callElement val labelReferenceClass = - if (callElement is KtInstanceExpressionWithLabel) { - context.trace.get(BindingContext.REFERENCE_TARGET, callElement.instanceReference) as? ClassDescriptor - } - else null + if (callElement is KtInstanceExpressionWithLabel) { + context.trace.get(BindingContext.REFERENCE_TARGET, callElement.instanceReference) as? ClassDescriptor + } else null if (dispatchReceiverClass == null && extensionReceiverClass == null && labelReferenceClass == null) return val classes = setOf(dispatchReceiverClass, extensionReceiverClass, labelReferenceClass) if (context.scope.parentsWithSelf.any { scope -> - scope is LexicalScope && scope.kind == LexicalScopeKind.CONSTRUCTOR_HEADER && - (scope.ownerDescriptor as ClassConstructorDescriptor).containingDeclaration in classes - }) { + scope is LexicalScope && scope.kind == LexicalScopeKind.CONSTRUCTOR_HEADER && + (scope.ownerDescriptor as ClassConstructorDescriptor).containingDeclaration in classes + }) { context.trace.report(Errors.INSTANCE_ACCESS_BEFORE_SUPER_CALL.on(reportOn, resolvedCall.resultingDescriptor)) } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/InlineChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/InlineChecker.kt index 1f35462ea13..9124a0debb8 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/InlineChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/InlineChecker.kt @@ -74,7 +74,8 @@ internal class InlineChecker(private val descriptor: FunctionDescriptor) : CallC if (inlinableParameters.contains(targetDescriptor)) { when { - !checkNotInDefaultParameter(context, targetDescriptor, expression) -> { /*error*/ } + !checkNotInDefaultParameter(context, targetDescriptor, expression) -> { /*error*/ + } !isInsideCall(expression) -> context.trace.report(USAGE_IS_NOT_INLINABLE.on(expression, expression, descriptor)) } } @@ -91,14 +92,20 @@ internal class InlineChecker(private val descriptor: FunctionDescriptor) : CallC checkRecursion(context, targetDescriptor, expression) } - private fun checkNotInDefaultParameter( context: CallCheckerContext , targetDescriptor: CallableDescriptor, expression: KtExpression) = - !supportDefaultValueInline || expression.getParentOfType(true)?.let { - val allow = it !in inlinableKtParameters - if (!allow) { - context.trace.report(NOT_SUPPORTED_INLINE_PARAMETER_IN_INLINE_PARAMETER_DEFAULT_VALUE.on(expression, expression, descriptor)) - } - allow - } ?: true + private fun checkNotInDefaultParameter(context: CallCheckerContext, targetDescriptor: CallableDescriptor, expression: KtExpression) = + !supportDefaultValueInline || expression.getParentOfType(true)?.let { + val allow = it !in inlinableKtParameters + if (!allow) { + context.trace.report( + NOT_SUPPORTED_INLINE_PARAMETER_IN_INLINE_PARAMETER_DEFAULT_VALUE.on( + expression, + expression, + descriptor + ) + ) + } + allow + } ?: true private fun isInsideCall(expression: KtExpression): Boolean { val parent = KtPsiUtil.getParentCallIfPresent(expression) @@ -126,23 +133,23 @@ internal class InlineChecker(private val descriptor: FunctionDescriptor) : CallC } private fun checkValueParameter( - context: CallCheckerContext, - targetDescriptor: CallableDescriptor, - targetArgument: ValueArgument, - targetParameterDescriptor: ValueParameterDescriptor + context: CallCheckerContext, + targetDescriptor: CallableDescriptor, + targetArgument: ValueArgument, + targetParameterDescriptor: ValueParameterDescriptor ) { val argumentExpression = targetArgument.getArgumentExpression() ?: return val argumentCallee = getCalleeDescriptor(context, argumentExpression, false) if (argumentCallee != null && inlinableParameters.contains(argumentCallee)) { when { - !checkNotInDefaultParameter(context, argumentCallee, argumentExpression) -> { /*error*/ } + !checkNotInDefaultParameter(context, argumentCallee, argumentExpression) -> { /*error*/ + } InlineUtil.isInline(targetDescriptor) && InlineUtil.isInlineParameter(targetParameterDescriptor) -> if (allowsNonLocalReturns(argumentCallee) && !allowsNonLocalReturns(targetParameterDescriptor)) { context.trace.report(NON_LOCAL_RETURN_NOT_ALLOWED.on(argumentExpression, argumentExpression)) - } - else { + } else { checkNonLocalReturn(context, argumentCallee, argumentExpression) } @@ -152,10 +159,10 @@ internal class InlineChecker(private val descriptor: FunctionDescriptor) : CallC } private fun checkCallWithReceiver( - context: CallCheckerContext, - targetDescriptor: CallableDescriptor, - receiver: ReceiverValue?, - expression: KtExpression? + context: CallCheckerContext, + targetDescriptor: CallableDescriptor, + receiver: ReceiverValue?, + expression: KtExpression? ) { if (receiver == null) return @@ -187,9 +194,9 @@ internal class InlineChecker(private val descriptor: FunctionDescriptor) : CallC } private fun getCalleeDescriptor( - context: CallCheckerContext, - expression: KtExpression, - unwrapVariableAsFunction: Boolean + context: CallCheckerContext, + expression: KtExpression, + unwrapVariableAsFunction: Boolean ): CallableDescriptor? { if (!(expression is KtSimpleNameExpression || expression is KtThisExpression)) return null @@ -201,24 +208,23 @@ internal class InlineChecker(private val descriptor: FunctionDescriptor) : CallC } private fun checkLambdaInvokeOrExtensionCall( - context: CallCheckerContext, - lambdaDescriptor: CallableDescriptor, - callDescriptor: CallableDescriptor, - receiverExpression: KtExpression + context: CallCheckerContext, + lambdaDescriptor: CallableDescriptor, + callDescriptor: CallableDescriptor, + receiverExpression: KtExpression ) { val inlinableCall = isInvokeOrInlineExtension(callDescriptor) if (!inlinableCall) { context.trace.report(USAGE_IS_NOT_INLINABLE.on(receiverExpression, receiverExpression, descriptor)) - } - else { + } else { checkNonLocalReturn(context, lambdaDescriptor, receiverExpression) } } private fun checkRecursion( - context: CallCheckerContext, - targetDescriptor: CallableDescriptor, - expression: KtElement + context: CallCheckerContext, + targetDescriptor: CallableDescriptor, + expression: KtElement ) { if (targetDescriptor.original === descriptor) { context.trace.report(Errors.RECURSION_IN_INLINE.on(expression, expression, descriptor)) @@ -232,16 +238,16 @@ internal class InlineChecker(private val descriptor: FunctionDescriptor) : CallC val containingDeclaration = descriptor.getContainingDeclaration() val isInvoke = descriptor.getName() == OperatorNameConventions.INVOKE && - containingDeclaration is ClassDescriptor && - containingDeclaration.defaultType.isFunctionType + containingDeclaration is ClassDescriptor && + containingDeclaration.defaultType.isFunctionType return isInvoke || InlineUtil.isInline(descriptor) } private fun checkVisibilityAndAccess( - calledDescriptor: CallableDescriptor, - expression: KtElement, - context: CallCheckerContext + calledDescriptor: CallableDescriptor, + expression: KtElement, + context: CallCheckerContext ) { val calledFunEffectiveVisibility = if (isDefinedInInlineFunction(calledDescriptor)) EffectiveVisibility.Public @@ -254,8 +260,7 @@ internal class InlineChecker(private val descriptor: FunctionDescriptor) : CallC !isCalledFunPublicOrPublishedApi && calledDescriptor.visibility !== Visibilities.LOCAL) { context.trace.report(Errors.NON_PUBLIC_CALL_FROM_PUBLIC_INLINE.on(expression, calledDescriptor, descriptor)) - } - else { + } else { checkPrivateClassMemberAccess(calledDescriptor, expression, context) } @@ -268,9 +273,9 @@ internal class InlineChecker(private val descriptor: FunctionDescriptor) : CallC } private fun checkPrivateClassMemberAccess( - declarationDescriptor: DeclarationDescriptor, - expression: KtElement, - context: CallCheckerContext + declarationDescriptor: DeclarationDescriptor, + expression: KtElement, + context: CallCheckerContext ) { if (!isEffectivelyPrivateApiFunction) { if (declarationDescriptor.isInsidePrivateClass) { @@ -292,9 +297,9 @@ internal class InlineChecker(private val descriptor: FunctionDescriptor) : CallC } private fun checkNonLocalReturn( - context: CallCheckerContext, - inlinableParameterDescriptor: CallableDescriptor, - parameterUsage: KtExpression + context: CallCheckerContext, + inlinableParameterDescriptor: CallableDescriptor, + parameterUsage: KtExpression ) { if (!allowsNonLocalReturns(inlinableParameterDescriptor)) return diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/LateinitIntrinsicApplicabilityChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/LateinitIntrinsicApplicabilityChecker.kt index c0f430ff06f..489b48ae948 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/LateinitIntrinsicApplicabilityChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/LateinitIntrinsicApplicabilityChecker.kt @@ -46,8 +46,7 @@ object LateinitIntrinsicApplicabilityChecker : CallChecker { val expression = (resolvedCall.extensionReceiver as? ExpressionReceiver)?.expression?.let(KtPsiUtil::safeDeparenthesize) if (expression !is KtCallableReferenceExpression) { context.trace.report(LATEINIT_INTRINSIC_CALL_ON_NON_LITERAL.on(reportOn)) - } - else { + } else { val propertyReferenceResolvedCall = expression.callableReference.getResolvedCall(context.trace.bindingContext) ?: return val referencedProperty = propertyReferenceResolvedCall.resultingDescriptor if (referencedProperty !is PropertyDescriptor) { @@ -56,11 +55,9 @@ object LateinitIntrinsicApplicabilityChecker : CallChecker { if (!referencedProperty.isLateInit) { context.trace.report(LATEINIT_INTRINSIC_CALL_ON_NON_LATEINIT.on(reportOn)) - } - else if (!isBackingFieldAccessible(referencedProperty, context)) { + } else if (!isBackingFieldAccessible(referencedProperty, context)) { context.trace.report(LATEINIT_INTRINSIC_CALL_ON_NON_ACCESSIBLE_PROPERTY.on(reportOn, referencedProperty)) - } - else if ((context.scope.ownerDescriptor as? FunctionDescriptor)?.isInline == true) { + } else if ((context.scope.ownerDescriptor as? FunctionDescriptor)?.isInline == true) { context.trace.report(LATEINIT_INTRINSIC_CALL_IN_INLINE_FUNCTION.on(reportOn)) } } @@ -70,7 +67,7 @@ object LateinitIntrinsicApplicabilityChecker : CallChecker { // We can generate direct access to the backing field only if the property is defined in the same source file, // and the property is originally declared in a scope that is a parent of the usage scope val declaration = - OverridingUtil.filterOutOverridden(OverridingUtil.getOverriddenDeclarations(descriptor)).singleOrNull() ?: return false + OverridingUtil.filterOutOverridden(OverridingUtil.getOverriddenDeclarations(descriptor)).singleOrNull() ?: return false val declarationSourceFile = DescriptorToSourceUtils.getContainingFile(declaration) ?: return false val usageSourceFile = DescriptorToSourceUtils.getContainingFile(context.scope.ownerDescriptor) ?: return false if (declarationSourceFile != usageSourceFile) return false diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/UnderscoreUsageChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/UnderscoreUsageChecker.kt index ffb0c0c91dd..ae5e9ba2957 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/UnderscoreUsageChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/UnderscoreUsageChecker.kt @@ -58,6 +58,6 @@ object UnderscoreUsageChecker : CallChecker { } private fun String.isUnderscoreOnlyName() = - isNotEmpty() && all { it == '_' } + isNotEmpty() && all { it == '_' } } \ No newline at end of file diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/context/CallPosition.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/context/CallPosition.kt index 2d6b86074cb..1eefab915a8 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/context/CallPosition.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/context/CallPosition.kt @@ -28,9 +28,9 @@ sealed class CallPosition { class ExtensionReceiverPosition(val resolvedCall: ResolvedCall<*>) : CallPosition() class ValueArgumentPosition( - val resolvedCall: ResolvedCall<*>, - val valueParameter: ValueParameterDescriptor, - val valueArgument: ValueArgument + val resolvedCall: ResolvedCall<*>, + val valueParameter: ValueParameterDescriptor, + val valueArgument: ValueArgument ) : CallPosition() class PropertyAssignment(val leftPart: KtExpression?) : CallPosition() diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/context/ResolutionResultsCache.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/context/ResolutionResultsCache.kt index 34de7bfbba8..6ce3aa452d1 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/context/ResolutionResultsCache.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/context/ResolutionResultsCache.kt @@ -26,18 +26,18 @@ import java.util.* interface ResolutionResultsCache { data class CachedData( - val resolutionResults: OverloadResolutionResultsImpl<*>, - val deferredComputation: BasicCallResolutionContext, - val tracing: TracingStrategy, - val resolutionTrace: DelegatingBindingTrace + val resolutionResults: OverloadResolutionResultsImpl<*>, + val deferredComputation: BasicCallResolutionContext, + val tracing: TracingStrategy, + val resolutionTrace: DelegatingBindingTrace ) fun record( - call: Call, - results: OverloadResolutionResultsImpl<*>, - deferredComputation: BasicCallResolutionContext, - tracing: TracingStrategy, - resolutionTrace: DelegatingBindingTrace + call: Call, + results: OverloadResolutionResultsImpl<*>, + deferredComputation: BasicCallResolutionContext, + tracing: TracingStrategy, + resolutionTrace: DelegatingBindingTrace ) operator fun get(call: Call): CachedData? @@ -47,11 +47,11 @@ class ResolutionResultsCacheImpl : ResolutionResultsCache { private val data = HashMap() override fun record( - call: Call, - results: OverloadResolutionResultsImpl, - deferredComputation: BasicCallResolutionContext, - tracing: TracingStrategy, - resolutionTrace: DelegatingBindingTrace + call: Call, + results: OverloadResolutionResultsImpl, + deferredComputation: BasicCallResolutionContext, + tracing: TracingStrategy, + resolutionTrace: DelegatingBindingTrace ) { data[call] = CachedData(results, deferredComputation, tracing, resolutionTrace) } @@ -67,11 +67,11 @@ class TemporaryResolutionResultsCache(private val parentCache: ResolutionResults private val innerCache = ResolutionResultsCacheImpl() override fun record( - call: Call, - results: OverloadResolutionResultsImpl, - deferredComputation: BasicCallResolutionContext, - tracing: TracingStrategy, - resolutionTrace: DelegatingBindingTrace + call: Call, + results: OverloadResolutionResultsImpl, + deferredComputation: BasicCallResolutionContext, + tracing: TracingStrategy, + resolutionTrace: DelegatingBindingTrace ) { innerCache.record(call, results, deferredComputation, tracing, resolutionTrace) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/ConstraintError.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/ConstraintError.kt index f44a117aef8..1195669c20b 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/ConstraintError.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/ConstraintError.kt @@ -22,13 +22,13 @@ import org.jetbrains.kotlin.resolve.calls.inference.constraintPosition.Constrain open class ConstraintError(val constraintPosition: ConstraintPosition) -class ParameterConstraintError(constraintPosition: ConstraintPosition): ConstraintError(constraintPosition) +class ParameterConstraintError(constraintPosition: ConstraintPosition) : ConstraintError(constraintPosition) -class ErrorInConstrainingType(constraintPosition: ConstraintPosition): ConstraintError(constraintPosition) +class ErrorInConstrainingType(constraintPosition: ConstraintPosition) : ConstraintError(constraintPosition) -class TypeInferenceError(constraintPosition: ConstraintPosition): ConstraintError(constraintPosition) +class TypeInferenceError(constraintPosition: ConstraintPosition) : ConstraintError(constraintPosition) -class CannotCapture(constraintPosition: ConstraintPosition, val typeVariable: TypeVariable): ConstraintError(constraintPosition) +class CannotCapture(constraintPosition: ConstraintPosition, val typeVariable: TypeVariable) : ConstraintError(constraintPosition) fun newTypeInferenceOrParameterConstraintError(constraintPosition: ConstraintPosition) = - if (constraintPosition.isParameter()) ParameterConstraintError(constraintPosition) else TypeInferenceError(constraintPosition) \ No newline at end of file + if (constraintPosition.isParameter()) ParameterConstraintError(constraintPosition) else TypeInferenceError(constraintPosition) \ No newline at end of file diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/ConstraintPosition.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/ConstraintPosition.kt index a344b1d0ab9..df79b9dd8ff 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/ConstraintPosition.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/ConstraintPosition.kt @@ -64,7 +64,7 @@ class CompoundConstraintPosition(vararg positions: ConstraintPosition) : Constra get() = COMPOUND_CONSTRAINT_POSITION val positions: Collection = - positions.flatMap { (it as? CompoundConstraintPosition)?.positions ?: listOf(it) }.toSet() + positions.flatMap { (it as? CompoundConstraintPosition)?.positions ?: listOf(it) }.toSet() override fun isStrong() = positions.any { it.isStrong() } @@ -76,19 +76,19 @@ fun ConstraintPosition.derivedFrom(kind: ConstraintPositionKind): Boolean { } class ValidityConstraintForConstituentType( - val typeArgument: KotlinType, - val typeParameter: TypeParameterDescriptor, - val bound: KotlinType + val typeArgument: KotlinType, + val typeParameter: TypeParameterDescriptor, + val bound: KotlinType ) : ConstraintPosition { override val kind: ConstraintPositionKind get() = TYPE_BOUND_POSITION } fun ConstraintPosition.getValidityConstraintForConstituentType(): ValidityConstraintForConstituentType? = - when (this) { - is ValidityConstraintForConstituentType -> - this - is CompoundConstraintPosition -> - positions.asSequence().map { it.getValidityConstraintForConstituentType() }.firstOrNull { it != null } - else -> - null - } \ No newline at end of file + when (this) { + is ValidityConstraintForConstituentType -> + this + is CompoundConstraintPosition -> + positions.asSequence().map { it.getValidityConstraintForConstituentType() }.firstOrNull { it != null } + else -> + null + } \ No newline at end of file diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/ConstraintSystem.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/ConstraintSystem.kt index 4a2076186fe..ef1bc545b5c 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/ConstraintSystem.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/ConstraintSystem.kt @@ -60,7 +60,7 @@ interface ConstraintSystem { * to the corresponding types of variables of the system. Use that substitutor to provide constraints to the system */ fun registerTypeVariables( - call: CallHandle, typeParameters: Collection, external: Boolean = false + call: CallHandle, typeParameters: Collection, external: Boolean = false ): TypeSubstitutor /** diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/TypeBounds.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/TypeBounds.kt index a5bb97065e2..b9787cc8476 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/TypeBounds.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/TypeBounds.kt @@ -38,13 +38,13 @@ interface TypeBounds { } class Bound( - val typeVariable: TypeVariable, - val constrainingType: KotlinType, - val kind: BoundKind, - val position: ConstraintPosition, - val isProper: Boolean, - // to prevent infinite recursion in incorporation we store the variables that was substituted to derive this bound - val derivedFrom: Set + val typeVariable: TypeVariable, + val constrainingType: KotlinType, + val kind: BoundKind, + val position: ConstraintPosition, + val isProper: Boolean, + // to prevent infinite recursion in incorporation we store the variables that was substituted to derive this bound + val derivedFrom: Set ) { override fun equals(other: Any?): Boolean { if (this === other) return true diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/TypeBoundsImpl.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/TypeBoundsImpl.kt index 38083079111..0919f0d207d 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/TypeBoundsImpl.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/inference/TypeBoundsImpl.kt @@ -46,14 +46,17 @@ class TypeBoundsImpl(override val typeVariable: TypeVariable) : TypeBounds { bounds.add(bound) } - private fun filterBounds(bounds: Collection, kind: BoundKind, errorValues: MutableCollection? = null): Set { + private fun filterBounds( + bounds: Collection, + kind: BoundKind, + errorValues: MutableCollection? = null + ): Set { val result = LinkedHashSet() for (bound in bounds) { if (bound.kind == kind) { if (!ErrorUtils.containsErrorType(bound.constrainingType)) { result.add(bound.constrainingType) - } - else { + } else { errorValues?.add(bound.constrainingType) } } @@ -116,7 +119,8 @@ class TypeBoundsImpl(override val typeVariable: TypeVariable) : TypeBounds { values.addIfNotNull(superTypeOfNumberLowerBounds) if (superTypeOfLowerBounds != null && superTypeOfNumberLowerBounds != null) { - val superTypeOfAllLowerBounds = CommonSupertypes.commonSupertypeForNonDenotableTypes(listOf(superTypeOfLowerBounds, superTypeOfNumberLowerBounds)) + val superTypeOfAllLowerBounds = + CommonSupertypes.commonSupertypeForNonDenotableTypes(listOf(superTypeOfLowerBounds, superTypeOfNumberLowerBounds)) if (tryPossibleAnswer(bounds, superTypeOfAllLowerBounds)) { return setOf(superTypeOfAllLowerBounds!!) } @@ -141,7 +145,8 @@ class TypeBoundsImpl(override val typeVariable: TypeVariable) : TypeBounds { if (!typeVariable.hasOnlyInputTypesAnnotation()) return true // Only type mentioned in bounds might be the result - val typesInBoundsSet = bounds.filter { it.isProper && it.constrainingType.constructor.isDenotable }.map { it.constrainingType }.toSet() + val typesInBoundsSet = + bounds.filter { it.isProper && it.constrainingType.constructor.isDenotable }.map { it.constrainingType }.toSet() // Flexible types are equal to inflexible if (typesInBoundsSet.any { KotlinTypeChecker.DEFAULT.equalTypes(it, possibleAnswer) }) return true @@ -181,8 +186,7 @@ class TypeBoundsImpl(override val typeVariable: TypeVariable) : TypeBounds { private fun commonSupertypeForNumberTypes(numberLowerBounds: Collection): KotlinType? { if (numberLowerBounds.isEmpty()) return null val intersectionOfSupertypes = getIntersectionOfSupertypes(numberLowerBounds) - return TypeUtils.getDefaultPrimitiveNumberType(intersectionOfSupertypes) ?: - CommonSupertypes.commonSupertype(numberLowerBounds) + return TypeUtils.getDefaultPrimitiveNumberType(intersectionOfSupertypes) ?: CommonSupertypes.commonSupertype(numberLowerBounds) } private fun getIntersectionOfSupertypes(types: Collection): Set { @@ -191,8 +195,7 @@ class TypeBoundsImpl(override val typeVariable: TypeVariable) : TypeBounds { val supertypes = type.constructor.supertypes if (upperBounds.isEmpty()) { upperBounds.addAll(supertypes) - } - else { + } else { upperBounds.retainAll(supertypes) } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/resolvedCallUtil.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/resolvedCallUtil.kt index d00d3bd21f4..30537cbc23f 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/resolvedCallUtil.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/resolvedCallUtil.kt @@ -44,7 +44,7 @@ import org.jetbrains.kotlin.types.TypeUtils // val y = other.x // return false for `other.x` as it's receiver is not `this` // } fun ResolvedCall<*>.hasThisOrNoDispatchReceiver( - context: BindingContext + context: BindingContext ): Boolean { val dispatchReceiverValue = dispatchReceiver if (resultingDescriptor.dispatchReceiverParameter == null || dispatchReceiverValue == null) return true @@ -77,30 +77,30 @@ fun ResolvedCall<*>.getExplicitReceiverValue(): ReceiverValue? { } fun ResolvedCall<*>.getImplicitReceiverValue(): ImplicitReceiver? = - getImplicitReceivers().firstOrNull() as? ImplicitReceiver + getImplicitReceivers().firstOrNull() as? ImplicitReceiver fun ResolvedCall<*>.getImplicitReceivers(): Collection = - when (explicitReceiverKind) { - ExplicitReceiverKind.NO_EXPLICIT_RECEIVER -> listOfNotNull(extensionReceiver, dispatchReceiver) - ExplicitReceiverKind.DISPATCH_RECEIVER -> listOfNotNull(extensionReceiver) - ExplicitReceiverKind.EXTENSION_RECEIVER -> listOfNotNull(dispatchReceiver) - ExplicitReceiverKind.BOTH_RECEIVERS -> emptyList() - } + when (explicitReceiverKind) { + ExplicitReceiverKind.NO_EXPLICIT_RECEIVER -> listOfNotNull(extensionReceiver, dispatchReceiver) + ExplicitReceiverKind.DISPATCH_RECEIVER -> listOfNotNull(extensionReceiver) + ExplicitReceiverKind.EXTENSION_RECEIVER -> listOfNotNull(dispatchReceiver) + ExplicitReceiverKind.BOTH_RECEIVERS -> emptyList() + } private fun ResolvedCall<*>.hasSafeNullableReceiver(context: CallResolutionContext<*>): Boolean { if (!call.isSafeCall()) return false val receiverValue = getExplicitReceiverValue()?.let { DataFlowValueFactory.createDataFlowValue(it, context) } - ?: return false + ?: return false return context.dataFlowInfo.getStableNullability(receiverValue).canBeNull() } fun ResolvedCall<*>.makeNullableTypeIfSafeReceiver(type: KotlinType?, context: CallResolutionContext<*>) = - type?.let { TypeUtils.makeNullableIfNeeded(type, hasSafeNullableReceiver(context)) } + type?.let { TypeUtils.makeNullableIfNeeded(type, hasSafeNullableReceiver(context)) } fun ResolvedCall<*>.hasBothReceivers() = dispatchReceiver != null && extensionReceiver != null -fun ResolvedCall<*>.getDispatchReceiverWithSmartCast(): ReceiverValue? - = getReceiverValueWithSmartCast(dispatchReceiver, smartCastDispatchReceiverType) +fun ResolvedCall<*>.getDispatchReceiverWithSmartCast(): ReceiverValue? = + getReceiverValueWithSmartCast(dispatchReceiver, smartCastDispatchReceiverType) fun KtCallElement.getArgumentByParameterIndex(index: Int, context: BindingContext): List { val resolvedCall = getResolvedCall(context) ?: return emptyList() diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/results/FlatSignatureForResolvedCall.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/results/FlatSignatureForResolvedCall.kt index 5a13f1cfd46..51f4ee9b366 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/results/FlatSignatureForResolvedCall.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/results/FlatSignatureForResolvedCall.kt @@ -38,8 +38,7 @@ fun > RC.createFlatSignature(): FlatSignature { for ((valueParameter, resolvedValueArgument) in valueArguments.entries) { if (resolvedValueArgument is DefaultValueArgument) { numDefaults++ - } - else { + } else { val originalValueParameter = originalValueParameters[valueParameter.index] val parameterType = originalValueParameter.argumentValueType for (valueArgument in resolvedValueArgument.arguments) { @@ -52,14 +51,14 @@ fun > RC.createFlatSignature(): FlatSignature { } fun createOverloadingConflictResolver( - builtIns: KotlinBuiltIns, - specificityComparator: TypeSpecificityComparator + builtIns: KotlinBuiltIns, + specificityComparator: TypeSpecificityComparator ) = OverloadingConflictResolver( - builtIns, - specificityComparator, - MutableResolvedCall<*>::getResultingDescriptor, - ConstraintSystemBuilderImpl.Companion::forSpecificity, - MutableResolvedCall<*>::createFlatSignature, - { (it as? VariableAsFunctionResolvedCallImpl)?.variableCall }, - { DescriptorToSourceUtils.descriptorToDeclaration(it) != null} + builtIns, + specificityComparator, + MutableResolvedCall<*>::getResultingDescriptor, + ConstraintSystemBuilderImpl.Companion::forSpecificity, + MutableResolvedCall<*>::createFlatSignature, + { (it as? VariableAsFunctionResolvedCallImpl)?.variableCall }, + { DescriptorToSourceUtils.descriptorToDeclaration(it) != null } ) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/results/NewOverloadResolutionResults.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/results/NewOverloadResolutionResults.kt index 2ebe3c484f9..2160f6af09a 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/results/NewOverloadResolutionResults.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/results/NewOverloadResolutionResults.kt @@ -28,7 +28,7 @@ abstract class AbstractOverloadResolutionResults : Overl override fun isIncomplete() = resultCode == OverloadResolutionResults.Code.INCOMPLETE_TYPE_INFERENCE } -class SingleOverloadResolutionResult(val result: ResolvedCall) : AbstractOverloadResolutionResults() { +class SingleOverloadResolutionResult(val result: ResolvedCall) : AbstractOverloadResolutionResults() { override fun getAllCandidates(): Collection>? = null override fun getResultingCalls(): Collection> = listOf(result) override fun getResultingCall() = result @@ -52,23 +52,22 @@ open class NameNotFoundResolutionResult : AbstractOverlo } class ManyCandidates( - val candidates: Collection> + val candidates: Collection> ) : AbstractOverloadResolutionResults() { override fun getAllCandidates(): Collection>? = null override fun getResultingCalls(): Collection> = candidates override fun getResultingCall() = error("Many candidates") override fun getResultingDescriptor() = error("Many candidates") override fun getResultCode() = - when(candidates.first().status) { - ResolutionStatus.RECEIVER_TYPE_ERROR -> Code.CANDIDATES_WITH_WRONG_RECEIVER - ResolutionStatus.SUCCESS -> Code.AMBIGUITY - ResolutionStatus.INCOMPLETE_TYPE_INFERENCE -> Code.INCOMPLETE_TYPE_INFERENCE - else -> Code.MANY_FAILED_CANDIDATES - } + when (candidates.first().status) { + ResolutionStatus.RECEIVER_TYPE_ERROR -> Code.CANDIDATES_WITH_WRONG_RECEIVER + ResolutionStatus.SUCCESS -> Code.AMBIGUITY + ResolutionStatus.INCOMPLETE_TYPE_INFERENCE -> Code.INCOMPLETE_TYPE_INFERENCE + else -> Code.MANY_FAILED_CANDIDATES + } } - -class AllCandidates(private val allCandidates: Collection>): NameNotFoundResolutionResult() { +class AllCandidates(private val allCandidates: Collection>) : NameNotFoundResolutionResult() { override fun getAllCandidates() = allCandidates } \ No newline at end of file diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/DataFlowValueFactory.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/DataFlowValueFactory.kt index ab62698ef55..523d6d8eee5 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/DataFlowValueFactory.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/DataFlowValueFactory.kt @@ -54,12 +54,12 @@ object DataFlowValueFactory { @JvmStatic fun createDataFlowValue( - expression: KtExpression, - type: KotlinType, - resolutionContext: ResolutionContext<*> + expression: KtExpression, + type: KotlinType, + resolutionContext: ResolutionContext<*> ) = createDataFlowValue(expression, type, resolutionContext.trace.bindingContext, resolutionContext.scope.ownerDescriptor) - private fun isComplexExpression(expression: KtExpression): Boolean = when(expression) { + private fun isComplexExpression(expression: KtExpression): Boolean = when (expression) { is KtBlockExpression, is KtIfExpression, is KtWhenExpression -> true is KtBinaryExpression -> expression.operationToken === KtTokens.ELVIS is KtParenthesizedExpression -> { @@ -71,10 +71,10 @@ object DataFlowValueFactory { @JvmStatic fun createDataFlowValue( - expression: KtExpression, - type: KotlinType, - bindingContext: BindingContext, - containingDeclarationOrModule: DeclarationDescriptor + expression: KtExpression, + type: KotlinType, + bindingContext: BindingContext, + containingDeclarationOrModule: DeclarationDescriptor ): DataFlowValue { if (expression is KtConstantExpression) { if (expression.node.elementType === KtNodeTypes.NULL) { @@ -92,9 +92,11 @@ object DataFlowValueFactory { // // But there are some problem with types built on type parameters, e.g. // fun foo(x: T) = x!!.hashCode() // there no way in type system to denote that `x!!` is not nullable - return DataFlowValue(ExpressionIdentifierInfo(expression), - type, - Nullability.NOT_NULL) + return DataFlowValue( + ExpressionIdentifierInfo(expression), + type, + Nullability.NOT_NULL + ) } if (isComplexExpression(expression)) { @@ -110,39 +112,44 @@ object DataFlowValueFactory { @JvmStatic fun createDataFlowValue( - receiverValue: ReceiverValue, - resolutionContext: ResolutionContext<*> + receiverValue: ReceiverValue, + resolutionContext: ResolutionContext<*> ) = createDataFlowValue(receiverValue, resolutionContext.trace.bindingContext, resolutionContext.scope.ownerDescriptor) @JvmStatic fun createDataFlowValue( - receiverValue: ReceiverValue, - bindingContext: BindingContext, - containingDeclarationOrModule: DeclarationDescriptor + receiverValue: ReceiverValue, + bindingContext: BindingContext, + containingDeclarationOrModule: DeclarationDescriptor ) = when (receiverValue) { is TransientReceiver, is ImplicitReceiver -> createDataFlowValueForStableReceiver(receiverValue) - is ExpressionReceiver -> createDataFlowValue(receiverValue.expression, - receiverValue.getType(), - bindingContext, - containingDeclarationOrModule) + is ExpressionReceiver -> createDataFlowValue( + receiverValue.expression, + receiverValue.getType(), + bindingContext, + containingDeclarationOrModule + ) else -> throw UnsupportedOperationException("Unsupported receiver value: " + receiverValue::class.java.name) } @JvmStatic fun createDataFlowValueForProperty( - property: KtProperty, - variableDescriptor: VariableDescriptor, - bindingContext: BindingContext, - usageContainingModule: ModuleDescriptor? - ) = DataFlowValue(IdentifierInfo.Variable(variableDescriptor, - variableKind(variableDescriptor, usageContainingModule, - bindingContext, property), - bindingContext[BOUND_INITIALIZER_VALUE, variableDescriptor]), - variableDescriptor.type) + property: KtProperty, + variableDescriptor: VariableDescriptor, + bindingContext: BindingContext, + usageContainingModule: ModuleDescriptor? + ) = DataFlowValue( + IdentifierInfo.Variable( + variableDescriptor, + variableKind(variableDescriptor, usageContainingModule, bindingContext, property), + bindingContext[BOUND_INITIALIZER_VALUE, variableDescriptor] + ), + variableDescriptor.type + ) private fun createDataFlowValueForComplexExpression( - expression: KtExpression, - type: KotlinType + expression: KtExpression, + type: KotlinType ) = DataFlowValue(ExpressionIdentifierInfo(expression, stableComplex = true), type) // For only ++ and -- postfix operations @@ -155,7 +162,7 @@ object DataFlowValueFactory { class ExpressionIdentifierInfo(val expression: KtExpression, stableComplex: Boolean = false) : IdentifierInfo { override val kind = if (stableComplex) STABLE_COMPLEX_EXPRESSION else OTHER - + override fun equals(other: Any?) = other is ExpressionIdentifierInfo && expression == other.expression override fun hashCode() = expression.hashCode() @@ -164,17 +171,16 @@ object DataFlowValueFactory { } private fun postfix(argumentInfo: IdentifierInfo, op: KtToken) = - if (argumentInfo == IdentifierInfo.NO) { - IdentifierInfo.NO - } - else { - PostfixIdentifierInfo(argumentInfo, op) - } + if (argumentInfo == IdentifierInfo.NO) { + IdentifierInfo.NO + } else { + PostfixIdentifierInfo(argumentInfo, op) + } private fun getIdForStableIdentifier( - expression: KtExpression?, - bindingContext: BindingContext, - containingDeclarationOrModule: DeclarationDescriptor + expression: KtExpression?, + bindingContext: BindingContext, + containingDeclarationOrModule: DeclarationDescriptor ): IdentifierInfo { if (expression != null) { val deparenthesized = KtPsiUtil.deparenthesize(expression) @@ -189,8 +195,10 @@ object DataFlowValueFactory { val receiverInfo = getIdForStableIdentifier(receiverExpression, bindingContext, containingDeclarationOrModule) val selectorInfo = getIdForStableIdentifier(selectorExpression, bindingContext, containingDeclarationOrModule) - IdentifierInfo.qualified(receiverInfo, bindingContext.getType(receiverExpression), - selectorInfo, expression.operationSign === KtTokens.SAFE_ACCESS) + IdentifierInfo.qualified( + receiverInfo, bindingContext.getType(receiverExpression), + selectorInfo, expression.operationSign === KtTokens.SAFE_ACCESS + ) } is KtBinaryExpressionWithTypeRHS -> { val subjectExpression = expression.left @@ -198,11 +206,12 @@ object DataFlowValueFactory { val operationToken = expression.operationReference.getReferencedNameElementType() if (operationToken == KtTokens.IS_KEYWORD || operationToken == KtTokens.AS_KEYWORD) { IdentifierInfo.NO - } - else { - IdentifierInfo.SafeCast(getIdForStableIdentifier(subjectExpression, bindingContext, containingDeclarationOrModule), - bindingContext.getType(subjectExpression), - bindingContext[BindingContext.TYPE, targetTypeReference]) + } else { + IdentifierInfo.SafeCast( + getIdForStableIdentifier(subjectExpression, bindingContext, containingDeclarationOrModule), + bindingContext.getType(subjectExpression), + bindingContext[BindingContext.TYPE, targetTypeReference] + ) } } is KtSimpleNameExpression -> @@ -214,10 +223,11 @@ object DataFlowValueFactory { is KtPostfixExpression -> { val operationType = expression.operationReference.getReferencedNameElementType() if (operationType === KtTokens.PLUSPLUS || operationType === KtTokens.MINUSMINUS) { - postfix(getIdForStableIdentifier(expression.baseExpression, bindingContext, containingDeclarationOrModule), - operationType) - } - else { + postfix( + getIdForStableIdentifier(expression.baseExpression, bindingContext, containingDeclarationOrModule), + operationType + ) + } else { IdentifierInfo.NO } } @@ -226,9 +236,9 @@ object DataFlowValueFactory { } private fun getIdForSimpleNameExpression( - simpleNameExpression: KtSimpleNameExpression, - bindingContext: BindingContext, - containingDeclarationOrModule: DeclarationDescriptor + simpleNameExpression: KtSimpleNameExpression, + bindingContext: BindingContext, + containingDeclarationOrModule: DeclarationDescriptor ): IdentifierInfo { val declarationDescriptor = bindingContext.get(REFERENCE_TARGET, simpleNameExpression) return when (declarationDescriptor) { @@ -240,24 +250,25 @@ object DataFlowValueFactory { // for now it fails for resolving 'invoke' convention, return it after 'invoke' algorithm changes // assert resolvedCall != null : "Cannot create right identifier info if the resolved call is not known yet for val usageModuleDescriptor = DescriptorUtils.getContainingModuleOrNull(containingDeclarationOrModule) - val selectorInfo = IdentifierInfo.Variable(declarationDescriptor, - variableKind(declarationDescriptor, usageModuleDescriptor, - bindingContext, simpleNameExpression), - bindingContext[BOUND_INITIALIZER_VALUE, declarationDescriptor]) + val selectorInfo = IdentifierInfo.Variable( + declarationDescriptor, + variableKind(declarationDescriptor, usageModuleDescriptor, bindingContext, simpleNameExpression), + bindingContext[BOUND_INITIALIZER_VALUE, declarationDescriptor] + ) val implicitReceiver = resolvedCall?.dispatchReceiver if (implicitReceiver == null) { selectorInfo - } - else { + } else { val receiverInfo = getIdForImplicitReceiver(implicitReceiver, simpleNameExpression) if (receiverInfo == null) { selectorInfo - } - else { - IdentifierInfo.qualified(receiverInfo, implicitReceiver.type, - selectorInfo, resolvedCall.call.isSafeCall()) + } else { + IdentifierInfo.qualified( + receiverInfo, implicitReceiver.type, + selectorInfo, resolvedCall.call.isSafeCall() + ) } } } @@ -267,17 +278,17 @@ object DataFlowValueFactory { } private fun getIdForImplicitReceiver(receiverValue: ReceiverValue?, expression: KtExpression?) = - when (receiverValue) { - is ImplicitReceiver -> getIdForThisReceiver(receiverValue.declarationDescriptor) - is TransientReceiver -> - throw AssertionError("Transient receiver is implicit for an explicit expression: $expression. Receiver: $receiverValue") - else -> null - } + when (receiverValue) { + is ImplicitReceiver -> getIdForThisReceiver(receiverValue.declarationDescriptor) + is TransientReceiver -> + throw AssertionError("Transient receiver is implicit for an explicit expression: $expression. Receiver: $receiverValue") + else -> null + } private fun getIdForThisReceiver(descriptorOfThisReceiver: DeclarationDescriptor?) = when (descriptorOfThisReceiver) { is CallableDescriptor -> { val receiverParameter = descriptorOfThisReceiver.extensionReceiverParameter - ?: error("'This' refers to the callable member without a receiver parameter: $descriptorOfThisReceiver") + ?: error("'This' refers to the callable member without a receiver parameter: $descriptorOfThisReceiver") IdentifierInfo.Receiver(receiverParameter.value) } is ClassDescriptor -> IdentifierInfo.Receiver(descriptorOfThisReceiver.thisAsReceiverParameter.value) @@ -285,13 +296,13 @@ object DataFlowValueFactory { } private fun isAccessedInsideClosure( - variableContainingDeclaration: DeclarationDescriptor, - bindingContext: BindingContext, - accessElement: KtElement + variableContainingDeclaration: DeclarationDescriptor, + bindingContext: BindingContext, + accessElement: KtElement ): Boolean { val parent = ControlFlowInformationProvider.getElementParentDeclaration(accessElement) return if (parent != null) - // Access is at the same declaration: not in closure, lower: in closure + // Access is at the same declaration: not in closure, lower: in closure ControlFlowInformationProvider.getDeclarationDescriptorIncludingConstructors(bindingContext, parent) != variableContainingDeclaration else @@ -299,9 +310,9 @@ object DataFlowValueFactory { } private fun hasNoWritersInClosures( - variableContainingDeclaration: DeclarationDescriptor, - writers: Set, - bindingContext: BindingContext + variableContainingDeclaration: DeclarationDescriptor, + writers: Set, + bindingContext: BindingContext ): Boolean { return writers.none { (_, writerDeclaration) -> val writerDescriptor = writerDeclaration?.let { @@ -312,24 +323,25 @@ object DataFlowValueFactory { } private fun isAccessedInsideClosureAfterAllWriters( - writers: Set, - accessElement: KtElement + writers: Set, + accessElement: KtElement ): Boolean { val parent = ControlFlowInformationProvider.getElementParentDeclaration(accessElement) ?: return false return writers.none { (assignment) -> !assignment.before(parent) } } private fun isAccessedBeforeAllClosureWriters( - variableContainingDeclaration: DeclarationDescriptor, - writers: Set, - bindingContext: BindingContext, - accessElement: KtElement + variableContainingDeclaration: DeclarationDescriptor, + writers: Set, + bindingContext: BindingContext, + accessElement: KtElement ): Boolean { // All writers should be before access element, with the exception: // writer which is the same with declaration site does not count writers.mapNotNull { it.declaration }.forEach { writerDeclaration -> val writerDescriptor = ControlFlowInformationProvider.getDeclarationDescriptorIncludingConstructors( - bindingContext, writerDeclaration) + bindingContext, writerDeclaration + ) // Access is after some writerDeclaration if (variableContainingDeclaration != writerDescriptor && !accessElement.before(writerDeclaration)) { return false @@ -353,10 +365,10 @@ object DataFlowValueFactory { } private fun variableKind( - variableDescriptor: VariableDescriptor, - usageModule: ModuleDescriptor?, - bindingContext: BindingContext, - accessElement: KtElement + variableDescriptor: VariableDescriptor, + usageModule: ModuleDescriptor?, + bindingContext: BindingContext, + accessElement: KtElement ): Kind { if (variableDescriptor is PropertyDescriptor) { return propertyKind(variableDescriptor, usageModule) @@ -367,8 +379,8 @@ object DataFlowValueFactory { // Local variable classification: STABLE or CAPTURED val preliminaryVisitor = PreliminaryDeclarationVisitor.getVisitorByVariable(variableDescriptor, bindingContext) - // A case when we just analyse an expression alone: counts as captured - ?: return CAPTURED_VARIABLE + // A case when we just analyse an expression alone: counts as captured + ?: return CAPTURED_VARIABLE // Analyze who writes variable // If there is no writer: stable @@ -380,11 +392,10 @@ object DataFlowValueFactory { if (isAccessedInsideClosure(variableContainingDeclaration, bindingContext, accessElement)) { // stable iff we have no writers in closures AND this closure is AFTER all writers return if (preliminaryVisitor.languageVersionSettings.supportsFeature(LanguageFeature.CapturedInClosureSmartCasts) && - hasNoWritersInClosures(variableContainingDeclaration, writers, bindingContext) && - isAccessedInsideClosureAfterAllWriters(writers, accessElement)) { + hasNoWritersInClosures(variableContainingDeclaration, writers, bindingContext) && + isAccessedInsideClosureAfterAllWriters(writers, accessElement)) { STABLE_VARIABLE - } - else { + } else { CAPTURED_VARIABLE } } @@ -415,8 +426,8 @@ object DataFlowValueFactory { * @return true if variable is stable, false otherwise */ fun isStableValue( - variableDescriptor: VariableDescriptor, - usageModule: ModuleDescriptor? + variableDescriptor: VariableDescriptor, + usageModule: ModuleDescriptor? ): Boolean { if (variableDescriptor.isVar) return false return variableDescriptor !is PropertyDescriptor || propertyKind(variableDescriptor, usageModule) === STABLE_VALUE diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/ExplicitSmartCasts.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/ExplicitSmartCasts.kt index dc461b392c0..e17639c6f68 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/ExplicitSmartCasts.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/ExplicitSmartCasts.kt @@ -33,8 +33,8 @@ data class SingleSmartCast(val call: Call?, val type: KotlinType) : ExplicitSmar override val defaultType: KotlinType get() = type override fun plus(smartCast: SingleSmartCast) = - if (this == smartCast) this - else MultipleSmartCasts(mapOf(call to type, smartCast.call to smartCast.type)) + if (this == smartCast) this + else MultipleSmartCasts(mapOf(call to type, smartCast.call to smartCast.type)) } data class MultipleSmartCasts internal constructor(val map: Map) : ExplicitSmartCasts { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/IdentifierInfo.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/IdentifierInfo.kt index b892a3a0397..d018bf46e00 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/IdentifierInfo.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/IdentifierInfo.kt @@ -42,9 +42,9 @@ interface IdentifierInfo { } class Variable( - val variable: VariableDescriptor, - override val kind: DataFlowValue.Kind, - val bound: DataFlowValue? + val variable: VariableDescriptor, + override val kind: DataFlowValue.Kind, + val bound: DataFlowValue? ) : IdentifierInfo { override val canBeBound @@ -72,10 +72,10 @@ interface IdentifierInfo { } class Qualified( - val receiverInfo: IdentifierInfo, - val selectorInfo: IdentifierInfo, - val safe: Boolean, - val receiverType: KotlinType? + val receiverInfo: IdentifierInfo, + val selectorInfo: IdentifierInfo, + val safe: Boolean, + val receiverType: KotlinType? ) : IdentifierInfo { override val kind: DataFlowValue.Kind get() = if (receiverInfo.kind == STABLE_VALUE) selectorInfo.kind else OTHER @@ -90,9 +90,9 @@ interface IdentifierInfo { } data class SafeCast( - val subjectInfo: IdentifierInfo, - val subjectType: KotlinType?, - val targetType: KotlinType? + val subjectInfo: IdentifierInfo, + val subjectType: KotlinType?, + val targetType: KotlinType? ) : IdentifierInfo { override val kind get() = OTHER @@ -104,10 +104,10 @@ interface IdentifierInfo { companion object { fun qualified( - receiverInfo: IdentifierInfo, - receiverType: KotlinType?, - selectorInfo: IdentifierInfo, - safe: Boolean + receiverInfo: IdentifierInfo, + receiverType: KotlinType?, + selectorInfo: IdentifierInfo, + safe: Boolean ) = when (receiverInfo) { NO -> NO is PackageOrClass -> selectorInfo diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/ImplicitSmartCasts.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/ImplicitSmartCasts.kt index 43503036c2c..3ecea146cfa 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/ImplicitSmartCasts.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/ImplicitSmartCasts.kt @@ -22,5 +22,5 @@ import org.jetbrains.kotlin.types.KotlinType data class ImplicitSmartCasts private constructor(val receiverTypes: Map) { operator fun plus(other: ImplicitSmartCasts) = ImplicitSmartCasts(receiverTypes + other.receiverTypes) - constructor(receiver: ImplicitReceiver, type: KotlinType): this(mapOf(receiver to type)) + constructor(receiver: ImplicitReceiver, type: KotlinType) : this(mapOf(receiver to type)) } \ No newline at end of file diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/SmartCastManager.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/SmartCastManager.kt index 95858594b2b..2419a6817e5 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/SmartCastManager.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/SmartCastManager.kt @@ -37,14 +37,15 @@ import java.util.* class SmartCastManager { fun getSmartCastVariants( - receiverToCast: ReceiverValue, - bindingContext: BindingContext, - containingDeclarationOrModule: DeclarationDescriptor, - dataFlowInfo: DataFlowInfo, - languageVersionSettings: LanguageVersionSettings + receiverToCast: ReceiverValue, + bindingContext: BindingContext, + containingDeclarationOrModule: DeclarationDescriptor, + dataFlowInfo: DataFlowInfo, + languageVersionSettings: LanguageVersionSettings ): List { val variants = getSmartCastVariantsExcludingReceiver( - bindingContext, containingDeclarationOrModule, dataFlowInfo, receiverToCast, languageVersionSettings) + bindingContext, containingDeclarationOrModule, dataFlowInfo, receiverToCast, languageVersionSettings + ) val result = ArrayList(variants.size + 1) result.add(receiverToCast.type) result.addAll(variants) @@ -55,34 +56,36 @@ class SmartCastManager { * @return variants @param receiverToCast may be cast to according to context dataFlowInfo, receiverToCast itself is NOT included */ fun getSmartCastVariantsExcludingReceiver( - context: ResolutionContext<*>, - receiverToCast: ReceiverValue + context: ResolutionContext<*>, + receiverToCast: ReceiverValue ): Collection { - return getSmartCastVariantsExcludingReceiver(context.trace.bindingContext, - context.scope.ownerDescriptor, - context.dataFlowInfo, - receiverToCast, - context.languageVersionSettings) + return getSmartCastVariantsExcludingReceiver( + context.trace.bindingContext, + context.scope.ownerDescriptor, + context.dataFlowInfo, + receiverToCast, + context.languageVersionSettings + ) } /** * @return variants @param receiverToCast may be cast to according to @param dataFlowInfo, @param receiverToCast itself is NOT included */ private fun getSmartCastVariantsExcludingReceiver( - bindingContext: BindingContext, - containingDeclarationOrModule: DeclarationDescriptor, - dataFlowInfo: DataFlowInfo, - receiverToCast: ReceiverValue, - languageVersionSettings: LanguageVersionSettings + bindingContext: BindingContext, + containingDeclarationOrModule: DeclarationDescriptor, + dataFlowInfo: DataFlowInfo, + receiverToCast: ReceiverValue, + languageVersionSettings: LanguageVersionSettings ): Collection { val dataFlowValue = DataFlowValueFactory.createDataFlowValue(receiverToCast, bindingContext, containingDeclarationOrModule) return dataFlowInfo.getCollectedTypes(dataFlowValue, languageVersionSettings) } fun getSmartCastReceiverResult( - receiverArgument: ReceiverValue, - receiverParameterType: KotlinType, - context: ResolutionContext<*> + receiverArgument: ReceiverValue, + receiverParameterType: KotlinType, + context: ResolutionContext<*> ): ReceiverSmartCastResult? { getSmartCastReceiverResultWithGivenNullability(receiverArgument, receiverParameterType, context)?.let { return it @@ -96,19 +99,19 @@ class SmartCastManager { } private fun getSmartCastReceiverResultWithGivenNullability( - receiverArgument: ReceiverValue, - receiverParameterType: KotlinType, - context: ResolutionContext<*> + receiverArgument: ReceiverValue, + receiverParameterType: KotlinType, + context: ResolutionContext<*> ): ReceiverSmartCastResult? = - when { - ArgumentTypeResolver.isSubtypeOfForArgumentType(receiverArgument.type, receiverParameterType) -> - ReceiverSmartCastResult.OK - getSmartCastVariantsExcludingReceiver(context, receiverArgument).any { - ArgumentTypeResolver.isSubtypeOfForArgumentType(it, receiverParameterType) - } -> - ReceiverSmartCastResult.SMARTCAST_NEEDED_OR_NOT_NULL_EXPECTED - else -> null - } + when { + ArgumentTypeResolver.isSubtypeOfForArgumentType(receiverArgument.type, receiverParameterType) -> + ReceiverSmartCastResult.OK + getSmartCastVariantsExcludingReceiver(context, receiverArgument).any { + ArgumentTypeResolver.isSubtypeOfForArgumentType(it, receiverParameterType) + } -> + ReceiverSmartCastResult.SMARTCAST_NEEDED_OR_NOT_NULL_EXPECTED + else -> null + } enum class ReceiverSmartCastResult { OK, @@ -118,12 +121,12 @@ class SmartCastManager { companion object { private fun recordCastOrError( - expression: KtExpression, - type: KotlinType, - trace: BindingTrace, - dataFlowValue: DataFlowValue, - call: Call?, - recordExpressionType: Boolean + expression: KtExpression, + type: KotlinType, + trace: BindingTrace, + dataFlowValue: DataFlowValue, + call: Call?, + recordExpressionType: Boolean ) { if (KotlinBuiltIns.isNullableNothing(type)) return if (dataFlowValue.isStable) { @@ -141,39 +144,39 @@ class SmartCastManager { //Why the expression type is rewritten for receivers and is not rewritten for arguments? Is it necessary? trace.recordType(expression, type) } - } - else { + } else { trace.report(SMARTCAST_IMPOSSIBLE.on(expression, type, expression.text, dataFlowValue.kind.description)) } } fun checkAndRecordPossibleCast( - dataFlowValue: DataFlowValue, - expectedType: KotlinType, - expression: KtExpression?, - c: ResolutionContext<*>, - call: Call?, - recordExpressionType: Boolean + dataFlowValue: DataFlowValue, + expectedType: KotlinType, + expression: KtExpression?, + c: ResolutionContext<*>, + call: Call?, + recordExpressionType: Boolean ): SmartCastResult? { return checkAndRecordPossibleCast(dataFlowValue, expectedType, null, expression, c, call, recordExpressionType) } fun checkAndRecordPossibleCast( - dataFlowValue: DataFlowValue, - expectedType: KotlinType, - additionalPredicate: ((KotlinType) -> Boolean)?, - expression: KtExpression?, - c: ResolutionContext<*>, - call: Call?, - recordExpressionType: Boolean + dataFlowValue: DataFlowValue, + expectedType: KotlinType, + additionalPredicate: ((KotlinType) -> Boolean)?, + expression: KtExpression?, + c: ResolutionContext<*>, + call: Call?, + recordExpressionType: Boolean ): SmartCastResult? { val calleeExpression = call?.calleeExpression for (possibleType in c.dataFlowInfo.getCollectedTypes(dataFlowValue, c.languageVersionSettings)) { - if (ArgumentTypeResolver.isSubtypeOfForArgumentType(possibleType, expectedType) && (additionalPredicate == null || additionalPredicate(possibleType))) { + if (ArgumentTypeResolver.isSubtypeOfForArgumentType(possibleType, expectedType) && + (additionalPredicate == null || additionalPredicate(possibleType)) + ) { if (expression != null) { recordCastOrError(expression, possibleType, c.trace, dataFlowValue, call, recordExpressionType) - } - else if (calleeExpression != null && dataFlowValue.isStable) { + } else if (calleeExpression != null && dataFlowValue.isStable) { val receiver = (dataFlowValue.identifierInfo as? IdentifierInfo.Receiver)?.value if (receiver is ImplicitReceiver) { val oldSmartCasts = c.trace[IMPLICIT_RECEIVER_SMARTCAST, calleeExpression] @@ -181,8 +184,10 @@ class SmartCastManager { if (oldSmartCasts != null) { val oldType = oldSmartCasts.receiverTypes[receiver] if (oldType != null && oldType != possibleType) { - throw AssertionError("Rewriting key $receiver for implicit smart cast on ${calleeExpression.text}: " + - "was $oldType, now $possibleType") + throw AssertionError( + "Rewriting key $receiver for implicit smart cast on ${calleeExpression.text}: " + + "was $oldType, now $possibleType" + ) } } c.trace.record(IMPLICIT_RECEIVER_SMARTCAST, calleeExpression, @@ -211,7 +216,9 @@ class SmartCastManager { val immanentlyNotNull = !dataFlowValue.immanentNullability.canBeNull() val nullableExpectedType = TypeUtils.makeNullable(expectedType) - if (ArgumentTypeResolver.isSubtypeOfForArgumentType(dataFlowValue.type, nullableExpectedType) && (additionalPredicate == null || additionalPredicate(dataFlowValue.type))) { + if (ArgumentTypeResolver.isSubtypeOfForArgumentType(dataFlowValue.type, nullableExpectedType) && + (additionalPredicate == null || additionalPredicate(dataFlowValue.type)) + ) { if (!immanentlyNotNull && expression != null) { recordCastOrError(expression, dataFlowValue.type, c.trace, dataFlowValue, call, recordExpressionType) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tasks/TracingStrategyForImplicitConstructorDelegationCall.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tasks/TracingStrategyForImplicitConstructorDelegationCall.kt index 76a37bf73d6..223b2c5b69c 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tasks/TracingStrategyForImplicitConstructorDelegationCall.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tasks/TracingStrategyForImplicitConstructorDelegationCall.kt @@ -37,7 +37,7 @@ import org.jetbrains.kotlin.types.KotlinType class TracingStrategyForImplicitConstructorDelegationCall( - val delegationCall: KtConstructorDelegationCall, call: Call + val delegationCall: KtConstructorDelegationCall, call: Call ) : AbstractTracingStrategy(delegationCall.calleeExpression!!, call) { val calleeExpression = delegationCall.calleeExpression @@ -83,9 +83,7 @@ class TracingStrategyForImplicitConstructorDelegationCall( } private fun reportError(trace: BindingTrace) { - if (!trace.bindingContext.diagnostics.forElement(delegationCall). - any { it.factory == Errors.EXPLICIT_DELEGATION_CALL_REQUIRED } - ) { + if (!trace.bindingContext.diagnostics.forElement(delegationCall).any { it.factory == Errors.EXPLICIT_DELEGATION_CALL_REQUIRED }) { trace.report(Errors.EXPLICIT_DELEGATION_CALL_REQUIRED.on(delegationCall)) } } @@ -105,7 +103,7 @@ class TracingStrategyForImplicitConstructorDelegationCall( } override fun nestedClassAccessViaInstanceReference( - trace: BindingTrace, classDescriptor: ClassDescriptor, explicitReceiverKind: ExplicitReceiverKind + trace: BindingTrace, classDescriptor: ClassDescriptor, explicitReceiverKind: ExplicitReceiverKind ) { unexpectedError("nestedClassAccessViaInstanceReference") } @@ -118,7 +116,12 @@ class TracingStrategyForImplicitConstructorDelegationCall( unexpectedError("missingReceiver") } - override fun wrongReceiverType(trace: BindingTrace, receiverParameter: ReceiverParameterDescriptor, receiverArgument: ReceiverValue, c: ResolutionContext<*>) { + override fun wrongReceiverType( + trace: BindingTrace, + receiverParameter: ReceiverParameterDescriptor, + receiverArgument: ReceiverValue, + c: ResolutionContext<*> + ) { unexpectedError("wrongReceiverType") } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/KotlinResolutionStatelessCallbacksImpl.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/KotlinResolutionStatelessCallbacksImpl.kt index 14dea6aafb2..539532b60b4 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/KotlinResolutionStatelessCallbacksImpl.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/KotlinResolutionStatelessCallbacksImpl.kt @@ -31,30 +31,30 @@ import org.jetbrains.kotlin.resolve.calls.model.SimpleKotlinCallArgument import org.jetbrains.kotlin.utils.addToStdlib.safeAs class KotlinResolutionStatelessCallbacksImpl( - private val deprecationResolver: DeprecationResolver + private val deprecationResolver: DeprecationResolver ) : KotlinResolutionStatelessCallbacks { override fun isDescriptorFromSource(descriptor: CallableDescriptor) = - DescriptorToSourceUtils.descriptorToDeclaration(descriptor) != null + DescriptorToSourceUtils.descriptorToDeclaration(descriptor) != null override fun isInfixCall(kotlinCall: KotlinCall) = - kotlinCall is PSIKotlinCallImpl && isInfixCall(kotlinCall.psiCall) + kotlinCall is PSIKotlinCallImpl && isInfixCall(kotlinCall.psiCall) override fun isOperatorCall(kotlinCall: KotlinCall) = - (kotlinCall is PSIKotlinCallForInvoke) || - (kotlinCall is PSIKotlinCallImpl && isConventionCall(kotlinCall.psiCall)) + (kotlinCall is PSIKotlinCallForInvoke) || + (kotlinCall is PSIKotlinCallImpl && isConventionCall(kotlinCall.psiCall)) override fun isSuperOrDelegatingConstructorCall(kotlinCall: KotlinCall) = - kotlinCall is PSIKotlinCallImpl && isSuperOrDelegatingConstructorCall(kotlinCall.psiCall) + kotlinCall is PSIKotlinCallImpl && isSuperOrDelegatingConstructorCall(kotlinCall.psiCall) override fun isHiddenInResolution(descriptor: DeclarationDescriptor, kotlinCall: KotlinCall) = - deprecationResolver.isHiddenInResolution(descriptor, isSuperOrDelegatingConstructorCall(kotlinCall)) + deprecationResolver.isHiddenInResolution(descriptor, isSuperOrDelegatingConstructorCall(kotlinCall)) override fun isSuperExpression(receiver: SimpleKotlinCallArgument?): Boolean = - receiver?.psiExpression is KtSuperExpression + receiver?.psiExpression is KtSuperExpression override fun getScopeTowerForCallableReferenceArgument(argument: CallableReferenceKotlinCallArgument): ImplicitScopeTower = - (argument as CallableReferenceKotlinCallArgumentImpl).scopeTowerForResolution + (argument as CallableReferenceKotlinCallArgumentImpl).scopeTowerForResolution override fun getVariableCandidateIfInvoke(functionCall: KotlinCall) = - functionCall.safeAs()?.variableCall + functionCall.safeAs()?.variableCall } 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 382c3bb9bd3..7156bda5fa9 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 @@ -61,16 +61,16 @@ import java.util.* class KotlinToResolvedCallTransformer( - private val callCheckers: Iterable, - private val languageFeatureSettings: LanguageVersionSettings, - private val dataFlowAnalyzer: DataFlowAnalyzer, - private val argumentTypeResolver: ArgumentTypeResolver, - private val constantExpressionEvaluator: ConstantExpressionEvaluator, - private val deprecationResolver: DeprecationResolver, - private val expressionTypingServices: ExpressionTypingServices, - private val doubleColonExpressionResolver: DoubleColonExpressionResolver, - private val additionalDiagnosticReporter: AdditionalDiagnosticReporter, - private val effectSystem: EffectSystem + private val callCheckers: Iterable, + private val languageFeatureSettings: LanguageVersionSettings, + private val dataFlowAnalyzer: DataFlowAnalyzer, + private val argumentTypeResolver: ArgumentTypeResolver, + private val constantExpressionEvaluator: ConstantExpressionEvaluator, + private val deprecationResolver: DeprecationResolver, + private val expressionTypingServices: ExpressionTypingServices, + private val doubleColonExpressionResolver: DoubleColonExpressionResolver, + private val additionalDiagnosticReporter: AdditionalDiagnosticReporter, + private val effectSystem: EffectSystem ) { companion object { @@ -79,13 +79,13 @@ class KotlinToResolvedCallTransformer( } fun onlyTransform( - resolvedCallAtom: ResolvedCallAtom, - diagnostics: Collection + resolvedCallAtom: ResolvedCallAtom, + diagnostics: Collection ): ResolvedCall = transformToResolvedCall(resolvedCallAtom, null, null, diagnostics) fun transformAndReport( - baseResolvedCall: CallResolutionResult, - context: BasicCallResolutionContext + baseResolvedCall: CallResolutionResult, + context: BasicCallResolutionContext ): ResolvedCall { val candidate = baseResolvedCall.resultCallAtom!! when (baseResolvedCall.type) { @@ -102,9 +102,11 @@ class KotlinToResolvedCallTransformer( } CallResolutionResult.Type.ERROR, CallResolutionResult.Type.COMPLETED -> { val resultSubstitutor = baseResolvedCall.constraintSystem.buildResultingSubstitutor() - val ktPrimitiveCompleter = ResolvedAtomCompleter(resultSubstitutor, context.trace, context, this, - expressionTypingServices, argumentTypeResolver, doubleColonExpressionResolver, - languageFeatureSettings, deprecationResolver) + val ktPrimitiveCompleter = ResolvedAtomCompleter( + resultSubstitutor, context.trace, context, this, + expressionTypingServices, argumentTypeResolver, doubleColonExpressionResolver, + languageFeatureSettings, deprecationResolver + ) for (subKtPrimitive in candidate.subResolvedAtoms) { ktPrimitiveCompleter.completeAll(subKtPrimitive) @@ -117,9 +119,9 @@ class KotlinToResolvedCallTransformer( } fun createStubResolvedCallAndWriteItToTrace( - candidate: ResolvedCallAtom, - trace: BindingTrace, - diagnostics: Collection + candidate: ResolvedCallAtom, + trace: BindingTrace, + diagnostics: Collection ): ResolvedCall { val result = transformToResolvedCall(candidate, trace, null, diagnostics) val psiKotlinCall = candidate.atom.psiKotlinCall @@ -131,33 +133,32 @@ class KotlinToResolvedCallTransformer( } fun transformToResolvedCall( - completedCallAtom: ResolvedCallAtom, - trace: BindingTrace?, - resultSubstitutor: NewTypeSubstitutor? = null, // if substitutor is not null, it means that this call is completed - diagnostics: Collection + completedCallAtom: ResolvedCallAtom, + trace: BindingTrace?, + resultSubstitutor: NewTypeSubstitutor? = null, // if substitutor is not null, it means that this call is completed + diagnostics: Collection ): ResolvedCall { val psiKotlinCall = completedCallAtom.atom.psiKotlinCall return if (psiKotlinCall is PSIKotlinCallForInvoke) { @Suppress("UNCHECKED_CAST") NewVariableAsFunctionResolvedCallImpl( - createOrGet(psiKotlinCall.variableCall.resolvedCall, trace, resultSubstitutor, diagnostics), - createOrGet(completedCallAtom, trace, resultSubstitutor, diagnostics) + createOrGet(psiKotlinCall.variableCall.resolvedCall, trace, resultSubstitutor, diagnostics), + createOrGet(completedCallAtom, trace, resultSubstitutor, diagnostics) ) as ResolvedCall - } - else { + } else { createOrGet(completedCallAtom, trace, resultSubstitutor, diagnostics) } } private fun createOrGet( - completedSimpleAtom: ResolvedCallAtom, - trace: BindingTrace?, - resultSubstitutor: NewTypeSubstitutor?, - diagnostics: Collection + completedSimpleAtom: ResolvedCallAtom, + trace: BindingTrace?, + resultSubstitutor: NewTypeSubstitutor?, + diagnostics: Collection ): NewResolvedCallImpl { if (trace != null) { - val storedResolvedCall = completedSimpleAtom.atom.psiKotlinCall.psiCall.getResolvedCall(trace.bindingContext)?. - safeAs>() + val storedResolvedCall = + completedSimpleAtom.atom.psiKotlinCall.psiCall.getResolvedCall(trace.bindingContext)?.safeAs>() if (storedResolvedCall != null) { storedResolvedCall.setResultingSubstitutor(resultSubstitutor) storedResolvedCall.updateDiagnostics(diagnostics) @@ -173,8 +174,8 @@ class KotlinToResolvedCallTransformer( else resolvedCall.call.calleeExpression val reportOn = - if (calleeExpression != null && !calleeExpression.isFakeElement) calleeExpression - else resolvedCall.call.callElement + if (calleeExpression != null && !calleeExpression.isFakeElement) calleeExpression + else resolvedCall.call.callElement for (callChecker in callCheckers) { callChecker.check(resolvedCall, reportOn, callCheckerContext) @@ -187,24 +188,25 @@ class KotlinToResolvedCallTransformer( // todo very beginning code fun runArgumentsChecks( - context: BasicCallResolutionContext, - trace: BindingTrace, - resolvedCall: NewResolvedCallImpl<*> + context: BasicCallResolutionContext, + trace: BindingTrace, + resolvedCall: NewResolvedCallImpl<*> ) { for (valueArgument in resolvedCall.call.valueArguments) { val argumentMapping = resolvedCall.getArgumentMapping(valueArgument!!) val (expectedType, callPosition) = when (argumentMapping) { is ArgumentMatch -> Pair( - getEffectiveExpectedType(argumentMapping.valueParameter, valueArgument, context), - CallPosition.ValueArgumentPosition(resolvedCall, argumentMapping.valueParameter, valueArgument)) + getEffectiveExpectedType(argumentMapping.valueParameter, valueArgument, context), + CallPosition.ValueArgumentPosition(resolvedCall, argumentMapping.valueParameter, valueArgument) + ) else -> Pair(TypeUtils.NO_EXPECTED_TYPE, CallPosition.Unknown) } val newContext = - context.replaceDataFlowInfo(resolvedCall.dataFlowInfoForArguments.getInfo(valueArgument)) - .replaceExpectedType(expectedType) - .replaceCallPosition(callPosition) - .replaceBindingTrace(trace) + context.replaceDataFlowInfo(resolvedCall.dataFlowInfoForArguments.getInfo(valueArgument)) + .replaceExpectedType(expectedType) + .replaceCallPosition(callPosition) + .replaceBindingTrace(trace) // todo external argument @@ -215,9 +217,9 @@ class KotlinToResolvedCallTransformer( } fun updateRecordedType( - expression: KtExpression, - context: BasicCallResolutionContext, - reportErrorForTypeMismatch: Boolean + expression: KtExpression, + context: BasicCallResolutionContext, + reportErrorForTypeMismatch: Boolean ): KotlinType? { val deparenthesized = expression.let { KtPsiUtil.getLastElementDeparenthesized(it, context.statementFilter) @@ -242,17 +244,17 @@ class KotlinToResolvedCallTransformer( } private fun getResolvedCallForArgumentExpression(expression: KtExpression, context: BasicCallResolutionContext) = - if (!ExpressionTypingUtils.dependsOnExpectedType(expression)) - null - else - expression.getResolvedCall(context.trace.bindingContext) + if (!ExpressionTypingUtils.dependsOnExpectedType(expression)) + null + else + expression.getResolvedCall(context.trace.bindingContext) // See CallCompleter#updateRecordedTypeForArgument private fun updateRecordedTypeForArgument( - updatedType: KotlinType?, - recordedType: KotlinType?, - argumentExpression: KtExpression, - context: BasicCallResolutionContext + updatedType: KotlinType?, + recordedType: KotlinType?, + argumentExpression: KtExpression, + context: BasicCallResolutionContext ): KotlinType? { if ((!ErrorUtils.containsErrorType(recordedType) && recordedType == updatedType) || updatedType == null) return updatedType @@ -300,20 +302,20 @@ class KotlinToResolvedCallTransformer( } internal fun bindAndReport( - context: BasicCallResolutionContext, - trace: BindingTrace, - resolvedCall: ResolvedCall<*>, - diagnostics: Collection + context: BasicCallResolutionContext, + trace: BindingTrace, + resolvedCall: ResolvedCall<*>, + diagnostics: Collection ) { resolvedCall.safeAs>()?.let { bindAndReport(context, trace, it, diagnostics) } resolvedCall.safeAs()?.let { bindAndReport(context, trace, it, diagnostics) } } private fun bindAndReport( - context: BasicCallResolutionContext, - trace: BindingTrace, - simpleResolvedCall: NewResolvedCallImpl<*>, - diagnostics: Collection + context: BasicCallResolutionContext, + trace: BindingTrace, + simpleResolvedCall: NewResolvedCallImpl<*>, + diagnostics: Collection ) { val tracing = simpleResolvedCall.resolvedCallAtom.atom.psiKotlinCall.tracingStrategy @@ -324,10 +326,10 @@ class KotlinToResolvedCallTransformer( } private fun bindAndReport( - context: BasicCallResolutionContext, - trace: BindingTrace, - variableAsFunction: NewVariableAsFunctionResolvedCallImpl, - diagnostics: Collection + context: BasicCallResolutionContext, + trace: BindingTrace, + variableAsFunction: NewVariableAsFunctionResolvedCallImpl, + diagnostics: Collection ) { val outerTracingStrategy = variableAsFunction.baseCall.tracingStrategy val variableCall = variableAsFunction.variableCall @@ -342,15 +344,16 @@ class KotlinToResolvedCallTransformer( } private fun reportCallDiagnostic( - context: BasicCallResolutionContext, - trace: BindingTrace, - completedCallAtom: ResolvedCallAtom, - resultingDescriptor: CallableDescriptor, - diagnostics: Collection + context: BasicCallResolutionContext, + trace: BindingTrace, + completedCallAtom: ResolvedCallAtom, + resultingDescriptor: CallableDescriptor, + diagnostics: Collection ) { val trackingTrace = TrackingBindingTrace(trace) val newContext = context.replaceBindingTrace(trackingTrace) - val diagnosticReporter = DiagnosticReporterByTrackingStrategy(constantExpressionEvaluator, newContext, completedCallAtom.atom.psiKotlinCall) + val diagnosticReporter = + DiagnosticReporterByTrackingStrategy(constantExpressionEvaluator, newContext, completedCallAtom.atom.psiKotlinCall) val diagnosticHolder = KotlinDiagnosticsHolder.SimpleHolder() additionalDiagnosticReporter.reportAdditionalDiagnostics(completedCallAtom, resultingDescriptor, diagnosticHolder, diagnostics) @@ -362,7 +365,8 @@ class KotlinToResolvedCallTransformer( val dontRecordToTraceAsIs = diagnostic is ResolutionDiagnostic && diagnostic !is VisibilityError val shouldReportMissingDiagnostic = !trackingTrace.reported && !dontRecordToTraceAsIs if (shouldReportMissingDiagnostic && REPORT_MISSING_NEW_INFERENCE_DIAGNOSTIC) { - val factory = if (diagnostic.candidateApplicability.isSuccess) Errors.NEW_INFERENCE_DIAGNOSTIC else Errors.NEW_INFERENCE_ERROR + val factory = + if (diagnostic.candidateApplicability.isSuccess) Errors.NEW_INFERENCE_DIAGNOSTIC else Errors.NEW_INFERENCE_ERROR trace.report(factory.on(diagnosticReporter.psiKotlinCall.psiCall.callElement, "Missing diagnostic: $diagnostic")) } } @@ -382,7 +386,7 @@ class TrackingBindingTrace(val trace: BindingTrace) : BindingTrace by trace { } } -sealed class NewAbstractResolvedCall(): ResolvedCall { +sealed class NewAbstractResolvedCall() : ResolvedCall { abstract val argumentMappingByOriginal: Map abstract val kotlinCall: KotlinCall @@ -448,47 +452,47 @@ sealed class NewAbstractResolvedCall(): ResolvedCall } private fun argumentToParameterMap( - resultingDescriptor: CallableDescriptor, - valueArguments: Map + resultingDescriptor: CallableDescriptor, + valueArguments: Map ): Map = - LinkedHashMap().also { result -> - for (parameter in resultingDescriptor.valueParameters) { - val resolvedArgument = valueArguments[parameter] ?: continue - for (arguments in resolvedArgument.arguments) { - result[arguments] = ArgumentMatchImpl(parameter).apply { recordMatchStatus(ArgumentMatchStatus.SUCCESS) } - } + LinkedHashMap().also { result -> + for (parameter in resultingDescriptor.valueParameters) { + val resolvedArgument = valueArguments[parameter] ?: continue + for (arguments in resolvedArgument.arguments) { + result[arguments] = ArgumentMatchImpl(parameter).apply { recordMatchStatus(ArgumentMatchStatus.SUCCESS) } } } + } private fun createValueArguments(): Map = - LinkedHashMap().also { result -> - for ((originalParameter, resolvedCallArgument) in argumentMappingByOriginal) { - val resultingParameter = resultingDescriptor.valueParameters[originalParameter.index] - result[resultingParameter] = when (resolvedCallArgument) { - ResolvedCallArgument.DefaultArgument -> - DefaultValueArgument.DEFAULT - is ResolvedCallArgument.SimpleArgument -> { - val valueArgument = resolvedCallArgument.callArgument.psiCallArgument.valueArgument - if (resultingParameter.isVararg) - VarargValueArgument().apply { addArgument(valueArgument) } - else - ExpressionValueArgument(valueArgument) - } - is ResolvedCallArgument.VarargArgument -> - VarargValueArgument().apply { - resolvedCallArgument.arguments.map { it.psiCallArgument.valueArgument }.forEach { addArgument(it) } - } + LinkedHashMap().also { result -> + for ((originalParameter, resolvedCallArgument) in argumentMappingByOriginal) { + val resultingParameter = resultingDescriptor.valueParameters[originalParameter.index] + result[resultingParameter] = when (resolvedCallArgument) { + ResolvedCallArgument.DefaultArgument -> + DefaultValueArgument.DEFAULT + is ResolvedCallArgument.SimpleArgument -> { + val valueArgument = resolvedCallArgument.callArgument.psiCallArgument.valueArgument + if (resultingParameter.isVararg) + VarargValueArgument().apply { addArgument(valueArgument) } + else + ExpressionValueArgument(valueArgument) } + is ResolvedCallArgument.VarargArgument -> + VarargValueArgument().apply { + resolvedCallArgument.arguments.map { it.psiCallArgument.valueArgument }.forEach { addArgument(it) } + } } } + } } class NewResolvedCallImpl( - val resolvedCallAtom: ResolvedCallAtom, - substitutor: NewTypeSubstitutor?, - private var diagnostics: Collection -): NewAbstractResolvedCall() { + val resolvedCallAtom: ResolvedCallAtom, + substitutor: NewTypeSubstitutor?, + private var diagnostics: Collection +) : NewAbstractResolvedCall() { var isCompleted = false private set private lateinit var resultingDescriptor: D @@ -521,8 +525,8 @@ class NewResolvedCallImpl( fun updateExtensionReceiverWithSmartCastIfNeeded(smartCastExtensionReceiverType: KotlinType) { if (extensionReceiver is ImplicitClassReceiver) { extensionReceiver = CastImplicitClassReceiver( - (extensionReceiver as ImplicitClassReceiver).classDescriptor, - smartCastExtensionReceiverType + (extensionReceiver as ImplicitClassReceiver).classDescriptor, + smartCastExtensionReceiverType ) } } @@ -550,11 +554,12 @@ class NewResolvedCallImpl( when { candidateDescriptor is FunctionDescriptor || - (candidateDescriptor is PropertyDescriptor && (candidateDescriptor.typeParameters.isNotEmpty() || containsCapturedTypes)) -> + (candidateDescriptor is PropertyDescriptor && (candidateDescriptor.typeParameters.isNotEmpty() || containsCapturedTypes)) -> // this code is very suspicious. Now it is very useful for BE, because they cannot do nothing with captured types, // but it seems like temporary solution. candidateDescriptor.substitute(resolvedCallAtom.substitutor).substituteAndApproximateCapturedTypes( - substitutor ?: FreshVariableNewTypeSubstitutor.Empty) + substitutor ?: FreshVariableNewTypeSubstitutor.Empty + ) else -> candidateDescriptor } @@ -578,9 +583,9 @@ fun ResolutionCandidateApplicability.toResolutionStatus(): ResolutionStatus = wh } class NewVariableAsFunctionResolvedCallImpl( - override val variableCall: NewResolvedCallImpl, - override val functionCall: NewResolvedCallImpl -): VariableAsFunctionResolvedCall, ResolvedCall by functionCall { + override val variableCall: NewResolvedCallImpl, + override val functionCall: NewResolvedCallImpl +) : VariableAsFunctionResolvedCall, ResolvedCall by functionCall { val baseCall get() = functionCall.resolvedCallAtom.atom.psiKotlinCall.cast().baseCall } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/NewCallArguments.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/NewCallArguments.kt index 8b07e2f7d8b..1a058645832 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/NewCallArguments.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/NewCallArguments.kt @@ -35,9 +35,9 @@ import org.jetbrains.kotlin.types.expressions.KotlinTypeInfo import org.jetbrains.kotlin.utils.addToStdlib.safeAs class SimpleTypeArgumentImpl( - val typeReference: KtTypeReference, - override val type: UnwrappedType -): SimpleTypeArgument + val typeReference: KtTypeReference, + override val type: UnwrappedType +) : SimpleTypeArgument // all arguments should be inherited from this class. // But receivers is not, because for them there is no corresponding valueArgument @@ -51,30 +51,32 @@ abstract class PSIKotlinCallArgument : KotlinCallArgument { abstract class SimplePSIKotlinCallArgument : PSIKotlinCallArgument(), SimpleKotlinCallArgument -val KotlinCallArgument.psiCallArgument: PSIKotlinCallArgument get() { - assert(this is PSIKotlinCallArgument) { - "Incorrect KotlinCallArgument: $this. Java class: ${javaClass.canonicalName}" +val KotlinCallArgument.psiCallArgument: PSIKotlinCallArgument + get() { + assert(this is PSIKotlinCallArgument) { + "Incorrect KotlinCallArgument: $this. Java class: ${javaClass.canonicalName}" + } + return this as PSIKotlinCallArgument } - return this as PSIKotlinCallArgument -} -val KotlinCallArgument.psiExpression: KtExpression? get() { - return when (this) { - is ReceiverExpressionKotlinCallArgument -> receiver.receiverValue.safeAs()?.expression - is QualifierReceiverKotlinCallArgument -> receiver.safeAs()?.expression - else -> psiCallArgument.valueArgument.getArgumentExpression() +val KotlinCallArgument.psiExpression: KtExpression? + get() { + return when (this) { + is ReceiverExpressionKotlinCallArgument -> receiver.receiverValue.safeAs()?.expression + is QualifierReceiverKotlinCallArgument -> receiver.safeAs()?.expression + else -> psiCallArgument.valueArgument.getArgumentExpression() + } } -} class ParseErrorKotlinCallArgument( - override val valueArgument: ValueArgument, - override val dataFlowInfoAfterThisArgument: DataFlowInfo, - builtIns: KotlinBuiltIns -): ExpressionKotlinCallArgument, SimplePSIKotlinCallArgument() { + override val valueArgument: ValueArgument, + override val dataFlowInfoAfterThisArgument: DataFlowInfo, + builtIns: KotlinBuiltIns +) : ExpressionKotlinCallArgument, SimplePSIKotlinCallArgument() { override val receiver = ReceiverValueWithSmartCastInfo( - TransientReceiver(ErrorUtils.createErrorType("Error type for ParseError-argument $valueArgument")), - possibleTypes = emptySet(), - isStable = true + TransientReceiver(ErrorUtils.createErrorType("Error type for ParseError-argument $valueArgument")), + possibleTypes = emptySet(), + isStable = true ) override val isSafeCall: Boolean get() = false @@ -87,10 +89,10 @@ class ParseErrorKotlinCallArgument( } abstract class PSIFunctionKotlinCallArgument( - val outerCallContext: BasicCallResolutionContext, - override val valueArgument: ValueArgument, - override val dataFlowInfoBeforeThisArgument: DataFlowInfo, - override val argumentName: Name? + val outerCallContext: BasicCallResolutionContext, + override val valueArgument: ValueArgument, + override val dataFlowInfoBeforeThisArgument: DataFlowInfo, + override val argumentName: Name? ) : LambdaKotlinCallArgument, PSIKotlinCallArgument() { override val dataFlowInfoAfterThisArgument: DataFlowInfo // todo drop this and use only lambdaInitialDataFlowInfo get() = dataFlowInfoBeforeThisArgument @@ -101,78 +103,78 @@ abstract class PSIFunctionKotlinCallArgument( } class LambdaKotlinCallArgumentImpl( - outerCallContext: BasicCallResolutionContext, - valueArgument: ValueArgument, - dataFlowInfoBeforeThisArgument: DataFlowInfo, - argumentName: Name?, - val ktLambdaExpression: KtLambdaExpression, - val containingBlockForLambda: KtExpression, - override val parametersTypes: Array? + outerCallContext: BasicCallResolutionContext, + valueArgument: ValueArgument, + dataFlowInfoBeforeThisArgument: DataFlowInfo, + argumentName: Name?, + val ktLambdaExpression: KtLambdaExpression, + val containingBlockForLambda: KtExpression, + override val parametersTypes: Array? ) : PSIFunctionKotlinCallArgument(outerCallContext, valueArgument, dataFlowInfoBeforeThisArgument, argumentName) { override val ktFunction get() = ktLambdaExpression.functionLiteral override val expression get() = containingBlockForLambda } class FunctionExpressionImpl( - outerCallContext: BasicCallResolutionContext, - valueArgument: ValueArgument, - dataFlowInfoBeforeThisArgument: DataFlowInfo, - argumentName: Name?, - val containingBlockForFunction: KtExpression, - override val ktFunction: KtNamedFunction, - override val receiverType: UnwrappedType?, - override val parametersTypes: Array, - override val returnType: UnwrappedType? + outerCallContext: BasicCallResolutionContext, + valueArgument: ValueArgument, + dataFlowInfoBeforeThisArgument: DataFlowInfo, + argumentName: Name?, + val containingBlockForFunction: KtExpression, + override val ktFunction: KtNamedFunction, + override val receiverType: UnwrappedType?, + override val parametersTypes: Array, + override val returnType: UnwrappedType? ) : FunctionExpression, PSIFunctionKotlinCallArgument(outerCallContext, valueArgument, dataFlowInfoBeforeThisArgument, argumentName) { override val expression get() = containingBlockForFunction } class CallableReferenceKotlinCallArgumentImpl( - val scopeTowerForResolution: ImplicitScopeTower, - override val valueArgument: ValueArgument, - override val dataFlowInfoBeforeThisArgument: DataFlowInfo, - override val dataFlowInfoAfterThisArgument: DataFlowInfo, - val ktCallableReferenceExpression: KtCallableReferenceExpression, - override val argumentName: Name?, - override val lhsResult: LHSResult, - override val rhsName: Name + val scopeTowerForResolution: ImplicitScopeTower, + override val valueArgument: ValueArgument, + override val dataFlowInfoBeforeThisArgument: DataFlowInfo, + override val dataFlowInfoAfterThisArgument: DataFlowInfo, + val ktCallableReferenceExpression: KtCallableReferenceExpression, + override val argumentName: Name?, + override val lhsResult: LHSResult, + override val rhsName: Name ) : CallableReferenceKotlinCallArgument, PSIKotlinCallArgument() class CollectionLiteralKotlinCallArgumentImpl( - override val valueArgument: ValueArgument, - override val argumentName: Name?, - override val dataFlowInfoBeforeThisArgument: DataFlowInfo, - override val dataFlowInfoAfterThisArgument: DataFlowInfo, - val collectionLiteralExpression: KtCollectionLiteralExpression, - val outerCallContext: BasicCallResolutionContext + override val valueArgument: ValueArgument, + override val argumentName: Name?, + override val dataFlowInfoBeforeThisArgument: DataFlowInfo, + override val dataFlowInfoAfterThisArgument: DataFlowInfo, + val collectionLiteralExpression: KtCollectionLiteralExpression, + val outerCallContext: BasicCallResolutionContext ) : CollectionLiteralKotlinCallArgument, PSIKotlinCallArgument() { override val isSpread: Boolean get() = valueArgument.getSpreadElement() != null } class SubKotlinCallArgumentImpl( - override val valueArgument: ValueArgument, - override val dataFlowInfoBeforeThisArgument: DataFlowInfo, - override val dataFlowInfoAfterThisArgument: DataFlowInfo, - override val receiver: ReceiverValueWithSmartCastInfo, - override val callResult: CallResolutionResult -): SimplePSIKotlinCallArgument(), SubKotlinCallArgument { + override val valueArgument: ValueArgument, + override val dataFlowInfoBeforeThisArgument: DataFlowInfo, + override val dataFlowInfoAfterThisArgument: DataFlowInfo, + override val receiver: ReceiverValueWithSmartCastInfo, + override val callResult: CallResolutionResult +) : SimplePSIKotlinCallArgument(), SubKotlinCallArgument { override val isSpread: Boolean get() = valueArgument.getSpreadElement() != null override val argumentName: Name? get() = valueArgument.getArgumentName()?.asName override val isSafeCall: Boolean get() = false } class ExpressionKotlinCallArgumentImpl( - override val valueArgument: ValueArgument, - override val dataFlowInfoBeforeThisArgument: DataFlowInfo, - override val dataFlowInfoAfterThisArgument: DataFlowInfo, - override val receiver: ReceiverValueWithSmartCastInfo -): SimplePSIKotlinCallArgument(), ExpressionKotlinCallArgument { + override val valueArgument: ValueArgument, + override val dataFlowInfoBeforeThisArgument: DataFlowInfo, + override val dataFlowInfoAfterThisArgument: DataFlowInfo, + override val receiver: ReceiverValueWithSmartCastInfo +) : SimplePSIKotlinCallArgument(), ExpressionKotlinCallArgument { override val isSpread: Boolean get() = valueArgument.getSpreadElement() != null override val argumentName: Name? get() = valueArgument.getArgumentName()?.asName override val isSafeCall: Boolean get() = false } -class FakeValueArgumentForLeftCallableReference(val ktExpression: KtCallableReferenceExpression): ValueArgument { +class FakeValueArgumentForLeftCallableReference(val ktExpression: KtCallableReferenceExpression) : ValueArgument { override fun getArgumentExpression() = ktExpression.receiverExpression override fun getArgumentName(): ValueArgumentName? = null @@ -183,8 +185,8 @@ class FakeValueArgumentForLeftCallableReference(val ktExpression: KtCallableRefe } class EmptyLabeledReturn( - val returnExpression: KtReturnExpression, - builtIns: KotlinBuiltIns + val returnExpression: KtReturnExpression, + builtIns: KotlinBuiltIns ) : ExpressionKotlinCallArgument { override val isSpread: Boolean get() = false override val argumentName: Name? get() = null @@ -201,22 +203,24 @@ internal fun KotlinCallArgument.setResultDataFlowInfoIfRelevant(resultDataFlowIn // context here is context for value argument analysis internal fun createSimplePSICallArgument( - contextForArgument: BasicCallResolutionContext, - valueArgument: ValueArgument, - typeInfoForArgument: KotlinTypeInfo -) = createSimplePSICallArgument(contextForArgument.trace.bindingContext, contextForArgument.statementFilter, - contextForArgument.scope.ownerDescriptor, valueArgument, - contextForArgument.dataFlowInfo, typeInfoForArgument, - contextForArgument.languageVersionSettings) + contextForArgument: BasicCallResolutionContext, + valueArgument: ValueArgument, + typeInfoForArgument: KotlinTypeInfo +) = createSimplePSICallArgument( + contextForArgument.trace.bindingContext, contextForArgument.statementFilter, + contextForArgument.scope.ownerDescriptor, valueArgument, + contextForArgument.dataFlowInfo, typeInfoForArgument, + contextForArgument.languageVersionSettings +) internal fun createSimplePSICallArgument( - bindingContext: BindingContext, - statementFilter: StatementFilter, - ownerDescriptor: DeclarationDescriptor, - valueArgument: ValueArgument, - dataFlowInfoBeforeThisArgument: DataFlowInfo, - typeInfoForArgument: KotlinTypeInfo, - languageVersionSettings: LanguageVersionSettings + bindingContext: BindingContext, + statementFilter: StatementFilter, + ownerDescriptor: DeclarationDescriptor, + valueArgument: ValueArgument, + dataFlowInfoBeforeThisArgument: DataFlowInfo, + typeInfoForArgument: KotlinTypeInfo, + languageVersionSettings: LanguageVersionSettings ): SimplePSIKotlinCallArgument? { val ktExpression = KtPsiUtil.getLastElementDeparenthesized(valueArgument.getArgumentExpression(), statementFilter) ?: return null @@ -224,24 +228,27 @@ internal fun createSimplePSICallArgument( bindingContext.get(BindingContext.ONLY_RESOLVED_CALL, it) } // todo hack for if expression: sometimes we not write properly type information for branches - val baseType = typeInfoForArgument.type?.unwrap() ?: - onlyResolvedCall?.resultCallAtom?.freshReturnType ?: - return null + val baseType = typeInfoForArgument.type?.unwrap() ?: onlyResolvedCall?.resultCallAtom?.freshReturnType ?: return null // we should use DFI after this argument, because there can be some useful smartcast. Popular case: if branches. val receiverToCast = transformToReceiverWithSmartCastInfo( - ownerDescriptor, bindingContext, - typeInfoForArgument.dataFlowInfo, // dataFlowInfoBeforeThisArgument cannot be used here, because of if() { if (x != null) return; x } - ExpressionReceiver.create(ktExpression, baseType, bindingContext), - languageVersionSettings + ownerDescriptor, bindingContext, + typeInfoForArgument.dataFlowInfo, // dataFlowInfoBeforeThisArgument cannot be used here, because of if() { if (x != null) return; x } + ExpressionReceiver.create(ktExpression, baseType, bindingContext), + languageVersionSettings ).let { if (onlyResolvedCall == null) it.prepareReceiverRegardingCaptureTypes() else it } return if (onlyResolvedCall == null) { ExpressionKotlinCallArgumentImpl(valueArgument, dataFlowInfoBeforeThisArgument, typeInfoForArgument.dataFlowInfo, receiverToCast) - } - else { - SubKotlinCallArgumentImpl(valueArgument, dataFlowInfoBeforeThisArgument, typeInfoForArgument.dataFlowInfo, receiverToCast, onlyResolvedCall) + } else { + SubKotlinCallArgumentImpl( + valueArgument, + dataFlowInfoBeforeThisArgument, + typeInfoForArgument.dataFlowInfo, + receiverToCast, + onlyResolvedCall + ) } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/PSIKotlinCalls.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/PSIKotlinCalls.kt index 6abd09d0178..621b0d5404d 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/PSIKotlinCalls.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/PSIKotlinCalls.kt @@ -27,12 +27,13 @@ import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue import org.jetbrains.kotlin.util.OperatorNameConventions -val KotlinCall.psiKotlinCall: PSIKotlinCall get() { - assert(this is PSIKotlinCall) { - "Incorrect ASTCAll: $this. Java class: ${javaClass.canonicalName}" +val KotlinCall.psiKotlinCall: PSIKotlinCall + get() { + assert(this is PSIKotlinCall) { + "Incorrect ASTCAll: $this. Java class: ${javaClass.canonicalName}" + } + return this as PSIKotlinCall } - return this as PSIKotlinCall -} abstract class PSIKotlinCall : KotlinCall { abstract val psiCall: Call @@ -45,23 +46,23 @@ abstract class PSIKotlinCall : KotlinCall { } class PSIKotlinCallImpl( - override val callKind: KotlinCallKind, - override val psiCall: Call, - override val tracingStrategy: TracingStrategy, - override val explicitReceiver: ReceiverKotlinCallArgument?, - override val name: Name, - override val typeArguments: List, - override val argumentsInParenthesis: List, - override val externalArgument: KotlinCallArgument?, - override val startingDataFlowInfo: DataFlowInfo, - override val resultDataFlowInfo: DataFlowInfo, - override val dataFlowInfoForArguments: DataFlowInfoForArguments + override val callKind: KotlinCallKind, + override val psiCall: Call, + override val tracingStrategy: TracingStrategy, + override val explicitReceiver: ReceiverKotlinCallArgument?, + override val name: Name, + override val typeArguments: List, + override val argumentsInParenthesis: List, + override val externalArgument: KotlinCallArgument?, + override val startingDataFlowInfo: DataFlowInfo, + override val resultDataFlowInfo: DataFlowInfo, + override val dataFlowInfoForArguments: DataFlowInfoForArguments ) : PSIKotlinCall() class PSIKotlinCallForVariable( - val baseCall: PSIKotlinCallImpl, - override val explicitReceiver: ReceiverKotlinCallArgument?, - override val name: Name + val baseCall: PSIKotlinCallImpl, + override val explicitReceiver: ReceiverKotlinCallArgument?, + override val name: Name ) : PSIKotlinCall() { override val callKind: KotlinCallKind get() = KotlinCallKind.VARIABLE override val typeArguments: List get() = emptyList() @@ -79,10 +80,10 @@ class PSIKotlinCallForVariable( } class PSIKotlinCallForInvoke( - val baseCall: PSIKotlinCallImpl, - val variableCall: KotlinResolutionCandidate, - override val explicitReceiver: ReceiverKotlinCallArgument, - override val dispatchReceiverForInvokeExtension: SimpleKotlinCallArgument? + val baseCall: PSIKotlinCallImpl, + val variableCall: KotlinResolutionCandidate, + override val explicitReceiver: ReceiverKotlinCallArgument, + override val dispatchReceiverForInvokeExtension: SimpleKotlinCallArgument? ) : PSIKotlinCall() { override val callKind: KotlinCallKind get() = KotlinCallKind.FUNCTION override val name: Name get() = OperatorNameConventions.INVOKE @@ -102,9 +103,11 @@ class PSIKotlinCallForInvoke( val calleeExpression = baseCall.psiCall.calleeExpression!! psiCall = CallTransformer.CallForImplicitInvoke( - explicitExtensionReceiver?.receiverValue, - variableReceiver.receiverValue as ExpressionReceiver, baseCall.psiCall, true) - tracingStrategy = TracingStrategyForInvoke(calleeExpression, psiCall, variableReceiver.receiverValue!!.type) // check for type parameters + explicitExtensionReceiver?.receiverValue, + variableReceiver.receiverValue as ExpressionReceiver, baseCall.psiCall, true + ) + tracingStrategy = + TracingStrategyForInvoke(calleeExpression, psiCall, variableReceiver.receiverValue!!.type) // check for type parameters } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/ClassifierUsageChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/ClassifierUsageChecker.kt index ea0d52a30f2..1525fd5ee32 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/ClassifierUsageChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/ClassifierUsageChecker.kt @@ -30,24 +30,23 @@ import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.BindingTrace import org.jetbrains.kotlin.resolve.DeprecationResolver import org.jetbrains.kotlin.resolve.DescriptorUtils -import org.jetbrains.kotlin.utils.addToStdlib.safeAs interface ClassifierUsageChecker { fun check( - targetDescriptor: ClassifierDescriptor, - trace: BindingTrace, - element: PsiElement, - languageVersionSettings: LanguageVersionSettings, - deprecationResolver: DeprecationResolver + targetDescriptor: ClassifierDescriptor, + trace: BindingTrace, + element: PsiElement, + languageVersionSettings: LanguageVersionSettings, + deprecationResolver: DeprecationResolver ) companion object { fun check( - declarations: Collection, - trace: BindingTrace, - languageVersionSettings: LanguageVersionSettings, - deprecationResolver: DeprecationResolver, - checkers: Iterable + declarations: Collection, + trace: BindingTrace, + languageVersionSettings: LanguageVersionSettings, + deprecationResolver: DeprecationResolver, + checkers: Iterable ) { val visitor = object : KtTreeVisitorVoid() { override fun visitReferenceExpression(expression: KtReferenceExpression) { @@ -92,7 +91,10 @@ interface ClassifierUsageChecker { return targets.filterIsInstance().singleOrNull() } - private fun getReferenceToCompanionViaClassifier(expression: KtReferenceExpression, target: ClassifierDescriptor): ClassifierDescriptor? { + private fun getReferenceToCompanionViaClassifier( + expression: KtReferenceExpression, + target: ClassifierDescriptor + ): ClassifierDescriptor? { if (!DescriptorUtils.isCompanionObject(target)) return null return trace.get(BindingContext.SHORT_REFERENCE_TO_COMPANION_OBJECT, expression) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/DataClassDeclarationChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/DataClassDeclarationChecker.kt index cc7f324ce64..33bad65c16f 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/DataClassDeclarationChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/DataClassDeclarationChecker.kt @@ -26,10 +26,10 @@ import org.jetbrains.kotlin.resolve.BindingContext class DataClassDeclarationChecker : SimpleDeclarationChecker { override fun check( - declaration: KtDeclaration, - descriptor: DeclarationDescriptor, - diagnosticHolder: DiagnosticSink, - bindingContext: BindingContext + declaration: KtDeclaration, + descriptor: DeclarationDescriptor, + diagnosticHolder: DiagnosticSink, + bindingContext: BindingContext ) { if (descriptor !is ClassDescriptor) return if (declaration !is KtClassOrObject) return diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/DeclarationChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/DeclarationChecker.kt index f9e623cc214..ebe501a62b0 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/DeclarationChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/DeclarationChecker.kt @@ -26,29 +26,29 @@ import org.jetbrains.kotlin.resolve.BindingContext interface DeclarationChecker { // TODO: Think about encapsulating these parameters into specific class like CheckerParameters when you're about to add another one fun check( - declaration: KtDeclaration, - descriptor: DeclarationDescriptor, - diagnosticHolder: DiagnosticSink, - bindingContext: BindingContext, - languageVersionSettings: LanguageVersionSettings, - expectActualTracker: ExpectActualTracker + declaration: KtDeclaration, + descriptor: DeclarationDescriptor, + diagnosticHolder: DiagnosticSink, + bindingContext: BindingContext, + languageVersionSettings: LanguageVersionSettings, + expectActualTracker: ExpectActualTracker ) } interface SimpleDeclarationChecker : DeclarationChecker { override fun check( - declaration: KtDeclaration, - descriptor: DeclarationDescriptor, - diagnosticHolder: DiagnosticSink, - bindingContext: BindingContext, - languageVersionSettings: LanguageVersionSettings, - expectActualTracker: ExpectActualTracker + declaration: KtDeclaration, + descriptor: DeclarationDescriptor, + diagnosticHolder: DiagnosticSink, + bindingContext: BindingContext, + languageVersionSettings: LanguageVersionSettings, + expectActualTracker: ExpectActualTracker ) = check(declaration, descriptor, diagnosticHolder, bindingContext) fun check( - declaration: KtDeclaration, - descriptor: DeclarationDescriptor, - diagnosticHolder: DiagnosticSink, - bindingContext: BindingContext + declaration: KtDeclaration, + descriptor: DeclarationDescriptor, + diagnosticHolder: DiagnosticSink, + bindingContext: BindingContext ) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/DynamicReceiverChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/DynamicReceiverChecker.kt index 10248c1da3a..b99295c37cc 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/DynamicReceiverChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/DynamicReceiverChecker.kt @@ -29,10 +29,10 @@ import org.jetbrains.kotlin.types.isDynamic object DynamicReceiverChecker : SimpleDeclarationChecker { override fun check( - declaration: KtDeclaration, - descriptor: DeclarationDescriptor, - diagnosticHolder: DiagnosticSink, - bindingContext: BindingContext + declaration: KtDeclaration, + descriptor: DeclarationDescriptor, + diagnosticHolder: DiagnosticSink, + bindingContext: BindingContext ) { if (descriptor !is CallableDescriptor || declaration !is KtCallableDeclaration || descriptor.hasDynamicExtensionAnnotation()) return diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/InfixModifierChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/InfixModifierChecker.kt index e9f838cc55e..25f985e90d7 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/InfixModifierChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/InfixModifierChecker.kt @@ -29,10 +29,10 @@ import org.jetbrains.kotlin.util.InfixChecks class InfixModifierChecker : SimpleDeclarationChecker { override fun check( - declaration: KtDeclaration, - descriptor: DeclarationDescriptor, - diagnosticHolder: DiagnosticSink, - bindingContext: BindingContext + declaration: KtDeclaration, + descriptor: DeclarationDescriptor, + diagnosticHolder: DiagnosticSink, + bindingContext: BindingContext ) { val functionDescriptor = descriptor as? FunctionDescriptor ?: return if (!functionDescriptor.isInfix) return diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/InlineParameterChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/InlineParameterChecker.kt index fee026a0808..9bbc018b701 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/InlineParameterChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/InlineParameterChecker.kt @@ -31,7 +31,7 @@ import org.jetbrains.kotlin.resolve.BindingContext object InlineParameterChecker : SimpleDeclarationChecker { override fun check( - declaration: KtDeclaration, descriptor: DeclarationDescriptor, diagnosticHolder: DiagnosticSink, bindingContext: BindingContext + declaration: KtDeclaration, descriptor: DeclarationDescriptor, diagnosticHolder: DiagnosticSink, bindingContext: BindingContext ) { if (declaration is KtFunction) { val inline = declaration.hasModifier(KtTokens.INLINE_KEYWORD) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/KotlinVersionStringAnnotationValueChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/KotlinVersionStringAnnotationValueChecker.kt index 121e571abeb..479866631d1 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/KotlinVersionStringAnnotationValueChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/KotlinVersionStringAnnotationValueChecker.kt @@ -31,22 +31,24 @@ import org.jetbrains.kotlin.resolve.SINCE_KOTLIN_FQ_NAME import org.jetbrains.kotlin.resolve.source.getPsi abstract class KotlinVersionStringAnnotationValueChecker( - private val annotationFqName: FqName + private val annotationFqName: FqName ) : DeclarationChecker { override fun check( - declaration: KtDeclaration, - descriptor: DeclarationDescriptor, - diagnosticHolder: DiagnosticSink, - bindingContext: BindingContext, - languageVersionSettings: LanguageVersionSettings, - expectActualTracker: ExpectActualTracker + declaration: KtDeclaration, + descriptor: DeclarationDescriptor, + diagnosticHolder: DiagnosticSink, + bindingContext: BindingContext, + languageVersionSettings: LanguageVersionSettings, + expectActualTracker: ExpectActualTracker ) { val annotation = descriptor.annotations.findAnnotation(annotationFqName) ?: return val version = annotation.allValueArguments.values.singleOrNull()?.value as? String ?: return if (!version.matches(VERSION_REGEX)) { - diagnosticHolder.report(Errors.ILLEGAL_KOTLIN_VERSION_STRING_VALUE.on( + diagnosticHolder.report( + Errors.ILLEGAL_KOTLIN_VERSION_STRING_VALUE.on( annotation.source.getPsi() ?: declaration, annotationFqName - )) + ) + ) return } @@ -54,12 +56,13 @@ abstract class KotlinVersionStringAnnotationValueChecker( } open fun extraCheck( - declaration: KtDeclaration, - annotation: AnnotationDescriptor, - version: String, - diagnosticHolder: DiagnosticSink, - languageVersionSettings: LanguageVersionSettings - ) {} + declaration: KtDeclaration, + annotation: AnnotationDescriptor, + version: String, + diagnosticHolder: DiagnosticSink, + languageVersionSettings: LanguageVersionSettings + ) { + } companion object { val VERSION_REGEX: Regex = "(0|[1-9][0-9]*)".let { number -> Regex("$number\\.$number(\\.$number)?") } @@ -68,16 +71,21 @@ abstract class KotlinVersionStringAnnotationValueChecker( object SinceKotlinAnnotationValueChecker : KotlinVersionStringAnnotationValueChecker(SINCE_KOTLIN_FQ_NAME) { override fun extraCheck( - declaration: KtDeclaration, - annotation: AnnotationDescriptor, - version: String, - diagnosticHolder: DiagnosticSink, - languageVersionSettings: LanguageVersionSettings + declaration: KtDeclaration, + annotation: AnnotationDescriptor, + version: String, + diagnosticHolder: DiagnosticSink, + languageVersionSettings: LanguageVersionSettings ) { val apiVersion = ApiVersion.parse(version) val specified = languageVersionSettings.apiVersion if (apiVersion != null && apiVersion > specified) { - diagnosticHolder.report(Errors.NEWER_VERSION_IN_SINCE_KOTLIN.on(annotation.source.getPsi() ?: declaration, specified.versionString)) + diagnosticHolder.report( + Errors.NEWER_VERSION_IN_SINCE_KOTLIN.on( + annotation.source.getPsi() ?: declaration, + specified.versionString + ) + ) } } } 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 bfc2ba978ba..7369741bff2 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/MissingDependencyClassChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/MissingDependencyClassChecker.kt @@ -93,11 +93,11 @@ object MissingDependencyClassChecker : CallChecker { object ClassifierUsage : ClassifierUsageChecker { override fun check( - targetDescriptor: ClassifierDescriptor, - trace: BindingTrace, - element: PsiElement, - languageVersionSettings: LanguageVersionSettings, - deprecationResolver: DeprecationResolver + targetDescriptor: ClassifierDescriptor, + trace: BindingTrace, + element: PsiElement, + languageVersionSettings: LanguageVersionSettings, + deprecationResolver: DeprecationResolver ) { diagnosticFor(targetDescriptor, element)?.let(trace::report) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/PublishedApiUsageChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/PublishedApiUsageChecker.kt index 0dad7682089..1d9047d8a3a 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/PublishedApiUsageChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/PublishedApiUsageChecker.kt @@ -28,9 +28,9 @@ import org.jetbrains.kotlin.resolve.BindingTrace object PublishedApiUsageChecker { fun check( - declaration: KtDeclaration, - descriptor: DeclarationDescriptor, - trace: BindingTrace + declaration: KtDeclaration, + descriptor: DeclarationDescriptor, + trace: BindingTrace ) { if (descriptor !is DeclarationDescriptorWithVisibility || descriptor.visibility == Visibilities.INTERNAL) return // Don't report the diagnostic twice diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/ReifiedTypeParameterAnnotationChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/ReifiedTypeParameterAnnotationChecker.kt index cc67bbcd336..ead5a62881e 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/ReifiedTypeParameterAnnotationChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/ReifiedTypeParameterAnnotationChecker.kt @@ -32,10 +32,10 @@ import org.jetbrains.kotlin.resolve.inline.InlineUtil class ReifiedTypeParameterAnnotationChecker : SimpleDeclarationChecker { override fun check( - declaration: KtDeclaration, - descriptor: DeclarationDescriptor, - diagnosticHolder: DiagnosticSink, - bindingContext: BindingContext + declaration: KtDeclaration, + descriptor: DeclarationDescriptor, + diagnosticHolder: DiagnosticSink, + bindingContext: BindingContext ) { if (descriptor is CallableDescriptor && !(InlineUtil.isInline(descriptor) || InlineUtil.isPropertyWithAllAccessorsAreInline(descriptor))) { @@ -49,17 +49,17 @@ class ReifiedTypeParameterAnnotationChecker : SimpleDeclarationChecker { private fun checkTypeParameterDescriptorsAreNotReified( - typeParameterDescriptors: List, - diagnosticHolder: DiagnosticSink + typeParameterDescriptors: List, + diagnosticHolder: DiagnosticSink ) { for (reifiedTypeParameterDescriptor in typeParameterDescriptors.filter { it.isReified }) { val typeParameterDeclaration = DescriptorToSourceUtils.descriptorToDeclaration(reifiedTypeParameterDescriptor) if (typeParameterDeclaration !is KtTypeParameter) throw AssertionError("JetTypeParameter expected") diagnosticHolder.report( - Errors.REIFIED_TYPE_PARAMETER_NO_INLINE.on( - typeParameterDeclaration.modifierList!!.getModifier(KtTokens.REIFIED_KEYWORD)!! - ) + Errors.REIFIED_TYPE_PARAMETER_NO_INLINE.on( + typeParameterDeclaration.modifierList!!.getModifier(KtTokens.REIFIED_KEYWORD)!! + ) ) } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/SuspendOperatorsCheckers.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/SuspendOperatorsCheckers.kt index c5eedb4c777..1e6d4353ac1 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/SuspendOperatorsCheckers.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/SuspendOperatorsCheckers.kt @@ -27,15 +27,15 @@ import org.jetbrains.kotlin.util.OperatorNameConventions object SuspendOperatorsCheckers : SimpleDeclarationChecker { private val UNSUPPORTED_OPERATOR_NAMES = setOf( - OperatorNameConventions.CONTAINS, - OperatorNameConventions.GET, OperatorNameConventions.SET + OperatorNameConventions.CONTAINS, + OperatorNameConventions.GET, OperatorNameConventions.SET ) override fun check( - declaration: KtDeclaration, - descriptor: DeclarationDescriptor, - diagnosticHolder: DiagnosticSink, - bindingContext: BindingContext + declaration: KtDeclaration, + descriptor: DeclarationDescriptor, + diagnosticHolder: DiagnosticSink, + bindingContext: BindingContext ) { if (descriptor is FunctionDescriptor && descriptor.isSuspend && descriptor.isOperator && descriptor.name in UNSUPPORTED_OPERATOR_NAMES) { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/UnderscoreChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/UnderscoreChecker.kt index 3a12fb6fd72..3a29ba7364c 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/UnderscoreChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/checkers/UnderscoreChecker.kt @@ -32,45 +32,49 @@ object UnderscoreChecker : DeclarationChecker { @JvmOverloads fun checkIdentifier( - identifier: PsiElement?, - diagnosticHolder: DiagnosticSink, - languageVersionSettings: LanguageVersionSettings, - allowSingleUnderscore: Boolean = false + identifier: PsiElement?, + diagnosticHolder: DiagnosticSink, + languageVersionSettings: LanguageVersionSettings, + allowSingleUnderscore: Boolean = false ) { if (identifier == null || identifier.text.isEmpty()) return val isValidSingleUnderscore = allowSingleUnderscore && identifier.text == "_" if (!isValidSingleUnderscore && identifier.text.all { it == '_' }) { diagnosticHolder.report(Errors.UNDERSCORE_IS_RESERVED.on(identifier)) - } - else if (isValidSingleUnderscore && !languageVersionSettings.supportsFeature(LanguageFeature.SingleUnderscoreForParameterName)) { - diagnosticHolder.report(Errors.UNSUPPORTED_FEATURE.on(identifier, LanguageFeature.SingleUnderscoreForParameterName to languageVersionSettings)) + } else if (isValidSingleUnderscore && !languageVersionSettings.supportsFeature(LanguageFeature.SingleUnderscoreForParameterName)) { + diagnosticHolder.report( + Errors.UNSUPPORTED_FEATURE.on( + identifier, + LanguageFeature.SingleUnderscoreForParameterName to languageVersionSettings + ) + ) } } @JvmOverloads fun checkNamed( - declaration: KtNamedDeclaration, - diagnosticHolder: DiagnosticSink, - languageVersionSettings: LanguageVersionSettings, - allowSingleUnderscore: Boolean = false + declaration: KtNamedDeclaration, + diagnosticHolder: DiagnosticSink, + languageVersionSettings: LanguageVersionSettings, + allowSingleUnderscore: Boolean = false ) { checkIdentifier(declaration.nameIdentifier, diagnosticHolder, languageVersionSettings, allowSingleUnderscore) } override fun check( - declaration: KtDeclaration, - descriptor: DeclarationDescriptor, - diagnosticHolder: DiagnosticSink, - bindingContext: BindingContext, - languageVersionSettings: LanguageVersionSettings, - expectActualTracker: ExpectActualTracker + declaration: KtDeclaration, + descriptor: DeclarationDescriptor, + diagnosticHolder: DiagnosticSink, + bindingContext: BindingContext, + languageVersionSettings: LanguageVersionSettings, + expectActualTracker: ExpectActualTracker ) { if (declaration is KtProperty && descriptor !is VariableDescriptor) return if (declaration is KtCallableDeclaration) { for (parameter in declaration.valueParameters) { checkNamed( - parameter, diagnosticHolder, languageVersionSettings, - allowSingleUnderscore = descriptor is FunctionExpressionDescriptor + parameter, diagnosticHolder, languageVersionSettings, + allowSingleUnderscore = descriptor is FunctionExpressionDescriptor ) } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/diagnostics/KotlinSuppressCache.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/diagnostics/KotlinSuppressCache.kt index 55dcd1fb941..dd723172b7a 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/diagnostics/KotlinSuppressCache.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/diagnostics/KotlinSuppressCache.kt @@ -38,7 +38,7 @@ interface DiagnosticSuppressor { companion object { val EP_NAME: ExtensionPointName = - ExtensionPointName.create("org.jetbrains.kotlin.diagnosticSuppressor") + ExtensionPointName.create("org.jetbrains.kotlin.diagnosticSuppressor") } } @@ -46,12 +46,12 @@ abstract class KotlinSuppressCache { private val diagnosticSuppressors = ExtensionProvider.create(DiagnosticSuppressor.EP_NAME) // The cache is weak: we're OK with losing it - private val suppressors = ContainerUtil.createConcurrentWeakValueMap() + private val suppressors = ContainerUtil.createConcurrentWeakValueMap() val filter: (Diagnostic) -> Boolean = { diagnostic: Diagnostic -> !isSuppressed(diagnostic) } fun isSuppressed(psiElement: PsiElement, suppressionKey: String, severity: Severity) = - isSuppressed(StringSuppressRequest(psiElement, severity, suppressionKey.toLowerCase())) + isSuppressed(StringSuppressRequest(psiElement, severity, suppressionKey.toLowerCase())) fun isSuppressed(diagnostic: Diagnostic): Boolean = isSuppressed(DiagnosticSuppressRequest(diagnostic)) @@ -224,12 +224,13 @@ abstract class KotlinSuppressCache { } private class StringSuppressRequest( - override val element: PsiElement, - override val severity: Severity, - override val suppressKey: String) : SuppressRequest + override val element: PsiElement, + override val severity: Severity, + override val suppressKey: String + ) : SuppressRequest private class DiagnosticSuppressRequest(val diagnostic: Diagnostic) : SuppressRequest { - override val element: PsiElement get() = diagnostic.psiElement + override val element: PsiElement get() = diagnostic.psiElement override val severity: Severity get() = diagnostic.severity override val suppressKey: String get() = getDiagnosticSuppressKey(diagnostic) } @@ -241,8 +242,7 @@ class BindingContextSuppressCache(val context: BindingContext) : KotlinSuppressC return if (descriptor != null) { descriptor.annotations.toList() - } - else { + } else { annotated.annotationEntries.mapNotNull { context.get(BindingContext.ANNOTATION, it) } } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/diagnostics/MutableDiagnosticsWithSuppression.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/diagnostics/MutableDiagnosticsWithSuppression.kt index 1db5dec54b2..47b3f4934ce 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/diagnostics/MutableDiagnosticsWithSuppression.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/diagnostics/MutableDiagnosticsWithSuppression.kt @@ -26,8 +26,8 @@ import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.resolve.BindingContext class MutableDiagnosticsWithSuppression @JvmOverloads constructor( - private val bindingContext: BindingContext, - private val delegateDiagnostics: Diagnostics = Diagnostics.EMPTY + private val bindingContext: BindingContext, + private val delegateDiagnostics: Diagnostics = Diagnostics.EMPTY ) : Diagnostics { private val diagnosticList = ArrayList() @@ -60,5 +60,6 @@ class MutableDiagnosticsWithSuppression @JvmOverloads constructor( modificationTracker.incModificationCount() } - @TestOnly fun getReadonlyView(): DiagnosticsWithSuppression = readonlyView() + @TestOnly + fun getReadonlyView(): DiagnosticsWithSuppression = readonlyView() } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/extensions/SyntheticResolveExtension.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/extensions/SyntheticResolveExtension.kt index 05f59d40ab0..987112fe0ab 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/extensions/SyntheticResolveExtension.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/extensions/SyntheticResolveExtension.kt @@ -33,39 +33,46 @@ import java.util.* interface SyntheticResolveExtension { companion object : ProjectExtensionDescriptor( - "org.jetbrains.kotlin.syntheticResolveExtension", SyntheticResolveExtension::class.java) { + "org.jetbrains.kotlin.syntheticResolveExtension", SyntheticResolveExtension::class.java + ) { fun getInstance(project: Project): SyntheticResolveExtension { val instances = getInstances(project) if (instances.size == 1) return instances.single() // return list combiner here return object : SyntheticResolveExtension { override fun getSyntheticNestedClassNames(thisDescriptor: ClassDescriptor): List = - instances.flatMap { it.getSyntheticNestedClassNames(thisDescriptor) } + instances.flatMap { it.getSyntheticNestedClassNames(thisDescriptor) } override fun getSyntheticFunctionNames(thisDescriptor: ClassDescriptor): List = - instances.flatMap { it.getSyntheticFunctionNames(thisDescriptor) } + instances.flatMap { it.getSyntheticFunctionNames(thisDescriptor) } - override fun generateSyntheticClasses(thisDescriptor: ClassDescriptor, name: Name, - ctx: LazyClassContext, declarationProvider: ClassMemberDeclarationProvider, - result: MutableSet) = - instances.forEach { it.generateSyntheticClasses(thisDescriptor, name, ctx, declarationProvider, result) } + override fun generateSyntheticClasses( + thisDescriptor: ClassDescriptor, name: Name, + ctx: LazyClassContext, declarationProvider: ClassMemberDeclarationProvider, + result: MutableSet + ) = + instances.forEach { it.generateSyntheticClasses(thisDescriptor, name, ctx, declarationProvider, result) } override fun getSyntheticCompanionObjectNameIfNeeded(thisDescriptor: ClassDescriptor): Name? = - instances.firstNotNullResult { it.getSyntheticCompanionObjectNameIfNeeded(thisDescriptor) } + instances.firstNotNullResult { it.getSyntheticCompanionObjectNameIfNeeded(thisDescriptor) } override fun addSyntheticSupertypes(thisDescriptor: ClassDescriptor, supertypes: MutableList) = - instances.forEach { it.addSyntheticSupertypes(thisDescriptor, supertypes) } + instances.forEach { it.addSyntheticSupertypes(thisDescriptor, supertypes) } // todo revert - override fun generateSyntheticMethods(thisDescriptor: ClassDescriptor, name: Name, - fromSupertypes: List, - result: MutableCollection) = - instances.forEach { it.generateSyntheticMethods(thisDescriptor, name, fromSupertypes, result) } + override fun generateSyntheticMethods( + thisDescriptor: ClassDescriptor, name: Name, + fromSupertypes: List, + result: MutableCollection + ) = + instances.forEach { it.generateSyntheticMethods(thisDescriptor, name, fromSupertypes, result) } - override fun generateSyntheticProperties(thisDescriptor: ClassDescriptor, name: Name, - fromSupertypes: ArrayList, - result: MutableSet) = - instances.forEach { it.generateSyntheticProperties(thisDescriptor, name, fromSupertypes, result) } + override fun generateSyntheticProperties( + thisDescriptor: ClassDescriptor, name: Name, + fromSupertypes: ArrayList, + result: MutableSet + ) = + instances.forEach { it.generateSyntheticProperties(thisDescriptor, name, fromSupertypes, result) } } } } @@ -78,22 +85,28 @@ interface SyntheticResolveExtension { fun addSyntheticSupertypes(thisDescriptor: ClassDescriptor, supertypes: MutableList) {} - fun generateSyntheticClasses(thisDescriptor: ClassDescriptor, - name: Name, - ctx: LazyClassContext, - declarationProvider: ClassMemberDeclarationProvider, - result: MutableSet) { + fun generateSyntheticClasses( + thisDescriptor: ClassDescriptor, + name: Name, + ctx: LazyClassContext, + declarationProvider: ClassMemberDeclarationProvider, + result: MutableSet + ) { } - fun generateSyntheticMethods(thisDescriptor: ClassDescriptor, - name: Name, - fromSupertypes: List, - result: MutableCollection) { + fun generateSyntheticMethods( + thisDescriptor: ClassDescriptor, + name: Name, + fromSupertypes: List, + result: MutableCollection + ) { } - fun generateSyntheticProperties(thisDescriptor: ClassDescriptor, - name: Name, - fromSupertypes: ArrayList, - result: MutableSet) { + fun generateSyntheticProperties( + thisDescriptor: ClassDescriptor, + name: Name, + fromSupertypes: ArrayList, + result: MutableSet + ) { } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/findLoopsInSupertypes.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/findLoopsInSupertypes.kt index cf9aeacbe22..cf6800408c8 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/findLoopsInSupertypes.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/findLoopsInSupertypes.kt @@ -15,6 +15,7 @@ */ @file:JvmName("FindLoopsInSupertypes") + package org.jetbrains.kotlin.resolve import org.jetbrains.kotlin.descriptors.SupertypeLoopChecker @@ -26,10 +27,10 @@ import org.jetbrains.kotlin.utils.SmartList class SupertypeLoopCheckerImpl : SupertypeLoopChecker { override fun findLoopsInSupertypesAndDisconnect( - currentTypeConstructor: TypeConstructor, - superTypes: Collection, - neighbors: (TypeConstructor) -> Iterable, - reportLoop: (KotlinType) -> Unit + currentTypeConstructor: TypeConstructor, + superTypes: Collection, + neighbors: (TypeConstructor) -> Iterable, + reportLoop: (KotlinType) -> Unit ): Collection { val graph = DFS.Neighbors { node -> neighbors(node).map { it.constructor } } @@ -53,8 +54,8 @@ class SupertypeLoopCheckerImpl : SupertypeLoopChecker { } private fun isReachable( - from: TypeConstructor, to: TypeConstructor, - neighbors: DFS.Neighbors + from: TypeConstructor, to: TypeConstructor, + neighbors: DFS.Neighbors ): Boolean { var result = false DFS.dfs(listOf(from), neighbors, DFS.VisitedWithSet(), object : DFS.AbstractNodeHandler() { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/importedFromObject.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/importedFromObject.kt index 4fb6b2c9756..202809b635d 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/importedFromObject.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/importedFromObject.kt @@ -20,14 +20,14 @@ import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.types.TypeSubstitutor fun FunctionDescriptor.asImportedFromObject(original: FunctionImportedFromObject? = null) = - FunctionImportedFromObject(this, original) + FunctionImportedFromObject(this, original) fun PropertyDescriptor.asImportedFromObject(original: PropertyImportedFromObject? = null) = - PropertyImportedFromObject(this, original) + PropertyImportedFromObject(this, original) abstract class ImportedFromObjectCallableDescriptor( - val callableFromObject: TCallable, - private val originalOrNull: TCallable? + val callableFromObject: TCallable, + private val originalOrNull: TCallable? ) : CallableDescriptor { val containingObject = callableFromObject.containingDeclaration as ClassDescriptor @@ -38,31 +38,31 @@ abstract class ImportedFromObjectCallableDescriptor(functionFromObject, originalOrNull), - FunctionDescriptor by functionFromObject { + FunctionDescriptor by functionFromObject { override fun getDispatchReceiverParameter(): ReceiverParameterDescriptor? = null override fun substitute(substitutor: TypeSubstitutor) = - callableFromObject.substitute(substitutor)?.asImportedFromObject(this) + callableFromObject.substitute(substitutor)?.asImportedFromObject(this) override fun getOriginal() = _original as FunctionDescriptor override fun copy( - newOwner: DeclarationDescriptor?, modality: Modality?, visibility: Visibility?, - kind: CallableMemberDescriptor.Kind?, copyOverrides: Boolean + newOwner: DeclarationDescriptor?, modality: Modality?, visibility: Visibility?, + kind: CallableMemberDescriptor.Kind?, copyOverrides: Boolean ): FunctionDescriptor { throw UnsupportedOperationException("copy() should not be called on ${this::class.java.simpleName}, was called for $this") } } class PropertyImportedFromObject( - propertyFromObject: PropertyDescriptor, - originalOrNull: PropertyDescriptor? = null + propertyFromObject: PropertyDescriptor, + originalOrNull: PropertyDescriptor? = null ) : ImportedFromObjectCallableDescriptor(propertyFromObject, originalOrNull), - PropertyDescriptor by propertyFromObject { + PropertyDescriptor by propertyFromObject { override fun getDispatchReceiverParameter(): ReceiverParameterDescriptor? = null @@ -71,8 +71,8 @@ class PropertyImportedFromObject( override fun getOriginal() = _original as PropertyDescriptor override fun copy( - newOwner: DeclarationDescriptor?, modality: Modality?, visibility: Visibility?, - kind: CallableMemberDescriptor.Kind?, copyOverrides: Boolean + newOwner: DeclarationDescriptor?, modality: Modality?, visibility: Visibility?, + kind: CallableMemberDescriptor.Kind?, copyOverrides: Boolean ): FunctionDescriptor { throw UnsupportedOperationException("copy() should not be called on ${this::class.java.simpleName}, was called for $this") } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/AbsentDescriptorHandler.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/AbsentDescriptorHandler.kt index eff680bfacd..30364f2ee77 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/AbsentDescriptorHandler.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/AbsentDescriptorHandler.kt @@ -19,9 +19,11 @@ class BasicAbsentDescriptorHandler : AbsentDescriptorHandler { } class NoDescriptorForDeclarationException @JvmOverloads constructor(declaration: KtDeclaration, additionalDetails: String? = null) : - KotlinExceptionWithAttachments("Descriptor wasn't found for declaration $declaration" - + (additionalDetails?.let { "\n---------------------------------------------------\n$it" } ?: "")) { + KotlinExceptionWithAttachments( + "Descriptor wasn't found for declaration $declaration" + + (additionalDetails?.let { "\n---------------------------------------------------\n$it" } ?: "") + ) { init { withAttachment("declaration.kt", declaration.getElementTextWithContext()) } -} +} \ No newline at end of file diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/FileScopeFactory.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/FileScopeFactory.kt index 0f23a3ba5e1..5809f57db6c 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/FileScopeFactory.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/FileScopeFactory.kt @@ -37,16 +37,16 @@ import org.jetbrains.kotlin.utils.Printer data class FileScopes(val lexicalScope: LexicalScope, val importingScope: ImportingScope, val importResolver: ImportResolver) class FileScopeFactory( - private val topLevelDescriptorProvider: TopLevelDescriptorProvider, - private val storageManager: StorageManager, - private val moduleDescriptor: ModuleDescriptor, - private val qualifiedExpressionResolver: QualifiedExpressionResolver, - private val bindingTrace: BindingTrace, - private val ktImportsFactory: KtImportsFactory, - private val platformToKotlinClassMap: PlatformToKotlinClassMap, - private val defaultImportProvider: DefaultImportProvider, - private val languageVersionSettings: LanguageVersionSettings, - private val deprecationResolver: DeprecationResolver + private val topLevelDescriptorProvider: TopLevelDescriptorProvider, + private val storageManager: StorageManager, + private val moduleDescriptor: ModuleDescriptor, + private val qualifiedExpressionResolver: QualifiedExpressionResolver, + private val bindingTrace: BindingTrace, + private val ktImportsFactory: KtImportsFactory, + private val platformToKotlinClassMap: PlatformToKotlinClassMap, + private val defaultImportProvider: DefaultImportProvider, + private val languageVersionSettings: LanguageVersionSettings, + private val deprecationResolver: DeprecationResolver ) { /* avoid constructing psi for default imports prematurely (time consuming in some scenarios) */ private val defaultImports by storageManager.createLazyValue { @@ -60,20 +60,33 @@ class FileScopeFactory( return FilesScopesBuilder(file, existingImports, packageFragment, packageView).result } - private fun createDefaultImportResolvers(extraImports: Collection, aliasImportNames: Collection): Pair { + private fun createDefaultImportResolvers( + extraImports: Collection, + aliasImportNames: Collection + ): Pair { val tempTrace = TemporaryBindingTrace.create(bindingTrace, "Transient trace for default imports lazy resolve", false) val allImplicitImports = defaultImports concat extraImports val defaultImportsFiltered = if (aliasImportNames.isEmpty()) { // optimization allImplicitImports - } - else { + } else { allImplicitImports.filter { it.isAllUnder || it.importedFqName !in aliasImportNames } } - val defaultExplicitImportResolver = createImportResolver(ExplicitImportsIndexed(defaultImportsFiltered), tempTrace, packageFragment = null, aliasImportNames = aliasImportNames) + val defaultExplicitImportResolver = createImportResolver( + ExplicitImportsIndexed(defaultImportsFiltered), + tempTrace, + packageFragment = null, + aliasImportNames = aliasImportNames + ) val defaultAllUnderImportResolver = - createImportResolver(AllUnderImportsIndexed(defaultImportsFiltered), tempTrace, packageFragment = null, aliasImportNames = aliasImportNames, excludedImports = defaultImportProvider.excludedImports) + createImportResolver( + AllUnderImportsIndexed(defaultImportsFiltered), + tempTrace, + packageFragment = null, + aliasImportNames = aliasImportNames, + excludedImports = defaultImportProvider.excludedImports + ) return defaultExplicitImportResolver to defaultAllUnderImportResolver } @@ -83,29 +96,34 @@ class FileScopeFactory( } private fun createImportResolver( - indexedImports: IndexedImports, - trace: BindingTrace, - aliasImportNames: Collection, - packageFragment: PackageFragmentDescriptor?, - excludedImports: List? = null + indexedImports: IndexedImports, + trace: BindingTrace, + aliasImportNames: Collection, + packageFragment: PackageFragmentDescriptor?, + excludedImports: List? = null ) = LazyImportResolver( - storageManager, qualifiedExpressionResolver, moduleDescriptor, platformToKotlinClassMap, languageVersionSettings, - indexedImports, aliasImportNames concat excludedImports, trace, packageFragment, - deprecationResolver - ) + storageManager, qualifiedExpressionResolver, moduleDescriptor, platformToKotlinClassMap, languageVersionSettings, + indexedImports, aliasImportNames concat excludedImports, trace, packageFragment, + deprecationResolver + ) private inner class FilesScopesBuilder( - private val file: KtFile, - private val existingImports: ImportingScope?, - private val packageFragment: PackageFragmentDescriptor, - private val packageView: PackageViewDescriptor + private val file: KtFile, + private val existingImports: ImportingScope?, + private val packageFragment: PackageFragmentDescriptor, + private val packageView: PackageViewDescriptor ) { val imports = file.importDirectives val aliasImportNames = imports.mapNotNull { if (it.aliasName != null) it.importedFqName else null } val explicitImportResolver = createImportResolver(ExplicitImportsIndexed(imports), bindingTrace, aliasImportNames, packageFragment) - val allUnderImportResolver = createImportResolver(AllUnderImportsIndexed(imports), bindingTrace, aliasImportNames, packageFragment) // TODO: should we count excludedImports here also? + val allUnderImportResolver = createImportResolver( + AllUnderImportsIndexed(imports), + bindingTrace, + aliasImportNames, + packageFragment + ) // TODO: should we count excludedImports here also? val lazyImportingScope = object : ImportingScope by ImportingScope.Empty { // avoid constructing the scope before we query it @@ -114,7 +132,8 @@ class FileScopeFactory( } } - val lexicalScope = LexicalScope.Base(lazyImportingScope, topLevelDescriptorProvider.getPackageFragmentOrDiagnoseFailure(file.packageFqName, file)) + val lexicalScope = + LexicalScope.Base(lazyImportingScope, topLevelDescriptorProvider.getPackageFragmentOrDiagnoseFailure(file.packageFqName, file)) val importResolver = object : ImportResolver { override fun forceResolveAllImports() { @@ -125,8 +144,7 @@ class FileScopeFactory( override fun forceResolveImport(importDirective: KtImportDirective) { if (importDirective.isAllUnder) { allUnderImportResolver.forceResolveImport(importDirective) - } - else { + } else { explicitImportResolver.forceResolveImport(importDirective) } } @@ -155,22 +173,32 @@ class FileScopeFactory( var scope: ImportingScope val debugName = "LazyFileScope for file " + file.name - scope = LazyImportScope(existingImports, defaultAllUnderImportResolver, LazyImportScope.FilteringKind.INVISIBLE_CLASSES, - "Default all under imports in $debugName (invisible classes only)") + scope = LazyImportScope( + existingImports, defaultAllUnderImportResolver, LazyImportScope.FilteringKind.INVISIBLE_CLASSES, + "Default all under imports in $debugName (invisible classes only)" + ) - scope = LazyImportScope(scope, allUnderImportResolver, LazyImportScope.FilteringKind.INVISIBLE_CLASSES, - "All under imports in $debugName (invisible classes only)") + scope = LazyImportScope( + scope, allUnderImportResolver, LazyImportScope.FilteringKind.INVISIBLE_CLASSES, + "All under imports in $debugName (invisible classes only)" + ) scope = currentPackageScope(packageView, aliasImportNames, dummyContainerDescriptor, FilteringKind.INVISIBLE_CLASSES, scope) - scope = LazyImportScope(scope, defaultAllUnderImportResolver, LazyImportScope.FilteringKind.VISIBLE_CLASSES, - "Default all under imports in $debugName (visible classes)") + scope = LazyImportScope( + scope, defaultAllUnderImportResolver, LazyImportScope.FilteringKind.VISIBLE_CLASSES, + "Default all under imports in $debugName (visible classes)" + ) - scope = LazyImportScope(scope, allUnderImportResolver, LazyImportScope.FilteringKind.VISIBLE_CLASSES, - "All under imports in $debugName (visible classes)") + scope = LazyImportScope( + scope, allUnderImportResolver, LazyImportScope.FilteringKind.VISIBLE_CLASSES, + "All under imports in $debugName (visible classes)" + ) - scope = LazyImportScope(scope, defaultExplicitImportResolver, LazyImportScope.FilteringKind.ALL, - "Default explicit imports in $debugName") + scope = LazyImportScope( + scope, defaultExplicitImportResolver, LazyImportScope.FilteringKind.ALL, + "Default explicit imports in $debugName" + ) scope = SubpackagesImportingScope(scope, moduleDescriptor, FqName.ROOT) @@ -186,14 +214,14 @@ class FileScopeFactory( } private fun currentPackageScope( - packageView: PackageViewDescriptor, - aliasImportNames: Collection, - fromDescriptor: DummyContainerDescriptor, - filteringKind: FilteringKind, - parentScope: ImportingScope + packageView: PackageViewDescriptor, + aliasImportNames: Collection, + fromDescriptor: DummyContainerDescriptor, + filteringKind: FilteringKind, + parentScope: ImportingScope ): ImportingScope { val scope = packageView.memberScope - val names by lazy(LazyThreadSafetyMode.PUBLICATION) { scope.computeAllNames () } + val names by lazy(LazyThreadSafetyMode.PUBLICATION) { scope.computeAllNames() } val packageName = packageView.fqName val excludedNames = aliasImportNames.mapNotNull { if (it.parent() == packageName) it.shortName() else null } @@ -222,15 +250,15 @@ class FileScopeFactory( } override fun getContributedDescriptors( - kindFilter: DescriptorKindFilter, - nameFilter: (Name) -> Boolean, - changeNamesForAliased: Boolean + kindFilter: DescriptorKindFilter, + nameFilter: (Name) -> Boolean, + changeNamesForAliased: Boolean ): Collection { // we do not perform any filtering by visibility here because all descriptors from both visible/invisible filter scopes are to be added anyway if (filteringKind == FilteringKind.INVISIBLE_CLASSES) return listOf() return scope.getContributedDescriptors( - kindFilter.withoutKinds(DescriptorKindFilter.PACKAGES_MASK), - { name -> name !in excludedNames && nameFilter(name) } + kindFilter.withoutKinds(DescriptorKindFilter.PACKAGES_MASK), + { name -> name !in excludedNames && nameFilter(name) } ).filter { it !is PackageViewDescriptor } // subpackages of the current package not accessible by the short name } @@ -247,7 +275,8 @@ class FileScopeFactory( } // we use this dummy implementation of DeclarationDescriptor to check accessibility of symbols from the current package - private class DummyContainerDescriptor(file: KtFile, private val packageFragment: PackageFragmentDescriptor) : DeclarationDescriptorNonRoot { + private class DummyContainerDescriptor(file: KtFile, private val packageFragment: PackageFragmentDescriptor) : + DeclarationDescriptorNonRoot { private val sourceElement = KotlinSourceElement(file) override fun getContainingDeclaration() = packageFragment @@ -272,4 +301,4 @@ class FileScopeFactory( } private infix fun Collection.concat(other: Collection?) = - if (other == null || other.isEmpty()) this else this + other + if (other == null || other.isEmpty()) this else this + other diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/FileScopeProvider.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/FileScopeProvider.kt index 8565778369a..58f06f9e99b 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/FileScopeProvider.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/FileScopeProvider.kt @@ -38,14 +38,14 @@ interface FileScopeProvider { } class FileScopeProviderImpl( - private val fileScopeFactory: FileScopeFactory, - private val bindingTrace: BindingTrace, - private val storageManager: StorageManager + private val fileScopeFactory: FileScopeFactory, + private val bindingTrace: BindingTrace, + private val storageManager: StorageManager ) : FileScopeProvider { private val cache = storageManager.createMemoizedFunction { file -> val scopes = (file.originalFile as KtFile?)?.fileScopesCustomizer?.createFileScopes(fileScopeFactory) - ?: fileScopeFactory.createScopesForFile(file) + ?: fileScopeFactory.createScopesForFile(file) bindingTrace.recordScope(scopes.lexicalScope, file) scopes } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/LazyImportScope.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/LazyImportScope.kt index fc6a4b3804b..b81aeb304a0 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/LazyImportScope.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/LazyImportScope.kt @@ -74,32 +74,30 @@ interface ImportResolver { } class LazyImportResolver( - val storageManager: StorageManager, - private val qualifiedExpressionResolver: QualifiedExpressionResolver, - val moduleDescriptor: ModuleDescriptor, - private val platformToKotlinClassMap: PlatformToKotlinClassMap, - val languageVersionSettings: LanguageVersionSettings, - val indexedImports: IndexedImports, - excludedImportNames: Collection, - private val traceForImportResolve: BindingTrace, - private val packageFragment: PackageFragmentDescriptor?, - val deprecationResolver: DeprecationResolver + val storageManager: StorageManager, + private val qualifiedExpressionResolver: QualifiedExpressionResolver, + val moduleDescriptor: ModuleDescriptor, + private val platformToKotlinClassMap: PlatformToKotlinClassMap, + val languageVersionSettings: LanguageVersionSettings, + val indexedImports: IndexedImports, + excludedImportNames: Collection, + private val traceForImportResolve: BindingTrace, + private val packageFragment: PackageFragmentDescriptor?, + val deprecationResolver: DeprecationResolver ) : ImportResolver { - private val importedScopesProvider = storageManager.createMemoizedFunctionWithNullableValues { - directive: KtImportDirective -> + private val importedScopesProvider = storageManager.createMemoizedFunctionWithNullableValues { directive: KtImportDirective -> qualifiedExpressionResolver.processImportReference( - directive, moduleDescriptor, traceForImportResolve, excludedImportNames, packageFragment + directive, moduleDescriptor, traceForImportResolve, excludedImportNames, packageFragment ) } - private val forceResolveImportDirective = storageManager.createMemoizedFunction { - directive: KtImportDirective -> + private val forceResolveImportDirective = storageManager.createMemoizedFunction { directive: KtImportDirective -> val scope = importedScopesProvider(directive) if (scope is LazyExplicitImportScope) { val allDescriptors = scope.storeReferencesToDescriptors() PlatformClassesMappedToKotlinChecker.checkPlatformClassesMappedToKotlin( - platformToKotlinClassMap, traceForImportResolve, directive, allDescriptors + platformToKotlinClassMap, traceForImportResolve, directive, allDescriptors ) } @@ -157,8 +155,8 @@ class LazyImportResolver( } fun selectSingleFromImports( - name: Name, - descriptorSelector: (ImportingScope, Name) -> D? + name: Name, + descriptorSelector: (ImportingScope, Name) -> D? ): D? { fun compute(): D? { val imports = indexedImports.importsForName(name) @@ -175,8 +173,8 @@ class LazyImportResolver( } fun collectFromImports( - name: Name, - descriptorsSelector: (ImportingScope, Name) -> Collection + name: Name, + descriptorsSelector: (ImportingScope, Name) -> Collection ): Collection { return storageManager.compute { var descriptors: Collection? = null @@ -208,10 +206,10 @@ class LazyImportResolver( } class LazyImportScope( - override val parent: ImportingScope?, - private val importResolver: LazyImportResolver, - private val filteringKind: LazyImportScope.FilteringKind, - private val debugName: String + override val parent: ImportingScope?, + private val importResolver: LazyImportResolver, + private val filteringKind: LazyImportScope.FilteringKind, + private val debugName: String ) : ImportingScope { enum class FilteringKind { @@ -254,9 +252,9 @@ class LazyImportScope( } override fun getContributedDescriptors( - kindFilter: DescriptorKindFilter, - nameFilter: (Name) -> Boolean, - changeNamesForAliased: Boolean + kindFilter: DescriptorKindFilter, + nameFilter: (Name) -> Boolean, + changeNamesForAliased: Boolean ): Collection { // we do not perform any filtering by visibility here because all descriptors from both visible/invisible filter scopes are to be added anyway if (filteringKind == FilteringKind.INVISIBLE_CLASSES) return listOf() @@ -267,7 +265,13 @@ class LazyImportScope( val importPath = directive.importPath ?: continue val importedName = importPath.importedName if (importedName == null || nameFilter(importedName)) { - descriptors.addAll(importResolver.getImportScope(directive).getContributedDescriptors(kindFilter, nameFilter, changeNamesForAliased)) + descriptors.addAll( + importResolver.getImportScope(directive).getContributedDescriptors( + kindFilter, + nameFilter, + changeNamesForAliased + ) + ) } } descriptors diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/LocalDescriptorResolver.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/LocalDescriptorResolver.kt index dc2ab7a7aa6..4c12d8792de 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/LocalDescriptorResolver.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/LocalDescriptorResolver.kt @@ -27,7 +27,7 @@ interface LocalDescriptorResolver { } class CompilerLocalDescriptorResolver( - private val lazyDeclarationResolver: LazyDeclarationResolver + private val lazyDeclarationResolver: LazyDeclarationResolver ) : LocalDescriptorResolver { override fun resolveLocalDeclaration(declaration: KtDeclaration): DeclarationDescriptor { return lazyDeclarationResolver.resolveToDescriptor(declaration) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/data/KtScriptInfo.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/data/KtScriptInfo.kt index 84bf614b9ab..01548056e55 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/data/KtScriptInfo.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/data/KtScriptInfo.kt @@ -23,7 +23,7 @@ import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.kotlin.psi.KtScript class KtScriptInfo( - val script: KtScript + val script: KtScript ) : KtClassLikeInfo { override fun getContainingPackageFqName() = script.fqName.parent() override fun getModifierList() = null diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/declarations/AbstractPsiBasedDeclarationProvider.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/declarations/AbstractPsiBasedDeclarationProvider.kt index 4d0e1c5c7c0..5296c84d963 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/declarations/AbstractPsiBasedDeclarationProvider.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/declarations/AbstractPsiBasedDeclarationProvider.kt @@ -90,21 +90,18 @@ abstract class AbstractPsiBasedDeclarationProvider(storageManager: StorageManage internal fun toInfoString() = toString() + ": " + index().toString() - override fun getDeclarations(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean): List - = index().allDeclarations + override fun getDeclarations(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean): List = + index().allDeclarations - override fun getFunctionDeclarations(name: Name): List - = index().functions[safeNameForLazyResolve(name)].toList() + override fun getFunctionDeclarations(name: Name): List = index().functions[safeNameForLazyResolve(name)].toList() - override fun getPropertyDeclarations(name: Name): List - = index().properties[safeNameForLazyResolve(name)].toList() + override fun getPropertyDeclarations(name: Name): List = index().properties[safeNameForLazyResolve(name)].toList() - override fun getDestructuringDeclarationsEntries(name: Name): Collection - = index().destructuringDeclarationsEntries[safeNameForLazyResolve(name)].toList() + override fun getDestructuringDeclarationsEntries(name: Name): Collection = + index().destructuringDeclarationsEntries[safeNameForLazyResolve(name)].toList() - override fun getClassOrObjectDeclarations(name: Name): Collection - = index().classesAndObjects[safeNameForLazyResolve(name)] + override fun getClassOrObjectDeclarations(name: Name): Collection = + index().classesAndObjects[safeNameForLazyResolve(name)] - override fun getTypeAliasDeclarations(name: Name): Collection - = index().typeAliases[safeNameForLazyResolve(name)] + override fun getTypeAliasDeclarations(name: Name): Collection = index().typeAliases[safeNameForLazyResolve(name)] } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/declarations/FileBasedPackageMemberDeclarationProvider.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/declarations/FileBasedPackageMemberDeclarationProvider.kt index d4b49f620f9..d9460941004 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/declarations/FileBasedPackageMemberDeclarationProvider.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/declarations/FileBasedPackageMemberDeclarationProvider.kt @@ -22,11 +22,11 @@ import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.storage.StorageManager class FileBasedPackageMemberDeclarationProvider( - storageManager: StorageManager, - private val fqName: FqName, - private val factory: FileBasedDeclarationProviderFactory, - private val packageFiles: Collection) -: AbstractPsiBasedDeclarationProvider(storageManager), PackageMemberDeclarationProvider { + storageManager: StorageManager, + private val fqName: FqName, + private val factory: FileBasedDeclarationProviderFactory, + private val packageFiles: Collection +) : AbstractPsiBasedDeclarationProvider(storageManager), PackageMemberDeclarationProvider { private val allDeclaredSubPackages = storageManager.createLazyValue> { factory.getAllDeclaredSubPackagesOf(fqName) @@ -48,5 +48,5 @@ class FileBasedPackageMemberDeclarationProvider( override fun containsFile(file: KtFile) = file in packageFiles override fun toString() = "Declarations for package $fqName with files ${packageFiles.map { it.name }} " + - "with declarations inside ${packageFiles.flatMap { it.declarations }.map { it.name ?: "???"}}" + "with declarations inside ${packageFiles.flatMap { it.declarations }.map { it.name ?: "???" }}" } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/ClassResolutionScopesSupport.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/ClassResolutionScopesSupport.kt index 8bcd4bb1cdc..bd15cdff870 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/ClassResolutionScopesSupport.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/ClassResolutionScopesSupport.kt @@ -28,9 +28,9 @@ import org.jetbrains.kotlin.utils.addIfNotNull import java.util.* class ClassResolutionScopesSupport( - private val classDescriptor: ClassDescriptor, - storageManager: StorageManager, - private val getOuterScope: () -> LexicalScope + private val classDescriptor: ClassDescriptor, + storageManager: StorageManager, + private val getOuterScope: () -> LexicalScope ) { private fun scopeWithGenerics(parent: LexicalScope): LexicalScopeImpl { return LexicalScopeImpl(parent, classDescriptor, false, null, LexicalScopeKind.CLASS_HEADER) { @@ -56,29 +56,36 @@ class ClassResolutionScopesSupport( createInheritanceScope(parent = inheritanceScopeWithoutMe(), ownerDescriptor = classDescriptor, classDescriptor = classDescriptor) } - val scopeForCompanionObjectHeaderResolution: () -> LexicalScope = storageManager.createLazyValue(onRecursion = createErrorLexicalScope) { - createInheritanceScope(inheritanceScopeWithoutMe(), classDescriptor, classDescriptor, withCompanionObject = false) - } + val scopeForCompanionObjectHeaderResolution: () -> LexicalScope = + storageManager.createLazyValue(onRecursion = createErrorLexicalScope) { + createInheritanceScope(inheritanceScopeWithoutMe(), classDescriptor, classDescriptor, withCompanionObject = false) + } val scopeForMemberDeclarationResolution: () -> LexicalScope = storageManager.createLazyValue(onRecursion = createErrorLexicalScope) { val scopeWithGenerics = scopeWithGenerics(inheritanceScopeWithMe()) - LexicalScopeImpl(scopeWithGenerics, classDescriptor, true, classDescriptor.thisAsReceiverParameter, LexicalScopeKind.CLASS_MEMBER_SCOPE) + LexicalScopeImpl( + scopeWithGenerics, + classDescriptor, + true, + classDescriptor.thisAsReceiverParameter, + LexicalScopeKind.CLASS_MEMBER_SCOPE + ) } - val scopeForStaticMemberDeclarationResolution: () -> LexicalScope = storageManager.createLazyValue(onRecursion = createErrorLexicalScope) { - if (classDescriptor.kind.isSingleton) { - scopeForMemberDeclarationResolution() + val scopeForStaticMemberDeclarationResolution: () -> LexicalScope = + storageManager.createLazyValue(onRecursion = createErrorLexicalScope) { + if (classDescriptor.kind.isSingleton) { + scopeForMemberDeclarationResolution() + } else { + inheritanceScopeWithMe() + } } - else { - inheritanceScopeWithMe() - } - } private fun createInheritanceScope( - parent: LexicalScope, - ownerDescriptor: DeclarationDescriptor, - classDescriptor: ClassDescriptor, - withCompanionObject: Boolean = true + parent: LexicalScope, + ownerDescriptor: DeclarationDescriptor, + classDescriptor: ClassDescriptor, + withCompanionObject: Boolean = true ): LexicalScope { val staticScopes = ArrayList(3) @@ -97,40 +104,46 @@ class ClassResolutionScopesSupport( parentForNewScope = classDescriptor.companionObjectDescriptor?.let { it.getAllSuperclassesWithoutAny().asReversed().fold(parent) { scope, currentClass -> - createInheritanceScope(parent = scope, ownerDescriptor = ownerDescriptor, classDescriptor = currentClass, withCompanionObject = false) + createInheritanceScope( + parent = scope, + ownerDescriptor = ownerDescriptor, + classDescriptor = currentClass, + withCompanionObject = false + ) } } ?: parent - } - else { + } else { implicitReceiver = null parentForNewScope = parent } - return LexicalChainedScope(parentForNewScope, ownerDescriptor, false, - implicitReceiver, - LexicalScopeKind.CLASS_INHERITANCE, - memberScopes = staticScopes, isStaticScope = true) + return LexicalChainedScope( + parentForNewScope, ownerDescriptor, false, + implicitReceiver, + LexicalScopeKind.CLASS_INHERITANCE, + memberScopes = staticScopes, isStaticScope = true + ) } private fun StorageManager.createLazyValue(onRecursion: ((Boolean) -> T), compute: () -> T) = - createLazyValueWithPostCompute(compute, onRecursion, {}) + createLazyValueWithPostCompute(compute, onRecursion, {}) companion object { - private val createErrorLexicalScope: (Boolean) -> LexicalScope = { ErrorLexicalScope() } + private val createErrorLexicalScope: (Boolean) -> LexicalScope = { ErrorLexicalScope() } } } fun scopeForInitializerResolution( - classDescriptor: LazyClassDescriptor, - parentDescriptor: DeclarationDescriptor, - primaryConstructorParameters: List + classDescriptor: LazyClassDescriptor, + parentDescriptor: DeclarationDescriptor, + primaryConstructorParameters: List ): LexicalScope { return LexicalScopeImpl( - classDescriptor.scopeForMemberDeclarationResolution, - parentDescriptor, - false, - null, - LexicalScopeKind.CLASS_INITIALIZER + classDescriptor.scopeForMemberDeclarationResolution, + parentDescriptor, + false, + null, + LexicalScopeKind.CLASS_INITIALIZER ) { if (primaryConstructorParameters.isNotEmpty()) { val parameterDescriptors = classDescriptor.unsubstitutedPrimaryConstructor!!.valueParameters diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/LazyScriptDescriptor.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/LazyScriptDescriptor.kt index 808e5c6b169..110619ad131 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/LazyScriptDescriptor.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/LazyScriptDescriptor.kt @@ -35,16 +35,16 @@ import org.jetbrains.kotlin.types.TypeSubstitutor import org.jetbrains.kotlin.utils.ifEmpty class LazyScriptDescriptor( - resolveSession: ResolveSession, - containingDeclaration: DeclarationDescriptor, - name: Name, - internal val scriptInfo: KtScriptInfo + resolveSession: ResolveSession, + containingDeclaration: DeclarationDescriptor, + name: Name, + internal val scriptInfo: KtScriptInfo ) : ScriptDescriptor, LazyClassDescriptor( - resolveSession, - containingDeclaration, - name, - scriptInfo, - /* isExternal = */ false + resolveSession, + containingDeclaration, + name, + scriptInfo, + /* isExternal = */ false ) { init { resolveSession.trace.record(BindingContext.SCRIPT, scriptInfo.script, this) @@ -67,18 +67,19 @@ class LazyScriptDescriptor( override fun substitute(substitutor: TypeSubstitutor) = this override fun accept(visitor: DeclarationDescriptorVisitor, data: D): R = - visitor.visitScriptDescriptor(this, data) + visitor.visitScriptDescriptor(this, data) - override fun createMemberScope( c: LazyClassContext, declarationProvider: ClassMemberDeclarationProvider): LazyScriptClassMemberScope = + override fun createMemberScope(c: LazyClassContext, declarationProvider: ClassMemberDeclarationProvider): LazyScriptClassMemberScope = LazyScriptClassMemberScope( - // Must be a ResolveSession for scripts - c as ResolveSession, - declarationProvider, - this, - c.trace + // Must be a ResolveSession for scripts + c as ResolveSession, + declarationProvider, + this, + c.trace ) override fun getUnsubstitutedPrimaryConstructor() = super.getUnsubstitutedPrimaryConstructor()!! - override fun computeSupertypes() = listOf(ScriptHelper.getInstance().getKotlinType(this, scriptDefinition.template)).ifEmpty { listOf(builtIns.anyType) } + override fun computeSupertypes() = + listOf(ScriptHelper.getInstance().getKotlinType(this, scriptDefinition.template)).ifEmpty { listOf(builtIns.anyType) } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/LazyTypeAliasDescriptor.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/LazyTypeAliasDescriptor.kt index e63a20325cf..e45b30d305c 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/LazyTypeAliasDescriptor.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/LazyTypeAliasDescriptor.kt @@ -32,15 +32,15 @@ import org.jetbrains.kotlin.storage.getValue import org.jetbrains.kotlin.types.* class LazyTypeAliasDescriptor( - override val storageManager: StorageManager, - private val trace: BindingTrace, - containingDeclaration: DeclarationDescriptor, - annotations: Annotations, - name: Name, - sourceElement: SourceElement, - visibility: Visibility + override val storageManager: StorageManager, + private val trace: BindingTrace, + containingDeclaration: DeclarationDescriptor, + annotations: Annotations, + name: Name, + sourceElement: SourceElement, + visibility: Visibility ) : AbstractTypeAliasDescriptor(containingDeclaration, annotations, name, sourceElement, visibility), - TypeAliasDescriptor { + TypeAliasDescriptor { override val constructors: Collection by storageManager.createLazyValue { getTypeAliasConstructors() } @@ -59,9 +59,9 @@ class LazyTypeAliasDescriptor( override fun isActual(): Boolean = isActual fun initialize( - declaredTypeParameters: List, - lazyUnderlyingType: NotNullLazyValue, - lazyExpandedType: NotNullLazyValue + declaredTypeParameters: List, + lazyUnderlyingType: NotNullLazyValue, + lazyExpandedType: NotNullLazyValue ) { super.initialize(declaredTypeParameters) this.underlyingTypeImpl = lazyUnderlyingType @@ -81,43 +81,52 @@ class LazyTypeAliasDescriptor( } private val lazyTypeConstructorParameters = - storageManager.createRecursionTolerantLazyValue({ this.computeConstructorTypeParameters() }, emptyList()) + storageManager.createRecursionTolerantLazyValue({ this.computeConstructorTypeParameters() }, emptyList()) fun initialize( - declaredTypeParameters: List, - underlyingType: SimpleType, - expandedType: SimpleType - ) = initialize(declaredTypeParameters, storageManager.createLazyValue { underlyingType }, storageManager.createLazyValue { expandedType }) + declaredTypeParameters: List, + underlyingType: SimpleType, + expandedType: SimpleType + ) = initialize( + declaredTypeParameters, + storageManager.createLazyValue { underlyingType }, + storageManager.createLazyValue { expandedType } + ) override fun substitute(substitutor: TypeSubstitutor): TypeAliasDescriptor { if (substitutor.isEmpty) return this - val substituted = LazyTypeAliasDescriptor(storageManager, trace, - containingDeclaration, annotations, name, source, visibility) + val substituted = LazyTypeAliasDescriptor( + storageManager, trace, + containingDeclaration, annotations, name, source, visibility + ) substituted.initialize(declaredTypeParameters, - storageManager.createLazyValue { - substitutor.substitute(underlyingType, Variance.INVARIANT)!!.asSimpleType() - }, - storageManager.createLazyValue { - substitutor.substitute(expandedType, Variance.INVARIANT)!!.asSimpleType() - } - ) + storageManager.createLazyValue { + substitutor.substitute(underlyingType, Variance.INVARIANT)!!.asSimpleType() + }, + storageManager.createLazyValue { + substitutor.substitute(expandedType, Variance.INVARIANT)!!.asSimpleType() + } + ) return substituted } override fun getTypeConstructorTypeParameters(): List = - lazyTypeConstructorParameters() + lazyTypeConstructorParameters() companion object { - @JvmStatic fun create( - storageManager: StorageManager, - trace: BindingTrace, - containingDeclaration: DeclarationDescriptor, - annotations: Annotations, - name: Name, - sourceElement: SourceElement, - visibility: Visibility + @JvmStatic + fun create( + storageManager: StorageManager, + trace: BindingTrace, + containingDeclaration: DeclarationDescriptor, + annotations: Annotations, + name: Name, + sourceElement: SourceElement, + visibility: Visibility ): LazyTypeAliasDescriptor = - LazyTypeAliasDescriptor(storageManager, trace, - containingDeclaration, annotations, name, sourceElement, visibility) + LazyTypeAliasDescriptor( + storageManager, trace, + containingDeclaration, annotations, name, sourceElement, visibility + ) } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/packageDescriptorUtil.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/packageDescriptorUtil.kt index 3f0fb3a4c65..b8210bf356c 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/packageDescriptorUtil.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/packageDescriptorUtil.kt @@ -21,6 +21,6 @@ import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor import org.jetbrains.kotlin.psi.KtFile fun ModuleDescriptor.findPackageFragmentForFile(ktFile: KtFile): PackageFragmentDescriptor? = - getPackage(ktFile.packageFqName).fragments - .filterIsInstance() - .firstOrNull { it.declarationProvider.containsFile(ktFile) } + getPackage(ktFile.packageFqName).fragments + .filterIsInstance() + .firstOrNull { it.declarationProvider.containsFile(ktFile) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/repl/ReplState.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/repl/ReplState.kt index 693b441526f..aac6e9453f7 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/repl/ReplState.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/repl/ReplState.kt @@ -62,7 +62,12 @@ class ReplState { abstract val parentLine: SuccessfulLine? class SubmittedLine(override val linePsi: KtFile, override val parentLine: SuccessfulLine?) : LineInfo() - class SuccessfulLine(override val linePsi: KtFile, override val parentLine: SuccessfulLine?, val lineDescriptor: LazyScriptDescriptor) : LineInfo() + class SuccessfulLine( + override val linePsi: KtFile, + override val parentLine: SuccessfulLine?, + val lineDescriptor: LazyScriptDescriptor + ) : LineInfo() + class FailedLine(override val linePsi: KtFile, override val parentLine: SuccessfulLine?) : LineInfo() } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/scopes/receivers/ExpressionReceiver.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/scopes/receivers/ExpressionReceiver.kt index edeccc03027..9498f5d6d19 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/scopes/receivers/ExpressionReceiver.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/scopes/receivers/ExpressionReceiver.kt @@ -21,44 +21,43 @@ import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.types.KotlinType -interface ExpressionReceiver : ReceiverValue { +interface ExpressionReceiver : ReceiverValue { val expression: KtExpression companion object { private open class ExpressionReceiverImpl( - override val expression: KtExpression, type: KotlinType - ): AbstractReceiverValue(type), ExpressionReceiver { + override val expression: KtExpression, type: KotlinType + ) : AbstractReceiverValue(type), ExpressionReceiver { override fun replaceType(newType: KotlinType) = ExpressionReceiverImpl(expression, newType) override fun toString() = "$type {$expression: ${expression.text}}" } private class ThisExpressionClassReceiver( - override val classDescriptor: ClassDescriptor, - expression: KtExpression, - type: KotlinType + override val classDescriptor: ClassDescriptor, + expression: KtExpression, + type: KotlinType ) : ExpressionReceiverImpl(expression, type), ThisClassReceiver { override fun replaceType(newType: KotlinType) = ThisExpressionClassReceiver(classDescriptor, expression, newType) } private class SuperExpressionReceiver( - override val thisType: KotlinType, - expression: KtExpression, - type: KotlinType + override val thisType: KotlinType, + expression: KtExpression, + type: KotlinType ) : ExpressionReceiverImpl(expression, type), SuperCallReceiverValue { override fun replaceType(newType: KotlinType) = SuperExpressionReceiver(thisType, expression, newType) } fun create( - expression: KtExpression, - type: KotlinType, - bindingContext: BindingContext + expression: KtExpression, + type: KotlinType, + bindingContext: BindingContext ): ExpressionReceiver { var referenceExpression: KtReferenceExpression? = null if (expression is KtThisExpression) { referenceExpression = expression.instanceReference - } - else if (expression is KtConstructorDelegationReferenceExpression) { // todo check this + } else if (expression is KtConstructorDelegationReferenceExpression) { // todo check this referenceExpression = expression } @@ -67,12 +66,11 @@ interface ExpressionReceiver : ReceiverValue { if (descriptor is ClassDescriptor) { return ThisExpressionClassReceiver(descriptor.original, expression, type) } - } - else if (expression is KtSuperExpression) { + } else if (expression is KtSuperExpression) { // if there is no THIS_TYPE_FOR_SUPER_EXPRESSION in binding context, we fall through into more restrictive option // i.e. just return common ExpressionReceiverImpl - bindingContext[BindingContext.THIS_TYPE_FOR_SUPER_EXPRESSION, expression]?.let { - thisType -> return SuperExpressionReceiver(thisType, expression, type) + bindingContext[BindingContext.THIS_TYPE_FOR_SUPER_EXPRESSION, expression]?.let { thisType -> + return SuperExpressionReceiver(thisType, expression, type) } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/scopes/receivers/Qualifier.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/scopes/receivers/Qualifier.kt index 4b6684f899a..d431ee375bd 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/scopes/receivers/Qualifier.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/scopes/receivers/Qualifier.kt @@ -39,8 +39,8 @@ val Qualifier.expression: KtExpression get() = referenceExpression.getTopmostParentQualifiedExpressionForSelector() ?: referenceExpression class PackageQualifier( - override val referenceExpression: KtSimpleNameExpression, - override val descriptor: PackageViewDescriptor + override val referenceExpression: KtSimpleNameExpression, + override val descriptor: PackageViewDescriptor ) : Qualifier { override val classValueReceiver: ReceiverValue? get() = null override val staticScope: MemberScope get() = descriptor.memberScope @@ -49,8 +49,8 @@ class PackageQualifier( } class TypeParameterQualifier( - override val referenceExpression: KtSimpleNameExpression, - override val descriptor: TypeParameterDescriptor + override val referenceExpression: KtSimpleNameExpression, + override val descriptor: TypeParameterDescriptor ) : Qualifier { override val classValueReceiver: ReceiverValue? get() = null override val staticScope: MemberScope get() = MemberScope.Empty @@ -63,32 +63,33 @@ interface ClassifierQualifier : Qualifier { } class ClassQualifier( - override val referenceExpression: KtSimpleNameExpression, - override val descriptor: ClassDescriptor + override val referenceExpression: KtSimpleNameExpression, + override val descriptor: ClassDescriptor ) : ClassifierQualifier { override val classValueReceiver: ClassValueReceiver? = descriptor.classValueType?.let { ClassValueReceiver(this, it) } - override val staticScope: MemberScope get() { - val scopes = ArrayList(2) + override val staticScope: MemberScope + get() { + val scopes = ArrayList(2) - scopes.add(descriptor.staticScope) + scopes.add(descriptor.staticScope) - if (descriptor.kind != ClassKind.ENUM_ENTRY) { - scopes.add(descriptor.unsubstitutedInnerClassesScope) + if (descriptor.kind != ClassKind.ENUM_ENTRY) { + scopes.add(descriptor.unsubstitutedInnerClassesScope) + } + + return ChainedMemberScope("Static scope for ${descriptor.name} as class or object", scopes) } - return ChainedMemberScope("Static scope for ${descriptor.name} as class or object", scopes) - } - override fun toString() = "Class{$descriptor}" } class TypeAliasQualifier( - override val referenceExpression: KtSimpleNameExpression, - override val descriptor: TypeAliasDescriptor, - val classDescriptor: ClassDescriptor + override val referenceExpression: KtSimpleNameExpression, + override val descriptor: TypeAliasDescriptor, + val classDescriptor: ClassDescriptor ) : ClassifierQualifier { override val classValueReceiver: ClassValueReceiver? get() = classDescriptor.classValueType?.let { @@ -98,17 +99,19 @@ class TypeAliasQualifier( override val staticScope: MemberScope get() = when { DescriptorUtils.isEnumClass(classDescriptor) -> - ChainedMemberScope("Static scope for typealias ${descriptor.name}", - listOf(classDescriptor.staticScope, EnumEntriesScope())) + ChainedMemberScope( + "Static scope for typealias ${descriptor.name}", + listOf(classDescriptor.staticScope, EnumEntriesScope()) + ) else -> classDescriptor.staticScope } private inner class EnumEntriesScope : MemberScopeImpl() { override fun getContributedClassifier(name: Name, location: LookupLocation): ClassifierDescriptor? = - classDescriptor.unsubstitutedInnerClassesScope - .getContributedClassifier(name, location) - ?.takeIf { DescriptorUtils.isEnumEntry(it) } + classDescriptor.unsubstitutedInnerClassesScope + .getContributedClassifier(name, location) + ?.takeIf { DescriptorUtils.isEnumEntry(it) } override fun printScopeStructure(p: Printer) { p.println(this::class.java.simpleName, " {") diff --git a/compiler/frontend/src/org/jetbrains/kotlin/script/KotlinScriptDefinition.kt b/compiler/frontend/src/org/jetbrains/kotlin/script/KotlinScriptDefinition.kt index d40ddadd32a..d62e5674c35 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/script/KotlinScriptDefinition.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/script/KotlinScriptDefinition.kt @@ -37,10 +37,10 @@ open class KotlinScriptDefinition(val template: KClass) { get() = emptyList() open fun isScript(fileName: String): Boolean = - fileName.endsWith(KotlinParserDefinition.STD_SCRIPT_EXT) + fileName.endsWith(KotlinParserDefinition.STD_SCRIPT_EXT) open fun getScriptName(script: KtScript): Name = - NameUtils.getScriptNameForFile(script.containingKtFile.name) + NameUtils.getScriptNameForFile(script.containingKtFile.name) open val dependencyResolver: DependenciesResolver get() = DependenciesResolver.NoDependencies diff --git a/compiler/frontend/src/org/jetbrains/kotlin/script/ScriptHelper.kt b/compiler/frontend/src/org/jetbrains/kotlin/script/ScriptHelper.kt index 657dbb96487..c9f592126f5 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/script/ScriptHelper.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/script/ScriptHelper.kt @@ -30,8 +30,8 @@ interface ScriptHelper { companion object { private val scriptHelperInstance: ScriptHelper = - ServiceLoader.load(ScriptHelper::class.java, ScriptHelper::class.java.classLoader).firstOrNull() - ?: error("ScriptHelper implementation is not found") + ServiceLoader.load(ScriptHelper::class.java, ScriptHelper::class.java.classLoader).firstOrNull() + ?: error("ScriptHelper implementation is not found") fun getInstance(): ScriptHelper = scriptHelperInstance } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/storage/LockBasedLazyResolveStorageManager.kt b/compiler/frontend/src/org/jetbrains/kotlin/storage/LockBasedLazyResolveStorageManager.kt index d4fc6674744..5792629cf97 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/storage/LockBasedLazyResolveStorageManager.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/storage/LockBasedLazyResolveStorageManager.kt @@ -28,7 +28,8 @@ import com.intellij.util.containers.ContainerUtil import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.types.KotlinType -class LockBasedLazyResolveStorageManager(private val storageManager: StorageManager): StorageManager by storageManager, LazyResolveStorageManager { +class LockBasedLazyResolveStorageManager(private val storageManager: StorageManager) : StorageManager by storageManager, + LazyResolveStorageManager { override fun createSoftlyRetainedMemoizedFunction(compute: Function1) = storageManager.createMemoizedFunction(compute, ContainerUtil.createConcurrentSoftValueMap()) @@ -36,7 +37,7 @@ class LockBasedLazyResolveStorageManager(private val storageManager: StorageMana storageManager.createMemoizedFunctionWithNullableValues(compute, ContainerUtil.createConcurrentSoftValueMap()) override fun createSafeTrace(originalTrace: BindingTrace): BindingTrace = - LockProtectedTrace(storageManager, originalTrace) + LockProtectedTrace(storageManager, originalTrace) private class LockProtectedContext(private val storageManager: StorageManager, private val context: BindingContext) : BindingContext { override fun getType(expression: KtExpression): KotlinType? = storageManager.compute { context.getType(expression) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/types/CastDiagnosticsUtil.kt b/compiler/frontend/src/org/jetbrains/kotlin/types/CastDiagnosticsUtil.kt index ff179a87a84..bb5e80e47c2 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/types/CastDiagnosticsUtil.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/types/CastDiagnosticsUtil.kt @@ -38,9 +38,9 @@ object CastDiagnosticsUtil { // it must be really impossible @JvmStatic fun isCastPossible( - lhsType: KotlinType, - rhsType: KotlinType, - platformToKotlinClassMap: PlatformToKotlinClassMap + lhsType: KotlinType, + rhsType: KotlinType, + platformToKotlinClassMap: PlatformToKotlinClassMap ): Boolean { val rhsNullable = TypeUtils.isNullableType(rhsType) val lhsNullable = TypeUtils.isNullableType(lhsType) @@ -77,8 +77,8 @@ object CastDiagnosticsUtil { } private fun mapToPlatformIndependentClasses( - type: KotlinType, - platformToKotlinClassMap: PlatformToKotlinClassMap + type: KotlinType, + platformToKotlinClassMap: PlatformToKotlinClassMap ): List { val descriptor = type.constructor.declarationDescriptor as? ClassDescriptor ?: return listOf() @@ -88,7 +88,7 @@ object CastDiagnosticsUtil { private fun isFinal(type: KotlinType) = !TypeUtils.canHaveSubtypes(KotlinTypeChecker.DEFAULT, type) private fun isTrait(type: KotlinType) = - type.constructor.declarationDescriptor.let { it is ClassDescriptor && it.kind == ClassKind.INTERFACE } + type.constructor.declarationDescriptor.let { it is ClassDescriptor && it.kind == ClassKind.INTERFACE } /** * Check if cast from supertype to subtype is erased. @@ -168,11 +168,10 @@ object CastDiagnosticsUtil { val substitution: MutableMap = if (supertypeWithVariables != null) { // Now, let's try to unify Collection and Collection solution is a map from T to Foo val solution = TypeUnifier.unify( - TypeProjectionImpl(supertype), TypeProjectionImpl(supertypeWithVariables), variableConstructors::contains + TypeProjectionImpl(supertype), TypeProjectionImpl(supertypeWithVariables), variableConstructors::contains ) Maps.newHashMap(solution.substitution) - } - else { + } else { // If there's no corresponding supertype, no variables are determined // This may be OK, e.g. in case 'Any as List<*>' Maps.newHashMapWithExpectedSize(variables.size) @@ -185,8 +184,9 @@ object CastDiagnosticsUtil { val value = substitution[variable.typeConstructor] if (value == null) { substitution.put( - variable.typeConstructor, - TypeUtils.makeStarProjection(variable)) + variable.typeConstructor, + TypeUtils.makeStarProjection(variable) + ) allArgumentsInferred = false } } @@ -201,10 +201,10 @@ object CastDiagnosticsUtil { private fun allParametersReified(subtype: KotlinType) = subtype.constructor.parameters.all { it.isReified } fun castIsUseless( - expression: KtBinaryExpressionWithTypeRHS, - context: ExpressionTypingContext, - targetType: KotlinType, - actualType: KotlinType + expression: KtBinaryExpressionWithTypeRHS, + context: ExpressionTypingContext, + targetType: KotlinType, + actualType: KotlinType ): Boolean { // Here: x as? Type <=> x as Type? val refinedTargetType = if (KtPsiUtil.isSafeCast(expression)) TypeUtils.makeNullable(targetType) else targetType @@ -214,9 +214,9 @@ object CastDiagnosticsUtil { // It is a warning "useless cast" for `as` and a warning "redundant is" for `is` fun isRefinementUseless( - possibleTypes: Collection, - targetType: KotlinType, - shouldCheckForExactType: Boolean + possibleTypes: Collection, + targetType: KotlinType, + shouldCheckForExactType: Boolean ): Boolean { val intersectedType = TypeIntersector.intersectTypes(possibleTypes.map { it.upperIfFlexible() }) ?: return false @@ -255,8 +255,8 @@ object CastDiagnosticsUtil { private fun checkExactTypeForUselessCast(expression: KtBinaryExpressionWithTypeRHS): Boolean { var parent = expression.parent while (parent is KtParenthesizedExpression || - parent is KtLabeledExpression || - parent is KtAnnotatedExpression) { + parent is KtLabeledExpression || + parent is KtAnnotatedExpression) { parent = parent.parent } @@ -279,4 +279,4 @@ object CastDiagnosticsUtil { else -> false } } -} +} \ No newline at end of file diff --git a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/AssignedVariablesSearcher.kt b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/AssignedVariablesSearcher.kt index 68baa0c661b..4704446156b 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/AssignedVariablesSearcher.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/AssignedVariablesSearcher.kt @@ -23,7 +23,7 @@ import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* -abstract class AssignedVariablesSearcher: KtTreeVisitorVoid() { +abstract class AssignedVariablesSearcher : KtTreeVisitorVoid() { data class Writer(val assignment: KtBinaryExpression, val declaration: KtDeclaration?) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/DestructuringDeclarationResolver.kt b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/DestructuringDeclarationResolver.kt index bbaa839e67c..1e45ab399f6 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/DestructuringDeclarationResolver.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/DestructuringDeclarationResolver.kt @@ -36,21 +36,22 @@ import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.checker.KotlinTypeChecker class DestructuringDeclarationResolver( - private val fakeCallResolver: FakeCallResolver, - private val localVariableResolver: LocalVariableResolver, - private val typeResolver: TypeResolver + private val fakeCallResolver: FakeCallResolver, + private val localVariableResolver: LocalVariableResolver, + private val typeResolver: TypeResolver ) { fun resolveLocalVariablesFromDestructuringDeclaration( - scope: LexicalScope, - destructuringDeclaration: KtDestructuringDeclaration, - receiver: ReceiverValue?, - initializer: KtExpression?, - context: ExpressionTypingContext + scope: LexicalScope, + destructuringDeclaration: KtDestructuringDeclaration, + receiver: ReceiverValue?, + initializer: KtExpression?, + context: ExpressionTypingContext ): List { val result = arrayListOf() for ((componentIndex, entry) in destructuringDeclaration.entries.withIndex()) { val componentType = resolveInitializer(entry, receiver, initializer, context, componentIndex) - val variableDescriptor = localVariableResolver.resolveLocalVariableDescriptorWithType(scope, entry, componentType, context.trace) + val variableDescriptor = + localVariableResolver.resolveLocalVariableDescriptorWithType(scope, entry, componentType, context.trace) result.add(variableDescriptor) } @@ -59,35 +60,35 @@ class DestructuringDeclarationResolver( } fun defineLocalVariablesFromDestructuringDeclaration( - writableScope: LexicalWritableScope, - destructuringDeclaration: KtDestructuringDeclaration, - receiver: ReceiverValue?, - initializer: KtExpression?, - context: ExpressionTypingContext + writableScope: LexicalWritableScope, + destructuringDeclaration: KtDestructuringDeclaration, + receiver: ReceiverValue?, + initializer: KtExpression?, + context: ExpressionTypingContext ) = resolveLocalVariablesFromDestructuringDeclaration( - writableScope, destructuringDeclaration, receiver, initializer, context + writableScope, destructuringDeclaration, receiver, initializer, context ).forEach { ExpressionTypingUtils.checkVariableShadowing(writableScope, context.trace, it) writableScope.addVariableDescriptor(it) } fun resolveInitializer( - entry: KtDestructuringDeclarationEntry, - receiver: ReceiverValue?, - initializer: KtExpression?, - context: ExpressionTypingContext, - componentIndex: Int + entry: KtDestructuringDeclarationEntry, + receiver: ReceiverValue?, + initializer: KtExpression?, + context: ExpressionTypingContext, + componentIndex: Int ): KotlinType { val componentName = DataClassDescriptorResolver.createComponentName(componentIndex + 1) return resolveComponentFunctionAndGetType(componentName, context, entry, receiver, initializer) } private fun resolveComponentFunctionAndGetType( - componentName: Name, - context: ExpressionTypingContext, - entry: KtDestructuringDeclarationEntry, - receiver: ReceiverValue?, - initializer: KtExpression? + componentName: Name, + context: ExpressionTypingContext, + entry: KtDestructuringDeclarationEntry, + receiver: ReceiverValue?, + initializer: KtExpression? ): KotlinType { fun errorType() = ErrorUtils.createErrorType("$componentName() return type") @@ -96,8 +97,8 @@ class DestructuringDeclarationResolver( val expectedType = getExpectedTypeForComponent(context, entry) val newContext = context.replaceExpectedType(expectedType).replaceContextDependency(ContextDependency.INDEPENDENT) val results = fakeCallResolver.resolveFakeCall( - newContext, receiver, componentName, - entry, initializer ?: entry, FakeCallKind.COMPONENT, emptyList() + newContext, receiver, componentName, + entry, initializer ?: entry, FakeCallKind.COMPONENT, emptyList() ) if (!results.isSuccess) { @@ -108,10 +109,12 @@ class DestructuringDeclarationResolver( val functionReturnType = results.resultingDescriptor.returnType if (functionReturnType != null && !TypeUtils.noExpectedType(expectedType) - && !KotlinTypeChecker.DEFAULT.isSubtypeOf(functionReturnType, expectedType) ) { + && !KotlinTypeChecker.DEFAULT.isSubtypeOf(functionReturnType, expectedType)) { context.trace.report( - Errors.COMPONENT_FUNCTION_RETURN_TYPE_MISMATCH.on( - initializer ?: entry, componentName, functionReturnType, expectedType)) + Errors.COMPONENT_FUNCTION_RETURN_TYPE_MISMATCH.on( + initializer ?: entry, componentName, functionReturnType, expectedType + ) + ) } return functionReturnType ?: errorType() } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/FakeCallResolver.kt b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/FakeCallResolver.kt index 93c8b5bafa9..241748e9471 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/FakeCallResolver.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/FakeCallResolver.kt @@ -44,33 +44,39 @@ enum class FakeCallKind { } class FakeCallResolver( - private val project: Project, - private val callResolver: CallResolver + private val project: Project, + private val callResolver: CallResolver ) { fun resolveFakeCall( - context: ResolutionContext<*>, - receiver: ReceiverValue?, - name: Name, - callElement: KtExpression, - reportErrorsOn: KtExpression, - callKind: FakeCallKind, - valueArguments: List + context: ResolutionContext<*>, + receiver: ReceiverValue?, + name: Name, + callElement: KtExpression, + reportErrorsOn: KtExpression, + callKind: FakeCallKind, + valueArguments: List ): OverloadResolutionResults { val fakeTrace = TemporaryBindingTrace.create(context.trace, "trace to resolve fake call for", name) val fakeBindingTrace = context.replaceBindingTrace(fakeTrace) var reportIsMissingError = false val realExpression = RealExpression(reportErrorsOn, callKind) - val result = makeAndResolveFakeCallInContext(receiver, fakeBindingTrace, valueArguments, name, callElement, realExpression) { fake -> - reportIsMissingError = fakeTrace.bindingContext.diagnostics.noSuppression().forElement(fake).any { it.severity == Severity.ERROR } - fakeTrace.commit({ _, key -> key != fake }, true) - } + val result = + makeAndResolveFakeCallInContext(receiver, fakeBindingTrace, valueArguments, name, callElement, realExpression) { fake -> + reportIsMissingError = + fakeTrace.bindingContext.diagnostics.noSuppression().forElement(fake).any { it.severity == Severity.ERROR } + fakeTrace.commit({ _, key -> key != fake }, true) + } val resolutionResults = result.second if (reportIsMissingError) { val diagnostic = when (callKind) { FakeCallKind.ITERATOR -> Errors.ITERATOR_MISSING.on(reportErrorsOn) - FakeCallKind.COMPONENT -> if (receiver != null) Errors.COMPONENT_FUNCTION_MISSING.on(reportErrorsOn, name, receiver.type) else null + FakeCallKind.COMPONENT -> if (receiver != null) Errors.COMPONENT_FUNCTION_MISSING.on( + reportErrorsOn, + name, + receiver.type + ) else null FakeCallKind.OTHER -> null } @@ -83,10 +89,10 @@ class FakeCallResolver( } private class TracingStrategyForComponentCall( - fakeExpression: KtReferenceExpression, - val reportErrorsOn: KtExpression, - val name: Name, - val call: Call + fakeExpression: KtReferenceExpression, + val reportErrorsOn: KtExpression, + val name: Name, + val call: Call ) : TracingStrategy by TracingStrategyImpl.create(fakeExpression, call) { override fun ambiguity(trace: BindingTrace, descriptors: Collection>) { @@ -106,9 +112,9 @@ class FakeCallResolver( } private class TracingStrategyForIteratorCall( - fakeExpression: KtReferenceExpression, - val reportErrorsOn: KtExpression, - val call: Call + fakeExpression: KtReferenceExpression, + val reportErrorsOn: KtExpression, + val call: Call ) : TracingStrategy by TracingStrategyImpl.create(fakeExpression, call) { override fun ambiguity(trace: BindingTrace, descriptors: Collection>) { @@ -129,20 +135,25 @@ class FakeCallResolver( @JvmOverloads fun makeAndResolveFakeCallInContext( - receiver: ReceiverValue?, - context: ResolutionContext<*>, - valueArguments: List, - name: Name, - callElement: KtExpression, - realExpression: RealExpression? = null, - onComplete: (KtSimpleNameExpression) -> Unit = { _ -> } + receiver: ReceiverValue?, + context: ResolutionContext<*>, + valueArguments: List, + name: Name, + callElement: KtExpression, + realExpression: RealExpression? = null, + onComplete: (KtSimpleNameExpression) -> Unit = { _ -> } ): Pair> { val fakeCalleeExpression = KtPsiFactory(project, markGenerated = false).createSimpleName(name.asString()) val call = CallMaker.makeCallWithExpressions(callElement, receiver, null, fakeCalleeExpression, valueArguments) val tracingStrategy = when (realExpression?.callKind) { FakeCallKind.ITERATOR -> TracingStrategyForIteratorCall(fakeCalleeExpression, realExpression.expressionToReportErrorsOn, call) - FakeCallKind.COMPONENT -> TracingStrategyForComponentCall(fakeCalleeExpression, realExpression.expressionToReportErrorsOn, name, call) + FakeCallKind.COMPONENT -> TracingStrategyForComponentCall( + fakeCalleeExpression, + realExpression.expressionToReportErrorsOn, + name, + call + ) else -> null } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/FunctionsTypingVisitor.kt b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/FunctionsTypingVisitor.kt index 8647ab17abf..69209036713 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/FunctionsTypingVisitor.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/FunctionsTypingVisitor.kt @@ -60,10 +60,10 @@ internal class FunctionsTypingVisitor(facade: ExpressionTypingInternals) : Expre } fun visitNamedFunction( - function: KtNamedFunction, - context: ExpressionTypingContext, - isDeclaration: Boolean, - statementScope: LexicalWritableScope? // must be not null if isDeclaration + function: KtNamedFunction, + context: ExpressionTypingContext, + isDeclaration: Boolean, + statementScope: LexicalWritableScope? // must be not null if isDeclaration ): KotlinTypeInfo { if (!isDeclaration) { // function expression @@ -88,33 +88,33 @@ internal class FunctionsTypingVisitor(facade: ExpressionTypingInternals) : Expre val functionDescriptor: SimpleFunctionDescriptor if (isDeclaration) { functionDescriptor = components.functionDescriptorResolver.resolveFunctionDescriptor( - context.scope.ownerDescriptor, context.scope, function, context.trace, context.dataFlowInfo) + context.scope.ownerDescriptor, context.scope, function, context.trace, context.dataFlowInfo + ) assert(statementScope != null) { "statementScope must be not null for function: " + function.name + " at location " + DiagnosticUtils.atLocation(function) } statementScope!!.addFunctionDescriptor(functionDescriptor) - } - else { + } else { functionDescriptor = components.functionDescriptorResolver.resolveFunctionExpressionDescriptor( - context.scope.ownerDescriptor, context.scope, function, - context.trace, context.dataFlowInfo, context.expectedType + context.scope.ownerDescriptor, context.scope, function, + context.trace, context.dataFlowInfo, context.expectedType ) } // Necessary for local functions ForceResolveUtil.forceResolveAllContents(functionDescriptor.annotations) - val functionInnerScope = FunctionDescriptorUtil.getFunctionInnerScope(context.scope, functionDescriptor, context.trace, components.overloadChecker) + val functionInnerScope = + FunctionDescriptorUtil.getFunctionInnerScope(context.scope, functionDescriptor, context.trace, components.overloadChecker) if (!function.hasDeclaredReturnType() && !function.hasBlockBody()) { ForceResolveUtil.forceResolveAllContents(functionDescriptor.returnType) - } - else { + } else { components.expressionTypingServices.checkFunctionReturnType( - functionInnerScope, function, functionDescriptor, context.dataFlowInfo, null, context.trace + functionInnerScope, function, functionDescriptor, context.dataFlowInfo, null, context.trace ) } components.valueParameterResolver.resolveValueParameters( - function.valueParameters, functionDescriptor.valueParameters, functionInnerScope, context.dataFlowInfo, context.trace + function.valueParameters, functionDescriptor.valueParameters, functionInnerScope, context.dataFlowInfo, context.trace ) components.modifiersChecker.withTrace(context.trace).checkModifiersForLocalDeclaration(function, functionDescriptor) @@ -123,8 +123,7 @@ internal class FunctionsTypingVisitor(facade: ExpressionTypingInternals) : Expre return if (isDeclaration) { createTypeInfo(components.dataFlowAnalyzer.checkStatementType(function, context), context) - } - else { + } else { val expectedType = context.expectedType val functionalTypeExpected = expectedType.isBuiltinFunctionalType() @@ -141,13 +140,13 @@ internal class FunctionsTypingVisitor(facade: ExpressionTypingInternals) : Expre private fun SimpleFunctionDescriptor.createFunctionType(suspendFunction: Boolean = false): KotlinType? { return createFunctionType( - components.builtIns, - Annotations.EMPTY, - extensionReceiverParameter?.type, - valueParameters.map { it.type }, - null, - returnType ?: return null, - suspendFunction = suspendFunction + components.builtIns, + Annotations.EMPTY, + extensionReceiverParameter?.type, + valueParameters.map { it.type }, + null, + returnType ?: return null, + suspendFunction = suspendFunction ) } @@ -181,19 +180,20 @@ internal class FunctionsTypingVisitor(facade: ExpressionTypingInternals) : Expre } private fun createFunctionLiteralDescriptor( - expression: KtLambdaExpression, - context: ExpressionTypingContext + expression: KtLambdaExpression, + context: ExpressionTypingContext ): AnonymousFunctionDescriptor { val functionLiteral = expression.functionLiteral val functionDescriptor = AnonymousFunctionDescriptor( - context.scope.ownerDescriptor, - components.annotationResolver.resolveAnnotationsWithArguments(context.scope, expression.getAnnotationEntries(), context.trace), - CallableMemberDescriptor.Kind.DECLARATION, functionLiteral.toSourceElement(), - context.expectedType.isSuspendFunctionType() + context.scope.ownerDescriptor, + components.annotationResolver.resolveAnnotationsWithArguments(context.scope, expression.getAnnotationEntries(), context.trace), + CallableMemberDescriptor.Kind.DECLARATION, functionLiteral.toSourceElement(), + context.expectedType.isSuspendFunctionType() + ) + components.functionDescriptorResolver.initializeFunctionDescriptorAndExplicitReturnType( + context.scope.ownerDescriptor, context.scope, functionLiteral, + functionDescriptor, context.trace, context.expectedType, context.dataFlowInfo ) - components.functionDescriptorResolver. - initializeFunctionDescriptorAndExplicitReturnType(context.scope.ownerDescriptor, context.scope, functionLiteral, - functionDescriptor, context.trace, context.expectedType, context.dataFlowInfo) for (parameterDescriptor in functionDescriptor.valueParameters) { ForceResolveUtil.forceResolveAllContents(parameterDescriptor.annotations) } @@ -202,16 +202,16 @@ internal class FunctionsTypingVisitor(facade: ExpressionTypingInternals) : Expre } private fun KotlinType.isBuiltinFunctionalType() = - !noExpectedType(this) && isBuiltinFunctionalType + !noExpectedType(this) && isBuiltinFunctionalType private fun KotlinType.isSuspendFunctionType() = - !noExpectedType(this) && isSuspendFunctionType + !noExpectedType(this) && isSuspendFunctionType private fun computeReturnType( - expression: KtLambdaExpression, - context: ExpressionTypingContext, - functionDescriptor: SimpleFunctionDescriptorImpl, - functionTypeExpected: Boolean + expression: KtLambdaExpression, + context: ExpressionTypingContext, + functionDescriptor: SimpleFunctionDescriptorImpl, + functionTypeExpected: Boolean ): KotlinType { val expectedReturnType = if (functionTypeExpected) context.expectedType.getReturnTypeFromFunctionType() else null val returnType = computeUnsafeReturnType(expression, context, functionDescriptor, expectedReturnType) @@ -225,15 +225,16 @@ internal class FunctionsTypingVisitor(facade: ExpressionTypingInternals) : Expre } private fun computeUnsafeReturnType( - expression: KtLambdaExpression, - context: ExpressionTypingContext, - functionDescriptor: SimpleFunctionDescriptorImpl, - expectedReturnType: KotlinType? + expression: KtLambdaExpression, + context: ExpressionTypingContext, + functionDescriptor: SimpleFunctionDescriptorImpl, + expectedReturnType: KotlinType? ): KotlinType? { val functionLiteral = expression.functionLiteral val expectedType = expectedReturnType ?: NO_EXPECTED_TYPE - val functionInnerScope = FunctionDescriptorUtil.getFunctionInnerScope(context.scope, functionDescriptor, context.trace, components.overloadChecker) + val functionInnerScope = + FunctionDescriptorUtil.getFunctionInnerScope(context.scope, functionDescriptor, context.trace, components.overloadChecker) var newContext = context.replaceScope(functionInnerScope).replaceExpectedType(expectedType) // This is needed for ControlStructureTypingVisitor#visitReturnExpression() to properly type-check returned expressions @@ -247,7 +248,8 @@ internal class FunctionsTypingVisitor(facade: ExpressionTypingInternals) : Expre } // Type-check the body - val blockReturnedType = components.expressionTypingServices.getBlockReturnedType(functionLiteral.bodyExpression!!, COERCION_TO_UNIT, newContext) + val blockReturnedType = + components.expressionTypingServices.getBlockReturnedType(functionLiteral.bodyExpression!!, COERCION_TO_UNIT, newContext) val typeOfBodyExpression = blockReturnedType.type newInferenceLambdaInfo?.let { @@ -259,9 +261,9 @@ internal class FunctionsTypingVisitor(facade: ExpressionTypingInternals) : Expre } private fun computeReturnTypeBasedOnReturnExpressions( - functionLiteral: KtFunctionLiteral, - context: ExpressionTypingContext, - typeOfBodyExpression: KotlinType? + functionLiteral: KtFunctionLiteral, + context: ExpressionTypingContext, + typeOfBodyExpression: KotlinType? ): KotlinType? { val returnedExpressionTypes = Lists.newArrayList() @@ -271,8 +273,7 @@ internal class FunctionsTypingVisitor(facade: ExpressionTypingInternals) : Expre val returnedExpression = returnExpression.returnedExpression if (returnedExpression == null) { hasEmptyReturn = true - } - else { + } else { // the type should have been computed by getBlockReturnedType() above, but can be null, if returnExpression contains some error returnedExpressionTypes.addIfNotNull(context.trace.getType(returnedExpression)) } @@ -300,7 +301,10 @@ internal class FunctionsTypingVisitor(facade: ExpressionTypingInternals) : Expre val result = Lists.newArrayList() val bodyExpression = functionLiteral.bodyExpression bodyExpression?.accept(object : KtTreeVisitor>() { - override fun visitReturnExpression(expression: KtReturnExpression, insideActualFunction: MutableList): Void? { + override fun visitReturnExpression( + expression: KtReturnExpression, + insideActualFunction: MutableList + ): Void? { insideActualFunction.add(expression) return null } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/LabelResolver.kt b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/LabelResolver.kt index b8d4baab8e8..70f71fb02a5 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/LabelResolver.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/LabelResolver.kt @@ -113,9 +113,9 @@ object LabelResolver { } private fun resolveNamedLabel( - labelName: Name, - labelExpression: KtSimpleNameExpression, - trace: BindingTrace + labelName: Name, + labelExpression: KtSimpleNameExpression, + trace: BindingTrace ): KtElement? { val list = getElementsByLabelName(labelName, labelExpression) if (list.isEmpty()) return null @@ -128,9 +128,9 @@ object LabelResolver { } fun resolveThisOrSuperLabel( - expression: KtInstanceExpressionWithLabel, - context: ResolutionContext<*>, - labelName: Name + expression: KtInstanceExpressionWithLabel, + context: ResolutionContext<*>, + labelName: Name ): LabeledReceiverResolutionResult { val referenceExpression = expression.instanceReference val targetLabel = expression.getTargetLabel() ?: error(expression) @@ -148,7 +148,7 @@ object LabelResolver { } val element = DescriptorToSourceUtils.descriptorToDeclaration(declarationDescriptor) - ?: error("No PSI element for descriptor: " + declarationDescriptor) + ?: error("No PSI element for descriptor: " + declarationDescriptor) context.trace.record(LABEL_TARGET, targetLabel, element) context.trace.record(REFERENCE_TARGET, referenceExpression, declarationDescriptor) @@ -170,8 +170,7 @@ object LabelResolver { context.trace.record(REFERENCE_TARGET, referenceExpression, declarationDescriptor) } return LabeledReceiverResolutionResult.labelResolutionSuccess(thisReceiver) - } - else { + } else { context.trace.report(UNRESOLVED_REFERENCE.on(targetLabel, targetLabel)) } } @@ -181,8 +180,8 @@ object LabelResolver { } class LabeledReceiverResolutionResult private constructor( - val code: LabeledReceiverResolutionResult.Code, - private val receiverParameterDescriptor: ReceiverParameterDescriptor? + val code: LabeledReceiverResolutionResult.Code, + private val receiverParameterDescriptor: ReceiverParameterDescriptor? ) { enum class Code { LABEL_RESOLUTION_ERROR, diff --git a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/PreliminaryLoopVisitor.kt b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/PreliminaryLoopVisitor.kt index 5fe06643f56..a5600f945a3 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/PreliminaryLoopVisitor.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/PreliminaryLoopVisitor.kt @@ -31,8 +31,10 @@ import java.util.* */ class PreliminaryLoopVisitor private constructor() : AssignedVariablesSearcher() { - fun clearDataFlowInfoForAssignedLocalVariables(dataFlowInfo: DataFlowInfo, - languageVersionSettings: LanguageVersionSettings): DataFlowInfo { + fun clearDataFlowInfoForAssignedLocalVariables( + dataFlowInfo: DataFlowInfo, + languageVersionSettings: LanguageVersionSettings + ): DataFlowInfo { var resultFlowInfo = dataFlowInfo val nullabilityMap = resultFlowInfo.completeNullabilityInfo val valueSetToClear = LinkedHashSet() diff --git a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/SenselessComparisonChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/SenselessComparisonChecker.kt index e8dc79cdc1d..451a09b4af8 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/SenselessComparisonChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/SenselessComparisonChecker.kt @@ -29,20 +29,21 @@ import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.isError object SenselessComparisonChecker { - @JvmStatic fun checkSenselessComparisonWithNull( - expression: KtBinaryExpression, - left: KtExpression, - right: KtExpression, - context: ResolutionContext<*>, - getType: (KtExpression) -> KotlinType?, - getNullability: (DataFlowValue) -> Nullability + @JvmStatic + fun checkSenselessComparisonWithNull( + expression: KtBinaryExpression, + left: KtExpression, + right: KtExpression, + context: ResolutionContext<*>, + getType: (KtExpression) -> KotlinType?, + getNullability: (DataFlowValue) -> Nullability ) { val expr = - when { - KtPsiUtil.isNullConstant(left) -> right - KtPsiUtil.isNullConstant(right) -> left - else -> return - } + when { + KtPsiUtil.isNullConstant(left) -> right + KtPsiUtil.isNullConstant(right) -> left + else -> return + } val type = getType(expr) if (type == null || type.isError) return @@ -50,16 +51,17 @@ object SenselessComparisonChecker { val operationSign = expression.operationReference val value = DataFlowValueFactory.createDataFlowValue(expr, type, context) - val equality = operationSign.getReferencedNameElementType() == KtTokens.EQEQ || operationSign.getReferencedNameElementType() == KtTokens.EQEQEQ + val equality = + operationSign.getReferencedNameElementType() == KtTokens.EQEQ || operationSign.getReferencedNameElementType() == KtTokens.EQEQEQ val nullability = getNullability(value) val expressionIsAlways = - when (nullability) { - Nullability.NULL -> equality - Nullability.NOT_NULL -> !equality - Nullability.IMPOSSIBLE -> false - else -> return - } + when (nullability) { + Nullability.NULL -> equality + Nullability.NOT_NULL -> !equality + Nullability.IMPOSSIBLE -> false + else -> return + } context.trace.report(Errors.SENSELESS_COMPARISON.on(expression, expression, expressionIsAlways)) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/TypeInfoFactory.kt b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/TypeInfoFactory.kt index f5726ee2386..a5096d63b5c 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/TypeInfoFactory.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/TypeInfoFactory.kt @@ -28,7 +28,7 @@ import org.jetbrains.kotlin.types.expressions.KotlinTypeInfo fun createTypeInfo(type: KotlinType?, dataFlowInfo: DataFlowInfo): KotlinTypeInfo = KotlinTypeInfo(type, dataFlowInfo) fun createTypeInfo(type: KotlinType?, dataFlowInfo: DataFlowInfo, jumpPossible: Boolean, jumpFlowInfo: DataFlowInfo): KotlinTypeInfo = - KotlinTypeInfo(type, dataFlowInfo, jumpPossible, jumpFlowInfo) + KotlinTypeInfo(type, dataFlowInfo, jumpPossible, jumpFlowInfo) fun createTypeInfo(type: KotlinType?): KotlinTypeInfo = createTypeInfo(type, DataFlowInfo.EMPTY) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/ValueParameterResolver.kt b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/ValueParameterResolver.kt index e7a5900dc7e..1e6f91e930b 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/ValueParameterResolver.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/ValueParameterResolver.kt @@ -32,22 +32,25 @@ import org.jetbrains.kotlin.resolve.scopes.LexicalScopeKind import org.jetbrains.kotlin.types.TypeUtils class ValueParameterResolver( - private val expressionTypingServices: ExpressionTypingServices, - private val constantExpressionEvaluator: ConstantExpressionEvaluator, - private val languageVersionSettings: LanguageVersionSettings + private val expressionTypingServices: ExpressionTypingServices, + private val constantExpressionEvaluator: ConstantExpressionEvaluator, + private val languageVersionSettings: LanguageVersionSettings ) { fun resolveValueParameters( - valueParameters: List, - valueParameterDescriptors: List, - declaringScope: LexicalScope, - dataFlowInfo: DataFlowInfo, - trace: BindingTrace + valueParameters: List, + valueParameterDescriptors: List, + declaringScope: LexicalScope, + dataFlowInfo: DataFlowInfo, + trace: BindingTrace ) { - val scopeForDefaultValue = LexicalScopeImpl(declaringScope, declaringScope.ownerDescriptor, false, null, LexicalScopeKind.DEFAULT_VALUE) + val scopeForDefaultValue = + LexicalScopeImpl(declaringScope, declaringScope.ownerDescriptor, false, null, LexicalScopeKind.DEFAULT_VALUE) - val contextForDefaultValue = ExpressionTypingContext.newContext(trace, scopeForDefaultValue, dataFlowInfo, TypeUtils.NO_EXPECTED_TYPE, - languageVersionSettings) + val contextForDefaultValue = ExpressionTypingContext.newContext( + trace, scopeForDefaultValue, dataFlowInfo, TypeUtils.NO_EXPECTED_TYPE, + languageVersionSettings + ) for ((descriptor, parameter) in valueParameterDescriptors.zip(valueParameters)) { ForceResolveUtil.forceResolveAllContents(descriptor.annotations) @@ -56,9 +59,9 @@ class ValueParameterResolver( } private fun resolveDefaultValue( - valueParameterDescriptor: ValueParameterDescriptor, - jetParameter: KtParameter, - context: ExpressionTypingContext + valueParameterDescriptor: ValueParameterDescriptor, + jetParameter: KtParameter, + context: ExpressionTypingContext ) { if (!valueParameterDescriptor.declaresDefaultValue()) return val defaultValue = jetParameter.defaultValue ?: return diff --git a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/unqualifiedSuper/unqualifiedSuper.kt b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/unqualifiedSuper/unqualifiedSuper.kt index eae56af8a15..1e88a95999c 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/unqualifiedSuper/unqualifiedSuper.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/unqualifiedSuper/unqualifiedSuper.kt @@ -35,9 +35,9 @@ import org.jetbrains.kotlin.types.checker.KotlinTypeChecker fun resolveUnqualifiedSuperFromExpressionContext( - superExpression: KtSuperExpression, - supertypes: Collection, - anyType: KotlinType + superExpression: KtSuperExpression, + supertypes: Collection, + anyType: KotlinType ): Collection { val parentElement = superExpression.parent @@ -51,8 +51,7 @@ fun resolveUnqualifiedSuperFromExpressionContext( val calleeName = calleeExpression.getReferencedNameAsName() return if (isCallingMethodOfAny(selectorExpression, calleeName)) { resolveSupertypesForMethodOfAny(supertypes, calleeName, anyType) - } - else { + } else { resolveSupertypesByCalleeName(supertypes, calleeName) } } @@ -71,11 +70,11 @@ fun resolveUnqualifiedSuperFromExpressionContext( private val ARITY_OF_METHODS_OF_ANY = hashMapOf("hashCode" to 0, "equals" to 1, "toString" to 0) private fun isCallingMethodOfAny(callExpression: KtCallExpression, calleeName: Name): Boolean = - ARITY_OF_METHODS_OF_ANY.getOrElse(calleeName.asString(), { -1 }) == callExpression.valueArguments.size + ARITY_OF_METHODS_OF_ANY.getOrElse(calleeName.asString(), { -1 }) == callExpression.valueArguments.size fun isPossiblyAmbiguousUnqualifiedSuper(superExpression: KtSuperExpression, supertypes: Collection): Boolean = - supertypes.size > 1 || - (supertypes.size == 1 && supertypes.single().isInterface() && isCallingMethodOfAnyWithSuper(superExpression)) + supertypes.size > 1 || + (supertypes.size == 1 && supertypes.single().isInterface() && isCallingMethodOfAnyWithSuper(superExpression)) private fun isCallingMethodOfAnyWithSuper(superExpression: KtSuperExpression): Boolean { val parent = superExpression.parent @@ -96,9 +95,13 @@ private fun isCallingMethodOfAnyWithSuper(superExpression: KtSuperExpression): B private val LOOKUP_LOCATION = NoLookupLocation.WHEN_GET_SUPER_MEMBERS private fun KotlinType.isInterface(): Boolean = - TypeUtils.getClassDescriptor(this)?.kind == ClassKind.INTERFACE + TypeUtils.getClassDescriptor(this)?.kind == ClassKind.INTERFACE -private fun resolveSupertypesForMethodOfAny(supertypes: Collection, calleeName: Name, anyType: KotlinType): Collection { +private fun resolveSupertypesForMethodOfAny( + supertypes: Collection, + calleeName: Name, + anyType: KotlinType +): Collection { val typesWithConcreteOverride = resolveSupertypesByMembers(supertypes, false) { getFunctionMembers(it, calleeName, LOOKUP_LOCATION) } @@ -109,20 +112,20 @@ private fun resolveSupertypesForMethodOfAny(supertypes: Collection, } private fun resolveSupertypesByCalleeName(supertypes: Collection, calleeName: Name): Collection = - resolveSupertypesByMembers(supertypes, true) { - getFunctionMembers(it, calleeName, LOOKUP_LOCATION) + - getPropertyMembers(it, calleeName, LOOKUP_LOCATION) - } + resolveSupertypesByMembers(supertypes, true) { + getFunctionMembers(it, calleeName, LOOKUP_LOCATION) + + getPropertyMembers(it, calleeName, LOOKUP_LOCATION) + } private fun resolveSupertypesByPropertyName(supertypes: Collection, propertyName: Name): Collection = - resolveSupertypesByMembers(supertypes, true) { - getPropertyMembers(it, propertyName, LOOKUP_LOCATION) - } + resolveSupertypesByMembers(supertypes, true) { + getPropertyMembers(it, propertyName, LOOKUP_LOCATION) + } private inline fun resolveSupertypesByMembers( - supertypes: Collection, - allowNonConcreteMembers: Boolean, - getMembers: (KotlinType) -> Collection + supertypes: Collection, + allowNonConcreteMembers: Boolean, + getMembers: (KotlinType) -> Collection ): Collection { val typesWithConcreteMembers = SmartList() val typesWithNonConcreteMembers = SmartList() @@ -154,10 +157,10 @@ private inline fun resolveSupertypesByMembers( } private fun getFunctionMembers(type: KotlinType, name: Name, location: LookupLocation): Collection = - type.memberScope.getContributedFunctions(name, location) + type.memberScope.getContributedFunctions(name, location) private fun getPropertyMembers(type: KotlinType, name: Name, location: LookupLocation): Collection = - type.memberScope.getContributedVariables(name, location).filterIsInstanceTo(SmartList()) + type.memberScope.getContributedVariables(name, location).filterIsInstanceTo(SmartList()) private fun isConcreteMember(supertype: KotlinType, memberDescriptor: MemberDescriptor): Boolean { // "Concrete member" is a function or a property that is not abstract, diff --git a/compiler/frontend/src/org/jetbrains/kotlin/util/KotlinFrontEndException.kt b/compiler/frontend/src/org/jetbrains/kotlin/util/KotlinFrontEndException.kt index 297eeb4440c..32a80df01d6 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/util/KotlinFrontEndException.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/util/KotlinFrontEndException.kt @@ -11,9 +11,9 @@ import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments class KotlinFrontEndException(message: String, cause: Throwable) : KotlinExceptionWithAttachments(message, cause) { constructor( - message: String, - cause: Throwable, - element: PsiElement + message: String, + cause: Throwable, + element: PsiElement ) : this(getExceptionMessage("Front-end", message, cause, DiagnosticUtils.atLocation(element)), cause) { withAttachment( "element.kt", diff --git a/compiler/frontend/src/org/jetbrains/kotlin/util/slicedMap/SetSlice.kt b/compiler/frontend/src/org/jetbrains/kotlin/util/slicedMap/SetSlice.kt index 26f48afdbfc..bf7b22703a7 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/util/slicedMap/SetSlice.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/util/slicedMap/SetSlice.kt @@ -18,7 +18,7 @@ package org.jetbrains.kotlin.util.slicedMap open class SetSlice @JvmOverloads constructor(rewritePolicy: RewritePolicy, isCollective: Boolean = false) : - BasicWritableSlice(rewritePolicy, isCollective) { + BasicWritableSlice(rewritePolicy, isCollective) { companion object { @JvmField val DEFAULT = false