Removed useless as casts from compiler code

It allows compiling code with K2 and enabled `-Werror`
This commit is contained in:
Ivan Kochurkin
2023-10-20 13:44:09 +02:00
committed by Space Team
parent d50c6f1b6d
commit 1827df82c4
40 changed files with 77 additions and 117 deletions
@@ -300,10 +300,9 @@ class KtFe10ExpressionTypeProvider(
} }
override fun isDefinitelyNotNull(expression: KtExpression): Boolean { override fun isDefinitelyNotNull(expression: KtExpression): Boolean {
val ktExpression = expression as? KtExpression ?: return false val bindingContext = analysisContext.analyze(expression)
val bindingContext = analysisContext.analyze(ktExpression)
val smartCasts = bindingContext[BindingContext.SMARTCAST, ktExpression] val smartCasts = bindingContext[BindingContext.SMARTCAST, expression]
if (smartCasts is MultipleSmartCasts) { if (smartCasts is MultipleSmartCasts) {
if (smartCasts.map.values.all { !it.isMarkedNullable }) { if (smartCasts.map.values.all { !it.isMarkedNullable }) {
@@ -13,7 +13,6 @@ import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithMembers
import org.jetbrains.kotlin.analysis.api.symbols.pointers.KtSymbolPointer import org.jetbrains.kotlin.analysis.api.symbols.pointers.KtSymbolPointer
import org.jetbrains.kotlin.analysis.utils.errors.requireIsInstance import org.jetbrains.kotlin.analysis.utils.errors.requireIsInstance
import org.jetbrains.kotlin.fir.FirSession import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.declarations.FirClass
import org.jetbrains.kotlin.fir.declarations.FirResolvePhase import org.jetbrains.kotlin.fir.declarations.FirResolvePhase
import org.jetbrains.kotlin.fir.scopes.FirScope import org.jetbrains.kotlin.fir.scopes.FirScope
import org.jetbrains.kotlin.fir.scopes.unsubstitutedScope import org.jetbrains.kotlin.fir.scopes.unsubstitutedScope
@@ -42,7 +41,7 @@ internal abstract class KtFirMemberSymbolPointer<S : KtSymbol>(
val firSession = useSiteSession val firSession = useSiteSession
val scopeSession = getScopeSessionFor(firSession) val scopeSession = getScopeSessionFor(firSession)
return if (isStatic) { return if (isStatic) {
val firClass = owner.fir as? FirClass ?: return null val firClass = owner.fir
firClass.scopeProvider.getStaticMemberScopeForCallables(firClass, firSession, scopeSession) firClass.scopeProvider.getStaticMemberScopeForCallables(firClass, firSession, scopeSession)
} else { } else {
owner.unsubstitutedScope( owner.unsubstitutedScope(
@@ -36,8 +36,7 @@ abstract class AbstractRendererTest : AbstractAnalysisApiSingleFileTest() {
buildString { buildString {
ktFile.declarations.forEach { declaration -> ktFile.declarations.forEach { declaration ->
analyseForTest(declaration) { analyseForTest(declaration) {
val symbol = declaration.getSymbol() as? KtDeclarationSymbol ?: return@analyseForTest append(declaration.getSymbol().render(renderer))
append(symbol.render(renderer))
appendLine() appendLine()
appendLine() appendLine()
} }
@@ -108,7 +108,7 @@ internal class StubBasedFirTypeDeserializer(
val annotations = annotationDeserializer.loadAnnotations(typeReference).toMutableList() val annotations = annotationDeserializer.loadAnnotations(typeReference).toMutableList()
val parent = (typeReference.stub ?: loadStubByElement(typeReference))?.parentStub val parent = (typeReference.stub ?: loadStubByElement(typeReference))?.parentStub
if (parent is KotlinParameterStubImpl) { if (parent is KotlinParameterStubImpl) {
(parent as? KotlinParameterStubImpl)?.functionTypeParameterName?.let { paramName -> parent.functionTypeParameterName?.let { paramName ->
annotations += buildAnnotation { annotations += buildAnnotation {
annotationTypeRef = buildResolvedTypeRef { annotationTypeRef = buildResolvedTypeRef {
type = StandardNames.FqNames.parameterNameClassId.toLookupTag() type = StandardNames.FqNames.parameterNameClassId.toLookupTag()
@@ -194,8 +194,7 @@ class PsiInlineCodegen(
override fun reorderArgumentsIfNeeded(actualArgsWithDeclIndex: List<ArgumentAndDeclIndex>, valueParameterTypes: List<Type>) = Unit override fun reorderArgumentsIfNeeded(actualArgsWithDeclIndex: List<ArgumentAndDeclIndex>, valueParameterTypes: List<Type>) = Unit
override fun isInlinedToInlineFunInKotlinRuntime(): Boolean { override fun isInlinedToInlineFunInKotlinRuntime(): Boolean {
val codegen = this.codegen as? ExpressionCodegen ?: return false val caller = this.codegen.context.functionDescriptor
val caller = codegen.context.functionDescriptor
if (!caller.isInline) return false if (!caller.isInline) return false
val callerPackage = DescriptorUtils.getParentOfType(caller, PackageFragmentDescriptor::class.java) ?: return false val callerPackage = DescriptorUtils.getParentOfType(caller, PackageFragmentDescriptor::class.java) ?: return false
return callerPackage.fqName.asString().startsWith("kotlin.") return callerPackage.fqName.asString().startsWith("kotlin.")
@@ -65,8 +65,7 @@ abstract class PrimitiveNumberRangeIntrinsicRangeValue(
return when (comparisonGenerator.comparedType) { return when (comparisonGenerator.comparedType) {
Type.DOUBLE_TYPE, Type.FLOAT_TYPE -> { Type.DOUBLE_TYPE, Type.FLOAT_TYPE -> {
val rangeLiteral = getBoundedValue(codegen) as? BoundedValue val rangeLiteral = getBoundedValue(codegen)
?: throw AssertionError("Floating point intrinsic range value should be a range literal")
InFloatingPointRangeLiteralExpressionGenerator(operatorReference, rangeLiteral, comparisonGenerator, codegen.frameMap) InFloatingPointRangeLiteralExpressionGenerator(operatorReference, rangeLiteral, comparisonGenerator, codegen.frameMap)
} }
else -> else ->
@@ -274,9 +274,7 @@ fun compileModuleToAnalyzedFir(
incrementalExcludesScope incrementalExcludesScope
)?.also { librariesScope -= it } )?.also { librariesScope -= it }
val extensionRegistrars = (projectEnvironment as? VfsBasedProjectEnvironment) val extensionRegistrars = FirExtensionRegistrar.getInstances(projectEnvironment.project)
?.let { FirExtensionRegistrar.getInstances(it.project) }
?: emptyList()
val allSources = mutableListOf<KtSourceFile>().apply { val allSources = mutableListOf<KtSourceFile>().apply {
addAll(input.groupedSources.commonSources) addAll(input.groupedSources.commonSources)
@@ -190,22 +190,20 @@ fun checkUpperBoundViolated(
if (argumentType != null && argumentSource != null) { if (argumentType != null && argumentSource != null) {
if (!isIgnoreTypeParameters || (argumentType.typeArguments.isEmpty() && argumentType !is ConeTypeParameterType)) { if (!isIgnoreTypeParameters || (argumentType.typeArguments.isEmpty() && argumentType !is ConeTypeParameterType)) {
val intersection = val intersection =
typeSystemContext.intersectTypes(typeParameters[index].resolvedBounds.map { it.coneType }) as? ConeKotlinType typeSystemContext.intersectTypes(typeParameters[index].resolvedBounds.map { it.coneType })
if (intersection != null) { val upperBound = substitutor.substituteOrSelf(intersection)
val upperBound = substitutor.substituteOrSelf(intersection) if (!AbstractTypeChecker.isSubtypeOf(
if (!AbstractTypeChecker.isSubtypeOf( typeSystemContext,
typeSystemContext, argumentType,
argumentType, upperBound,
upperBound, stubTypesEqualToAnything = true
stubTypesEqualToAnything = true )
) ) {
) { val factory = when {
val factory = when { isReportExpansionError && argumentTypeRef == null -> FirErrors.UPPER_BOUND_VIOLATED_IN_TYPEALIAS_EXPANSION
isReportExpansionError && argumentTypeRef == null -> FirErrors.UPPER_BOUND_VIOLATED_IN_TYPEALIAS_EXPANSION else -> FirErrors.UPPER_BOUND_VIOLATED
else -> FirErrors.UPPER_BOUND_VIOLATED
}
reporter.reportOn(argumentSource, factory, upperBound, argumentType.type, context)
} }
reporter.reportOn(argumentSource, factory, upperBound, argumentType.type, context)
} }
} }
@@ -27,7 +27,6 @@ import org.jetbrains.kotlin.fir.declarations.utils.*
import org.jetbrains.kotlin.fir.resolve.dfa.cfg.NormalPath import org.jetbrains.kotlin.fir.resolve.dfa.cfg.NormalPath
import org.jetbrains.kotlin.fir.resolve.dfa.controlFlowGraph import org.jetbrains.kotlin.fir.resolve.dfa.controlFlowGraph
import org.jetbrains.kotlin.fir.resolve.diagnostics.ConeLocalVariableNoTypeOrInitializer import org.jetbrains.kotlin.fir.resolve.diagnostics.ConeLocalVariableNoTypeOrInitializer
import org.jetbrains.kotlin.fir.symbols.impl.FirPropertySymbol
import org.jetbrains.kotlin.fir.types.FirErrorTypeRef import org.jetbrains.kotlin.fir.types.FirErrorTypeRef
import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.lexer.KtTokens
@@ -58,7 +57,7 @@ object FirTopLevelPropertiesChecker : FirFileChecker() {
} }
val propertySymbols = topLevelProperties.mapNotNullTo(mutableSetOf()) { declaration -> val propertySymbols = topLevelProperties.mapNotNullTo(mutableSetOf()) { declaration ->
(declaration.symbol as? FirPropertySymbol)?.takeIf { it.requiresInitialization(isForInitialization = true) } declaration.symbol.takeIf { it.requiresInitialization(isForInitialization = true) }
} }
if (propertySymbols.isEmpty()) return null if (propertySymbols.isEmpty()) return null
@@ -284,7 +284,7 @@ object FirValueClassDeclarationChecker : FirRegularClassChecker() {
return lookupSuperTypes(this, lookupInterfaces = true, deep = true, session, substituteTypes = false).any { superType -> return lookupSuperTypes(this, lookupInterfaces = true, deep = true, session, substituteTypes = false).any { superType ->
// Note: We check just classId here, so type substitution isn't needed ^ (we aren't interested in type arguments) // Note: We check just classId here, so type substitution isn't needed ^ (we aren't interested in type arguments)
(superType as? ConeClassLikeType)?.fullyExpandedType(session)?.lookupTag?.classId?.isCloneableId() == true superType.fullyExpandedType(session).lookupTag.classId.isCloneableId()
} }
} }
@@ -136,8 +136,8 @@ class FirJvmTypeMapper(val session: FirSession) : FirSessionComponent {
return when (val symbol = lookupTag.toSymbol(session)) { return when (val symbol = lookupTag.toSymbol(session)) {
is FirRegularClassSymbol -> buildPossiblyInnerType(symbol, 0) is FirRegularClassSymbol -> buildPossiblyInnerType(symbol, 0)
is FirTypeAliasSymbol -> { is FirTypeAliasSymbol -> {
val expandedType = fullyExpandedType(session) as? ConeClassLikeType val expandedType = fullyExpandedType(session)
val classSymbol = expandedType?.lookupTag?.toSymbol(session) as? FirRegularClassSymbol val classSymbol = expandedType.lookupTag.toSymbol(session) as? FirRegularClassSymbol
classSymbol?.let { expandedType.buildPossiblyInnerType(it, 0) } classSymbol?.let { expandedType.buildPossiblyInnerType(it, 0) }
} }
else -> null else -> null
@@ -369,13 +369,13 @@ class DelegatedMemberGenerator(private val components: Fir2IrComponents) : Fir2I
subClassLookupTag: ConeClassLikeLookupTag, subClassLookupTag: ConeClassLikeLookupTag,
firField: FirField, firField: FirField,
): D? { ): D? {
val callable = this.fir as? D ?: return null val callable = this.fir
val delegatedWrapperData = callable.delegatedWrapperData ?: return null val delegatedWrapperData = callable.delegatedWrapperData ?: return null
if (delegatedWrapperData.containingClass != subClassLookupTag) return null if (delegatedWrapperData.containingClass != subClassLookupTag) return null
if (delegatedWrapperData.delegateField != firField) return null if (delegatedWrapperData.delegateField != firField) return null
val wrapped = delegatedWrapperData.wrapped as? D ?: return null val wrapped = delegatedWrapperData.wrapped
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
val wrappedSymbol = wrapped.symbol as? S ?: return null val wrappedSymbol = wrapped.symbol as? S ?: return null
@@ -442,8 +442,7 @@ class FakeOverrideGenerator(
overridden.containingClassLookupTag()?.toSymbol(session)?.fir as? FirClass ?: return emptyList() overridden.containingClassLookupTag()?.toSymbol(session)?.fir as? FirClass ?: return emptyList()
val overriddenContainingIrClass = val overriddenContainingIrClass =
declarationStorage.classifierStorage.getOrCreateIrClass(overriddenContainingClass.symbol).symbol.owner as? IrClass declarationStorage.classifierStorage.getOrCreateIrClass(overriddenContainingClass.symbol).symbol.owner
?: return emptyList()
return superClasses.mapNotNull { superClass -> return superClasses.mapNotNull { superClass ->
if (superClass == overriddenContainingIrClass || if (superClass == overriddenContainingIrClass ||
@@ -12,7 +12,6 @@ import org.jetbrains.kotlin.fir.scopes.FirContainingNamesAwareScope
import org.jetbrains.kotlin.fir.symbols.impl.FirNamedFunctionSymbol import org.jetbrains.kotlin.fir.symbols.impl.FirNamedFunctionSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirVariableSymbol import org.jetbrains.kotlin.fir.symbols.impl.FirVariableSymbol
import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.utils.addIfNotNull
class JavaClassStaticUseSiteScope internal constructor( class JavaClassStaticUseSiteScope internal constructor(
session: FirSession, session: FirSession,
@@ -34,7 +33,7 @@ class JavaClassStaticUseSiteScope internal constructor(
private fun computeFunctions(name: Name): MutableList<FirNamedFunctionSymbol> { private fun computeFunctions(name: Name): MutableList<FirNamedFunctionSymbol> {
val superClassSymbols = mutableListOf<FirNamedFunctionSymbol>() val superClassSymbols = mutableListOf<FirNamedFunctionSymbol>()
superClassScope.processFunctionsByName(name) { superClassScope.processFunctionsByName(name) {
superClassSymbols.addIfNotNull(it as? FirNamedFunctionSymbol) superClassSymbols.add(it)
} }
val result = mutableListOf<FirNamedFunctionSymbol>() val result = mutableListOf<FirNamedFunctionSymbol>()
@@ -22,7 +22,6 @@ import org.jetbrains.kotlin.fir.resolve.inference.model.ConeReceiverConstraintPo
import org.jetbrains.kotlin.fir.resolve.inference.preprocessCallableReference import org.jetbrains.kotlin.fir.resolve.inference.preprocessCallableReference
import org.jetbrains.kotlin.fir.resolve.inference.preprocessLambdaArgument import org.jetbrains.kotlin.fir.resolve.inference.preprocessLambdaArgument
import org.jetbrains.kotlin.fir.resolve.transformers.ReturnTypeCalculator import org.jetbrains.kotlin.fir.resolve.transformers.ReturnTypeCalculator
import org.jetbrains.kotlin.fir.resolve.transformers.body.resolve.resultType
import org.jetbrains.kotlin.fir.resolve.transformers.ensureResolvedTypeDeclaration import org.jetbrains.kotlin.fir.resolve.transformers.ensureResolvedTypeDeclaration
import org.jetbrains.kotlin.fir.returnExpressions import org.jetbrains.kotlin.fir.returnExpressions
import org.jetbrains.kotlin.fir.symbols.ConeClassLikeLookupTag import org.jetbrains.kotlin.fir.symbols.ConeClassLikeLookupTag
@@ -362,9 +361,7 @@ private fun checkApplicabilityForArgumentType(
return ConeTypeIntersector.intersectTypes(context.session.typeContext, constraintTypes) return ConeTypeIntersector.intersectTypes(context.session.typeContext, constraintTypes)
} }
val originalTypeParameter = val originalTypeParameter = lookupTag.originalTypeParameter as? ConeTypeParameterLookupTag
(lookupTag as? ConeTypeVariableTypeConstructor)?.originalTypeParameter as? ConeTypeParameterLookupTag
if (originalTypeParameter != null) if (originalTypeParameter != null)
return ConeTypeParameterTypeImpl(originalTypeParameter, type.isNullable, type.attributes) return ConeTypeParameterTypeImpl(originalTypeParameter, type.isNullable, type.attributes)
} else if (type is ConeIntegerLiteralType) { } else if (type is ConeIntegerLiteralType) {
@@ -10,7 +10,6 @@ import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.descriptors.isClass import org.jetbrains.kotlin.descriptors.isClass
import org.jetbrains.kotlin.fir.declarations.FirCallableDeclaration import org.jetbrains.kotlin.fir.declarations.FirCallableDeclaration
import org.jetbrains.kotlin.fir.declarations.FirResolvePhase import org.jetbrains.kotlin.fir.declarations.FirResolvePhase
import org.jetbrains.kotlin.fir.declarations.FirVariable
import org.jetbrains.kotlin.fir.declarations.utils.modality import org.jetbrains.kotlin.fir.declarations.utils.modality
import org.jetbrains.kotlin.fir.dispatchReceiverClassLookupTagOrNull import org.jetbrains.kotlin.fir.dispatchReceiverClassLookupTagOrNull
import org.jetbrains.kotlin.fir.expressions.FirFunctionCall import org.jetbrains.kotlin.fir.expressions.FirFunctionCall
@@ -27,7 +26,6 @@ import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.name.StandardClassIds import org.jetbrains.kotlin.name.StandardClassIds
import org.jetbrains.kotlin.types.AbstractTypeChecker import org.jetbrains.kotlin.types.AbstractTypeChecker
import org.jetbrains.kotlin.utils.SmartList import org.jetbrains.kotlin.utils.SmartList
import org.jetbrains.kotlin.utils.addIfNotNull
fun BodyResolveComponents.findTypesForSuperCandidates( fun BodyResolveComponents.findTypesForSuperCandidates(
superTypeRefs: List<FirTypeRef>, superTypeRefs: List<FirTypeRef>,
@@ -144,7 +142,7 @@ private fun BodyResolveComponents.getPropertyMembers(type: ConeKotlinType, name:
scopeSession = scopeSession, scopeSession = scopeSession,
callableCopyTypeCalculator = CallableCopyTypeCalculator.DoNothing, callableCopyTypeCalculator = CallableCopyTypeCalculator.DoNothing,
requiredMembersPhase = FirResolvePhase.STATUS, requiredMembersPhase = FirResolvePhase.STATUS,
)?.processPropertiesByName(name) { addIfNotNull(it.fir as? FirVariable) } )?.processPropertiesByName(name) { add(it.fir) }
} }
@@ -421,7 +421,7 @@ class ConstraintSystemCompleter(components: BodyResolveComponents, private val c
processBlocks = true processBlocks = true
) { candidate -> ) { candidate ->
candidate.postponedAtoms.forEach { atom -> candidate.postponedAtoms.forEach { atom ->
notAnalyzedArguments.addIfNotNull((atom as? PostponedResolvedAtom)?.takeUnless { it.analyzed }) notAnalyzedArguments.addIfNotNull(atom.takeUnless { it.analyzed })
} }
} }
} }
@@ -1027,7 +1027,7 @@ open class FirExpressionsResolveTransformer(transformer: FirAbstractBodyResolveT
), ),
) )
(result as? FirVariableAssignment)?.let { dataFlowAnalyzer.exitVariableAssignment(it) } dataFlowAnalyzer.exitVariableAssignment(result)
return result return result
} }
@@ -22,10 +22,8 @@ import org.jetbrains.kotlin.fir.types.ConeErrorType
import org.jetbrains.kotlin.fir.types.ConeKotlinType import org.jetbrains.kotlin.fir.types.ConeKotlinType
import org.jetbrains.kotlin.fir.types.ConeStubType import org.jetbrains.kotlin.fir.types.ConeStubType
import org.jetbrains.kotlin.fir.types.coneType import org.jetbrains.kotlin.fir.types.coneType
import org.jetbrains.kotlin.fir.utils.exceptions.withConeTypeEntry
import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.utils.addIfNotNull import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.utils.exceptions.errorWithAttachment
fun SessionHolder.collectImplicitReceivers( fun SessionHolder.collectImplicitReceivers(
type: ConeKotlinType?, type: ConeKotlinType?,
@@ -87,7 +85,7 @@ fun SessionHolder.collectTowerDataElementsForClass(owner: FirClass, defaultType:
?.asTowerDataElementForStaticScope(staticScopeOwnerSymbol = superClass.symbol) ?.asTowerDataElementForStaticScope(staticScopeOwnerSymbol = superClass.symbol)
?.let(superClassesStaticsAndCompanionReceivers::add) ?.let(superClassesStaticsAndCompanionReceivers::add)
(superClass as? FirRegularClass)?.companionObjectSymbol?.let { superClass.companionObjectSymbol?.let {
val superCompanionReceiver = ImplicitDispatchReceiverValue( val superCompanionReceiver = ImplicitDispatchReceiverValue(
it, session, scopeSession it, session, scopeSession
) )
@@ -15,7 +15,6 @@ import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.resolve.calls.tower.NewResolvedCallImpl import org.jetbrains.kotlin.resolve.calls.tower.NewResolvedCallImpl
import org.jetbrains.kotlin.resolve.calls.tower.SimplePSIKotlinCallArgument import org.jetbrains.kotlin.resolve.calls.tower.SimplePSIKotlinCallArgument
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValueWithSmartCastInfo
import org.jetbrains.kotlin.types.FlexibleType import org.jetbrains.kotlin.types.FlexibleType
import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.TypeUtils
@@ -32,7 +31,7 @@ object NullableVarargArgumentCallChecker : CallChecker {
if (!arg.isSpread || arg !is SimplePSIKotlinCallArgument) continue if (!arg.isSpread || arg !is SimplePSIKotlinCallArgument) continue
val spreadElement = arg.valueArgument.getSpreadElement() ?: continue val spreadElement = arg.valueArgument.getSpreadElement() ?: continue
val receiver = (arg.receiver as? ReceiverValueWithSmartCastInfo) ?: continue val receiver = arg.receiver
val type = if (receiver.stableType.constructor is TypeVariableTypeConstructor) { val type = if (receiver.stableType.constructor is TypeVariableTypeConstructor) {
context.trace.bindingContext[EXPRESSION_TYPE_INFO, arg.valueArgument.getArgumentExpression()]?.type context.trace.bindingContext[EXPRESSION_TYPE_INFO, arg.valueArgument.getArgumentExpression()]?.type
@@ -5,7 +5,6 @@
package org.jetbrains.kotlin.resolve.checkers package org.jetbrains.kotlin.resolve.checkers
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.StandardNames import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.*
@@ -89,7 +88,7 @@ object ValueClassDeclarationChecker : DeclarationChecker {
} }
var baseParametersOk = true var baseParametersOk = true
val baseParameterTypes = (descriptor as? ClassDescriptor)?.defaultType?.substitutedUnderlyingTypes() ?: emptyList() val baseParameterTypes = descriptor.defaultType.substitutedUnderlyingTypes()
for ((baseParameter, baseParameterType) in primaryConstructor.valueParameters zip baseParameterTypes) { for ((baseParameter, baseParameterType) in primaryConstructor.valueParameters zip baseParameterTypes) {
if (!isParameterAcceptableForInlineClass(baseParameter)) { if (!isParameterAcceptableForInlineClass(baseParameter)) {
@@ -282,8 +282,7 @@ open class IncrementalFirJvmCompilerRunner(
allowNonCachedDeclarations = false, allowNonCachedDeclarations = false,
useIrFakeOverrideBuilder = configuration.getBoolean(CommonConfigurationKeys.USE_IR_FAKE_OVERRIDE_BUILDER), useIrFakeOverrideBuilder = configuration.getBoolean(CommonConfigurationKeys.USE_IR_FAKE_OVERRIDE_BUILDER),
) )
val irGenerationExtensions = val irGenerationExtensions = projectEnvironment.project.let { IrGenerationExtension.getInstances(it) }
(projectEnvironment as? VfsBasedProjectEnvironment)?.project?.let { IrGenerationExtension.getInstances(it) }.orEmpty()
val (irModuleFragment, components, pluginContext, irActualizedResult) = cycleResult.convertToIrAndActualizeForJvm( val (irModuleFragment, components, pluginContext, irActualizedResult) = cycleResult.convertToIrAndActualizeForJvm(
extensions, fir2IrConfiguration, irGenerationExtensions, extensions, fir2IrConfiguration, irGenerationExtensions,
) )
@@ -120,9 +120,7 @@ class FlattenStringConcatenationLowering(val context: CommonBackendContext) : Fi
if (superQualifierSymbol != null) if (superQualifierSymbol != null)
return false return false
val function = symbol.owner as? IrSimpleFunction val function = symbol.owner
?: return false
return function.isToString || function.isNullableToString return function.isToString || function.isNullableToString
} }
@@ -137,7 +137,7 @@ fun translateFunction(declaration: IrFunction, name: JsName?, context: JsGenerat
private fun isFunctionTypeInvoke(receiver: JsExpression?, call: IrCall): Boolean { private fun isFunctionTypeInvoke(receiver: JsExpression?, call: IrCall): Boolean {
if (receiver == null || receiver is JsThisRef) return false if (receiver == null || receiver is JsThisRef) return false
val simpleFunction = call.symbol.owner as? IrSimpleFunction ?: return false val simpleFunction = call.symbol.owner
val receiverType = simpleFunction.dispatchReceiverParameter?.type ?: return false val receiverType = simpleFunction.dispatchReceiverParameter?.type ?: return false
if (call.origin === JsStatementOrigins.EXPLICIT_INVOKE) return false if (call.origin === JsStatementOrigins.EXPLICIT_INVOKE) return false
@@ -22,7 +22,6 @@ import org.jetbrains.kotlin.ir.builders.irExprBody
import org.jetbrains.kotlin.ir.declarations.IrClass import org.jetbrains.kotlin.ir.declarations.IrClass
import org.jetbrains.kotlin.ir.declarations.IrField import org.jetbrains.kotlin.ir.declarations.IrField
import org.jetbrains.kotlin.ir.declarations.IrFile import org.jetbrains.kotlin.ir.declarations.IrFile
import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction
import org.jetbrains.kotlin.ir.expressions.IrCall import org.jetbrains.kotlin.ir.expressions.IrCall
import org.jetbrains.kotlin.ir.expressions.IrExpression import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.ir.expressions.impl.IrGetFieldImpl import org.jetbrains.kotlin.ir.expressions.impl.IrGetFieldImpl
@@ -101,8 +100,8 @@ class EnumExternalEntriesLowering(private val context: JvmBackendContext) : File
} }
override fun visitCall(expression: IrCall): IrExpression { override fun visitCall(expression: IrCall): IrExpression {
val owner = expression.symbol.owner as? IrSimpleFunction val owner = expression.symbol.owner
val parentClass = owner?.parent as? IrClass ?: return super.visitCall(expression) val parentClass = owner.parent as? IrClass ?: return super.visitCall(expression)
val shouldBeLowered = owner.name == SpecialNames.ENUM_GET_ENTRIES && parentClass.isEnumClassWhichRequiresExternalEntries() val shouldBeLowered = owner.name == SpecialNames.ENUM_GET_ENTRIES && parentClass.isEnumClassWhichRequiresExternalEntries()
if (!shouldBeLowered) return super.visitCall(expression) if (!shouldBeLowered) return super.visitCall(expression)
val field = state!!.getEntriesFieldForEnum(parentClass) val field = state!!.getEntriesFieldForEnum(parentClass)
@@ -114,7 +114,7 @@ class JvmOptimizationLowering(val context: JvmBackendContext) : FileLoweringPass
} }
private fun optimizePropertyAccess(expression: IrCall, data: IrDeclaration?): IrExpression { private fun optimizePropertyAccess(expression: IrCall, data: IrDeclaration?): IrExpression {
val accessor = expression.symbol.owner as? IrSimpleFunction ?: return expression val accessor = expression.symbol.owner
if (accessor.modality != Modality.FINAL || accessor.isExternal) return expression if (accessor.modality != Modality.FINAL || accessor.isExternal) return expression
val property = accessor.correspondingPropertySymbol?.owner ?: return expression val property = accessor.correspondingPropertySymbol?.owner ?: return expression
if (property.isLateinit) return expression if (property.isLateinit) return expression
@@ -357,9 +357,8 @@ class JvmOptimizationLowering(val context: JvmBackendContext) : FileLoweringPass
when (statement) { when (statement) {
is IrDoWhileLoop -> { is IrDoWhileLoop -> {
// Expecting counter loop // Expecting counter loop
val doWhileLoop = statement as? IrDoWhileLoop ?: return null if (statement.origin != JvmLoweredStatementOrigin.DO_WHILE_COUNTER_LOOP) return null
if (doWhileLoop.origin != JvmLoweredStatementOrigin.DO_WHILE_COUNTER_LOOP) return null val doWhileLoopBody = statement.body as? IrComposite ?: return null
val doWhileLoopBody = doWhileLoop.body as? IrComposite ?: return null
if (doWhileLoopBody.origin != IrStatementOrigin.FOR_LOOP_INNER_WHILE) return null if (doWhileLoopBody.origin != IrStatementOrigin.FOR_LOOP_INNER_WHILE) return null
val iterationInitialization = doWhileLoopBody.statements[0] as? IrComposite ?: return null val iterationInitialization = doWhileLoopBody.statements[0] as? IrComposite ?: return null
val loopVariableIndex = iterationInitialization.statements.indexOfFirst { it.isLoopVariable() } val loopVariableIndex = iterationInitialization.statements.indexOfFirst { it.isLoopVariable() }
@@ -51,7 +51,7 @@ class JvmPropertiesLowering(private val backendContext: JvmBackendContext) : IrE
} }
override fun visitCall(expression: IrCall): IrExpression { override fun visitCall(expression: IrCall): IrExpression {
val simpleFunction = (expression.symbol.owner as? IrSimpleFunction) ?: return super.visitCall(expression) val simpleFunction = expression.symbol.owner
val property = simpleFunction.correspondingPropertySymbol?.owner ?: return super.visitCall(expression) val property = simpleFunction.correspondingPropertySymbol?.owner ?: return super.visitCall(expression)
expression.transformChildrenVoid() expression.transformChildrenVoid()
@@ -39,7 +39,7 @@ class ResolveInlineCalls(val context: JvmBackendContext) : IrElementVisitorVoid,
expression.acceptChildren(this, null) expression.acceptChildren(this, null)
if (!expression.symbol.owner.isInlineFunctionCall(context)) return if (!expression.symbol.owner.isInlineFunctionCall(context)) return
val maybeFakeOverrideOfMultiFileBridge = expression.symbol.owner as? IrSimpleFunction ?: return val maybeFakeOverrideOfMultiFileBridge = expression.symbol.owner
val resolved = val resolved =
maybeFakeOverrideOfMultiFileBridge.resolveMultiFileFacadeMember() ?: maybeFakeOverrideOfMultiFileBridge.resolveFakeOverride() maybeFakeOverrideOfMultiFileBridge.resolveMultiFileFacadeMember() ?: maybeFakeOverrideOfMultiFileBridge.resolveFakeOverride()
?: return ?: return
@@ -8,20 +8,17 @@ package org.jetbrains.kotlin.backend.wasm.lower
import org.jetbrains.kotlin.backend.common.FileLoweringPass import org.jetbrains.kotlin.backend.common.FileLoweringPass
import org.jetbrains.kotlin.backend.common.IrElementTransformerVoidWithContext import org.jetbrains.kotlin.backend.common.IrElementTransformerVoidWithContext
import org.jetbrains.kotlin.backend.common.lower.createIrBuilder import org.jetbrains.kotlin.backend.common.lower.createIrBuilder
import org.jetbrains.kotlin.backend.common.lower.irComposite
import org.jetbrains.kotlin.backend.wasm.WasmBackendContext import org.jetbrains.kotlin.backend.wasm.WasmBackendContext
import org.jetbrains.kotlin.ir.backend.js.utils.erasedUpperBound import org.jetbrains.kotlin.ir.backend.js.utils.erasedUpperBound
import org.jetbrains.kotlin.ir.backend.js.utils.realOverrideTarget import org.jetbrains.kotlin.ir.backend.js.utils.realOverrideTarget
import org.jetbrains.kotlin.ir.builders.irImplicitCast import org.jetbrains.kotlin.ir.builders.irImplicitCast
import org.jetbrains.kotlin.ir.declarations.IrFile import org.jetbrains.kotlin.ir.declarations.IrFile
import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction
import org.jetbrains.kotlin.ir.expressions.IrCall import org.jetbrains.kotlin.ir.expressions.IrCall
import org.jetbrains.kotlin.ir.expressions.IrExpression import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.ir.symbols.IrSymbol import org.jetbrains.kotlin.ir.symbols.IrSymbol
import org.jetbrains.kotlin.ir.types.* import org.jetbrains.kotlin.ir.types.*
import org.jetbrains.kotlin.ir.util.defaultType import org.jetbrains.kotlin.ir.util.defaultType
import org.jetbrains.kotlin.ir.util.irCall import org.jetbrains.kotlin.ir.util.irCall
import org.jetbrains.kotlin.ir.util.isTypeParameter
import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
/** /**
@@ -48,8 +45,7 @@ class GenericReturnTypeLowering(val context: WasmBackendContext) : FileLoweringP
} }
private fun transformGenericCall(call: IrCall, scopeOwnerSymbol: IrSymbol): IrExpression { private fun transformGenericCall(call: IrCall, scopeOwnerSymbol: IrSymbol): IrExpression {
val function: IrSimpleFunction = val function = call.symbol.owner
call.symbol.owner as? IrSimpleFunction ?: return call
val erasedReturnType: IrType = val erasedReturnType: IrType =
function.realOverrideTarget.returnType.eraseUpperBoundType() function.realOverrideTarget.returnType.eraseUpperBoundType()
@@ -11,7 +11,6 @@ import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET
import org.jetbrains.kotlin.ir.declarations.IrDeclarationOrigin import org.jetbrains.kotlin.ir.declarations.IrDeclarationOrigin
import org.jetbrains.kotlin.ir.declarations.IrField import org.jetbrains.kotlin.ir.declarations.IrField
import org.jetbrains.kotlin.ir.declarations.IrFunction import org.jetbrains.kotlin.ir.declarations.IrFunction
import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction
import org.jetbrains.kotlin.ir.expressions.* import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.IrCompositeImpl import org.jetbrains.kotlin.ir.expressions.impl.IrCompositeImpl
import org.jetbrains.kotlin.ir.expressions.impl.IrGetObjectValueImpl import org.jetbrains.kotlin.ir.expressions.impl.IrGetObjectValueImpl
@@ -25,8 +24,7 @@ class IrInterpreterConstGetterPreprocessor : IrInterpreterPreprocessor {
} }
override fun visitCall(expression: IrCall, data: IrInterpreterPreprocessorData): IrElement { override fun visitCall(expression: IrCall, data: IrInterpreterPreprocessorData): IrElement {
val function = (expression.symbol.owner as? IrSimpleFunction) ?: return super.visitCall(expression, data) val field = expression.symbol.owner.correspondingPropertySymbol?.owner?.backingField ?: return super.visitCall(expression, data)
val field = function.correspondingPropertySymbol?.owner?.backingField ?: return super.visitCall(expression, data)
return expression.lowerConstRead(field, data) ?: super.visitCall(expression, data) return expression.lowerConstRead(field, data) ?: super.visitCall(expression, data)
} }
@@ -11,7 +11,6 @@ import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.IrStatement import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.declarations.IrField import org.jetbrains.kotlin.ir.declarations.IrField
import org.jetbrains.kotlin.ir.declarations.IrFile import org.jetbrains.kotlin.ir.declarations.IrFile
import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction
import org.jetbrains.kotlin.ir.expressions.* import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.interpreter.IrInterpreter import org.jetbrains.kotlin.ir.interpreter.IrInterpreter
import org.jetbrains.kotlin.ir.interpreter.checker.EvaluationMode import org.jetbrains.kotlin.ir.interpreter.checker.EvaluationMode
@@ -35,7 +34,7 @@ internal class IrConstOnlyNecessaryTransformer(
interpreter, irFile, mode, checker, evaluatedConstTracker, inlineConstTracker, onWarning, onError, suppressExceptions interpreter, irFile, mode, checker, evaluatedConstTracker, inlineConstTracker, onWarning, onError, suppressExceptions
) { ) {
override fun visitCall(expression: IrCall, data: Data): IrElement { override fun visitCall(expression: IrCall, data: Data): IrElement {
val isConstGetter = (expression.symbol.owner as? IrSimpleFunction)?.correspondingPropertySymbol?.owner?.isConst == true val isConstGetter = expression.symbol.owner.correspondingPropertySymbol?.owner?.isConst == true
if (!data.inAnnotation && !isConstGetter) { if (!data.inAnnotation && !isConstGetter) {
expression.transformChildren(this, data) expression.transformChildren(this, data)
return expression return expression
@@ -17,9 +17,9 @@ import org.jetbrains.kotlin.ir.builders.irImplicitCast
import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.expressions.* import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.* import org.jetbrains.kotlin.ir.expressions.impl.*
import org.jetbrains.kotlin.ir.overrides.IrUnimplementedOverridesStrategy
import org.jetbrains.kotlin.ir.overrides.FakeOverrideBuilderStrategy import org.jetbrains.kotlin.ir.overrides.FakeOverrideBuilderStrategy
import org.jetbrains.kotlin.ir.overrides.IrFakeOverrideBuilder import org.jetbrains.kotlin.ir.overrides.IrFakeOverrideBuilder
import org.jetbrains.kotlin.ir.overrides.IrUnimplementedOverridesStrategy
import org.jetbrains.kotlin.ir.symbols.* import org.jetbrains.kotlin.ir.symbols.*
import org.jetbrains.kotlin.ir.symbols.impl.IrPropertySymbolImpl import org.jetbrains.kotlin.ir.symbols.impl.IrPropertySymbolImpl
import org.jetbrains.kotlin.ir.symbols.impl.IrSimpleFunctionSymbolImpl import org.jetbrains.kotlin.ir.symbols.impl.IrSimpleFunctionSymbolImpl
@@ -28,11 +28,7 @@ import org.jetbrains.kotlin.ir.types.*
import org.jetbrains.kotlin.ir.types.impl.IrSimpleTypeImpl import org.jetbrains.kotlin.ir.types.impl.IrSimpleTypeImpl
import org.jetbrains.kotlin.ir.types.impl.makeTypeProjection import org.jetbrains.kotlin.ir.types.impl.makeTypeProjection
import org.jetbrains.kotlin.ir.visitors.IrElementVisitor import org.jetbrains.kotlin.ir.visitors.IrElementVisitor
import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.*
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.name.StandardClassIds
import org.jetbrains.kotlin.util.OperatorNameConventions import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.kotlin.utils.* import org.jetbrains.kotlin.utils.*
import java.io.StringWriter import java.io.StringWriter
@@ -842,7 +838,7 @@ fun IrClass.addSimpleDelegatingConstructor(
) )
} }
val IrCall.isSuspend get() = (symbol.owner as? IrSimpleFunction)?.isSuspend == true val IrCall.isSuspend get() = symbol.owner.isSuspend
val IrFunctionReference.isSuspend get() = (symbol.owner as? IrSimpleFunction)?.isSuspend == true val IrFunctionReference.isSuspend get() = (symbol.owner as? IrSimpleFunction)?.isSuspend == true
val IrFunction.isOverridable get() = this is IrSimpleFunction && this.isOverridable val IrFunction.isOverridable get() = this is IrSimpleFunction && this.isOverridable
@@ -193,7 +193,7 @@ internal open class KtUltraLightFieldImpl protected constructor(
override val lightMemberOrigin = LightMemberOriginForDeclaration(declaration, JvmDeclarationOriginKind.OTHER) override val lightMemberOrigin = LightMemberOriginForDeclaration(declaration, JvmDeclarationOriginKind.OTHER)
override fun setName(@NonNls name: String): PsiElement { override fun setName(@NonNls name: String): PsiElement {
(kotlinOrigin as? KtNamedDeclaration)?.setName(name) kotlinOrigin.setName(name)
return this return this
} }
@@ -75,7 +75,7 @@ internal class RawSubstitution(typeParameterUpperBoundEraser: TypeParameterUpper
}, },
type.isMarkedNullable, memberScope type.isMarkedNullable, memberScope
) factory@{ kotlinTypeRefiner -> ) factory@{ kotlinTypeRefiner ->
val classId = (declaration as? ClassDescriptor)?.classId ?: return@factory null val classId = declaration.classId ?: return@factory null
@OptIn(TypeRefinement::class) @OptIn(TypeRefinement::class)
val refinedClassDescriptor = kotlinTypeRefiner.findClassAcrossModuleDependencies(classId) ?: return@factory null val refinedClassDescriptor = kotlinTypeRefiner.findClassAcrossModuleDependencies(classId) ?: return@factory null
@@ -7,23 +7,24 @@ package org.jetbrains.kotlin.backend.konan.descriptors
import llvm.LLVMABIAlignmentOfType import llvm.LLVMABIAlignmentOfType
import llvm.LLVMABISizeOfType import llvm.LLVMABISizeOfType
import llvm.LLVMPreferredAlignmentOfType
import llvm.LLVMStoreSizeOfType import llvm.LLVMStoreSizeOfType
import org.jetbrains.kotlin.backend.common.lower.coroutines.getOrCreateFunctionWithContinuationStub import org.jetbrains.kotlin.backend.common.lower.coroutines.getOrCreateFunctionWithContinuationStub
import org.jetbrains.kotlin.backend.konan.* import org.jetbrains.kotlin.backend.konan.*
import org.jetbrains.kotlin.backend.konan.ir.* import org.jetbrains.kotlin.backend.konan.ir.getSuperClassNotAny
import org.jetbrains.kotlin.backend.konan.ir.isSpecialClassWithNoSupertypes
import org.jetbrains.kotlin.backend.konan.llvm.CodegenLlvmHelpers import org.jetbrains.kotlin.backend.konan.llvm.CodegenLlvmHelpers
import org.jetbrains.kotlin.backend.konan.llvm.computeFunctionName import org.jetbrains.kotlin.backend.konan.llvm.computeFunctionName
import org.jetbrains.kotlin.backend.konan.llvm.toLLVMType
import org.jetbrains.kotlin.backend.konan.llvm.localHash import org.jetbrains.kotlin.backend.konan.llvm.localHash
import org.jetbrains.kotlin.backend.konan.llvm.toLLVMType
import org.jetbrains.kotlin.backend.konan.lower.bridgeTarget import org.jetbrains.kotlin.backend.konan.lower.bridgeTarget
import org.jetbrains.kotlin.backend.konan.serialization.KonanIrLinker
import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.ir.IrElement import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.expressions.IrClassReference import org.jetbrains.kotlin.ir.expressions.IrClassReference
import org.jetbrains.kotlin.ir.expressions.IrConst import org.jetbrains.kotlin.ir.expressions.IrConst
import org.jetbrains.kotlin.ir.objcinterop.* import org.jetbrains.kotlin.ir.objcinterop.canObjCClassMethodBeCalledVirtually
import org.jetbrains.kotlin.ir.objcinterop.isKotlinObjCClass
import org.jetbrains.kotlin.ir.objcinterop.isObjCClassMethod
import org.jetbrains.kotlin.ir.symbols.IrFieldSymbol import org.jetbrains.kotlin.ir.symbols.IrFieldSymbol
import org.jetbrains.kotlin.ir.types.IrType import org.jetbrains.kotlin.ir.types.IrType
import org.jetbrains.kotlin.ir.util.* import org.jetbrains.kotlin.ir.util.*
@@ -470,8 +471,7 @@ internal class ClassLayoutBuilder(val irClass: IrClass, val context: Context) {
irClass.annotations.forEach { irClass.annotations.forEach {
val irFile = irClass.fileOrNull val irFile = irClass.fileOrNull
val annotationClass = (it.symbol.owner as? IrConstructor)?.constructedClass val annotationClass = it.symbol.owner.constructedClass
?: error(irFile, it, "unexpected annotation")
if (annotationClass.hasAnnotation(RuntimeNames.associatedObjectKey)) { if (annotationClass.hasAnnotation(RuntimeNames.associatedObjectKey)) {
val argument = it.getValueArgument(0) val argument = it.getValueArgument(0)
@@ -51,8 +51,6 @@ import org.jetbrains.kotlin.konan.library.KonanLibrary
import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.native.interop.ObjCMethodInfo import org.jetbrains.kotlin.native.interop.ObjCMethodInfo
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.resolve.descriptorUtil.module
internal class InteropLowering(generationState: NativeGenerationState) : FileLoweringPass { internal class InteropLowering(generationState: NativeGenerationState) : FileLoweringPass {
// TODO: merge these lowerings. // TODO: merge these lowerings.
@@ -1034,11 +1032,7 @@ private class InteropTransformer(
if (!function.isFromInteropLibrary()) return null if (!function.isFromInteropLibrary()) return null
if (!function.isGetter) return null if (!function.isGetter) return null
val constantProperty = (function as? IrSimpleFunction) val constantProperty = function.correspondingPropertySymbol?.owner?.takeIf { it.isConst } ?: return null
?.correspondingPropertySymbol
?.owner
?.takeIf { it.isConst }
?: return null
val initializer = constantProperty.backingField?.initializer?.expression val initializer = constantProperty.backingField?.initializer?.expression
require(initializer is IrConst<*>) { renderCompilerError(expression) } require(initializer is IrConst<*>) { renderCompilerError(expression) }
@@ -1088,9 +1082,7 @@ private class InteropTransformer(
builder.at(expression) builder.at(expression)
val function = expression.symbol.owner val function = expression.symbol.owner
if ((function as? IrSimpleFunction)?.resolveFakeOverrideMaybeAbstract()?.symbol if (function.resolveFakeOverrideMaybeAbstract()?.symbol == symbols.interopNativePointedRawPtrGetter) {
== symbols.interopNativePointedRawPtrGetter) {
// Replace by the intrinsic call to be handled by code generator: // Replace by the intrinsic call to be handled by code generator:
return builder.irCall(symbols.interopNativePointedGetRawPointer).apply { return builder.irCall(symbols.interopNativePointedGetRawPointer).apply {
extensionReceiver = expression.dispatchReceiver extensionReceiver = expression.dispatchReceiver
@@ -23,7 +23,6 @@ import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.expressions.* import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.objcinterop.* import org.jetbrains.kotlin.ir.objcinterop.*
import org.jetbrains.kotlin.ir.util.* import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.ir.util.irCall
internal fun Context.getObjectClassInstanceFunction(clazz: IrClass) = mapping.objectInstanceGetter.getOrPut(clazz) { internal fun Context.getObjectClassInstanceFunction(clazz: IrClass) = mapping.objectInstanceGetter.getOrPut(clazz) {
when { when {
@@ -159,8 +158,7 @@ internal class ObjectClassLowering(val generationState: NativeGenerationState) :
val statements = this.body?.statements ?: return false val statements = this.body?.statements ?: return false
if (statements.isEmpty()) return false if (statements.isEmpty()) return false
val constructorCall = statements[0] as? IrDelegatingConstructorCall ?: return false val constructorCall = statements[0] as? IrDelegatingConstructorCall ?: return false
val constructor = constructorCall.symbol.owner as? IrConstructor ?: return false if (!constructorCall.symbol.owner.constructedClass.isAny()) return false
if (!constructor.constructedClass.isAny()) return false
return statements.asSequence().drop(1).all { return statements.asSequence().drop(1).all {
it is IrBlock && it.origin == IrStatementOrigin.INITIALIZE_FIELD it is IrBlock && it.origin == IrStatementOrigin.INITIALIZE_FIELD
} }
@@ -6,7 +6,6 @@
package org.jetbrains.kotlin.backend.konan.lower package org.jetbrains.kotlin.backend.konan.lower
import org.jetbrains.kotlin.backend.common.BodyLoweringPass import org.jetbrains.kotlin.backend.common.BodyLoweringPass
import org.jetbrains.kotlin.backend.common.ir.Symbols
import org.jetbrains.kotlin.backend.common.lower.at import org.jetbrains.kotlin.backend.common.lower.at
import org.jetbrains.kotlin.backend.common.lower.createIrBuilder import org.jetbrains.kotlin.backend.common.lower.createIrBuilder
import org.jetbrains.kotlin.backend.konan.Context import org.jetbrains.kotlin.backend.konan.Context
@@ -83,7 +82,7 @@ internal class PostInlineLowering(val context: Context) : BodyLoweringPass {
val builder = StringBuilder() val builder = StringBuilder()
args.elements.forEach { args.elements.forEach {
require(it is IrConst<*>) { renderCompilerError(irFile, it, "expected const") } require(it is IrConst<*>) { renderCompilerError(irFile, it, "expected const") }
val value = (it as? IrConst<*>)?.value val value = it.value
require(value is Short && value >= 0 && value <= 0xff) { require(value is Short && value >= 0 && value <= 0xff) {
renderCompilerError(irFile, it, "incorrect value for binary data: $value") renderCompilerError(irFile, it, "incorrect value for binary data: $value")
} }
@@ -31,8 +31,8 @@ fun invokeInterop(flavor: String, args: Array<String>, runFromDaemon: Boolean):
val purgeUserLibs = arguments.purgeUserLibs val purgeUserLibs = arguments.purgeUserLibs
val nopack = arguments.nopack val nopack = arguments.nopack
val temporaryFilesDir = arguments.tempDir val temporaryFilesDir = arguments.tempDir
val moduleName = (arguments as? CInteropArguments)?.moduleName val moduleName = arguments.moduleName
val shortModuleName = (arguments as? CInteropArguments)?.shortModuleName val shortModuleName = arguments.shortModuleName
val buildDir = File("$outputFileName-build") val buildDir = File("$outputFileName-build")
val generatedDir = File(buildDir, "kotlin") val generatedDir = File(buildDir, "kotlin")
@@ -339,8 +339,16 @@ class ClassFileToSourceStubConverter(val kaptContext: KaptContextForStubGenerati
if (!checkIfValidTypeName(clazz, Type.getObjectType(clazz.name))) return null if (!checkIfValidTypeName(clazz, Type.getObjectType(clazz.name))) return null
val descriptor = kaptContext.origins[clazz]?.descriptor ?: return null val descriptor = kaptContext.origins[clazz]?.descriptor ?: return null
val isNested = (descriptor as? ClassDescriptor)?.isNested ?: false
val isInner = isNested && (descriptor as? ClassDescriptor)?.isInner ?: false val isNested: Boolean
val isInner: Boolean
if (descriptor is ClassDescriptor) {
isNested = descriptor.isNested
isInner = isNested && descriptor.isInner
} else {
isNested = false
isInner = false
}
val flags = getClassAccessFlags(clazz, descriptor, isInner, isNested) val flags = getClassAccessFlags(clazz, descriptor, isInner, isNested)