Replace usages of addToStdlib.firstNotNullResult with firstNotNullOfOrNull

This commit is contained in:
Dmitriy Novozhilov
2021-04-19 13:36:30 +03:00
committed by TeamCityServer
parent 24b6c5df56
commit d114913cd2
58 changed files with 107 additions and 194 deletions
@@ -20,7 +20,6 @@ import org.jetbrains.kotlin.lexer.KtTokens.VISIBILITY_MODIFIERS
import org.jetbrains.kotlin.psi.KtParameter.VAL_VAR_TOKEN_SET import org.jetbrains.kotlin.psi.KtParameter.VAL_VAR_TOKEN_SET
import org.jetbrains.kotlin.psi.stubs.elements.KtConstantExpressionElementType import org.jetbrains.kotlin.psi.stubs.elements.KtConstantExpressionElementType
import org.jetbrains.kotlin.psi.stubs.elements.KtStringTemplateExpressionElementType import org.jetbrains.kotlin.psi.stubs.elements.KtStringTemplateExpressionElementType
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
object LightTreePositioningStrategies { object LightTreePositioningStrategies {
val DEFAULT = object : LightTreePositioningStrategy() { val DEFAULT = object : LightTreePositioningStrategy() {
@@ -900,14 +899,14 @@ fun FlyweightCapableTreeStructure<LighterASTNode>.findDescendantByType(node: Lig
val childrenRef = Ref<Array<LighterASTNode?>>() val childrenRef = Ref<Array<LighterASTNode?>>()
getChildren(node, childrenRef) getChildren(node, childrenRef)
return childrenRef.get()?.firstOrNull { it?.tokenType == type } ?: childrenRef.get() return childrenRef.get()?.firstOrNull { it?.tokenType == type } ?: childrenRef.get()
?.firstNotNullResult { child -> child?.let { findDescendantByType(it, type) } } ?.firstNotNullOfOrNull { child -> child?.let { findDescendantByType(it, type) } }
} }
fun FlyweightCapableTreeStructure<LighterASTNode>.findDescendantByTypes(node: LighterASTNode, types: TokenSet): LighterASTNode? { fun FlyweightCapableTreeStructure<LighterASTNode>.findDescendantByTypes(node: LighterASTNode, types: TokenSet): LighterASTNode? {
val childrenRef = Ref<Array<LighterASTNode?>>() val childrenRef = Ref<Array<LighterASTNode?>>()
getChildren(node, childrenRef) getChildren(node, childrenRef)
return childrenRef.get()?.firstOrNull { types.contains(it?.tokenType) } ?: childrenRef.get() return childrenRef.get()?.firstOrNull { types.contains(it?.tokenType) } ?: childrenRef.get()
?.firstNotNullResult { child -> child?.let { findDescendantByTypes(it, types) } } ?.firstNotNullOfOrNull { child -> child?.let { findDescendantByTypes(it, types) } }
} }
fun FlyweightCapableTreeStructure<LighterASTNode>.findFirstDescendant( fun FlyweightCapableTreeStructure<LighterASTNode>.findFirstDescendant(
@@ -917,7 +916,7 @@ fun FlyweightCapableTreeStructure<LighterASTNode>.findFirstDescendant(
val childrenRef = Ref<Array<LighterASTNode?>>() val childrenRef = Ref<Array<LighterASTNode?>>()
getChildren(node, childrenRef) getChildren(node, childrenRef)
return childrenRef.get()?.firstOrNull { it != null && predicate(it) } return childrenRef.get()?.firstOrNull { it != null && predicate(it) }
?: childrenRef.get()?.firstNotNullResult { child -> child?.let { findFirstDescendant(it, predicate) } } ?: childrenRef.get()?.firstNotNullOfOrNull { child -> child?.let { findFirstDescendant(it, predicate) } }
} }
fun FlyweightCapableTreeStructure<LighterASTNode>.collectDescendantsOfType( fun FlyweightCapableTreeStructure<LighterASTNode>.collectDescendantsOfType(
@@ -41,7 +41,6 @@ import org.jetbrains.kotlin.serialization.deserialization.builtins.BuiltInSerial
import org.jetbrains.kotlin.serialization.deserialization.getName import org.jetbrains.kotlin.serialization.deserialization.getName
import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.util.OperatorNameConventions import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
import org.jetbrains.kotlin.utils.addToStdlib.getOrPut import org.jetbrains.kotlin.utils.addToStdlib.getOrPut
import java.io.InputStream import java.io.InputStream
@@ -72,7 +71,7 @@ open class FirBuiltinSymbolProvider(session: FirSession, val kotlinScopeProvider
} }
override fun getClassLikeSymbolByFqName(classId: ClassId): FirRegularClassSymbol? { override fun getClassLikeSymbolByFqName(classId: ClassId): FirRegularClassSymbol? {
return allPackageFragments[classId.packageFqName]?.firstNotNullResult { return allPackageFragments[classId.packageFqName]?.firstNotNullOfOrNull {
it.getClassLikeSymbolByFqName(classId) it.getClassLikeSymbolByFqName(classId)
} ?: trySyntheticFunctionalInterface(classId) } ?: trySyntheticFunctionalInterface(classId)
} }
@@ -11,7 +11,6 @@ import org.jetbrains.kotlin.fir.expressions.FirExpression
import org.jetbrains.kotlin.fir.expressions.arguments import org.jetbrains.kotlin.fir.expressions.arguments
import org.jetbrains.kotlin.name.StandardClassIds import org.jetbrains.kotlin.name.StandardClassIds
import org.jetbrains.kotlin.fir.types.* import org.jetbrains.kotlin.fir.types.*
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
class PrimitiveConeNumericComparisonInfo( class PrimitiveConeNumericComparisonInfo(
val comparisonType: ConeClassLikeType, val comparisonType: ConeClassLikeType,
@@ -61,7 +60,7 @@ private fun ConeClassLikeType.promoteIntegerTypeToIntIfRequired(): ConeClassLike
private fun ConeKotlinType.getPrimitiveTypeOrSupertype(): ConeClassLikeType? = private fun ConeKotlinType.getPrimitiveTypeOrSupertype(): ConeClassLikeType? =
when { when {
this is ConeTypeParameterType -> this is ConeTypeParameterType ->
this.lookupTag.typeParameterSymbol.fir.bounds.firstNotNullResult { this.lookupTag.typeParameterSymbol.fir.bounds.firstNotNullOfOrNull {
it.coneType.getPrimitiveTypeOrSupertype() it.coneType.getPrimitiveTypeOrSupertype()
} }
this is ConeClassLikeType && isPrimitiveNumberType() -> this is ConeClassLikeType && isPrimitiveNumberType() ->
@@ -16,7 +16,6 @@ import org.jetbrains.kotlin.fir.scopes.impl.*
import org.jetbrains.kotlin.name.StandardClassIds import org.jetbrains.kotlin.name.StandardClassIds
import org.jetbrains.kotlin.fir.symbols.impl.FirRegularClassSymbol import org.jetbrains.kotlin.fir.symbols.impl.FirRegularClassSymbol
import org.jetbrains.kotlin.utils.DFS import org.jetbrains.kotlin.utils.DFS
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
class JavaScopeProvider( class JavaScopeProvider(
val symbolProvider: JavaSymbolProvider val symbolProvider: JavaSymbolProvider
@@ -150,7 +149,7 @@ class JavaScopeProvider(
} }
private tailrec fun FirRegularClass.findJavaSuperClass(useSiteSession: FirSession): FirRegularClass? { private tailrec fun FirRegularClass.findJavaSuperClass(useSiteSession: FirSession): FirRegularClass? {
val superClass = superConeTypes.firstNotNullResult { val superClass = superConeTypes.firstNotNullOfOrNull {
(it.lookupTag.toSymbol(useSiteSession)?.fir as? FirRegularClass)?.takeIf { superClass -> (it.lookupTag.toSymbol(useSiteSession)?.fir as? FirRegularClass)?.takeIf { superClass ->
superClass.classKind == ClassKind.CLASS superClass.classKind == ClassKind.CLASS
} }
@@ -37,7 +37,6 @@ import org.jetbrains.kotlin.name.isOneSegmentFQN
import org.jetbrains.kotlin.resolve.jvm.JvmClassName import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.kotlin.serialization.deserialization.IncompatibleVersionErrorData import org.jetbrains.kotlin.serialization.deserialization.IncompatibleVersionErrorData
import org.jetbrains.kotlin.serialization.deserialization.getName import org.jetbrains.kotlin.serialization.deserialization.getName
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
@ThreadSafeMutableState @ThreadSafeMutableState
class KotlinDeserializedJvmSymbolsProvider( class KotlinDeserializedJvmSymbolsProvider(
@@ -142,9 +141,9 @@ class KotlinDeserializedJvmSymbolsProvider(
} }
private fun findAndDeserializeTypeAlias(classId: ClassId): FirTypeAliasSymbol? { private fun findAndDeserializeTypeAlias(classId: ClassId): FirTypeAliasSymbol? {
return getPackageParts(classId.packageFqName).firstNotNullResult { part -> return getPackageParts(classId.packageFqName).firstNotNullOfOrNull { part ->
val ids = part.typeAliasNameIndex[classId.shortClassName] val ids = part.typeAliasNameIndex[classId.shortClassName]
if (ids == null || ids.isEmpty()) return@firstNotNullResult null if (ids == null || ids.isEmpty()) return@firstNotNullOfOrNull null
val aliasProto = ids.map { part.proto.getTypeAlias(it) }.single() val aliasProto = ids.map { part.proto.getTypeAlias(it) }.single()
part.context.memberDeserializer.loadTypeAlias(aliasProto).symbol part.context.memberDeserializer.loadTypeAlias(aliasProto).symbol
} }
@@ -16,7 +16,6 @@ import org.jetbrains.kotlin.load.java.JvmAnnotationNames.DEFAULT_ANNOTATION_MEMB
import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.utils.JavaTypeEnhancementState import org.jetbrains.kotlin.utils.JavaTypeEnhancementState
import org.jetbrains.kotlin.utils.ReportLevel import org.jetbrains.kotlin.utils.ReportLevel
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
class FirAnnotationTypeQualifierResolver(private val session: FirSession, private val javaTypeEnhancementState: JavaTypeEnhancementState) { class FirAnnotationTypeQualifierResolver(private val session: FirSession, private val javaTypeEnhancementState: JavaTypeEnhancementState) {
@@ -40,7 +39,7 @@ class FirAnnotationTypeQualifierResolver(private val session: FirSession, privat
private fun computeTypeQualifierNickname(klass: FirRegularClass): FirAnnotationCall? { private fun computeTypeQualifierNickname(klass: FirRegularClass): FirAnnotationCall? {
if (klass.annotations.none { it.classId == TYPE_QUALIFIER_NICKNAME_ID }) return null if (klass.annotations.none { it.classId == TYPE_QUALIFIER_NICKNAME_ID }) return null
return klass.annotations.firstNotNullResult(this::resolveTypeQualifierAnnotation) return klass.annotations.firstNotNullOfOrNull(this::resolveTypeQualifierAnnotation)
} }
private fun resolveTypeQualifierNickname(klass: FirRegularClass): FirAnnotationCall? { private fun resolveTypeQualifierNickname(klass: FirRegularClass): FirAnnotationCall? {
@@ -14,13 +14,12 @@ import org.jetbrains.kotlin.load.java.typeEnhancement.NullabilityQualifier
import org.jetbrains.kotlin.load.java.typeEnhancement.NullabilityQualifierWithMigrationStatus import org.jetbrains.kotlin.load.java.typeEnhancement.NullabilityQualifierWithMigrationStatus
import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.utils.JavaTypeEnhancementState import org.jetbrains.kotlin.utils.JavaTypeEnhancementState
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
fun List<FirAnnotationCall>.extractNullability( fun List<FirAnnotationCall>.extractNullability(
annotationTypeQualifierResolver: FirAnnotationTypeQualifierResolver, annotationTypeQualifierResolver: FirAnnotationTypeQualifierResolver,
javaTypeEnhancementState: JavaTypeEnhancementState javaTypeEnhancementState: JavaTypeEnhancementState
): NullabilityQualifierWithMigrationStatus? = ): NullabilityQualifierWithMigrationStatus? =
this.firstNotNullResult { annotationCall -> this.firstNotNullOfOrNull { annotationCall ->
annotationCall.extractNullability(annotationTypeQualifierResolver, javaTypeEnhancementState) annotationCall.extractNullability(annotationTypeQualifierResolver, javaTypeEnhancementState)
} }
@@ -30,7 +30,6 @@ import org.jetbrains.kotlin.load.java.SpecialGenericSignatures.Companion.sameAsR
import org.jetbrains.kotlin.load.java.getPropertyNamesCandidatesByAccessorName import org.jetbrains.kotlin.load.java.getPropertyNamesCandidatesByAccessorName
import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.types.AbstractTypeChecker import org.jetbrains.kotlin.types.AbstractTypeChecker
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
class JavaClassUseSiteMemberScope( class JavaClassUseSiteMemberScope(
klass: FirJavaClass, klass: FirJavaClass,
@@ -151,7 +150,7 @@ class JavaClassUseSiteMemberScope(
): FirNamedFunctionSymbol? { ): FirNamedFunctionSymbol? {
val propertyFromSupertype = fir val propertyFromSupertype = fir
val expectedReturnType = propertyFromSupertype.returnTypeRef.coneTypeSafe<ConeKotlinType>() val expectedReturnType = propertyFromSupertype.returnTypeRef.coneTypeSafe<ConeKotlinType>()
return scope.getFunctions(Name.identifier(getterName)).firstNotNullResult factory@{ candidateSymbol -> return scope.getFunctions(Name.identifier(getterName)).firstNotNullOfOrNull factory@{ candidateSymbol ->
val candidate = candidateSymbol.fir val candidate = candidateSymbol.fir
if (candidate.valueParameters.isNotEmpty()) return@factory null if (candidate.valueParameters.isNotEmpty()) return@factory null
@@ -168,7 +167,7 @@ class JavaClassUseSiteMemberScope(
scope: FirScope, scope: FirScope,
): FirNamedFunctionSymbol? { ): FirNamedFunctionSymbol? {
val propertyType = fir.returnTypeRef.coneTypeSafe<ConeKotlinType>() ?: return null val propertyType = fir.returnTypeRef.coneTypeSafe<ConeKotlinType>() ?: return null
return scope.getFunctions(Name.identifier(JvmAbi.setterName(fir.name.asString()))).firstNotNullResult factory@{ candidateSymbol -> return scope.getFunctions(Name.identifier(JvmAbi.setterName(fir.name.asString()))).firstNotNullOfOrNull factory@{ candidateSymbol ->
val candidate = candidateSymbol.fir val candidate = candidateSymbol.fir
if (candidate.valueParameters.size != 1) return@factory null if (candidate.valueParameters.size != 1) return@factory null
@@ -16,7 +16,6 @@ import org.jetbrains.kotlin.fir.symbols.impl.FirPropertySymbol
import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.ClassId
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.utils.addToStdlib.firstNotNullResult
@NoMutableState @NoMutableState
class FirCompositeSymbolProvider(session: FirSession, val providers: List<FirSymbolProvider>) : FirSymbolProvider(session) { class FirCompositeSymbolProvider(session: FirSession, val providers: List<FirSymbolProvider>) : FirSymbolProvider(session) {
@@ -44,10 +43,10 @@ class FirCompositeSymbolProvider(session: FirSession, val providers: List<FirSym
} }
override fun getPackage(fqName: FqName): FqName? { override fun getPackage(fqName: FqName): FqName? {
return providers.firstNotNullResult { it.getPackage(fqName) } return providers.firstNotNullOfOrNull { it.getPackage(fqName) }
} }
override fun getClassLikeSymbolByFqName(classId: ClassId): FirClassLikeSymbol<*>? { override fun getClassLikeSymbolByFqName(classId: ClassId): FirClassLikeSymbol<*>? {
return providers.firstNotNullResult { it.getClassLikeSymbolByFqName(classId) } return providers.firstNotNullOfOrNull { it.getClassLikeSymbolByFqName(classId) }
} }
} }
@@ -20,7 +20,6 @@ import org.jetbrains.kotlin.fir.symbols.impl.FirPropertySymbol
import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.ClassId
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.utils.addToStdlib.firstNotNullResult
@ThreadSafeMutableState @ThreadSafeMutableState
open class FirDependenciesSymbolProviderImpl(session: FirSession) : FirSymbolProvider(session) { open class FirDependenciesSymbolProviderImpl(session: FirSession) : FirSymbolProvider(session) {
@@ -54,10 +53,10 @@ open class FirDependenciesSymbolProviderImpl(session: FirSession) : FirSymbolPro
} }
private fun computePackage(it: FqName): FqName? = private fun computePackage(it: FqName): FqName? =
dependencyProviders.firstNotNullResult { provider -> provider.getPackage(it) } dependencyProviders.firstNotNullOfOrNull { provider -> provider.getPackage(it) }
private fun computeClass(classId: ClassId): FirClassLikeSymbol<*>? = private fun computeClass(classId: ClassId): FirClassLikeSymbol<*>? =
dependencyProviders.firstNotNullResult { provider -> provider.getClassLikeSymbolByFqName(classId) } dependencyProviders.firstNotNullOfOrNull { provider -> provider.getClassLikeSymbolByFqName(classId) }
@FirSymbolProviderInternals @FirSymbolProviderInternals
@@ -37,7 +37,6 @@ import org.jetbrains.kotlin.fir.types.builder.buildResolvedTypeRef
import org.jetbrains.kotlin.fir.types.impl.FirImplicitUnitTypeRef import org.jetbrains.kotlin.fir.types.impl.FirImplicitUnitTypeRef
import org.jetbrains.kotlin.fir.visitors.* import org.jetbrains.kotlin.fir.visitors.*
import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
open class FirDeclarationsResolveTransformer(transformer: FirBodyResolveTransformer) : FirPartialBodyResolveTransformer(transformer) { open class FirDeclarationsResolveTransformer(transformer: FirBodyResolveTransformer) : FirPartialBodyResolveTransformer(transformer) {
private val statusResolver: FirStatusResolver = FirStatusResolver(session, scopeSession) private val statusResolver: FirStatusResolver = FirStatusResolver(session, scopeSession)
@@ -434,7 +433,7 @@ open class FirDeclarationsResolveTransformer(transformer: FirBodyResolveTransfor
// should be replaced there properly // should be replaced there properly
val returnType = val returnType =
dataFlowAnalyzer.returnExpressionsOfAnonymousFunction(result) dataFlowAnalyzer.returnExpressionsOfAnonymousFunction(result)
.firstNotNullResult { (it as? FirExpression)?.resultType?.coneTypeSafe() } .firstNotNullOfOrNull { (it as? FirExpression)?.resultType?.coneTypeSafe() }
if (returnType != null) { if (returnType != null) {
result.transformReturnTypeRef(transformer, withExpectedType(returnType)) result.transformReturnTypeRef(transformer, withExpectedType(returnType))
@@ -18,14 +18,13 @@ import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.checkers.DeclarationChecker import org.jetbrains.kotlin.resolve.checkers.DeclarationChecker
import org.jetbrains.kotlin.resolve.checkers.DeclarationCheckerContext import org.jetbrains.kotlin.resolve.checkers.DeclarationCheckerContext
import org.jetbrains.kotlin.resolve.deprecation.DEPRECATED_FUNCTION_KEY import org.jetbrains.kotlin.resolve.deprecation.DEPRECATED_FUNCTION_KEY
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
object BadInheritedJavaSignaturesChecker : DeclarationChecker { object BadInheritedJavaSignaturesChecker : DeclarationChecker {
override fun check(declaration: KtDeclaration, descriptor: DeclarationDescriptor, context: DeclarationCheckerContext) { override fun check(declaration: KtDeclaration, descriptor: DeclarationDescriptor, context: DeclarationCheckerContext) {
if (descriptor !is ClassDescriptor) return if (descriptor !is ClassDescriptor) return
val badSignatureOverriddenDescriptor = val badSignatureOverriddenDescriptor =
descriptor.unsubstitutedMemberScope.getContributedDescriptors().firstNotNullResult(::findFirstBadJavaSignatureOverridden) descriptor.unsubstitutedMemberScope.getContributedDescriptors().firstNotNullOfOrNull(::findFirstBadJavaSignatureOverridden)
if (badSignatureOverriddenDescriptor != null) { if (badSignatureOverriddenDescriptor != null) {
val reportOn = val reportOn =
@@ -26,7 +26,6 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.jvm.annotations.* import org.jetbrains.kotlin.resolve.jvm.annotations.*
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm
import org.jetbrains.kotlin.util.getNonPrivateTraitMembersForDelegation import org.jetbrains.kotlin.util.getNonPrivateTraitMembersForDelegation
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
class JvmDefaultChecker(private val jvmTarget: JvmTarget, private val project: Project) : DeclarationChecker { class JvmDefaultChecker(private val jvmTarget: JvmTarget, private val project: Project) : DeclarationChecker {
@@ -212,7 +211,7 @@ class JvmDefaultChecker(private val jvmTarget: JvmTarget, private val project: P
getNonPrivateTraitMembersForDelegation(it, true)?.isCompiledToJvmDefaultWithProperMode(jvmDefaultMode) == false getNonPrivateTraitMembersForDelegation(it, true)?.isCompiledToJvmDefaultWithProperMode(jvmDefaultMode) == false
} }
if (implicitDefaultImplsDelegate != null) return implicitDefaultImplsDelegate if (implicitDefaultImplsDelegate != null) return implicitDefaultImplsDelegate
return classMembers.firstNotNullResult { findPossibleClashMember(it, jvmDefaultMode) } return classMembers.firstNotNullOfOrNull { findPossibleClashMember(it, jvmDefaultMode) }
} }
private fun checkJvmDefaultsInHierarchy(descriptor: DeclarationDescriptor, jvmDefaultMode: JvmDefaultMode): Boolean { private fun checkJvmDefaultsInHierarchy(descriptor: DeclarationDescriptor, jvmDefaultMode: JvmDefaultMode): Boolean {
@@ -26,7 +26,6 @@ import org.jetbrains.kotlin.resolve.jvm.JAVA_LANG_RECORD_FQ_NAME
import org.jetbrains.kotlin.resolve.jvm.annotations.JVM_RECORD_ANNOTATION_FQ_NAME import org.jetbrains.kotlin.resolve.jvm.annotations.JVM_RECORD_ANNOTATION_FQ_NAME
import org.jetbrains.kotlin.resolve.jvm.annotations.isJvmRecord import org.jetbrains.kotlin.resolve.jvm.annotations.isJvmRecord
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
class JvmRecordApplicabilityChecker(private val jvmTarget: JvmTarget) : DeclarationChecker { class JvmRecordApplicabilityChecker(private val jvmTarget: JvmTarget) : DeclarationChecker {
override fun check(declaration: KtDeclaration, descriptor: DeclarationDescriptor, context: DeclarationCheckerContext) { override fun check(declaration: KtDeclaration, descriptor: DeclarationDescriptor, context: DeclarationCheckerContext) {
@@ -161,7 +160,7 @@ class JvmRecordApplicabilityChecker(private val jvmTarget: JvmTarget) : Declarat
} }
private fun KtModifierList.findOneOfModifiers(vararg modifierTokens: KtModifierKeywordToken): PsiElement? = private fun KtModifierList.findOneOfModifiers(vararg modifierTokens: KtModifierKeywordToken): PsiElement? =
modifierTokens.firstNotNullResult(this::getModifier) modifierTokens.firstNotNullOfOrNull(this::getModifier)
private fun JvmTarget.areRecordsAllowed(enableJvmPreview: Boolean): Boolean { private fun JvmTarget.areRecordsAllowed(enableJvmPreview: Boolean): Boolean {
if (majorVersion < JvmTarget.JVM_15.majorVersion) return false if (majorVersion < JvmTarget.JVM_15.majorVersion) return false
@@ -46,7 +46,6 @@ import org.jetbrains.kotlin.resolve.lazy.declarations.DeclarationProviderFactory
import org.jetbrains.kotlin.resolve.lazy.declarations.DeclarationProviderFactoryService import org.jetbrains.kotlin.resolve.lazy.declarations.DeclarationProviderFactoryService
import org.jetbrains.kotlin.serialization.deserialization.MetadataPackageFragmentProvider import org.jetbrains.kotlin.serialization.deserialization.MetadataPackageFragmentProvider
import org.jetbrains.kotlin.serialization.deserialization.MetadataPartProvider import org.jetbrains.kotlin.serialization.deserialization.MetadataPartProvider
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
class CommonAnalysisParameters( class CommonAnalysisParameters(
val metadataPartProviderFactory: (ModuleContent<*>) -> MetadataPartProvider val metadataPartProviderFactory: (ModuleContent<*>) -> MetadataPartProvider
@@ -176,14 +175,14 @@ class CommonResolverForModuleFactory(
// Mimic the behavior in the jvm frontend. The extensions have 2 chances to override the normal analysis: // Mimic the behavior in the jvm frontend. The extensions have 2 chances to override the normal analysis:
// * If any of the extensions returns a non-null result, it. Otherwise do the normal analysis. // * If any of the extensions returns a non-null result, it. Otherwise do the normal analysis.
// * `analysisCompleted` can be used to override the result, too. // * `analysisCompleted` can be used to override the result, too.
var result = analysisHandlerExtensions.firstNotNullResult { extension -> var result = analysisHandlerExtensions.firstNotNullOfOrNull { extension ->
extension.doAnalysis(project, moduleDescriptor, projectContext, files, trace, container) extension.doAnalysis(project, moduleDescriptor, projectContext, files, trace, container)
} ?: run { } ?: run {
container.get<LazyTopDownAnalyzer>().analyzeDeclarations(TopDownAnalysisMode.TopLevelDeclarations, files) container.get<LazyTopDownAnalyzer>().analyzeDeclarations(TopDownAnalysisMode.TopLevelDeclarations, files)
AnalysisResult.success(trace.bindingContext, moduleDescriptor) AnalysisResult.success(trace.bindingContext, moduleDescriptor)
} }
result = analysisHandlerExtensions.firstNotNullResult { extension -> result = analysisHandlerExtensions.firstNotNullOfOrNull { extension ->
extension.analysisCompleted(project, moduleDescriptor, trace, files) extension.analysisCompleted(project, moduleDescriptor, trace, files)
} ?: result } ?: result
@@ -12,11 +12,9 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.config.LanguageVersion; import org.jetbrains.kotlin.config.LanguageVersion;
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory; import org.jetbrains.kotlin.diagnostics.DiagnosticFactory;
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory0;
import org.jetbrains.kotlin.diagnostics.Errors; import org.jetbrains.kotlin.diagnostics.Errors;
import org.jetbrains.kotlin.diagnostics.UnboundDiagnostic; import org.jetbrains.kotlin.diagnostics.UnboundDiagnostic;
import org.jetbrains.kotlin.metadata.deserialization.VersionRequirement; import org.jetbrains.kotlin.metadata.deserialization.VersionRequirement;
import org.jetbrains.kotlin.psi.KtExpression;
import org.jetbrains.kotlin.resolve.VarianceConflictDiagnosticData; import org.jetbrains.kotlin.resolve.VarianceConflictDiagnosticData;
import org.jetbrains.kotlin.types.KotlinTypeKt; import org.jetbrains.kotlin.types.KotlinTypeKt;
import org.jetbrains.kotlin.util.OperatorNameConventions; import org.jetbrains.kotlin.util.OperatorNameConventions;
@@ -29,8 +27,6 @@ import java.util.List;
import java.util.ServiceLoader; import java.util.ServiceLoader;
import static org.jetbrains.kotlin.diagnostics.Errors.*; import static org.jetbrains.kotlin.diagnostics.Errors.*;
import static org.jetbrains.kotlin.diagnostics.Severity.ERROR;
import static org.jetbrains.kotlin.diagnostics.Severity.WARNING;
import static org.jetbrains.kotlin.diagnostics.rendering.Renderers.*; import static org.jetbrains.kotlin.diagnostics.rendering.Renderers.*;
import static org.jetbrains.kotlin.diagnostics.rendering.RenderingContext.of; import static org.jetbrains.kotlin.diagnostics.rendering.RenderingContext.of;
@@ -60,6 +56,8 @@ public class DefaultErrorMessages {
@Nullable @Nullable
public static DiagnosticRenderer getRendererForDiagnostic(@NotNull UnboundDiagnostic diagnostic) { public static DiagnosticRenderer getRendererForDiagnostic(@NotNull UnboundDiagnostic diagnostic) {
// firstNotNullOfOrNull from stdlib can not be used here because it is InlineOnly function and can not be accessed from Java
@SuppressWarnings("deprecation")
DiagnosticRenderer<?> renderer = AddToStdlibKt.firstNotNullResult(RENDERER_MAPS, map -> map.get(diagnostic.getFactory())); DiagnosticRenderer<?> renderer = AddToStdlibKt.firstNotNullResult(RENDERER_MAPS, map -> map.get(diagnostic.getFactory()));
if (renderer != null) if (renderer != null)
return renderer; return renderer;
@@ -19,7 +19,6 @@ package org.jetbrains.kotlin.extensions
import com.intellij.openapi.project.Project import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.LightVirtualFile import com.intellij.testFramework.LightVirtualFile
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
/** /**
* The interface for the extensions that are used to substitute VirtualFile on the creation of KtFile, allows to preprocess a file before * The interface for the extensions that are used to substitute VirtualFile on the creation of KtFile, allows to preprocess a file before
@@ -43,10 +42,10 @@ class PreprocessedFileCreator(val project: Project) {
PreprocessedVirtualFileFactoryExtension.getInstances(project).filterNot { it.isPassThrough() }.toTypedArray() PreprocessedVirtualFileFactoryExtension.getInstances(project).filterNot { it.isPassThrough() }.toTypedArray()
} }
fun create(file: VirtualFile): VirtualFile = validExts.firstNotNullResult { it.createPreprocessedFile(file) } ?: file fun create(file: VirtualFile): VirtualFile = validExts.firstNotNullOfOrNull { it.createPreprocessedFile(file) } ?: file
// unused now, but could be used in the IDE at some point // unused now, but could be used in the IDE at some point
fun createLight(file: LightVirtualFile): LightVirtualFile = fun createLight(file: LightVirtualFile): LightVirtualFile =
validExts.firstNotNullResult { it.createPreprocessedLightFile(file) } ?: file validExts.firstNotNullOfOrNull { it.createPreprocessedLightFile(file) } ?: file
} }
@@ -13,7 +13,6 @@ import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore
import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
fun KtExpression.getKotlinTypeForComparison(bindingContext: BindingContext): KotlinType? = fun KtExpression.getKotlinTypeForComparison(bindingContext: BindingContext): KotlinType? =
when { when {
@@ -41,7 +40,7 @@ fun KtExpression?.getKotlinTypeWithPossibleSmartCastToFP(
if (descriptor != null) { if (descriptor != null) {
val dataFlow = dataFlowValueFactory.createDataFlowValue(this, givenType, bindingContext, descriptor) val dataFlow = dataFlowValueFactory.createDataFlowValue(this, givenType, bindingContext, descriptor)
val stableTypes = bindingContext.getDataFlowInfoBefore(this).getStableTypes(dataFlow, languageVersionSettings) val stableTypes = bindingContext.getDataFlowInfoBefore(this).getStableTypes(dataFlow, languageVersionSettings)
return stableTypes.firstNotNullResult { return stableTypes.firstNotNullOfOrNull {
when { when {
KotlinBuiltIns.isDoubleOrNullableDouble(it) -> it KotlinBuiltIns.isDoubleOrNullableDouble(it) -> it
KotlinBuiltIns.isFloatOrNullableFloat(it) -> it KotlinBuiltIns.isFloatOrNullableFloat(it) -> it
@@ -48,7 +48,6 @@ import org.jetbrains.kotlin.types.expressions.*
import org.jetbrains.kotlin.types.model.TypeSystemInferenceExtensionContext import org.jetbrains.kotlin.types.model.TypeSystemInferenceExtensionContext
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
import java.util.* import java.util.*
class PSICallResolver( class PSICallResolver(
@@ -124,7 +123,7 @@ class PSICallResolver(
resolutionCandidates: Collection<ResolutionCandidate<D>>, resolutionCandidates: Collection<ResolutionCandidate<D>>,
tracingStrategy: TracingStrategy tracingStrategy: TracingStrategy
): OverloadResolutionResults<D> { ): OverloadResolutionResults<D> {
val dispatchReceiver = resolutionCandidates.firstNotNullResult { it.dispatchReceiver } val dispatchReceiver = resolutionCandidates.firstNotNullOfOrNull { it.dispatchReceiver }
val isSpecialFunction = resolutionCandidates.any { it.descriptor.name in SPECIAL_FUNCTION_NAMES } val isSpecialFunction = resolutionCandidates.any { it.descriptor.name in SPECIAL_FUNCTION_NAMES }
val kotlinCall = toKotlinCall( val kotlinCall = toKotlinCall(
@@ -18,7 +18,6 @@ import org.jetbrains.kotlin.resolve.calls.checkers.CallCheckerContext
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.* import org.jetbrains.kotlin.types.typeUtil.*
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
class PrimitiveNumericComparisonInfo( class PrimitiveNumericComparisonInfo(
val comparisonType: KotlinType, val comparisonType: KotlinType,
@@ -107,12 +106,12 @@ object PrimitiveNumericComparisonCallChecker : CallChecker {
} }
private fun List<KotlinType>.findPrimitiveOrNullablePrimitiveType() = private fun List<KotlinType>.findPrimitiveOrNullablePrimitiveType() =
firstNotNullResult { it.getPrimitiveTypeOrSupertype() } firstNotNullOfOrNull { it.getPrimitiveTypeOrSupertype() }
private fun KotlinType.getPrimitiveTypeOrSupertype(): KotlinType? = private fun KotlinType.getPrimitiveTypeOrSupertype(): KotlinType? =
when { when {
constructor.declarationDescriptor is TypeParameterDescriptor -> constructor.declarationDescriptor is TypeParameterDescriptor ->
immediateSupertypes().firstNotNullResult { immediateSupertypes().firstNotNullOfOrNull {
it.getPrimitiveTypeOrSupertype() it.getPrimitiveTypeOrSupertype()
} }
isPrimitiveNumberOrNullableType() -> isPrimitiveNumberOrNullableType() ->
@@ -25,7 +25,6 @@ import org.jetbrains.kotlin.resolve.lazy.LazyClassContext
import org.jetbrains.kotlin.resolve.lazy.declarations.ClassMemberDeclarationProvider import org.jetbrains.kotlin.resolve.lazy.declarations.ClassMemberDeclarationProvider
import org.jetbrains.kotlin.resolve.lazy.declarations.PackageMemberDeclarationProvider import org.jetbrains.kotlin.resolve.lazy.declarations.PackageMemberDeclarationProvider
import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
import org.jetbrains.kotlin.utils.addToStdlib.flatMapToNullable import org.jetbrains.kotlin.utils.addToStdlib.flatMapToNullable
import java.util.* import java.util.*
@@ -80,7 +79,7 @@ interface SyntheticResolveExtension {
} }
override fun getSyntheticCompanionObjectNameIfNeeded(thisDescriptor: ClassDescriptor): Name? = override fun getSyntheticCompanionObjectNameIfNeeded(thisDescriptor: ClassDescriptor): Name? =
instances.firstNotNullResult { withLinkageErrorLogger(it) { getSyntheticCompanionObjectNameIfNeeded(thisDescriptor) } } instances.firstNotNullOfOrNull { withLinkageErrorLogger(it) { getSyntheticCompanionObjectNameIfNeeded(thisDescriptor) } }
override fun addSyntheticSupertypes(thisDescriptor: ClassDescriptor, supertypes: MutableList<KotlinType>) = override fun addSyntheticSupertypes(thisDescriptor: ClassDescriptor, supertypes: MutableList<KotlinType>) =
instances.forEach { withLinkageErrorLogger(it) { addSyntheticSupertypes(thisDescriptor, supertypes) } } instances.forEach { withLinkageErrorLogger(it) { addSyntheticSupertypes(thisDescriptor, supertypes) } }
@@ -18,7 +18,6 @@ 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.visitors.IrElementVisitor import org.jetbrains.kotlin.ir.visitors.IrElementVisitor
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
internal enum class ProgressionDirection { internal enum class ProgressionDirection {
DECREASING { DECREASING {
@@ -282,21 +281,21 @@ internal abstract class HeaderInfoBuilder(
override fun visitCall(expression: IrCall, data: IrCall?): HeaderInfo? { override fun visitCall(expression: IrCall, data: IrCall?): HeaderInfo? {
// Return the HeaderInfo from the first successful match. // Return the HeaderInfo from the first successful match.
// First, try to match a `reversed()` or `withIndex()` call. // First, try to match a `reversed()` or `withIndex()` call.
val callHeaderInfo = callHandlers.firstNotNullResult { it.handle(expression, data, null, scopeOwnerSymbol()) } val callHeaderInfo = callHandlers.firstNotNullOfOrNull { it.handle(expression, data, null, scopeOwnerSymbol()) }
if (callHeaderInfo != null) if (callHeaderInfo != null)
return callHeaderInfo return callHeaderInfo
// Try to match a call to build a progression (e.g., `.indices`, `downTo`). // Try to match a call to build a progression (e.g., `.indices`, `downTo`).
val progressionType = ProgressionType.fromIrType(expression.type, symbols, allowUnsignedBounds) val progressionType = ProgressionType.fromIrType(expression.type, symbols, allowUnsignedBounds)
val progressionHeaderInfo = val progressionHeaderInfo =
progressionType?.run { progressionHandlers.firstNotNullResult { it.handle(expression, data, this, scopeOwnerSymbol()) } } progressionType?.run { progressionHandlers.firstNotNullOfOrNull { it.handle(expression, data, this, scopeOwnerSymbol()) } }
return progressionHeaderInfo ?: super.visitCall(expression, data) return progressionHeaderInfo ?: super.visitCall(expression, data)
} }
/** Builds a [HeaderInfo] for iterable expressions not handled in [visitCall]. */ /** Builds a [HeaderInfo] for iterable expressions not handled in [visitCall]. */
override fun visitExpression(expression: IrExpression, data: IrCall?): HeaderInfo? { override fun visitExpression(expression: IrExpression, data: IrCall?): HeaderInfo? {
return expressionHandlers.firstNotNullResult { it.handle(expression, data, null, scopeOwnerSymbol()) } return expressionHandlers.firstNotNullOfOrNull { it.handle(expression, data, null, scopeOwnerSymbol()) }
?: super.visitExpression(expression, data) ?: super.visitExpression(expression, data)
} }
} }
@@ -16,7 +16,6 @@ import org.jetbrains.kotlin.ir.symbols.IrTypeParameterSymbol
import org.jetbrains.kotlin.ir.util.file import org.jetbrains.kotlin.ir.util.file
import org.jetbrains.kotlin.ir.util.fileEntry import org.jetbrains.kotlin.ir.util.fileEntry
import org.jetbrains.kotlin.ir.util.fqNameWhenAvailable import org.jetbrains.kotlin.ir.util.fqNameWhenAvailable
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
internal interface Stack { internal interface Stack {
fun newFrame(asSubFrame: Boolean = false, initPool: List<Variable> = listOf(), block: () -> ExecutionResult): ExecutionResult fun newFrame(asSubFrame: Boolean = false, initPool: List<Variable> = listOf(), block: () -> ExecutionResult): ExecutionResult
@@ -132,7 +131,7 @@ private class FrameContainer(current: Frame = InterpreterFrame()) {
fun addAll(variables: List<Variable>) = getTopFrame().addAll(variables) fun addAll(variables: List<Variable>) = getTopFrame().addAll(variables)
fun getAll() = innerStack.flatMap { it.getAll() } fun getAll() = innerStack.flatMap { it.getAll() }
fun getVariable(symbol: IrSymbol): Variable { fun getVariable(symbol: IrSymbol): Variable {
return innerStack.firstNotNullResult { it.getVariable(symbol) } return innerStack.firstNotNullOfOrNull { it.getVariable(symbol) }
?: throw InterpreterException("$symbol not found") // TODO better message ?: throw InterpreterException("$symbol not found") // TODO better message
} }
@@ -21,7 +21,6 @@ import org.jetbrains.kotlin.ir.declarations.IrDeclaration
import org.jetbrains.kotlin.ir.linkage.IrProvider import org.jetbrains.kotlin.ir.linkage.IrProvider
import org.jetbrains.kotlin.ir.linkage.KotlinIrLinkerInternalException import org.jetbrains.kotlin.ir.linkage.KotlinIrLinkerInternalException
import org.jetbrains.kotlin.ir.symbols.IrSymbol import org.jetbrains.kotlin.ir.symbols.IrSymbol
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
class ExternalDependenciesGenerator( class ExternalDependenciesGenerator(
val symbolTable: SymbolTable, val symbolTable: SymbolTable,
@@ -57,6 +56,6 @@ class ExternalDependenciesGenerator(
} }
fun List<IrProvider>.getDeclaration(symbol: IrSymbol): IrDeclaration? = fun List<IrProvider>.getDeclaration(symbol: IrSymbol): IrDeclaration? =
firstNotNullResult { provider -> firstNotNullOfOrNull { provider ->
provider.getDeclaration(symbol) provider.getDeclaration(symbol)
} }
@@ -13,22 +13,16 @@ import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.ir.builders.TranslationPluginContext import org.jetbrains.kotlin.ir.builders.TranslationPluginContext
import org.jetbrains.kotlin.ir.declarations.IrDeclaration import org.jetbrains.kotlin.ir.declarations.IrDeclaration
import org.jetbrains.kotlin.ir.declarations.IrFile
import org.jetbrains.kotlin.ir.declarations.IrModuleFragment import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
import org.jetbrains.kotlin.ir.descriptors.* import org.jetbrains.kotlin.ir.descriptors.*
import org.jetbrains.kotlin.ir.expressions.IrBody
import org.jetbrains.kotlin.ir.linkage.IrDeserializer import org.jetbrains.kotlin.ir.linkage.IrDeserializer
import org.jetbrains.kotlin.ir.linkage.KotlinIrLinkerInternalException import org.jetbrains.kotlin.ir.linkage.KotlinIrLinkerInternalException
import org.jetbrains.kotlin.ir.symbols.* import org.jetbrains.kotlin.ir.symbols.*
import org.jetbrains.kotlin.ir.util.* import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.library.IrLibrary import org.jetbrains.kotlin.library.IrLibrary
import org.jetbrains.kotlin.library.KotlinLibrary import org.jetbrains.kotlin.library.KotlinLibrary
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.protobuf.CodedInputStream
import org.jetbrains.kotlin.protobuf.ExtensionRegistryLite.newInstance
import org.jetbrains.kotlin.resolve.descriptorUtil.module import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
abstract class KotlinIrLinker( abstract class KotlinIrLinker(
private val currentModule: ModuleDescriptor?, private val currentModule: ModuleDescriptor?,
@@ -141,7 +135,7 @@ abstract class KotlinIrLinker(
} }
return translationPluginContext?.let { ctx -> return translationPluginContext?.let { ctx ->
linkerExtensions.firstNotNullResult { linkerExtensions.firstNotNullOfOrNull {
it.resolveSymbol(symbol, ctx) it.resolveSymbol(symbol, ctx)
}?.also { }?.also {
require(symbol.owner == it) require(symbol.owner == it)
@@ -27,7 +27,6 @@ import org.jetbrains.kotlin.util.collectionUtils.getFirstClassifierDiscriminateH
import org.jetbrains.kotlin.util.collectionUtils.getFromAllScopes import org.jetbrains.kotlin.util.collectionUtils.getFromAllScopes
import org.jetbrains.kotlin.util.collectionUtils.listOfNonEmptyScopes import org.jetbrains.kotlin.util.collectionUtils.listOfNonEmptyScopes
import org.jetbrains.kotlin.utils.Printer import org.jetbrains.kotlin.utils.Printer
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
class LexicalChainedScope private constructor( class LexicalChainedScope private constructor(
parent: LexicalScope, parent: LexicalScope,
@@ -50,7 +49,7 @@ class LexicalChainedScope private constructor(
getFirstClassifierDiscriminateHeaders(memberScopes) { it.getContributedClassifier(name, location) } getFirstClassifierDiscriminateHeaders(memberScopes) { it.getContributedClassifier(name, location) }
override fun getContributedClassifierIncludeDeprecated(name: Name, location: LookupLocation): DescriptorWithDeprecation<ClassifierDescriptor>? { override fun getContributedClassifierIncludeDeprecated(name: Name, location: LookupLocation): DescriptorWithDeprecation<ClassifierDescriptor>? {
val (firstClassifier, isFirstDeprecated) = memberScopes.firstNotNullResult { val (firstClassifier, isFirstDeprecated) = memberScopes.firstNotNullOfOrNull {
it.getContributedClassifierIncludeDeprecated(name, location) it.getContributedClassifierIncludeDeprecated(name, location)
} ?: return null } ?: return null
@@ -7,7 +7,6 @@ package org.jetbrains.kotlin.codegen
import org.jetbrains.kotlin.ObsoleteTestInfrastructure import org.jetbrains.kotlin.ObsoleteTestInfrastructure
import org.jetbrains.kotlin.test.KotlinTestUtils import org.jetbrains.kotlin.test.KotlinTestUtils
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
import org.jetbrains.kotlin.utils.sure import org.jetbrains.kotlin.utils.sure
import java.io.File import java.io.File
@@ -28,7 +27,7 @@ abstract class AbstractBytecodeListingTest : CodegenTestCase() {
} }
val txtFile = val txtFile =
prefixes.firstNotNullResult { File(wholeFile.parentFile, wholeFile.nameWithoutExtension + "$it.txt").takeIf(File::exists) } prefixes.firstNotNullOfOrNull { File(wholeFile.parentFile, wholeFile.nameWithoutExtension + "$it.txt").takeIf(File::exists) }
.sure { "No testData file exists: ${wholeFile.nameWithoutExtension}.txt" } .sure { "No testData file exists: ${wholeFile.nameWithoutExtension}.txt" }
KotlinTestUtils.assertEqualsToFile(txtFile, actualTxt) KotlinTestUtils.assertEqualsToFile(txtFile, actualTxt)
@@ -6,7 +6,6 @@ import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor
import org.jetbrains.kotlin.descriptors.impl.PackageFragmentDescriptorImpl import org.jetbrains.kotlin.descriptors.impl.PackageFragmentDescriptorImpl
import org.jetbrains.kotlin.incremental.components.LookupLocation import org.jetbrains.kotlin.incremental.components.LookupLocation
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.library.* import org.jetbrains.kotlin.library.*
import org.jetbrains.kotlin.library.metadata.KlibMetadataCachedPackageFragment import org.jetbrains.kotlin.library.metadata.KlibMetadataCachedPackageFragment
import org.jetbrains.kotlin.library.metadata.KlibMetadataDeserializedPackageFragment import org.jetbrains.kotlin.library.metadata.KlibMetadataDeserializedPackageFragment
@@ -20,7 +19,6 @@ import org.jetbrains.kotlin.resolve.scopes.MemberScopeImpl
import org.jetbrains.kotlin.serialization.konan.impl.ForwardDeclarationsFqNames import org.jetbrains.kotlin.serialization.konan.impl.ForwardDeclarationsFqNames
import org.jetbrains.kotlin.storage.StorageManager import org.jetbrains.kotlin.storage.StorageManager
import org.jetbrains.kotlin.utils.Printer import org.jetbrains.kotlin.utils.Printer
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
// TODO decouple and move interop-specific logic back to Kotlin/Native. // TODO decouple and move interop-specific logic back to Kotlin/Native.
open class KlibMetadataDeserializedPackageFragmentsFactoryImpl : KlibMetadataDeserializedPackageFragmentsFactory { open class KlibMetadataDeserializedPackageFragmentsFactoryImpl : KlibMetadataDeserializedPackageFragmentsFactory {
@@ -125,7 +123,7 @@ class ClassifierAliasingPackageFragmentDescriptor(
private val memberScope = object : MemberScopeImpl() { private val memberScope = object : MemberScopeImpl() {
override fun getContributedClassifier(name: Name, location: LookupLocation) = override fun getContributedClassifier(name: Name, location: LookupLocation) =
targets.firstNotNullResult { targets.firstNotNullOfOrNull {
if (it.hasTopLevelClassifier(name)) { if (it.hasTopLevelClassifier(name)) {
it.getMemberScope().getContributedClassifier(name, location) it.getMemberScope().getContributedClassifier(name, location)
} else { } else {
@@ -29,7 +29,6 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.storage.StorageManager import org.jetbrains.kotlin.storage.StorageManager
import org.jetbrains.kotlin.utils.JavaTypeEnhancementState import org.jetbrains.kotlin.utils.JavaTypeEnhancementState
import org.jetbrains.kotlin.utils.ReportLevel import org.jetbrains.kotlin.utils.ReportLevel
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
class AnnotationTypeQualifierResolver(storageManager: StorageManager, private val javaTypeEnhancementState: JavaTypeEnhancementState) { class AnnotationTypeQualifierResolver(storageManager: StorageManager, private val javaTypeEnhancementState: JavaTypeEnhancementState) {
class TypeQualifierWithApplicability( class TypeQualifierWithApplicability(
@@ -59,7 +58,7 @@ class AnnotationTypeQualifierResolver(storageManager: StorageManager, private va
private fun computeTypeQualifierNickname(classDescriptor: ClassDescriptor): AnnotationDescriptor? { private fun computeTypeQualifierNickname(classDescriptor: ClassDescriptor): AnnotationDescriptor? {
if (!classDescriptor.annotations.hasAnnotation(TYPE_QUALIFIER_NICKNAME_FQNAME)) return null if (!classDescriptor.annotations.hasAnnotation(TYPE_QUALIFIER_NICKNAME_FQNAME)) return null
return classDescriptor.annotations.firstNotNullResult(this::resolveTypeQualifierAnnotation) return classDescriptor.annotations.firstNotNullOfOrNull(this::resolveTypeQualifierAnnotation)
} }
private fun resolveTypeQualifierNickname(classDescriptor: ClassDescriptor): AnnotationDescriptor? { private fun resolveTypeQualifierNickname(classDescriptor: ClassDescriptor): AnnotationDescriptor? {
@@ -57,7 +57,6 @@ import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
import org.jetbrains.kotlin.types.refinement.TypeRefinement import org.jetbrains.kotlin.types.refinement.TypeRefinement
import org.jetbrains.kotlin.utils.SmartSet import org.jetbrains.kotlin.utils.SmartSet
import org.jetbrains.kotlin.utils.addIfNotNull import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
import org.jetbrains.kotlin.utils.ifEmpty import org.jetbrains.kotlin.utils.ifEmpty
import java.util.* import java.util.*
@@ -288,7 +287,7 @@ class LazyJavaClassMemberScope(
getterName: String, getterName: String,
functions: (Name) -> Collection<SimpleFunctionDescriptor> functions: (Name) -> Collection<SimpleFunctionDescriptor>
): SimpleFunctionDescriptor? { ): SimpleFunctionDescriptor? {
return functions(Name.identifier(getterName)).firstNotNullResult factory@{ descriptor -> return functions(Name.identifier(getterName)).firstNotNullOfOrNull factory@{ descriptor ->
if (descriptor.valueParameters.size != 0) return@factory null if (descriptor.valueParameters.size != 0) return@factory null
descriptor.takeIf { KotlinTypeChecker.DEFAULT.isSubtypeOf(descriptor.returnType ?: return@takeIf false, type) } descriptor.takeIf { KotlinTypeChecker.DEFAULT.isSubtypeOf(descriptor.returnType ?: return@takeIf false, type) }
@@ -298,7 +297,7 @@ class LazyJavaClassMemberScope(
private fun PropertyDescriptor.findSetterOverride( private fun PropertyDescriptor.findSetterOverride(
functions: (Name) -> Collection<SimpleFunctionDescriptor> functions: (Name) -> Collection<SimpleFunctionDescriptor>
): SimpleFunctionDescriptor? { ): SimpleFunctionDescriptor? {
return functions(Name.identifier(JvmAbi.setterName(name.asString()))).firstNotNullResult factory@{ descriptor -> return functions(Name.identifier(JvmAbi.setterName(name.asString()))).firstNotNullOfOrNull factory@{ descriptor ->
if (descriptor.valueParameters.size != 1) return@factory null if (descriptor.valueParameters.size != 1) return@factory null
if (!KotlinBuiltIns.isUnit(descriptor.returnType ?: return@factory null)) return@factory null if (!KotlinBuiltIns.isUnit(descriptor.returnType ?: return@factory null)) return@factory null
@@ -448,7 +447,7 @@ class LazyJavaClassMemberScope(
): SimpleFunctionDescriptor? { ): SimpleFunctionDescriptor? {
if (!descriptor.isSuspend) return null if (!descriptor.isSuspend) return null
return functions(descriptor.name).firstNotNullResult { overrideCandidate -> return functions(descriptor.name).firstNotNullOfOrNull { overrideCandidate ->
overrideCandidate.createSuspendView()?.takeIf { suspendView -> suspendView.doesOverride(descriptor) } overrideCandidate.createSuspendView()?.takeIf { suspendView -> suspendView.doesOverride(descriptor) }
} }
} }
@@ -41,7 +41,6 @@ import org.jetbrains.kotlin.types.typeUtil.contains
import org.jetbrains.kotlin.types.typeUtil.isTypeParameter import org.jetbrains.kotlin.types.typeUtil.isTypeParameter
import org.jetbrains.kotlin.utils.JavaTypeEnhancementState import org.jetbrains.kotlin.utils.JavaTypeEnhancementState
import org.jetbrains.kotlin.utils.ReportLevel import org.jetbrains.kotlin.utils.ReportLevel
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
import org.jetbrains.kotlin.utils.addToStdlib.safeAs import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class SignatureEnhancement( class SignatureEnhancement(
@@ -461,7 +460,7 @@ class SignatureEnhancement(
areImprovementsEnabled: Boolean, areImprovementsEnabled: Boolean,
typeParameterBounds: Boolean typeParameterBounds: Boolean
): NullabilityQualifierWithMigrationStatus? = ): NullabilityQualifierWithMigrationStatus? =
this.firstNotNullResult { extractNullability(it, areImprovementsEnabled, typeParameterBounds) } this.firstNotNullOfOrNull { extractNullability(it, areImprovementsEnabled, typeParameterBounds) }
private fun computeIndexedQualifiersForOverride(): (Int) -> JavaTypeQualifiers { private fun computeIndexedQualifiersForOverride(): (Int) -> JavaTypeQualifiers {
@@ -93,11 +93,16 @@ fun <T : Any> constant(calculator: () -> T): T {
private val constantMap = ConcurrentHashMap<Function0<*>, Any>() private val constantMap = ConcurrentHashMap<Function0<*>, Any>()
fun String.indexOfOrNull(char: Char, startIndex: Int = 0, ignoreCase: Boolean = false): Int? = fun String.indexOfOrNull(char: Char, startIndex: Int = 0, ignoreCase: Boolean = false): Int? =
indexOf(char, startIndex, ignoreCase).takeIf { it >= 0 } indexOf(char, startIndex, ignoreCase).takeIf { it >= 0 }
fun String.lastIndexOfOrNull(char: Char, startIndex: Int = lastIndex, ignoreCase: Boolean = false): Int? = fun String.lastIndexOfOrNull(char: Char, startIndex: Int = lastIndex, ignoreCase: Boolean = false): Int? =
lastIndexOf(char, startIndex, ignoreCase).takeIf { it >= 0 } lastIndexOf(char, startIndex, ignoreCase).takeIf { it >= 0 }
@Deprecated(
message = "Use firstNotNullOfOrNull from stdlib instead",
replaceWith = ReplaceWith("firstNotNullOfOrNull(transform)"),
level = DeprecationLevel.ERROR
)
inline fun <T, R : Any> Iterable<T>.firstNotNullResult(transform: (T) -> R?): R? { inline fun <T, R : Any> Iterable<T>.firstNotNullResult(transform: (T) -> R?): R? {
for (element in this) { for (element in this) {
val result = transform(element) val result = transform(element)
@@ -106,14 +111,6 @@ inline fun <T, R : Any> Iterable<T>.firstNotNullResult(transform: (T) -> R?): R?
return null return null
} }
inline fun <T, R : Any> Array<T>.firstNotNullResult(transform: (T) -> R?): R? {
for (element in this) {
val result = transform(element)
if (result != null) return result
}
return null
}
inline fun <T> Iterable<T>.sumByLong(selector: (T) -> Long): Long { inline fun <T> Iterable<T>.sumByLong(selector: (T) -> Long): Long {
var sum: Long = 0 var sum: Long = 0
for (element in this) { for (element in this) {
@@ -126,7 +123,7 @@ inline fun <T, C : Collection<T>, O> C.ifNotEmpty(body: C.() -> O?): O? = if (is
inline fun <T, O> Array<out T>.ifNotEmpty(body: Array<out T>.() -> O?): O? = if (isNotEmpty()) this.body() else null inline fun <T, O> Array<out T>.ifNotEmpty(body: Array<out T>.() -> O?): O? = if (isNotEmpty()) this.body() else null
inline fun <T> measureTimeMillisWithResult(block: () -> T) : Pair<Long, T> { inline fun <T> measureTimeMillisWithResult(block: () -> T): Pair<Long, T> {
val start = System.currentTimeMillis() val start = System.currentTimeMillis()
val result = block() val result = block()
return Pair(System.currentTimeMillis() - start, result) return Pair(System.currentTimeMillis() - start, result)
@@ -27,7 +27,6 @@ import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.CompositeBindingContext import org.jetbrains.kotlin.resolve.CompositeBindingContext
import org.jetbrains.kotlin.storage.CancellableSimpleLock import org.jetbrains.kotlin.storage.CancellableSimpleLock
import org.jetbrains.kotlin.storage.guarded import org.jetbrains.kotlin.storage.guarded
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
import java.util.concurrent.locks.ReentrantLock import java.util.concurrent.locks.ReentrantLock
internal class ProjectResolutionFacade( internal class ProjectResolutionFacade(
@@ -132,7 +131,7 @@ internal class ProjectResolutionFacade(
internal fun resolverForElement(element: PsiElement): ResolverForModule { internal fun resolverForElement(element: PsiElement): ResolverForModule {
val infos = element.getModuleInfos() val infos = element.getModuleInfos()
return infos.asIterable().firstNotNullResult { cachedResolverForProject.tryGetResolverForModule(it) } return infos.asIterable().firstNotNullOfOrNull { cachedResolverForProject.tryGetResolverForModule(it) }
?: cachedResolverForProject.tryGetResolverForModule(NotUnderContentRootModuleInfo) ?: cachedResolverForProject.tryGetResolverForModule(NotUnderContentRootModuleInfo)
?: cachedResolverForProject.diagnoseUnknownModuleInfo(infos.toList()) ?: cachedResolverForProject.diagnoseUnknownModuleInfo(infos.toList())
} }
@@ -38,7 +38,6 @@ import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.debugText.getDebugText import org.jetbrains.kotlin.psi.debugText.getDebugText
import org.jetbrains.kotlin.platform.isCommon import org.jetbrains.kotlin.platform.isCommon
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
object SourceNavigationHelper { object SourceNavigationHelper {
private val LOG = Logger.getInstance(SourceNavigationHelper::class.java) private val LOG = Logger.getInstance(SourceNavigationHelper::class.java)
@@ -213,7 +212,7 @@ object SourceNavigationHelper {
index: StringStubIndexExtension<T> index: StringStubIndexExtension<T>
): T? { ): T? {
val classFqName = entity.fqName ?: return null val classFqName = entity.fqName ?: return null
return targetScopes(entity, navigationKind).firstNotNullResult { scope -> return targetScopes(entity, navigationKind).firstNotNullOfOrNull { scope ->
index.get(classFqName.asString(), entity.project, scope).minByOrNull { it.isExpectDeclaration() } index.get(classFqName.asString(), entity.project, scope).minByOrNull { it.isExpectDeclaration() }
} }
} }
@@ -25,7 +25,6 @@ import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.psi.KtSimpleNameExpression import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
abstract class AfterAnalysisHighlightingVisitor protected constructor( abstract class AfterAnalysisHighlightingVisitor protected constructor(
holder: HighlightInfoHolder, protected var bindingContext: BindingContext holder: HighlightInfoHolder, protected var bindingContext: BindingContext
@@ -33,7 +32,7 @@ abstract class AfterAnalysisHighlightingVisitor protected constructor(
protected fun attributeKeyForDeclarationFromExtensions(element: PsiElement, descriptor: DeclarationDescriptor): TextAttributesKey? { protected fun attributeKeyForDeclarationFromExtensions(element: PsiElement, descriptor: DeclarationDescriptor): TextAttributesKey? {
@Suppress("DEPRECATION") @Suppress("DEPRECATION")
return Extensions.getExtensions(HighlighterExtension.EP_NAME).firstNotNullResult { extension -> return Extensions.getExtensions(HighlighterExtension.EP_NAME).firstNotNullOfOrNull { extension ->
extension.highlightDeclaration(element, descriptor) extension.highlightDeclaration(element, descriptor)
} }
} }
@@ -43,7 +42,7 @@ abstract class AfterAnalysisHighlightingVisitor protected constructor(
resolvedCall: ResolvedCall<out CallableDescriptor> resolvedCall: ResolvedCall<out CallableDescriptor>
): TextAttributesKey? { ): TextAttributesKey? {
@Suppress("DEPRECATION") @Suppress("DEPRECATION")
return Extensions.getExtensions(HighlighterExtension.EP_NAME).firstNotNullResult { extension -> return Extensions.getExtensions(HighlighterExtension.EP_NAME).firstNotNullOfOrNull { extension ->
extension.highlightCall(expression, resolvedCall) extension.highlightCall(expression, resolvedCall)
} }
} }
@@ -23,7 +23,6 @@ import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.resolve.calls.tasks.isDynamic import org.jetbrains.kotlin.resolve.calls.tasks.isDynamic
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.serialization.deserialization.KOTLIN_SUSPEND_BUILT_IN_FUNCTION_FQ_NAME import org.jetbrains.kotlin.serialization.deserialization.KOTLIN_SUSPEND_BUILT_IN_FUNCTION_FQ_NAME
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
internal class FunctionsHighlightingVisitor(holder: HighlightInfoHolder, bindingContext: BindingContext) : internal class FunctionsHighlightingVisitor(holder: HighlightInfoHolder, bindingContext: BindingContext) :
AfterAnalysisHighlightingVisitor(holder, bindingContext) { AfterAnalysisHighlightingVisitor(holder, bindingContext) {
@@ -54,7 +53,7 @@ internal class FunctionsHighlightingVisitor(holder: HighlightInfoHolder, binding
@Suppress("DEPRECATION") @Suppress("DEPRECATION")
val extensions = Extensions.getExtensions(HighlighterExtension.EP_NAME) val extensions = Extensions.getExtensions(HighlighterExtension.EP_NAME)
val key = extensions.firstNotNullResult { extension -> val key = extensions.firstNotNullOfOrNull { extension ->
extension.highlightCall(callee, resolvedCall) extension.highlightCall(callee, resolvedCall)
} ?: when { } ?: when {
calleeDescriptor.fqNameOrNull() == KOTLIN_SUSPEND_BUILT_IN_FUNCTION_FQ_NAME -> KEYWORD calleeDescriptor.fqNameOrNull() == KOTLIN_SUSPEND_BUILT_IN_FUNCTION_FQ_NAME -> KEYWORD
@@ -21,7 +21,6 @@ import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.tasks.isDynamic import org.jetbrains.kotlin.resolve.calls.tasks.isDynamic
import org.jetbrains.kotlin.resolve.calls.tower.isSynthesized import org.jetbrains.kotlin.resolve.calls.tower.isSynthesized
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
internal class PropertiesHighlightingVisitor(holder: HighlightInfoHolder, bindingContext: BindingContext) : internal class PropertiesHighlightingVisitor(holder: HighlightInfoHolder, bindingContext: BindingContext) :
AfterAnalysisHighlightingVisitor(holder, bindingContext) { AfterAnalysisHighlightingVisitor(holder, bindingContext) {
@@ -43,7 +42,7 @@ internal class PropertiesHighlightingVisitor(holder: HighlightInfoHolder, bindin
val attributesKey = resolvedCall?.let { call -> val attributesKey = resolvedCall?.let { call ->
@Suppress("DEPRECATION") @Suppress("DEPRECATION")
Extensions.getExtensions(HighlighterExtension.EP_NAME).firstNotNullResult { extension -> Extensions.getExtensions(HighlighterExtension.EP_NAME).firstNotNullOfOrNull { extension ->
extension.highlightCall(expression, call) extension.highlightCall(expression, call)
} }
} ?: attributeKeyByPropertyType(target) } ?: attributeKeyByPropertyType(target)
@@ -31,7 +31,6 @@ import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import org.jetbrains.kotlin.synthetic.SamAdapterExtensionFunctionDescriptor import org.jetbrains.kotlin.synthetic.SamAdapterExtensionFunctionDescriptor
import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
import java.awt.Font import java.awt.Font
class BasicLookupElementFactory( class BasicLookupElementFactory(
@@ -277,7 +276,7 @@ class BasicLookupElementFactory(
} }
fun appendContainerAndReceiverInformation(descriptor: CallableDescriptor, appendTailText: (String) -> Unit) { fun appendContainerAndReceiverInformation(descriptor: CallableDescriptor, appendTailText: (String) -> Unit) {
val information = CompletionInformationProvider.EP_NAME.extensions.firstNotNullResult { val information = CompletionInformationProvider.EP_NAME.extensions.firstNotNullOfOrNull {
it.getContainerAndReceiverInformation(descriptor) it.getContainerAndReceiverInformation(descriptor)
} }
@@ -33,7 +33,6 @@ import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.util.findCallableMemberBySignature import org.jetbrains.kotlin.util.findCallableMemberBySignature
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
abstract class GenerateMembersHandler : AbstractGenerateMembersHandler<OverrideMemberChooserObject>() { abstract class GenerateMembersHandler : AbstractGenerateMembersHandler<OverrideMemberChooserObject>() {
@@ -100,12 +99,12 @@ abstract class GenerateMembersHandler : AbstractGenerateMembersHandler<OverrideM
if (index == -1) return lastElement if (index == -1) return lastElement
val classDescriptor = classOrObject.descriptor as? ClassDescriptor ?: return lastElement val classDescriptor = classOrObject.descriptor as? ClassDescriptor ?: return lastElement
val upperElement = ((index - 1) downTo 0).firstNotNullResult { val upperElement = ((index - 1) downTo 0).firstNotNullOfOrNull {
classDescriptor.findElement(superMemberDescriptors[it]) classDescriptor.findElement(superMemberDescriptors[it])
} }
if (upperElement != null) return upperElement if (upperElement != null) return upperElement
val lowerElement = ((index + 1) until superMemberDescriptors.size).firstNotNullResult { val lowerElement = ((index + 1) until superMemberDescriptors.size).firstNotNullOfOrNull {
classDescriptor.findElement(superMemberDescriptors[it]) classDescriptor.findElement(superMemberDescriptors[it])
} }
if (lowerElement != null) return lowerElement.prevSiblingOfSameType() ?: classLeftBrace if (lowerElement != null) return lowerElement.prevSiblingOfSameType() ?: classLeftBrace
@@ -29,7 +29,6 @@ import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.prevSiblingOfSameType import org.jetbrains.kotlin.psi.psiUtil.prevSiblingOfSameType
import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
internal abstract class KtGenerateMembersHandler : AbstractGenerateMembersHandler<KtClassMember>() { internal abstract class KtGenerateMembersHandler : AbstractGenerateMembersHandler<KtClassMember>() {
@OptIn(HackToForceAllowRunningAnalyzeOnEDT::class) @OptIn(HackToForceAllowRunningAnalyzeOnEDT::class)
@@ -70,7 +69,7 @@ internal abstract class KtGenerateMembersHandler : AbstractGenerateMembersHandle
} }
} }
} }
insertedBlocks.firstOrNull()?.declarations?.firstNotNullResult { it.element }?.let { insertedBlocks.firstOrNull()?.declarations?.firstNotNullOfOrNull { it.element }?.let {
moveCaretIntoGeneratedElement(editor, it) moveCaretIntoGeneratedElement(editor, it)
} }
} }
@@ -7,23 +7,17 @@ package org.jetbrains.kotlin.idea.fir.low.level.api
import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement import com.intellij.psi.PsiElement
import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.PsiShortNamesCache
import com.intellij.psi.stubs.StringStubIndexExtension import com.intellij.psi.stubs.StringStubIndexExtension
import com.intellij.psi.stubs.StubIndex import com.intellij.psi.stubs.StubIndex
import com.intellij.psi.stubs.StubIndexKey import com.intellij.psi.stubs.StubIndexKey
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.util.resolveToDescriptor
import org.jetbrains.kotlin.name.CallableId
import org.jetbrains.kotlin.idea.stubindex.* import org.jetbrains.kotlin.idea.stubindex.*
import org.jetbrains.kotlin.name.CallableId
import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.ClassId
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.psi.* import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.contains
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
/* /*
* Move to another module * Move to another module
@@ -15,7 +15,6 @@ import org.jetbrains.kotlin.fir.symbols.impl.FirPropertySymbol
import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.ClassId
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.utils.addToStdlib.firstNotNullResult
internal class FirModuleWithDependenciesSymbolProvider( internal class FirModuleWithDependenciesSymbolProvider(
session: FirSession, session: FirSession,
@@ -30,7 +29,7 @@ internal class FirModuleWithDependenciesSymbolProvider(
fun getClassLikeSymbolByFqNameWithoutDependencies(classId: ClassId): FirClassLikeSymbol<*>? = fun getClassLikeSymbolByFqNameWithoutDependencies(classId: ClassId): FirClassLikeSymbol<*>? =
providers.firstNotNullResult { it.getClassLikeSymbolByFqName(classId) } providers.firstNotNullOfOrNull { it.getClassLikeSymbolByFqName(classId) }
@FirSymbolProviderInternals @FirSymbolProviderInternals
override fun getTopLevelCallableSymbolsTo(destination: MutableList<FirCallableSymbol<*>>, packageFqName: FqName, name: Name) { override fun getTopLevelCallableSymbolsTo(destination: MutableList<FirCallableSymbol<*>>, packageFqName: FqName, name: Name) {
@@ -75,12 +74,12 @@ internal class FirModuleWithDependenciesSymbolProvider(
fun getPackageWithoutDependencies(fqName: FqName): FqName? = fun getPackageWithoutDependencies(fqName: FqName): FqName? =
providers.firstNotNullResult { it.getPackage(fqName) } providers.firstNotNullOfOrNull { it.getPackage(fqName) }
} }
private class DependentModuleProviders(session: FirSession, private val providers: List<FirSymbolProvider>) : FirSymbolProvider(session) { private class DependentModuleProviders(session: FirSession, private val providers: List<FirSymbolProvider>) : FirSymbolProvider(session) {
override fun getClassLikeSymbolByFqName(classId: ClassId): FirClassLikeSymbol<*>? = override fun getClassLikeSymbolByFqName(classId: ClassId): FirClassLikeSymbol<*>? =
providers.firstNotNullResult { provider -> providers.firstNotNullOfOrNull { provider ->
when (provider) { when (provider) {
is FirModuleWithDependenciesSymbolProvider -> provider.getClassLikeSymbolByFqNameWithoutDependencies(classId) is FirModuleWithDependenciesSymbolProvider -> provider.getClassLikeSymbolByFqNameWithoutDependencies(classId)
else -> provider.getClassLikeSymbolByFqName(classId) else -> provider.getClassLikeSymbolByFqName(classId)
@@ -122,7 +121,7 @@ private class DependentModuleProviders(session: FirSession, private val provider
} }
override fun getPackage(fqName: FqName): FqName? = override fun getPackage(fqName: FqName): FqName? =
providers.firstNotNullResult { provider -> providers.firstNotNullOfOrNull { provider ->
when (provider) { when (provider) {
is FirModuleWithDependenciesSymbolProvider -> provider.getPackageWithoutDependencies(fqName) is FirModuleWithDependenciesSymbolProvider -> provider.getPackageWithoutDependencies(fqName)
else -> provider.getPackage(fqName) else -> provider.getPackage(fqName)
@@ -42,7 +42,6 @@ import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector
import org.jetbrains.kotlin.psi.psiUtil.unwrapNullability import org.jetbrains.kotlin.psi.psiUtil.unwrapNullability
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
internal object FirReferenceResolveHelper { internal object FirReferenceResolveHelper {
fun FirResolvedTypeRef.toTargetSymbol(session: FirSession, symbolBuilder: KtSymbolByFirBuilder): KtSymbol? { fun FirResolvedTypeRef.toTargetSymbol(session: FirSession, symbolBuilder: KtSymbolByFirBuilder): KtSymbol? {
@@ -220,7 +219,7 @@ internal object FirReferenceResolveHelper {
} }
private fun FirCall.findCorrespondingParameter(ktValueArgument: KtValueArgument): FirValueParameter? = private fun FirCall.findCorrespondingParameter(ktValueArgument: KtValueArgument): FirValueParameter? =
argumentMapping?.entries?.firstNotNullResult { (firArgument, firParameter) -> argumentMapping?.entries?.firstNotNullOfOrNull { (firArgument, firParameter) ->
if (firArgument.psi == ktValueArgument) firParameter if (firArgument.psi == ktValueArgument) firParameter
else null else null
} }
@@ -5,9 +5,6 @@
package org.jetbrains.kotlin.idea.configuration package org.jetbrains.kotlin.idea.configuration
import com.google.common.graph.GraphBuilder
import com.google.common.graph.Graphs
import com.intellij.build.events.MessageEvent
import com.intellij.ide.plugins.PluginManager import com.intellij.ide.plugins.PluginManager
import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.DataNode
@@ -18,7 +15,6 @@ import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil.normalizeP
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil.toCanonicalPath import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil.toCanonicalPath
import com.intellij.openapi.externalSystem.util.ExternalSystemConstants import com.intellij.openapi.externalSystem.util.ExternalSystemConstants
import com.intellij.openapi.externalSystem.util.Order import com.intellij.openapi.externalSystem.util.Order
import com.intellij.openapi.roots.DependencyScope
import com.intellij.openapi.util.Key import com.intellij.openapi.util.Key
import com.intellij.openapi.util.Pair import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtil
@@ -30,7 +26,6 @@ import com.intellij.util.text.VersionComparatorUtil
import org.gradle.tooling.model.UnsupportedMethodException import org.gradle.tooling.model.UnsupportedMethodException
import org.gradle.tooling.model.idea.IdeaContentRoot import org.gradle.tooling.model.idea.IdeaContentRoot
import org.gradle.tooling.model.idea.IdeaModule import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.cli.common.arguments.ManualLanguageFeatureSetting import org.jetbrains.kotlin.cli.common.arguments.ManualLanguageFeatureSetting
@@ -40,11 +35,7 @@ import org.jetbrains.kotlin.config.ExternalSystemRunTask
import org.jetbrains.kotlin.config.ExternalSystemTestRunTask import org.jetbrains.kotlin.config.ExternalSystemTestRunTask
import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.gradle.* import org.jetbrains.kotlin.gradle.*
import org.jetbrains.kotlin.idea.PlatformVersion
import org.jetbrains.kotlin.idea.configuration.GradlePropertiesFileFacade.Companion.KOTLIN_NOT_IMPORTED_COMMON_SOURCE_SETS_SETTING import org.jetbrains.kotlin.idea.configuration.GradlePropertiesFileFacade.Companion.KOTLIN_NOT_IMPORTED_COMMON_SOURCE_SETS_SETTING
import org.jetbrains.kotlin.idea.configuration.klib.KotlinNativeLibrariesDependencySubstitutor
import org.jetbrains.kotlin.idea.configuration.klib.KotlinNativeLibrariesFixer
import org.jetbrains.kotlin.idea.configuration.klib.KotlinNativeLibraryNameUtil.KOTLIN_NATIVE_LIBRARY_PREFIX_PLUS_SPACE
import org.jetbrains.kotlin.idea.configuration.mpp.createPopulateModuleDependenciesContext import org.jetbrains.kotlin.idea.configuration.mpp.createPopulateModuleDependenciesContext
import org.jetbrains.kotlin.idea.configuration.mpp.getCompilations import org.jetbrains.kotlin.idea.configuration.mpp.getCompilations
import org.jetbrains.kotlin.idea.configuration.mpp.populateModuleDependenciesByCompilations import org.jetbrains.kotlin.idea.configuration.mpp.populateModuleDependenciesByCompilations
@@ -54,14 +45,12 @@ import org.jetbrains.kotlin.idea.configuration.utils.predictedProductionSourceSe
import org.jetbrains.kotlin.idea.platform.IdePlatformKindTooling import org.jetbrains.kotlin.idea.platform.IdePlatformKindTooling
import org.jetbrains.kotlin.idea.util.NotNullableCopyableDataNodeUserDataProperty import org.jetbrains.kotlin.idea.util.NotNullableCopyableDataNodeUserDataProperty
import org.jetbrains.kotlin.util.removeSuffixIfPresent import org.jetbrains.kotlin.util.removeSuffixIfPresent
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
import org.jetbrains.plugins.gradle.model.* import org.jetbrains.plugins.gradle.model.*
import org.jetbrains.plugins.gradle.model.data.BuildScriptClasspathData import org.jetbrains.plugins.gradle.model.data.BuildScriptClasspathData
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import org.jetbrains.plugins.gradle.service.project.GradleProjectResolver import org.jetbrains.plugins.gradle.service.project.GradleProjectResolver
import org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.CONFIGURATION_ARTIFACTS import org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.CONFIGURATION_ARTIFACTS
import org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.MODULES_OUTPUTS import org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.MODULES_OUTPUTS
import org.jetbrains.plugins.gradle.service.project.GradleProjectResolverUtil.buildDependencies
import org.jetbrains.plugins.gradle.service.project.GradleProjectResolverUtil.getModuleId import org.jetbrains.plugins.gradle.service.project.GradleProjectResolverUtil.getModuleId
import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext
import org.jetbrains.plugins.gradle.util.GradleConstants import org.jetbrains.plugins.gradle.util.GradleConstants
@@ -372,7 +361,7 @@ open class KotlinMPPGradleProjectResolver : AbstractProjectResolverExtensionComp
resolverCtx resolverCtx
) ?: continue ) ?: continue
kotlinSourceSet.externalSystemRunTasks = kotlinSourceSet.externalSystemRunTasks =
compilation.declaredSourceSets.firstNotNullResult { sourceSetToRunTasks[it] } ?: emptyList() compilation.declaredSourceSets.firstNotNullOfOrNull { sourceSetToRunTasks[it] } ?: emptyList()
if (compilation.platform == KotlinPlatform.JVM || compilation.platform == KotlinPlatform.ANDROID) { if (compilation.platform == KotlinPlatform.JVM || compilation.platform == KotlinPlatform.ANDROID) {
compilationData.targetCompatibility = (kotlinSourceSet.compilerArguments as? K2JVMCompilerArguments)?.jvmTarget compilationData.targetCompatibility = (kotlinSourceSet.compilerArguments as? K2JVMCompilerArguments)?.jvmTarget
@@ -15,7 +15,6 @@ import org.jetbrains.kotlin.platform.impl.CommonIdePlatformKind
import org.jetbrains.kotlin.platform.impl.JsIdePlatformKind import org.jetbrains.kotlin.platform.impl.JsIdePlatformKind
import org.jetbrains.kotlin.platform.impl.JvmIdePlatformKind import org.jetbrains.kotlin.platform.impl.JvmIdePlatformKind
import org.jetbrains.kotlin.platform.impl.NativeIdePlatformKind import org.jetbrains.kotlin.platform.impl.NativeIdePlatformKind
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
abstract class IdePlatformKind<Kind : IdePlatformKind<Kind>> { abstract class IdePlatformKind<Kind : IdePlatformKind<Kind>> {
abstract fun supportsTargetPlatform(platform: TargetPlatform): Boolean abstract fun supportsTargetPlatform(platform: TargetPlatform): Boolean
@@ -66,7 +65,7 @@ abstract class IdePlatformKind<Kind : IdePlatformKind<Kind>> {
fun <Args : CommonCompilerArguments> platformByCompilerArguments(arguments: Args): TargetPlatform? = fun <Args : CommonCompilerArguments> platformByCompilerArguments(arguments: Args): TargetPlatform? =
ALL_KINDS.firstNotNullResult { it.platformByCompilerArguments(arguments) } ALL_KINDS.firstNotNullOfOrNull { it.platformByCompilerArguments(arguments) }
} }
} }
@@ -28,7 +28,6 @@ import org.jetbrains.kotlin.psi.declarationVisitor
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.isPrivate import org.jetbrains.kotlin.psi.psiUtil.isPrivate
import org.jetbrains.kotlin.psi.psiUtil.visibilityModifier import org.jetbrains.kotlin.psi.psiUtil.visibilityModifier
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
import org.jetbrains.kotlin.resolve.descriptorUtil.isEffectivelyPublicApi import org.jetbrains.kotlin.resolve.descriptorUtil.isEffectivelyPublicApi
class RedundantVisibilityModifierInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool { class RedundantVisibilityModifierInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool {
@@ -79,7 +78,7 @@ class RedundantVisibilityModifierInspection : AbstractKotlinInspection(), Cleanu
} }
return (descriptor as? CallableMemberDescriptor) return (descriptor as? CallableMemberDescriptor)
?.overriddenDescriptors ?.overriddenDescriptors
?.firstNotNullResult { (it as? PropertyDescriptor)?.setter } ?.firstNotNullOfOrNull { (it as? PropertyDescriptor)?.setter }
?.visibility ?.visibility
} }
} }
@@ -32,8 +32,6 @@ import org.jetbrains.kotlin.idea.core.quoteIfNeeded
import org.jetbrains.kotlin.idea.intentions.ImportAllMembersIntention import org.jetbrains.kotlin.idea.intentions.ImportAllMembersIntention
import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
class AddWhenRemainingBranchesFix( class AddWhenRemainingBranchesFix(
expression: KtWhenExpression, expression: KtWhenExpression,
@@ -122,7 +120,7 @@ class AddWhenRemainingBranchesFix(
element.entries element.entries
.map { it.conditions.toList() } .map { it.conditions.toList() }
.flatten() .flatten()
.firstNotNullResult { .firstNotNullOfOrNull {
(it as? KtWhenConditionWithExpression)?.expression as? KtDotQualifiedExpression (it as? KtWhenConditionWithExpression)?.expression as? KtDotQualifiedExpression
}?.importReceiverMembers() }?.importReceiverMembers()
} }
@@ -22,7 +22,6 @@ import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.psi.KtReferenceExpression import org.jetbrains.kotlin.psi.KtReferenceExpression
import org.jetbrains.kotlin.resolve.calls.tower.WrongResolutionToClassifier import org.jetbrains.kotlin.resolve.calls.tower.WrongResolutionToClassifier
import org.jetbrains.kotlin.resolve.sam.getAbstractMembers import org.jetbrains.kotlin.resolve.sam.getAbstractMembers
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
class ConvertToAnonymousObjectFix(element: KtNameReferenceExpression) : KotlinQuickFixAction<KtNameReferenceExpression>(element) { class ConvertToAnonymousObjectFix(element: KtNameReferenceExpression) : KotlinQuickFixAction<KtNameReferenceExpression>(element) {
override fun getFamilyName() = KotlinBundle.message("convert.to.anonymous.object") override fun getFamilyName() = KotlinBundle.message("convert.to.anonymous.object")
@@ -33,7 +32,7 @@ class ConvertToAnonymousObjectFix(element: KtNameReferenceExpression) : KotlinQu
val nameReference = element ?: return val nameReference = element ?: return
val call = nameReference.parent as? KtCallExpression ?: return val call = nameReference.parent as? KtCallExpression ?: return
val lambda = SamConversionToAnonymousObjectIntention.getLambdaExpression(call) ?: return val lambda = SamConversionToAnonymousObjectIntention.getLambdaExpression(call) ?: return
val functionDescriptor = nameReference.analyze().diagnostics.forElement(nameReference).firstNotNullResult { val functionDescriptor = nameReference.analyze().diagnostics.forElement(nameReference).firstNotNullOfOrNull {
if (it.factory == Errors.RESOLUTION_TO_CLASSIFIER) getFunctionDescriptor(Errors.RESOLUTION_TO_CLASSIFIER.cast(it)) else null if (it.factory == Errors.RESOLUTION_TO_CLASSIFIER) getFunctionDescriptor(Errors.RESOLUTION_TO_CLASSIFIER.cast(it)) else null
} ?: return } ?: return
val functionName = functionDescriptor.name.asString() val functionName = functionDescriptor.name.asString()
@@ -39,7 +39,6 @@ import org.jetbrains.kotlin.serialization.js.KotlinJavascriptSerializationUtil
import org.jetbrains.kotlin.serialization.js.ModuleKind import org.jetbrains.kotlin.serialization.js.ModuleKind
import org.jetbrains.kotlin.serialization.js.PackagesWithHeaderMetadata import org.jetbrains.kotlin.serialization.js.PackagesWithHeaderMetadata
import org.jetbrains.kotlin.utils.JsMetadataVersion import org.jetbrains.kotlin.utils.JsMetadataVersion
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
abstract class AbstractTopDownAnalyzerFacadeForJS { abstract class AbstractTopDownAnalyzerFacadeForJS {
@@ -126,14 +125,14 @@ abstract class AbstractTopDownAnalyzerFacadeForJS {
// Mimic the behavior in the jvm frontend. The extensions have 2 chances to override the normal analysis: // Mimic the behavior in the jvm frontend. The extensions have 2 chances to override the normal analysis:
// * If any of the extensions returns a non-null result, it. Otherwise do the normal analysis. // * If any of the extensions returns a non-null result, it. Otherwise do the normal analysis.
// * `analysisCompleted` can be used to override the result, too. // * `analysisCompleted` can be used to override the result, too.
var result = analysisHandlerExtensions.firstNotNullResult { extension -> var result = analysisHandlerExtensions.firstNotNullOfOrNull { extension ->
extension.doAnalysis(project, moduleContext.module, moduleContext, files, trace, container) extension.doAnalysis(project, moduleContext.module, moduleContext, files, trace, container)
} ?: run { } ?: run {
container.get<LazyTopDownAnalyzer>().analyzeDeclarations(TopDownAnalysisMode.TopLevelDeclarations, files) container.get<LazyTopDownAnalyzer>().analyzeDeclarations(TopDownAnalysisMode.TopLevelDeclarations, files)
AnalysisResult.success(trace.bindingContext, moduleContext.module) AnalysisResult.success(trace.bindingContext, moduleContext.module)
} }
result = analysisHandlerExtensions.firstNotNullResult { extension -> result = analysisHandlerExtensions.firstNotNullOfOrNull { extension ->
extension.analysisCompleted(project, moduleContext.module, trace, files) extension.analysisCompleted(project, moduleContext.module, trace, files)
} ?: result } ?: result
@@ -20,7 +20,6 @@ import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.js.translate.context.TranslationContext import org.jetbrains.kotlin.js.translate.context.TranslationContext
import org.jetbrains.kotlin.js.translate.intrinsic.functions.basic.FunctionIntrinsic import org.jetbrains.kotlin.js.translate.intrinsic.functions.basic.FunctionIntrinsic
import org.jetbrains.kotlin.js.translate.intrinsic.functions.factories.* import org.jetbrains.kotlin.js.translate.intrinsic.functions.factories.*
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
class FunctionIntrinsics { class FunctionIntrinsics {
@@ -46,7 +45,7 @@ class FunctionIntrinsics {
fun getIntrinsic(descriptor: FunctionDescriptor, context: TranslationContext): FunctionIntrinsic? { fun getIntrinsic(descriptor: FunctionDescriptor, context: TranslationContext): FunctionIntrinsic? {
if (descriptor in intrinsicCache) return intrinsicCache[descriptor] if (descriptor in intrinsicCache) return intrinsicCache[descriptor]
return factories.firstNotNullResult { it.getIntrinsic(descriptor, context) }.also { return factories.firstNotNullOfOrNull { it.getIntrinsic(descriptor, context) }.also {
intrinsicCache[descriptor] = it intrinsicCache[descriptor] = it
} }
} }
@@ -30,7 +30,6 @@ import org.jetbrains.kotlin.js.translate.utils.getPrimitiveNumericComparisonInfo
import org.jetbrains.kotlin.lexer.KtToken import org.jetbrains.kotlin.lexer.KtToken
import org.jetbrains.kotlin.psi.KtBinaryExpression import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
class BinaryOperationIntrinsics { class BinaryOperationIntrinsics {
@@ -59,7 +58,7 @@ class BinaryOperationIntrinsics {
private fun computeAndCache(key: IntrinsicKey): BinaryOperationIntrinsic? { private fun computeAndCache(key: IntrinsicKey): BinaryOperationIntrinsic? {
if (key in intrinsicCache) return intrinsicCache[key] if (key in intrinsicCache) return intrinsicCache[key]
val result = factories.firstNotNullResult { factory -> val result = factories.firstNotNullOfOrNull { factory ->
if (factory.getSupportTokens().contains(key.token)) { if (factory.getSupportTokens().contains(key.token)) {
factory.getIntrinsic(key.function, key.leftType, key.rightType) factory.getIntrinsic(key.function, key.leftType, key.rightType)
} else null } else null
@@ -10,7 +10,6 @@ import org.jetbrains.kotlin.konan.target.CompilerOutputKind
import org.jetbrains.kotlin.konan.target.KonanTarget import org.jetbrains.kotlin.konan.target.KonanTarget
import org.jetbrains.kotlin.library.KotlinLibrary import org.jetbrains.kotlin.library.KotlinLibrary
import org.jetbrains.kotlin.library.uniqueName import org.jetbrains.kotlin.library.uniqueName
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
class CachedLibraries( class CachedLibraries(
private val target: KonanTarget, private val target: KonanTarget,
@@ -57,7 +56,7 @@ class CachedLibraries(
selectCache(library, File(explicitPath)) selectCache(library, File(explicitPath))
?: error("No cache found for library ${library.libraryName} at $explicitPath") ?: error("No cache found for library ${library.libraryName} at $explicitPath")
} else { } else {
implicitCacheDirectories.firstNotNullResult { dir -> implicitCacheDirectories.firstNotNullOfOrNull { dir ->
selectCache(library, dir.child(getCachedLibraryName(library))) selectCache(library, dir.child(getCachedLibraryName(library)))
} }
} }
@@ -5,13 +5,10 @@
package org.jetbrains.kotlin.backend.konan package org.jetbrains.kotlin.backend.konan
import org.jetbrains.kotlin.backend.konan.descriptors.findPackage import org.jetbrains.kotlin.backend.konan.descriptors.*
import org.jetbrains.kotlin.backend.konan.descriptors.getArgumentValueOrNull import org.jetbrains.kotlin.backend.konan.ir.getAnnotationArgumentValue
import org.jetbrains.kotlin.backend.konan.descriptors.getAnnotationValueOrNull import org.jetbrains.kotlin.backend.konan.ir.isOverridable
import org.jetbrains.kotlin.backend.konan.descriptors.getStringValue import org.jetbrains.kotlin.backend.konan.ir.parentDeclarationsWithSelf
import org.jetbrains.kotlin.backend.konan.descriptors.getAnnotationStringValue
import org.jetbrains.kotlin.backend.konan.descriptors.getStringValueOrNull
import org.jetbrains.kotlin.backend.konan.ir.*
import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor
import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.incremental.components.NoLookupLocation
@@ -31,7 +28,6 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.parentsWithSelf
import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.typeUtil.supertypes import org.jetbrains.kotlin.types.typeUtil.supertypes
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
internal val interopPackageName = InteropFqNames.packageName internal val interopPackageName = InteropFqNames.packageName
internal val objCObjectFqName = interopPackageName.child(Name.identifier("ObjCObject")) internal val objCObjectFqName = interopPackageName.child(Name.identifier("ObjCObject"))
@@ -155,7 +151,7 @@ private fun FunctionDescriptor.getObjCMethodInfo(onlyExternal: Boolean): ObjCMet
} }
} }
return overriddenDescriptors.firstNotNullResult { it.getObjCMethodInfo(onlyExternal) } return overriddenDescriptors.firstNotNullOfOrNull { it.getObjCMethodInfo(onlyExternal) }
} }
/** /**
@@ -170,7 +166,7 @@ private fun IrSimpleFunction.getObjCMethodInfo(onlyExternal: Boolean): ObjCMetho
} }
} }
return overriddenSymbols.firstNotNullResult { it.owner.getObjCMethodInfo(onlyExternal) } return overriddenSymbols.firstNotNullOfOrNull { it.owner.getObjCMethodInfo(onlyExternal) }
} }
fun FunctionDescriptor.getExternalObjCMethodInfo(): ObjCMethodInfo? = this.getObjCMethodInfo(onlyExternal = true) fun FunctionDescriptor.getExternalObjCMethodInfo(): ObjCMethodInfo? = this.getObjCMethodInfo(onlyExternal = true)
@@ -5,7 +5,6 @@
package org.jetbrains.kotlin.backend.konan package org.jetbrains.kotlin.backend.konan
import org.jetbrains.kotlin.library.resolver.KotlinLibraryResolveResult
import org.jetbrains.kotlin.analyzer.AnalysisResult import org.jetbrains.kotlin.analyzer.AnalysisResult
import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.functions.functionInterfacePackageFragmentProvider import org.jetbrains.kotlin.builtins.functions.functionInterfacePackageFragmentProvider
@@ -25,6 +24,7 @@ import org.jetbrains.kotlin.konan.util.KlibMetadataFactories
import org.jetbrains.kotlin.library.KotlinLibrary import org.jetbrains.kotlin.library.KotlinLibrary
import org.jetbrains.kotlin.library.metadata.NativeTypeTransformer import org.jetbrains.kotlin.library.metadata.NativeTypeTransformer
import org.jetbrains.kotlin.library.metadata.NullFlexibleTypeDeserializer import org.jetbrains.kotlin.library.metadata.NullFlexibleTypeDeserializer
import org.jetbrains.kotlin.library.resolver.KotlinLibraryResolveResult
import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.* import org.jetbrains.kotlin.resolve.*
@@ -32,7 +32,6 @@ import org.jetbrains.kotlin.resolve.extensions.AnalysisHandlerExtension
import org.jetbrains.kotlin.resolve.lazy.declarations.FileBasedDeclarationProviderFactory import org.jetbrains.kotlin.resolve.lazy.declarations.FileBasedDeclarationProviderFactory
import org.jetbrains.kotlin.serialization.konan.KotlinResolvedModuleDescriptors import org.jetbrains.kotlin.serialization.konan.KotlinResolvedModuleDescriptors
import org.jetbrains.kotlin.storage.StorageManager import org.jetbrains.kotlin.storage.StorageManager
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
internal object TopDownAnalyzerFacadeForKonan { internal object TopDownAnalyzerFacadeForKonan {
@@ -102,14 +101,14 @@ internal object TopDownAnalyzerFacadeForKonan {
// Mimic the behavior in the jvm frontend. The extensions have 2 chances to override the normal analysis: // Mimic the behavior in the jvm frontend. The extensions have 2 chances to override the normal analysis:
// * If any of the extensions returns a non-null result, use it. Otherwise do the normal analysis. // * If any of the extensions returns a non-null result, use it. Otherwise do the normal analysis.
// * `analysisCompleted` can be used to override the result, too. // * `analysisCompleted` can be used to override the result, too.
var result = analysisHandlerExtensions.firstNotNullResult { extension -> var result = analysisHandlerExtensions.firstNotNullOfOrNull { extension ->
extension.doAnalysis(project, moduleDescriptor, projectContext, files, trace, container) extension.doAnalysis(project, moduleDescriptor, projectContext, files, trace, container)
} ?: run { } ?: run {
analyzerForKonan.analyzeDeclarations(TopDownAnalysisMode.TopLevelDeclarations, files) analyzerForKonan.analyzeDeclarations(TopDownAnalysisMode.TopLevelDeclarations, files)
AnalysisResult.success(trace.bindingContext, moduleDescriptor) AnalysisResult.success(trace.bindingContext, moduleDescriptor)
} }
result = analysisHandlerExtensions.firstNotNullResult { extension -> result = analysisHandlerExtensions.firstNotNullOfOrNull { extension ->
extension.analysisCompleted(project, moduleDescriptor, trace, files) extension.analysisCompleted(project, moduleDescriptor, trace, files)
} ?: result } ?: result
@@ -10,8 +10,8 @@ import org.jetbrains.kotlin.backend.konan.ir.interop.findDeclarationByName
import org.jetbrains.kotlin.backend.konan.ir.interop.irInstanceInitializer import org.jetbrains.kotlin.backend.konan.ir.interop.irInstanceInitializer
import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.ir.builders.* import org.jetbrains.kotlin.ir.builders.*
import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.descriptors.IrBuiltIns import org.jetbrains.kotlin.ir.descriptors.IrBuiltIns
@@ -25,7 +25,6 @@ import org.jetbrains.kotlin.psi2ir.generators.DeclarationGenerator
import org.jetbrains.kotlin.psi2ir.generators.EnumClassMembersGenerator import org.jetbrains.kotlin.psi2ir.generators.EnumClassMembersGenerator
import org.jetbrains.kotlin.psi2ir.generators.GeneratorContext import org.jetbrains.kotlin.psi2ir.generators.GeneratorContext
import org.jetbrains.kotlin.resolve.constants.ConstantValue import org.jetbrains.kotlin.resolve.constants.ConstantValue
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
private fun extractConstantValue(descriptor: DeclarationDescriptor, type: String): ConstantValue<*>? = private fun extractConstantValue(descriptor: DeclarationDescriptor, type: String): ConstantValue<*>? =
descriptor.annotations descriptor.annotations
@@ -148,7 +147,7 @@ internal class CEnumClassGenerator(
* This function extracts value from the annotation. * This function extracts value from the annotation.
*/ */
private fun extractEnumEntryValue(entryDescriptor: ClassDescriptor): IrExpression = private fun extractEnumEntryValue(entryDescriptor: ClassDescriptor): IrExpression =
cEnumEntryValueTypes.firstNotNullResult { extractConstantValue(entryDescriptor, it) } ?.let { cEnumEntryValueTypes.firstNotNullOfOrNull { extractConstantValue(entryDescriptor, it) }?.let {
context.constantValueGenerator.generateConstantValueAsExpression(SYNTHETIC_OFFSET, SYNTHETIC_OFFSET, it) context.constantValueGenerator.generateConstantValueAsExpression(SYNTHETIC_OFFSET, SYNTHETIC_OFFSET, it)
} ?: error("Enum entry $entryDescriptor has no appropriate @$cEnumEntryValueAnnotationName annotation!") } ?: error("Enum entry $entryDescriptor has no appropriate @$cEnumEntryValueAnnotationName annotation!")
@@ -36,7 +36,6 @@ import org.jetbrains.kotlin.load.kotlin.PackagePartClassUtils
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.resolve.descriptorUtil.module import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
internal class TestProcessor (val context: Context) { internal class TestProcessor (val context: Context) {
@@ -203,7 +202,7 @@ internal class TestProcessor (val context: Context) {
return (owner as? IrSimpleFunction) return (owner as? IrSimpleFunction)
?.overriddenSymbols ?.overriddenSymbols
?.firstNotNullResult { ?.firstNotNullOfOrNull {
it.findAnnotatedFunction(testAnnotation) it.findAnnotatedFunction(testAnnotation)
} }
} }
@@ -21,8 +21,6 @@ import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getChildOfType import org.jetbrains.kotlin.psi.psiUtil.getChildOfType
import org.jetbrains.kotlin.resolve.ImportPath import org.jetbrains.kotlin.resolve.ImportPath
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
class JKResolver(val project: Project, module: Module?, private val contextElement: PsiElement) { class JKResolver(val project: Project, module: Module?, private val contextElement: PsiElement) {
private val scope = module?.let { private val scope = module?.let {
@@ -79,7 +77,7 @@ class JKResolver(val project: Project, module: Module?, private val contextEleme
.getChildOfType<KtDotQualifiedExpression>() .getChildOfType<KtDotQualifiedExpression>()
?.selectorExpression ?.selectorExpression
?.references ?.references
?.firstNotNullResult(PsiReference::resolve) ?.firstNotNullOfOrNull(PsiReference::resolve)
} }
@@ -18,7 +18,6 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyAnnotationDescriptor import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyAnnotationDescriptor
import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.KotlinTypeFactory import org.jetbrains.kotlin.types.KotlinTypeFactory
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
internal fun ClassConstructorDescriptor.isSerializationCtor(): Boolean { internal fun ClassConstructorDescriptor.isSerializationCtor(): Boolean {
/*kind == CallableMemberDescriptor.Kind.SYNTHESIZED does not work because DeserializedClassConstructorDescriptor loses its kind*/ /*kind == CallableMemberDescriptor.Kind.SYNTHESIZED does not work because DeserializedClassConstructorDescriptor loses its kind*/
@@ -104,7 +103,7 @@ internal fun getSerializationPackageFqn(classSimpleName: String): FqName =
SerializationPackages.packageFqName.child(Name.identifier(classSimpleName)) SerializationPackages.packageFqName.child(Name.identifier(classSimpleName))
internal fun ModuleDescriptor.getClassFromSerializationPackage(classSimpleName: String) = internal fun ModuleDescriptor.getClassFromSerializationPackage(classSimpleName: String) =
SerializationPackages.allPublicPackages.firstNotNullResult { pkg -> SerializationPackages.allPublicPackages.firstNotNullOfOrNull { pkg ->
module.findClassAcrossModuleDependencies(ClassId( module.findClassAcrossModuleDependencies(ClassId(
pkg, pkg,
Name.identifier(classSimpleName) Name.identifier(classSimpleName)