Replace map { ... }.filterNotNull() with mapNotNull { ... }

This commit is contained in:
Ilya Gorbunov
2015-11-13 23:43:05 +03:00
parent 5b02a59cb7
commit 32151c077e
112 changed files with 197 additions and 269 deletions
@@ -127,7 +127,7 @@ public class PropertyReferenceCodegen(
StackValue.singleton(containingObject, typeMapper).put(typeMapper.mapClass(containingObject), this) StackValue.singleton(containingObject, typeMapper).put(typeMapper.mapClass(containingObject), this)
} }
for ((index, type) in listOf(dispatchReceiverType, extensionReceiverType).filterNotNull().withIndex()) { for ((index, type) in listOfNotNull(dispatchReceiverType, extensionReceiverType).withIndex()) {
StackValue.local(index + 1, OBJECT_TYPE).put(typeMapper.mapType(type), this) StackValue.local(index + 1, OBJECT_TYPE).put(typeMapper.mapType(type), this)
} }
@@ -40,10 +40,10 @@ class BuilderFactoryForDuplicateClassNameDiagnostics(
} }
private fun reportError(internalName: String, vararg another: JvmDeclarationOrigin) { private fun reportError(internalName: String, vararg another: JvmDeclarationOrigin) {
val fromString = another.map { it.descriptor }.filterNotNull(). val fromString = another.mapNotNull { it.descriptor }.
joinToString { DescriptorRenderer.ONLY_NAMES_WITH_SHORT_TYPES.render(it) } joinToString { DescriptorRenderer.ONLY_NAMES_WITH_SHORT_TYPES.render(it) }
another.map { it.element }.filterNotNull().forEach { another.mapNotNull { it.element }.forEach {
diagnostics.report(ErrorsJvm.DUPLICATE_CLASS_NAMES.on(it, internalName, fromString)) diagnostics.report(ErrorsJvm.DUPLICATE_CLASS_NAMES.on(it, internalName, fromString))
} }
} }
@@ -92,13 +92,13 @@ public class CliLightClassGenerationSupport(project: Project) : LightClassGenera
} }
override fun findClassOrObjectDeclarations(fqName: FqName, searchScope: GlobalSearchScope): Collection<KtClassOrObject> { override fun findClassOrObjectDeclarations(fqName: FqName, searchScope: GlobalSearchScope): Collection<KtClassOrObject> {
return ResolveSessionUtils.getClassDescriptorsByFqName(module, fqName).map { return ResolveSessionUtils.getClassDescriptorsByFqName(module, fqName).mapNotNull {
val element = DescriptorToSourceUtils.getSourceFromDescriptor(it) val element = DescriptorToSourceUtils.getSourceFromDescriptor(it)
if (element is KtClassOrObject && PsiSearchScopeUtil.isInScope(searchScope, element)) { if (element is KtClassOrObject && PsiSearchScopeUtil.isInScope(searchScope, element)) {
element element
} }
else null else null
}.filterNotNull() }
} }
override fun findFilesForPackage(fqName: FqName, searchScope: GlobalSearchScope): Collection<KtFile> { override fun findFilesForPackage(fqName: FqName, searchScope: GlobalSearchScope): Collection<KtFile> {
@@ -216,7 +216,7 @@ public class CliLightClassGenerationSupport(project: Project) : LightClassGenera
override fun getFacadeClassesInPackage(packageFqName: FqName, scope: GlobalSearchScope): Collection<PsiClass> { override fun getFacadeClassesInPackage(packageFqName: FqName, scope: GlobalSearchScope): Collection<PsiClass> {
return PackagePartClassUtils.getFilesWithCallables(findFilesForPackage(packageFqName, scope)).groupBy { return PackagePartClassUtils.getFilesWithCallables(findFilesForPackage(packageFqName, scope)).groupBy {
JvmFileClassUtil.getFileClassInfoNoResolve(it).facadeClassFqName JvmFileClassUtil.getFileClassInfoNoResolve(it).facadeClassFqName
}.map { KtLightClassForFacade.createForFacade(psiManager, it.key, scope, it.value) }.filterNotNull() }.mapNotNull { KtLightClassForFacade.createForFacade(psiManager, it.key, scope, it.value) }
} }
override fun getFacadeNames(packageFqName: FqName, scope: GlobalSearchScope): Collection<String> { override fun getFacadeNames(packageFqName: FqName, scope: GlobalSearchScope): Collection<String> {
@@ -28,9 +28,9 @@ public class JvmPackagePartProvider(val env: KotlinCoreEnvironment) : PackagePar
val roots by lazy { val roots by lazy {
env.configuration.getList(CommonConfigurationKeys.CONTENT_ROOTS). env.configuration.getList(CommonConfigurationKeys.CONTENT_ROOTS).
filterIsInstance<JvmClasspathRoot>(). filterIsInstance<JvmClasspathRoot>().
map { mapNotNull {
env.contentRootToVirtualFile(it); env.contentRootToVirtualFile(it);
}.filter { it?.findChild("META-INF") != null }.filterNotNull() }.filter { it.findChild("META-INF") != null }
} }
override fun findPackageParts(packageFqName: String): List<String> { override fun findPackageParts(packageFqName: String): List<String> {
@@ -43,10 +43,10 @@ public class JvmPackagePartProvider(val env: KotlinCoreEnvironment) : PackagePar
else parent.findChild(part) ?: return@filter false else parent.findChild(part) ?: return@filter false
} }
true true
}.map { }.mapNotNull {
it.findChild("META-INF") it.findChild("META-INF")
}.filterNotNull().flatMap { }.flatMap {
it.children.filter { it.name.endsWith(ModuleMapping.MAPPING_FILE_EXT) }.toList<VirtualFile>() it.children.filter<VirtualFile> { it.name.endsWith(ModuleMapping.MAPPING_FILE_EXT) }
}.map { }.map {
try { try {
ModuleMapping.create(it.contentsToByteArray()) ModuleMapping.create(it.contentsToByteArray())
@@ -55,6 +55,6 @@ public class JvmPackagePartProvider(val env: KotlinCoreEnvironment) : PackagePar
} }
} }
return mappings.map { it.findPackageParts(packageFqName) }.filterNotNull().flatMap { it.parts }.distinct() return mappings.mapNotNull { it.findPackageParts(packageFqName) }.flatMap { it.parts }.distinct()
} }
} }
@@ -49,10 +49,10 @@ public fun inlineFunctionsJvmNames(bytes: ByteArray): Set<String> {
private fun inlineFunctionsJvmNames(functions: List<ProtoBuf.Function>, nameResolver: NameResolver, protoTypeTable: ProtoBuf.TypeTable): Set<String> { private fun inlineFunctionsJvmNames(functions: List<ProtoBuf.Function>, nameResolver: NameResolver, protoTypeTable: ProtoBuf.TypeTable): Set<String> {
val typeTable = TypeTable(protoTypeTable) val typeTable = TypeTable(protoTypeTable)
val inlineFunctions = functions.filter { Flags.IS_INLINE.get(it.flags) } val inlineFunctions = functions.filter { Flags.IS_INLINE.get(it.flags) }
val jvmNames = inlineFunctions.map { val jvmNames = inlineFunctions.mapNotNull {
JvmProtoBufUtil.getJvmMethodSignature(it, nameResolver, typeTable) JvmProtoBufUtil.getJvmMethodSignature(it, nameResolver, typeTable)
} }
return jvmNames.filterNotNull().toSet() return jvmNames.toSet()
} }
private fun readKotlinHeader(bytes: ByteArray): KotlinClassHeader { private fun readKotlinHeader(bytes: ByteArray): KotlinClassHeader {
@@ -119,10 +119,9 @@ public class IncrementalPackageFragmentProvider(
} ?: emptyList<String>() } ?: emptyList<String>()
val scopes = actualPackagePartFiles val scopes = actualPackagePartFiles
.map { .mapNotNull {
incrementalCache.getPackagePartData(it) incrementalCache.getPackagePartData(it)
} }
.filterNotNull()
.map { .map {
IncrementalPackageScope(JvmProtoBufUtil.readPackageDataFrom(it.data, it.strings)) IncrementalPackageScope(JvmProtoBufUtil.readPackageDataFrom(it.data, it.strings))
} }
@@ -149,7 +148,7 @@ public class IncrementalPackageFragmentProvider(
val partsNames: Collection<String> val partsNames: Collection<String>
) : PackageFragmentDescriptorImpl(moduleDescriptor, multifileClassFqName.parent()) { ) : PackageFragmentDescriptorImpl(moduleDescriptor, multifileClassFqName.parent()) {
val memberScope = storageManager.createLazyValue { val memberScope = storageManager.createLazyValue {
val partsData = partsNames.map { incrementalCache.getPackagePartData(it) }.filterNotNull() val partsData = partsNames.mapNotNull { incrementalCache.getPackagePartData(it) }
if (partsData.isEmpty()) if (partsData.isEmpty())
MemberScope.Empty MemberScope.Empty
else { else {
@@ -182,8 +181,7 @@ public class IncrementalPackageFragmentProvider(
if (LOG.isDebugEnabled) { if (LOG.isDebugEnabled) {
val allPackageParts = allMemberProtos val allPackageParts = allMemberProtos
.map(::getPackagePart) .mapNotNull(::getPackagePart)
.filterNotNull()
.toSet() .toSet()
val skippedPackageParts = allPackageParts.filter { shouldSkipPackagePart(it) } val skippedPackageParts = allPackageParts.filter { shouldSkipPackagePart(it) }
@@ -38,7 +38,7 @@ internal class IncrementalPackagePartProvider private constructor(
val packagePartsFromParent = parent.findPackageParts(packageFqName) val packagePartsFromParent = parent.findPackageParts(packageFqName)
if (packageFqName in fqNamesToIgnore) return packagePartsFromParent if (packageFqName in fqNamesToIgnore) return packagePartsFromParent
val packagePartsFromCompiled = moduleMappings().map { it.findPackageParts(packageFqName) }.filterNotNull().flatMap { it.parts } val packagePartsFromCompiled = moduleMappings().mapNotNull { it.findPackageParts(packageFqName) }.flatMap { it.parts }
return (packagePartsFromCompiled + packagePartsFromParent).distinct() return (packagePartsFromCompiled + packagePartsFromParent).distinct()
} }
@@ -77,8 +77,7 @@ class SamAdapterFunctionsScope(storageManager: StorageManager) : BaseImportingSc
return receiverTypes.flatMapTo(LinkedHashSet<FunctionDescriptor>()) { type -> return receiverTypes.flatMapTo(LinkedHashSet<FunctionDescriptor>()) { type ->
type.memberScope.getContributedDescriptors(DescriptorKindFilter.FUNCTIONS) type.memberScope.getContributedDescriptors(DescriptorKindFilter.FUNCTIONS)
.filterIsInstance<FunctionDescriptor>() .filterIsInstance<FunctionDescriptor>()
.map { extensionForFunction(it.original) } .mapNotNull { extensionForFunction(it.original) }
.filterNotNull()
} }
} }
@@ -60,9 +60,9 @@ fun getReceiverTypePredicate(resolvedCall: ResolvedCall<*>, receiverValue: Recei
} }
resolvedCall.getDispatchReceiver() -> { resolvedCall.getDispatchReceiver() -> {
val rootCallableDescriptors = callableDescriptor.findTopMostOverriddenDescriptors() val rootCallableDescriptors = callableDescriptor.findTopMostOverriddenDescriptors()
return or(rootCallableDescriptors.map { return or(rootCallableDescriptors.mapNotNull {
it.getDispatchReceiverParameter()?.getType()?.let { TypeUtils.makeNullableIfNeeded(it, resolvedCall.isSafeCall()) }?.getSubtypesPredicate() it.getDispatchReceiverParameter()?.getType()?.let { TypeUtils.makeNullableIfNeeded(it, resolvedCall.isSafeCall()) }?.getSubtypesPredicate()
}.filterNotNull()) })
} }
} }
@@ -253,7 +253,7 @@ public object PositioningStrategies {
val visibilityTokens = listOf(KtTokens.PRIVATE_KEYWORD, KtTokens.PROTECTED_KEYWORD, KtTokens.PUBLIC_KEYWORD, KtTokens.INTERNAL_KEYWORD) val visibilityTokens = listOf(KtTokens.PRIVATE_KEYWORD, KtTokens.PROTECTED_KEYWORD, KtTokens.PUBLIC_KEYWORD, KtTokens.INTERNAL_KEYWORD)
val modifierList = element.getModifierList() val modifierList = element.getModifierList()
val result = visibilityTokens.map { modifierList?.getModifier(it)?.getTextRange() }.filterNotNull() val result = visibilityTokens.mapNotNull { modifierList?.getModifier(it)?.getTextRange() }
if (!result.isEmpty()) return result if (!result.isEmpty()) return result
// Try to resolve situation when there's no visibility modifiers written before element // Try to resolve situation when there's no visibility modifiers written before element
@@ -282,8 +282,8 @@ private object DebugTextBuildingVisitor : KtVisitor<String, Unit>() {
} }
fun renderChildren(element: KtElementImplStub<*>, separator: String, prefix: String = "", postfix: String = ""): String? { fun renderChildren(element: KtElementImplStub<*>, separator: String, prefix: String = "", postfix: String = ""): String? {
val childrenTexts = element.getStub()?.getChildrenStubs()?.map { (it?.getPsi() as? KtElement)?.getDebugText() } val childrenTexts = element.getStub()?.getChildrenStubs()?.mapNotNull { (it?.getPsi() as? KtElement)?.getDebugText() }
return childrenTexts?.filterNotNull()?.joinToString(separator, prefix, postfix) ?: element.getText() return childrenTexts?.joinToString(separator, prefix, postfix) ?: element.getText()
} }
fun render(element: KtElementImplStub<*>, vararg relevantChildren: KtElement?): String? { fun render(element: KtElementImplStub<*>, vararg relevantChildren: KtElement?): String? {
@@ -58,8 +58,7 @@ internal fun addModifier(modifierList: KtModifierList, modifier: KtModifierKeywo
val newModifier = KtPsiFactory(modifierList).createModifier(modifier) val newModifier = KtPsiFactory(modifierList).createModifier(modifier)
val modifierToReplace = MODIFIERS_TO_REPLACE[modifier] val modifierToReplace = MODIFIERS_TO_REPLACE[modifier]
?.map { modifierList.getModifier(it) } ?.mapNotNull { modifierList.getModifier(it) }
?.filterNotNull()
?.firstOrNull() ?.firstOrNull()
if (modifierToReplace != null) { if (modifierToReplace != null) {
@@ -40,7 +40,7 @@ public open class KotlinStubBaseImpl<T : KtElementImplStub<*>>(parent: StubEleme
} }
private fun renderPropertyValues(stubInterface: Class<out Any?>): List<String> { private fun renderPropertyValues(stubInterface: Class<out Any?>): List<String> {
return collectProperties(stubInterface).map { property -> renderProperty(property) }.filterNotNull().sorted() return collectProperties(stubInterface).mapNotNull { property -> renderProperty(property) }.sorted()
} }
private fun collectProperties(stubInterface: Class<*>): Collection<Method> { private fun collectProperties(stubInterface: Class<*>): Collection<Method> {
@@ -40,7 +40,7 @@ class AllUnderImportsScope(descriptor: DeclarationDescriptor) : BaseImportingSco
= scopes.flatMap { it.getContributedDescriptors(kindFilter, nameFilter) } = scopes.flatMap { it.getContributedDescriptors(kindFilter, nameFilter) }
override fun getContributedClassifier(name: Name, location: LookupLocation) override fun getContributedClassifier(name: Name, location: LookupLocation)
= scopes.asSequence().map { it.getContributedClassifier(name, location) }.filterNotNull().singleOrNull() = scopes.asSequence().mapNotNull { it.getContributedClassifier(name, location) }.singleOrNull()
override fun getContributedVariables(name: Name, location: LookupLocation) override fun getContributedVariables(name: Name, location: LookupLocation)
= scopes.flatMap { it.getContributedVariables(name, location) } = scopes.flatMap { it.getContributedVariables(name, location) }
@@ -157,9 +157,9 @@ public class AnnotationChecker(private val additionalCheckers: Iterable<Addition
?: return null ?: return null
val valueArguments = targetEntryDescriptor.allValueArguments val valueArguments = targetEntryDescriptor.allValueArguments
val valueArgument = valueArguments.entrySet().firstOrNull()?.getValue() as? ArrayValue ?: return null val valueArgument = valueArguments.entrySet().firstOrNull()?.getValue() as? ArrayValue ?: return null
return valueArgument.value.filterIsInstance<EnumValue>().map { return valueArgument.value.filterIsInstance<EnumValue>().mapNotNull {
KotlinTarget.valueOrNull(it.value.name.asString()) KotlinTarget.valueOrNull(it.value.name.asString())
}.filterNotNull().toSet() }.toSet()
} }
public fun getDeclarationSiteActualTargetList(annotated: KtElement, descriptor: ClassDescriptor?): List<KotlinTarget> { public fun getDeclarationSiteActualTargetList(annotated: KtElement, descriptor: ClassDescriptor?): List<KotlinTarget> {
@@ -119,7 +119,7 @@ public object NonExpansiveInheritanceRestrictionChecker {
val bounds = hashSetOf<KotlinType>() val bounds = hashSetOf<KotlinType>()
val substitutor = constituentType.substitution.buildSubstitutor() val substitutor = constituentType.substitution.buildSubstitutor()
val adaptedUpperBounds = originalTypeParameter.upperBounds.map { substitutor.substitute(it, Variance.INVARIANT) }.filterNotNull() val adaptedUpperBounds = originalTypeParameter.upperBounds.mapNotNull { substitutor.substitute(it, Variance.INVARIANT) }
bounds.addAll(adaptedUpperBounds) bounds.addAll(adaptedUpperBounds)
if (!typeProjection.isStarProjection) { if (!typeProjection.isStarProjection) {
@@ -237,8 +237,7 @@ public class TypeResolver(
val modifierList = param.modifierList val modifierList = param.modifierList
if (modifierList != null) { if (modifierList != null) {
KtTokens.MODIFIER_KEYWORDS_ARRAY KtTokens.MODIFIER_KEYWORDS_ARRAY
.map { modifierList.getModifier(it) } .mapNotNull { modifierList.getModifier(it) }
.filterNotNull()
.forEach { c.trace.report(Errors.UNSUPPORTED.on(it, "modifier on parameter in function type")) .forEach { c.trace.report(Errors.UNSUPPORTED.on(it, "modifier on parameter in function type"))
} }
} }
@@ -171,7 +171,7 @@ class GenericCandidateResolver(private val argumentTypeResolver: ArgumentTypeRes
val candidateWithFreshVariables = FunctionDescriptorUtil.alphaConvertTypeParameters(candidateDescriptor) val candidateWithFreshVariables = FunctionDescriptorUtil.alphaConvertTypeParameters(candidateDescriptor)
val conversion = candidateDescriptor.typeParameters.zip(candidateWithFreshVariables.typeParameters).toMap() val conversion = candidateDescriptor.typeParameters.zip(candidateWithFreshVariables.typeParameters).toMap()
val freshVariables = returnType.getNestedTypeParameters().map { conversion[it] }.filterNotNull() val freshVariables = returnType.getNestedTypeParameters().mapNotNull { conversion[it] }
builder.registerTypeVariables(resultingCall.call.toHandle(), freshVariables, external = true) builder.registerTypeVariables(resultingCall.call.toHandle(), freshVariables, external = true)
builder.addSubtypeConstraint( builder.addSubtypeConstraint(
@@ -58,9 +58,7 @@ public abstract class DeclarationProviderFactoryService {
private class SyntheticFilesFilteringScope(syntheticFiles: Collection<KtFile>, baseScope: GlobalSearchScope) private class SyntheticFilesFilteringScope(syntheticFiles: Collection<KtFile>, baseScope: GlobalSearchScope)
: DelegatingGlobalSearchScope(baseScope) { : DelegatingGlobalSearchScope(baseScope) {
private val originals = syntheticFiles private val originals = syntheticFiles.mapNotNullTo(HashSet<VirtualFile>()) { it.getOriginalFile().getVirtualFile() }
.map { it.getOriginalFile().getVirtualFile() }
.filterNotNullTo(HashSet<VirtualFile>())
override fun contains(file: VirtualFile) = super.contains(file) && file !in originals override fun contains(file: VirtualFile) = super.contains(file) && file !in originals
} }
@@ -86,11 +86,10 @@ public class LazyAnnotations(
override fun getUseSiteTargetedAnnotations(): List<AnnotationWithTarget> { override fun getUseSiteTargetedAnnotations(): List<AnnotationWithTarget> {
return annotationEntries return annotationEntries
.asSequence() .mapNotNull {
.map {
val (descriptor, target) = annotation(it) val (descriptor, target) = annotation(it)
if (target == null) null else AnnotationWithTarget(descriptor, target) if (target == null) null else AnnotationWithTarget(descriptor, target)
}.filterNotNull().toList() }
} }
override fun getAllAnnotations() = annotationEntries.map(annotation) override fun getAllAnnotations() = annotationEntries.map(annotation)
@@ -98,10 +97,10 @@ public class LazyAnnotations(
override fun iterator(): Iterator<AnnotationDescriptor> { override fun iterator(): Iterator<AnnotationDescriptor> {
return annotationEntries return annotationEntries
.asSequence() .asSequence()
.map { .mapNotNull {
val (descriptor, target) = annotation(it) val (descriptor, target) = annotation(it)
if (target == null) descriptor else null // Filter out annotations with target if (target == null) descriptor else null // Filter out annotations with target
}.filterNotNull().iterator() }.iterator()
} }
override fun forceResolveAllContents() { override fun forceResolveAllContents() {
@@ -365,13 +365,13 @@ public open class KtLightClassForExplicitDeclaration(
override fun toString() = "${KtLightClass::class.java.simpleName}:$classFqName" override fun toString() = "${KtLightClass::class.java.simpleName}:$classFqName"
override fun getOwnInnerClasses(): List<PsiClass> { override fun getOwnInnerClasses(): List<PsiClass> {
val result = ArrayList<PsiClass?>() val result = ArrayList<PsiClass>()
classOrObject.declarations.filterIsInstance<KtClassOrObject>().mapTo(result) { create(it) } classOrObject.declarations.filterIsInstance<KtClassOrObject>().mapNotNullTo(result) { create(it) }
if (classOrObject.hasInterfaceDefaultImpls) { if (classOrObject.hasInterfaceDefaultImpls) {
result.add(KtLightClassForInterfaceDefaultImpls(classFqName.defaultImplsChild(), classOrObject)) result.add(KtLightClassForInterfaceDefaultImpls(classFqName.defaultImplsChild(), classOrObject))
} }
return result.filterNotNull() return result
} }
override fun getUseScope(): SearchScope = getOrigin().useScope override fun getUseScope(): SearchScope = getOrigin().useScope
@@ -327,14 +327,17 @@ public object LightClassUtil {
public val setter: PsiMethod?, public val setter: PsiMethod?,
public val backingField: PsiField?, public val backingField: PsiField?,
additionalAccessors: List<PsiMethod>) : Iterable<PsiMethod> { additionalAccessors: List<PsiMethod>) : Iterable<PsiMethod> {
private val allMethods = arrayListOf<PsiMethod>() private val allMethods: List<PsiMethod>
val allDeclarations = arrayListOf<PsiNamedElement>() val allDeclarations: List<PsiNamedElement>
init { init {
listOf(getter, setter).filterNotNullTo(allMethods) allMethods = arrayListOf<PsiMethod>()
listOf<PsiNamedElement?>(getter, setter, backingField).filterNotNullTo(allDeclarations) arrayOf(getter, setter).filterNotNullTo(allMethods)
allDeclarations.addAll(additionalAccessors)
additionalAccessors.filterIsInstanceTo<PsiMethod, MutableList<PsiMethod>>(allMethods) additionalAccessors.filterIsInstanceTo<PsiMethod, MutableList<PsiMethod>>(allMethods)
allDeclarations = arrayListOf<PsiNamedElement>()
arrayOf<PsiNamedElement?>(getter, setter, backingField).filterNotNullTo(allDeclarations)
allDeclarations.addAll(additionalAccessors)
} }
override fun iterator(): Iterator<PsiMethod> = allMethods.iterator() override fun iterator(): Iterator<PsiMethod> = allMethods.iterator()
@@ -45,9 +45,9 @@ public fun cliPluginUsageString(pluginId: String, options: Collection<CliOption>
"\n" + " ".repeat(MAX_OPTION_WIDTH + LEFT_INDENT + 1) "\n" + " ".repeat(MAX_OPTION_WIDTH + LEFT_INDENT + 1)
} else " ".repeat(1 + MAX_OPTION_WIDTH - name.length()) } else " ".repeat(1 + MAX_OPTION_WIDTH - name.length())
val modifiers = listOf( val modifiers = listOfNotNull(
if (it.required) "required" else null, if (it.required) "required" else null,
if (it.allowMultipleOccurrences) "multiple" else null).filterNotNull() if (it.allowMultipleOccurrences) "multiple" else null)
val modifiersEnclosed = if (modifiers.isEmpty()) "" else " (${modifiers.joinToString()})" val modifiersEnclosed = if (modifiers.isEmpty()) "" else " (${modifiers.joinToString()})"
" ".repeat(LEFT_INDENT) + name + margin + it.description + modifiersEnclosed " ".repeat(LEFT_INDENT) + name + margin + it.description + modifiersEnclosed
@@ -236,11 +236,10 @@ public object KotlinCompilerClient {
?.split(File.pathSeparator) ?.split(File.pathSeparator)
?.map { File(it).parentFile } ?.map { File(it).parentFile }
?.distinct() ?.distinct()
?.map { ?.mapNotNull {
it?.walk() it?.walk()
?.firstOrNull { it.name.equals(COMPILER_JAR_NAME, ignoreCase = true) } ?.firstOrNull { it.name.equals(COMPILER_JAR_NAME, ignoreCase = true) }
} }
?.filterNotNull()
?.firstOrNull() ?.firstOrNull()
?.let { listOf(it.absolutePath) } ?.let { listOf(it.absolutePath) }
@@ -266,7 +265,7 @@ public object KotlinCompilerClient {
val daemons = registryDir.walk() val daemons = registryDir.walk()
.map { Pair(it, it.name.extractPortFromRunFilename(classPathDigest)) } .map { Pair(it, it.name.extractPortFromRunFilename(classPathDigest)) }
.filter { it.second != 0 } .filter { it.second != 0 }
.map { .mapNotNull {
assert(it.second > 0 && it.second < 0xffff) assert(it.second > 0 && it.second < 0xffff)
reportingTargets.report(DaemonReportCategory.DEBUG, "found suitable daemon on port ${it.second}, trying to connect") reportingTargets.report(DaemonReportCategory.DEBUG, "found suitable daemon on port ${it.second}, trying to connect")
val daemon = tryConnectToDaemon(it.second, reportingTargets) val daemon = tryConnectToDaemon(it.second, reportingTargets)
@@ -276,7 +275,6 @@ public object KotlinCompilerClient {
} }
daemon daemon
} }
.filterNotNull()
.toList() .toList()
return when (daemons.size) { return when (daemons.size) {
0 -> null 0 -> null
@@ -66,8 +66,8 @@ open class PropMapper<C, V, P : KMutableProperty1<C, V>>(val dest: C,
open fun toArgs(prefix: String = COMPILE_DAEMON_CMDLINE_OPTIONS_PREFIX): List<String> = open fun toArgs(prefix: String = COMPILE_DAEMON_CMDLINE_OPTIONS_PREFIX): List<String> =
when { when {
skipIf(prop.get(dest)) -> listOf<String>() skipIf(prop.get(dest)) -> listOf<String>()
mergeDelimiter != null -> listOf(listOf(prefix + names.first(), toString(prop.get(dest))).filterNotNull().joinToString(mergeDelimiter)) mergeDelimiter != null -> listOf(listOfNotNull(prefix + names.first(), toString(prop.get(dest))).joinToString(mergeDelimiter))
else -> listOf(prefix + names.first(), toString(prop.get(dest))).filterNotNull() else -> listOfNotNull(prefix + names.first(), toString(prop.get(dest)))
} }
open fun apply(s: String) = prop.set(dest, fromString(s)) open fun apply(s: String) = prop.set(dest, fromString(s))
@@ -66,8 +66,7 @@ public abstract class AbstractPseudoValueTest : AbstractPseudocodeTest() {
val elementToValues = getElementToValueMap(pseudocode) val elementToValues = getElementToValueMap(pseudocode)
val unboundValues = pseudocode.getInstructions() val unboundValues = pseudocode.getInstructions()
.map { (it as? InstructionWithValue)?.outputValue } .mapNotNull { (it as? InstructionWithValue)?.outputValue }
.filterNotNull()
.filter { it.element == null } .filter { it.element == null }
.sortedBy { it.debugName } .sortedBy { it.debugName }
val allValues = elementToValues.values() + unboundValues val allValues = elementToValues.values() + unboundValues
@@ -32,7 +32,7 @@ import java.io.File
public interface AbstractSMAPBaseTest { public interface AbstractSMAPBaseTest {
private fun extractSMAPFromClasses(outputFiles: Iterable<OutputFile>): List<SMAPAndFile> { private fun extractSMAPFromClasses(outputFiles: Iterable<OutputFile>): List<SMAPAndFile> {
return outputFiles.map { outputFile -> return outputFiles.mapNotNull { outputFile ->
var debugInfo: String? = null var debugInfo: String? = null
ClassReader(outputFile.asByteArray()).accept(object : ClassVisitor(Opcodes.ASM5) { ClassReader(outputFile.asByteArray()).accept(object : ClassVisitor(Opcodes.ASM5) {
override fun visitSource(source: String?, debug: String?) { override fun visitSource(source: String?, debug: String?) {
@@ -41,7 +41,7 @@ public interface AbstractSMAPBaseTest {
}, 0) }, 0)
SMAPAndFile.SMAPAndFile(debugInfo, outputFile.sourceFiles.single()) SMAPAndFile.SMAPAndFile(debugInfo, outputFile.sourceFiles.single())
}.filterNotNull() }
} }
private fun extractSmapFromSource(file: KtFile): SMAPAndFile? { private fun extractSmapFromSource(file: KtFile): SMAPAndFile? {
@@ -63,11 +63,11 @@ public interface AbstractSMAPBaseTest {
return return
} }
val sourceData = inputFiles.map { extractSmapFromSource(it) }.filterNotNull() val sourceData = inputFiles.mapNotNull { extractSmapFromSource(it) }
val compiledData = extractSMAPFromClasses(outputFiles).groupBy { val compiledData = extractSMAPFromClasses(outputFiles).groupBy {
it.sourceFile it.sourceFile
}.map { }.map {
val smap = it.getValue().map { replaceHash(it.smap) }.filterNotNull().joinToString("\n") val smap = it.getValue().mapNotNull { it.smap?.replaceHash() }.joinToString("\n")
SMAPAndFile(if (smap.isNotEmpty()) smap else null, it.key) SMAPAndFile(if (smap.isNotEmpty()) smap else null, it.key)
}.toMap { it.sourceFile } }.toMap { it.sourceFile }
@@ -77,17 +77,16 @@ public interface AbstractSMAPBaseTest {
} }
} }
fun replaceHash(data: String?): String? {
if (data == null) return null
val fileSectionStart = data.indexOf("*F") + 3 private fun String.replaceHash(): String {
val lineSection = data.indexOf("*L") - 1 val fileSectionStart = indexOf("*F") + 3
val lineSection = indexOf("*L") - 1
val files = data.substring(fileSectionStart, lineSection).split("\n") val files = substring(fileSectionStart, lineSection).split("\n")
val cleaned = files.joinToString("\n") val cleaned = files.joinToString("\n")
return data.substring(0, fileSectionStart) + cleaned + data.substring(lineSection) return substring(0, fileSectionStart) + cleaned + substring(lineSection)
} }
class SMAPAndFile(val smap: String?, val sourceFile: String) { class SMAPAndFile(val smap: String?, val sourceFile: String) {
@@ -85,7 +85,7 @@ public fun <TCallable : CallableDescriptor> TCallable.substituteExtensionIfCalla
val extensionReceiverType = fuzzyExtensionReceiverType()!! val extensionReceiverType = fuzzyExtensionReceiverType()!!
val substitutors = types val substitutors = types
.map { .mapNotNull {
var substitutor = extensionReceiverType.checkIsSuperTypeOf(it) var substitutor = extensionReceiverType.checkIsSuperTypeOf(it)
// check if we may fail due to receiver expression being nullable // check if we may fail due to receiver expression being nullable
if (substitutor == null && it.nullability() == TypeNullability.NULLABLE && extensionReceiverType.nullability() == TypeNullability.NOT_NULL) { if (substitutor == null && it.nullability() == TypeNullability.NULLABLE && extensionReceiverType.nullability() == TypeNullability.NOT_NULL) {
@@ -93,7 +93,6 @@ public fun <TCallable : CallableDescriptor> TCallable.substituteExtensionIfCalla
} }
substitutor substitutor
} }
.filterNotNull()
if (getTypeParameters().isEmpty()) { // optimization for non-generic callables if (getTypeParameters().isEmpty()) { // optimization for non-generic callables
return if (substitutors.any()) listOf(this) else listOf() return if (substitutors.any()) listOf(this) else listOf()
} }
@@ -282,7 +282,7 @@ class PartialBodyResolveFilter(
else { else {
val leftName = left.smartCastExpressionName() val leftName = left.smartCastExpressionName()
val rightName = right.smartCastExpressionName() val rightName = right.smartCastExpressionName()
val names = listOf(leftName, rightName).filterNotNull().toSet() val names = listOfNotNull(leftName, rightName).toSet()
return Pair(names, setOf()) return Pair(names, setOf())
} }
} }
@@ -138,9 +138,9 @@ public class CodeFragmentAnalyzer(
return scopeForContextElement to dataFlowInfo return scopeForContextElement to dataFlowInfo
} }
val importScopes = importList.imports.map { val importScopes = importList.imports.mapNotNull {
qualifierResolver.processImportReference(it, resolveSession.moduleDescriptor, resolveSession.trace, null) qualifierResolver.processImportReference(it, resolveSession.moduleDescriptor, resolveSession.trace, null)
}.filterNotNull() }
return scopeForContextElement.addImportingScopes(importScopes) to dataFlowInfo return scopeForContextElement.addImportingScopes(importScopes) to dataFlowInfo
} }
@@ -185,7 +185,7 @@ public class IDELightClassGenerationSupport(private val project: Project) : Ligh
return withFakeLightClasses(lightClassForFacade, facadeFiles) return withFakeLightClasses(lightClassForFacade, facadeFiles)
} }
else { else {
return facadeFiles.filter { it.isCompiled }.map { createLightClassForDecompiledKotlinFile(it) }.filterNotNull() return facadeFiles.filter { it.isCompiled }.mapNotNull { createLightClassForDecompiledKotlinFile(it) }
} }
} }
@@ -61,8 +61,7 @@ public object JsAnalyzerFacade : AnalyzerFacade<PlatformAnalysisParameters>() {
val providers = moduleInfo.library.getFiles(OrderRootType.CLASSES) val providers = moduleInfo.library.getFiles(OrderRootType.CLASSES)
.flatMap { KotlinJavascriptMetadataUtils.loadMetadata(PathUtil.getLocalPath(it)!!) } .flatMap { KotlinJavascriptMetadataUtils.loadMetadata(PathUtil.getLocalPath(it)!!) }
.filter { it.isAbiVersionCompatible } .filter { it.isAbiVersionCompatible }
.map { KotlinJavascriptSerializationUtil.createPackageFragmentProvider(moduleDescriptor, it.body, moduleContext.storageManager) } .mapNotNull { KotlinJavascriptSerializationUtil.createPackageFragmentProvider(moduleDescriptor, it.body, moduleContext.storageManager) }
.filterNotNull()
if (providers.isNotEmpty()) { if (providers.isNotEmpty()) {
packageFragmentProvider = CompositePackageFragmentProvider(listOf(packageFragmentProvider) + providers) packageFragmentProvider = CompositePackageFragmentProvider(listOf(packageFragmentProvider) + providers)
@@ -177,9 +177,9 @@ public class KotlinCacheService(val project: Project) {
return ResolutionFacadeImpl(projectFacade, file.getModuleInfo()) return ResolutionFacadeImpl(projectFacade, file.getModuleInfo())
} }
private fun findSyntheticFiles(files: Collection<KtFile>) = files.map { private fun findSyntheticFiles(files: Collection<KtFile>) = files.mapNotNull {
if (it is KtCodeFragment) it.getContextFile() else it if (it is KtCodeFragment) it.getContextFile() else it
}.filterNotNull().filter { }.filter {
!ProjectRootsUtil.isInProjectSource(it) !ProjectRootsUtil.isInProjectSource(it)
}.toSet() }.toSet()
@@ -72,11 +72,10 @@ public fun KtElement.addToShorteningWaitSet(options: Options = Options.DEFAULT)
public fun performDelayedShortening(project: Project) { public fun performDelayedShortening(project: Project) {
project.elementsToShorten?.let { requests -> project.elementsToShorten?.let { requests ->
project.elementsToShorten = null project.elementsToShorten = null
val elements = requests.map { it.pointer.getElement() } val elementToOptions = requests.mapNotNull { req -> req.pointer.element?.let { it to req.options } }.toMap()
val options = requests.map { it.options } val elements = elementToOptions.keys
val elementToOptions = (elements zip options).toMap()
//TODO: this is not correct because it should not shorten deep into the elements! //TODO: this is not correct because it should not shorten deep into the elements!
ShortenReferences({ elementToOptions[it] ?: ShortenReferences.Options.DEFAULT }).process(elements.filterNotNull()) ShortenReferences({ elementToOptions[it] ?: ShortenReferences.Options.DEFAULT }).process(elements)
} }
} }
@@ -88,7 +88,7 @@ public fun findMultifileClassParts(file: VirtualFile, multifileClass: KotlinJvmB
val packageFqName = multifileClass.classId.packageFqName val packageFqName = multifileClass.classId.packageFqName
val partsFinder = DirectoryBasedClassFinder(file.parent!!, packageFqName) val partsFinder = DirectoryBasedClassFinder(file.parent!!, packageFqName)
val partNames = multifileClass.classHeader.filePartClassNames ?: return emptyList() val partNames = multifileClass.classHeader.filePartClassNames ?: return emptyList()
return partNames.map { return partNames.mapNotNull {
partsFinder.findKotlinClass(ClassId(packageFqName, Name.identifier(it.substringAfterLast('/')))) partsFinder.findKotlinClass(ClassId(packageFqName, Name.identifier(it.substringAfterLast('/'))))
}.filterNotNull() }
} }
@@ -244,7 +244,7 @@ fun createModifierListStubForDeclaration(
): KotlinModifierListStubImpl { ): KotlinModifierListStubImpl {
assert(flagsToTranslate.isNotEmpty()) assert(flagsToTranslate.isNotEmpty())
val modifiers = flagsToTranslate.map { it.getModifiers(flags) }.filterNotNull() + additionalModifiers val modifiers = flagsToTranslate.mapNotNull { it.getModifiers(flags) } + additionalModifiers
return createModifierListStub(parent, modifiers)!! return createModifierListStub(parent, modifiers)!!
} }
@@ -70,7 +70,7 @@ public fun buildDecompiledText(
classHeader.isCompatibleFileFacadeKind() -> classHeader.isCompatibleFileFacadeKind() ->
buildDecompiledText(packageFqName, ArrayList(resolver.resolveDeclarationsInFacade(classId.asSingleFqName()))) buildDecompiledText(packageFqName, ArrayList(resolver.resolveDeclarationsInFacade(classId.asSingleFqName())))
classHeader.isCompatibleClassKind() -> classHeader.isCompatibleClassKind() ->
buildDecompiledText(packageFqName, listOf(resolver.resolveTopLevelClass(classId)).filterNotNull()) buildDecompiledText(packageFqName, listOfNotNull(resolver.resolveTopLevelClass(classId)))
classHeader.isCompatibleMultifileClassKind() -> { classHeader.isCompatibleMultifileClassKind() -> {
val partClasses = findMultifileClassParts(classFile, kotlinClass) val partClasses = findMultifileClassParts(classFile, kotlinClass)
val partMembers = partClasses.flatMap { partClass -> resolver.resolveDeclarationsInFacade(partClass.classId.asSingleFqName()) } val partMembers = partClasses.flatMap { partClass -> resolver.resolveDeclarationsInFacade(partClass.classId.asSingleFqName()) }
@@ -95,7 +95,7 @@ public fun buildDecompiledTextFromJsMetadata(
} }
else { else {
val classId = JsMetaFileUtils.getClassId(classFile) val classId = JsMetaFileUtils.getClassId(classFile)
return buildDecompiledText(packageFqName, listOf(resolver.resolveTopLevelClass(classId)).filterNotNull(), descriptorRendererForKotlinJavascriptDecompiler) return buildDecompiledText(packageFqName, listOfNotNull(resolver.resolveTopLevelClass(classId)), descriptorRendererForKotlinJavascriptDecompiler)
} }
} }
@@ -78,8 +78,7 @@ public object IdeRenderers {
data: ConflictingJvmDeclarationsData -> data: ConflictingJvmDeclarationsData ->
val conflicts = data.signatureOrigins val conflicts = data.signatureOrigins
.map { it.descriptor } .mapNotNull { it.descriptor }
.filterNotNull()
.sortedWith(MemberComparator.INSTANCE) .sortedWith(MemberComparator.INSTANCE)
.joinToString("") { "<li>" + HTML_COMPACT_WITH_MODIFIERS.render(it) + "</li>\n" } .joinToString("") { "<li>" + HTML_COMPACT_WITH_MODIFIERS.render(it) + "</li>\n" }
@@ -38,7 +38,7 @@ public class KtForLoopInReference(element: KtForExpression) : KtMultiReference<K
if (loopRange == null) { if (loopRange == null) {
return Collections.emptyList() return Collections.emptyList()
} }
return LOOP_RANGE_KEYS.map { key -> context.get(key, loopRange)?.getCandidateDescriptor() }.filterNotNull() return LOOP_RANGE_KEYS.mapNotNull { key -> context.get(key, loopRange)?.getCandidateDescriptor() }
} }
companion object { companion object {
@@ -27,9 +27,9 @@ import org.jetbrains.kotlin.idea.caches.resolve.analyze
class KtMultiDeclarationReference(element: KtMultiDeclaration) : KtMultiReference<KtMultiDeclaration>(element) { class KtMultiDeclarationReference(element: KtMultiDeclaration) : KtMultiReference<KtMultiDeclaration>(element) {
override fun getTargetDescriptors(context: BindingContext): Collection<DeclarationDescriptor> { override fun getTargetDescriptors(context: BindingContext): Collection<DeclarationDescriptor> {
return expression.getEntries().map { entry -> return expression.getEntries().mapNotNull { entry ->
context.get(BindingContext.COMPONENT_RESOLVED_CALL, entry)?.getCandidateDescriptor() context.get(BindingContext.COMPONENT_RESOLVED_CALL, entry)?.getCandidateDescriptor()
}.filterNotNull() }
} }
override fun getRangeInElement(): TextRange? { override fun getRangeInElement(): TextRange? {
@@ -42,9 +42,9 @@ public class KtPropertyDelegationMethodsReference(element: KtPropertyDelegate) :
if (descriptor !is PropertyDescriptor) { if (descriptor !is PropertyDescriptor) {
return Collections.emptyList() return Collections.emptyList()
} }
return (descriptor.getAccessors().map { return (descriptor.getAccessors().mapNotNull {
accessor -> accessor ->
context.get(BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, accessor)?.getCandidateDescriptor() context.get(BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, accessor)?.getCandidateDescriptor()
} + listOf(context.get(BindingContext.DELEGATED_PROPERTY_PD_RESOLVED_CALL, descriptor)?.getCandidateDescriptor())).filterNotNull() } + listOfNotNull(context.get(BindingContext.DELEGATED_PROPERTY_PD_RESOLVED_CALL, descriptor)?.getCandidateDescriptor()))
} }
} }
@@ -55,7 +55,7 @@ public val PsiReference.unwrappedTargets: Set<PsiElement>
} }
return when (this) { return when (this) {
is PsiPolyVariantReference -> multiResolve(false).map { it.getElement()?.adjust() }.filterNotNullTo(HashSet<PsiElement>()) is PsiPolyVariantReference -> multiResolve(false).mapNotNullTo(HashSet<PsiElement>()) { it.getElement()?.adjust() }
else -> emptyOrSingletonList(resolve()?.adjust()).toSet() else -> emptyOrSingletonList(resolve()?.adjust()).toSet()
} }
} }
@@ -333,8 +333,7 @@ public class CommentSaver(originalElements: PsiChildRange, private val saveLineB
if (leaf is LineBreakTreeElement) return null if (leaf is LineBreakTreeElement) return null
return leaf.parentsWithSelf return leaf.parentsWithSelf
.takeWhile { it != lineBreakParent } .takeWhile { it != lineBreakParent }
.map { toNewPsiElementMap[it]?.first() } //TODO: what about multiple? .mapNotNull { toNewPsiElementMap[it]?.first() } //TODO: what about multiple?
.filterNotNull()
.firstOrNull() .firstOrNull()
} }
@@ -500,8 +500,7 @@ class BasicCompletionSession(
val classOrObject = position.parents.firstIsInstanceOrNull<KtClassOrObject>() ?: return val classOrObject = position.parents.firstIsInstanceOrNull<KtClassOrObject>() ?: return
val classDescriptor = resolutionFacade.resolveToDescriptor(classOrObject) as ClassDescriptor val classDescriptor = resolutionFacade.resolveToDescriptor(classOrObject) as ClassDescriptor
var superClasses = classDescriptor.defaultType.constructor.supertypesWithAny() var superClasses = classDescriptor.defaultType.constructor.supertypesWithAny()
.map { it.constructor.declarationDescriptor as? ClassDescriptor } .mapNotNull { it.constructor.declarationDescriptor as? ClassDescriptor }
.filterNotNull()
if (callTypeAndReceiver.receiver != null) { if (callTypeAndReceiver.receiver != null) {
val referenceVariantsSet = referenceVariants!!.imported.toSet() val referenceVariantsSet = referenceVariants!!.imported.toSet()
@@ -281,16 +281,14 @@ abstract class CompletionSession(
if (expectedInfos.isEmpty()) return null if (expectedInfos.isEmpty()) return null
var context = expectedInfos var context = expectedInfos
.map { it.fuzzyType?.type?.constructor?.declarationDescriptor?.importableFqName } .mapNotNull { it.fuzzyType?.type?.constructor?.declarationDescriptor?.importableFqName }
.filterNotNull()
.distinct() .distinct()
.singleOrNull() .singleOrNull()
?.let { "expectedType=$it" } ?.let { "expectedType=$it" }
if (context == null) { if (context == null) {
context = expectedInfos context = expectedInfos
.map { it.expectedName } .mapNotNull { it.expectedName }
.filterNotNull()
.distinct() .distinct()
.singleOrNull() .singleOrNull()
?.let { "expectedName=$it" } ?.let { "expectedName=$it" }
@@ -211,8 +211,7 @@ class ExpectedInfos(
val callExpression = (call.callElement as? KtExpression)?.getQualifiedExpressionForSelectorOrThis() ?: return results val callExpression = (call.callElement as? KtExpression)?.getQualifiedExpressionForSelectorOrThis() ?: return results
val expectedFuzzyTypes = ExpectedInfos(bindingContext, resolutionFacade, useHeuristicSignatures, useOuterCallsExpectedTypeCount - 1) val expectedFuzzyTypes = ExpectedInfos(bindingContext, resolutionFacade, useHeuristicSignatures, useOuterCallsExpectedTypeCount - 1)
.calculate(callExpression) .calculate(callExpression)
.map { it.fuzzyType } .mapNotNull { it.fuzzyType }
.filterNotNull()
if (expectedFuzzyTypes.isEmpty() || expectedFuzzyTypes.any { it.freeParameters.isNotEmpty() }) return results if (expectedFuzzyTypes.isEmpty() || expectedFuzzyTypes.any { it.freeParameters.isNotEmpty() }) return results
return expectedFuzzyTypes return expectedFuzzyTypes
@@ -469,8 +468,7 @@ class ExpectedInfos(
if (functionLiteral != null) { if (functionLiteral != null) {
val literalExpression = functionLiteral.parent as KtFunctionLiteralExpression val literalExpression = functionLiteral.parent as KtFunctionLiteralExpression
return calculate(literalExpression) return calculate(literalExpression)
.map { it.fuzzyType } .mapNotNull { it.fuzzyType }
.filterNotNull()
.filter { KotlinBuiltIns.isExactFunctionOrExtensionFunctionType(it.type) } .filter { KotlinBuiltIns.isExactFunctionOrExtensionFunctionType(it.type) }
.map { .map {
val returnType = KotlinBuiltIns.getReturnTypeFromFunctionType(it.type) val returnType = KotlinBuiltIns.getReturnTypeFromFunctionType(it.type)
@@ -68,13 +68,12 @@ class StaticMembersCompletion(
fun membersFromImports(file: KtFile): Collection<DeclarationDescriptor> { fun membersFromImports(file: KtFile): Collection<DeclarationDescriptor> {
val containers = file.importDirectives val containers = file.importDirectives
.filter { !it.isAllUnder } .filter { !it.isAllUnder }
.map { .mapNotNull {
it.targetDescriptors(resolutionFacade) it.targetDescriptors(resolutionFacade)
.map { it.containingDeclaration } .map { it.containingDeclaration }
.distinct() .distinct()
.singleOrNull() as? ClassDescriptor .singleOrNull() as? ClassDescriptor
} }
.filterNotNull()
.toSet() .toSet()
val result = ArrayList<DeclarationDescriptor>() val result = ArrayList<DeclarationDescriptor>()
@@ -82,8 +82,7 @@ private fun needExplicitParameterTypes(context: InsertionContext, placeholderRan
val expectedInfos = ExpectedInfos(bindingContext, resolutionFacade, useHeuristicSignatures = false).calculate(expression) val expectedInfos = ExpectedInfos(bindingContext, resolutionFacade, useHeuristicSignatures = false).calculate(expression)
val functionTypes = expectedInfos val functionTypes = expectedInfos
.map { it.fuzzyType?.type } .mapNotNull { it.fuzzyType?.type }
.filterNotNull()
.filter { KotlinBuiltIns.isExactFunctionOrExtensionFunctionType(it) } .filter { KotlinBuiltIns.isExactFunctionOrExtensionFunctionType(it) }
.toSet() .toSet()
if (functionTypes.size() <= 1) return false if (functionTypes.size() <= 1) return false
@@ -39,8 +39,7 @@ object LambdaItems {
if (functionExpectedInfos.isEmpty()) return if (functionExpectedInfos.isEmpty()) return
val distinctTypes = functionExpectedInfos val distinctTypes = functionExpectedInfos
.map { it.fuzzyType?.type } .mapNotNull { it.fuzzyType?.type }
.filterNotNull()
.toSet() .toSet()
val singleType = if (distinctTypes.size() == 1) distinctTypes.single() else null val singleType = if (distinctTypes.size() == 1) distinctTypes.single() else null
@@ -32,8 +32,7 @@ object NameSimilarityWeigher : LookupElementWeigher("kotlin.nameSimilarity") {
fun calcNameSimilarity(name: String, expectedInfos: Collection<ExpectedInfo>): Int { fun calcNameSimilarity(name: String, expectedInfos: Collection<ExpectedInfo>): Int {
return expectedInfos return expectedInfos
.map { it.expectedName } .mapNotNull { it.expectedName }
.filterNotNull()
.map { calcNameSimilarity(name, it) } .map { calcNameSimilarity(name, it) }
.max() ?: 0 .max() ?: 0
} }
@@ -363,8 +363,7 @@ class SmartCompletion(
if (descriptor.modality != Modality.ABSTRACT && !descriptor.isInner) { if (descriptor.modality != Modality.ABSTRACT && !descriptor.isInner) {
descriptor.constructors descriptor.constructors
.filter(visibilityFilter) .filter(visibilityFilter)
.map { toLookupElement(it) } .mapNotNullTo(this) { toLookupElement(it) }
.filterNotNullTo(this)
} }
} }
} }
@@ -48,8 +48,7 @@ public class IterableTypesDetection(
private val typesWithExtensionIterator: Collection<KotlinType> = scope private val typesWithExtensionIterator: Collection<KotlinType> = scope
.collectFunctions(iteratorName, NoLookupLocation.FROM_IDE) .collectFunctions(iteratorName, NoLookupLocation.FROM_IDE)
.map { it.extensionReceiverParameter } .mapNotNull { it.extensionReceiverParameter }
.filterNotNull()
.map { it.type } .map { it.type }
override fun isIterable(type: FuzzyType, loopVarType: KotlinType?): Boolean { override fun isIterable(type: FuzzyType, loopVarType: KotlinType?): Boolean {
@@ -189,8 +189,7 @@ public class KotlinIndicesHelper(
public fun getJvmClassesByName(name: String): Collection<ClassDescriptor> { public fun getJvmClassesByName(name: String): Collection<ClassDescriptor> {
return PsiShortNamesCache.getInstance(project).getClassesByName(name, scope) return PsiShortNamesCache.getInstance(project).getClassesByName(name, scope)
.map { it.resolveToDescriptor(resolutionFacade) } .mapNotNull { it.resolveToDescriptor(resolutionFacade) }
.filterNotNull()
.filter(descriptorFilter) .filter(descriptorFilter)
.toSet() .toSet()
} }
@@ -90,8 +90,7 @@ public object KotlinNameSuggester {
val result = LinkedHashSet<String>() val result = LinkedHashSet<String>()
suggestNamesByExpressionOnly(collection, bindingContext, { true }) suggestNamesByExpressionOnly(collection, bindingContext, { true })
.map { StringUtil.unpluralize(it) } .mapNotNull { StringUtil.unpluralize(it) }
.filterNotNull()
.mapTo(result) { suggestNameByName(it, validator) } .mapTo(result) { suggestNameByName(it, validator) }
result.addNamesByType(elementType, validator) result.addNamesByType(elementType, validator)
@@ -47,8 +47,7 @@ public object OptionalParametersHelper {
val descriptor = resolvedCall.getResultingDescriptor() val descriptor = resolvedCall.getResultingDescriptor()
val parameterToDefaultValue = descriptor.getValueParameters() val parameterToDefaultValue = descriptor.getValueParameters()
.map { parameter -> defaultParameterValue(parameter, project)?.let { parameter to it } } .mapNotNull { parameter -> defaultParameterValue(parameter, project)?.let { parameter to it } }
.filterNotNull()
.toMap() .toMap()
if (parameterToDefaultValue.isEmpty()) return emptyList() if (parameterToDefaultValue.isEmpty()) return emptyList()
@@ -76,8 +76,7 @@ public class KotlinJavaScriptLibraryManager private constructor(private var myPr
val changedFiles = events val changedFiles = events
.filter { it !is MyVFileContentChangeEvent && it is VFileContentChangeEvent } .filter { it !is MyVFileContentChangeEvent && it is VFileContentChangeEvent }
.map { it.file } .mapNotNull { it.file }
.filterNotNull()
val files = update(changedFiles, addToMapIfAbsent = false) val files = update(changedFiles, addToMapIfAbsent = false)
val application = ApplicationManager.getApplication() val application = ApplicationManager.getApplication()
@@ -147,8 +147,7 @@ public class JavaToKotlinAction : AnAction() {
val manager = PsiManager.getInstance(project) val manager = PsiManager.getInstance(project)
return allFiles(filesOrDirs) return allFiles(filesOrDirs)
.asSequence() .asSequence()
.map { manager.findFile(it) as? PsiJavaFile } .mapNotNull { manager.findFile(it) as? PsiJavaFile }
.filterNotNull()
} }
private fun allFiles(filesOrDirs: Array<VirtualFile>): Collection<VirtualFile> { private fun allFiles(filesOrDirs: Array<VirtualFile>): Collection<VirtualFile> {
@@ -125,7 +125,7 @@ class KotlinGenerateSecondaryConstructorAction : KotlinGenerateMemberActionBase<
return with(info) { return with(info) {
val prototypes = if (superConstructors.isNotEmpty()) { val prototypes = if (superConstructors.isNotEmpty()) {
superConstructors.map { generateConstructor(classDescriptor, propertiesToInitialize, it) }.filterNotNull() superConstructors.mapNotNull { generateConstructor(classDescriptor, propertiesToInitialize, it) }
} else { } else {
generateConstructor(classDescriptor, propertiesToInitialize, null).singletonOrEmptyList() generateConstructor(classDescriptor, propertiesToInitialize, null).singletonOrEmptyList()
} }
@@ -170,8 +170,7 @@ public class CheckPartialBodyResolveAction : AnAction() {
val manager = PsiManager.getInstance(project) val manager = PsiManager.getInstance(project)
return allFiles(filesOrDirs) return allFiles(filesOrDirs)
.asSequence() .asSequence()
.map { manager.findFile(it) as? KtFile } .mapNotNull { manager.findFile(it) as? KtFile }
.filterNotNull()
} }
private fun allFiles(filesOrDirs: Array<VirtualFile>): Collection<VirtualFile> { private fun allFiles(filesOrDirs: Array<VirtualFile>): Collection<VirtualFile> {
@@ -156,8 +156,7 @@ public class FindImplicitNothingAction : AnAction() {
val manager = PsiManager.getInstance(project) val manager = PsiManager.getInstance(project)
return allFiles(filesOrDirs) return allFiles(filesOrDirs)
.asSequence() .asSequence()
.map { manager.findFile(it) as? KtFile } .mapNotNull { manager.findFile(it) as? KtFile }
.filterNotNull()
} }
private fun allFiles(filesOrDirs: Array<VirtualFile>): Collection<VirtualFile> { private fun allFiles(filesOrDirs: Array<VirtualFile>): Collection<VirtualFile> {
@@ -202,13 +202,13 @@ public class KotlinCopyPasteReferenceProcessor() : CopyPastePostProcessor<Kotlin
if (file !is KtFile) return listOf() if (file !is KtFile) return listOf()
val fileResolutionScope = file.getResolutionFacade().getFileResolutionScope(file) val fileResolutionScope = file.getResolutionFacade().getFileResolutionScope(file)
return referenceData.map { return referenceData.mapNotNull {
val reference = findReference(it, file, blockStart) val reference = findReference(it, file, blockStart)
if (reference != null) if (reference != null)
createReferenceToRestoreData(reference, it, file, fileResolutionScope) createReferenceToRestoreData(reference, it, file, fileResolutionScope)
else else
null null
}.filterNotNull() }
} }
private fun findReference(data: KotlinReferenceData, file: KtFile, blockStart: Int): KtReference? { private fun findReference(data: KotlinReferenceData, file: KtFile, blockStart: Int): KtReference? {
@@ -250,8 +250,7 @@ public class KotlinCopyPasteReferenceProcessor() : CopyPastePostProcessor<Kotlin
} }
val referencedFqNames = referencedDescriptors val referencedFqNames = referencedDescriptors
.filterNot { ErrorUtils.isError(it) } .filterNot { ErrorUtils.isError(it) }
.map { it.importableFqName } .mapNotNull { it.importableFqName }
.filterNotNull()
.toSet() .toSet()
if (referencedFqNames.singleOrNull() == originalFqName) return null if (referencedFqNames.singleOrNull() == originalFqName) return null
@@ -23,7 +23,7 @@ class RuntimeLibraryFiles(
val reflectJar: File?, val reflectJar: File?,
val runtimeSourcesJar: File val runtimeSourcesJar: File
) { ) {
fun getAllJars(): List<File> = listOf(runtimeJar, reflectJar, runtimeSourcesJar).filterNotNull() fun getAllJars(): List<File> = listOfNotNull(runtimeJar, reflectJar, runtimeSourcesJar)
fun getRuntimeDestination(dirToCopyJar: String): File = fun getRuntimeDestination(dirToCopyJar: String): File =
File(dirToCopyJar + "/" + runtimeJar.name) File(dirToCopyJar + "/" + runtimeJar.name)
@@ -252,10 +252,10 @@ public class KotlinPositionManager(private val myDebugProcess: DebugProcess) : M
val lambdas = getLambdasAtLineIfAny(sourcePosition) val lambdas = getLambdasAtLineIfAny(sourcePosition)
val file = sourcePosition.file.containingFile as KtFile val file = sourcePosition.file.containingFile as KtFile
val isInLibrary = LibraryUtil.findLibraryEntry(file.virtualFile, file.project) != null val isInLibrary = LibraryUtil.findLibraryEntry(file.virtualFile, file.project) != null
lambdas.map { lambdas.mapNotNull {
val typeMapper = if (!isInLibrary) prepareTypeMapper(file) else createTypeMapperForLibraryFile(it, file) val typeMapper = if (!isInLibrary) prepareTypeMapper(file) else createTypeMapperForLibraryFile(it, file)
getInternalClassNameForElement(it, typeMapper, file, isInLibrary).className getInternalClassNameForElement(it, typeMapper, file, isInLibrary).className
}.filterNotNull() }
} }
} }
@@ -327,9 +327,9 @@ public class KotlinPositionManager(private val myDebugProcess: DebugProcess) : M
throw NoDataException.INSTANCE throw NoDataException.INSTANCE
} }
return classNameForPositionAndInlinedOnes(position).map { return classNameForPositionAndInlinedOnes(position).mapNotNull {
className -> myDebugProcess.requestsManager.createClassPrepareRequest(requestor, className.replace('/', '.')) className -> myDebugProcess.requestsManager.createClassPrepareRequest(requestor, className.replace('/', '.'))
}.filterNotNull() }
} }
@TestOnly @TestOnly
@@ -91,7 +91,7 @@ public class KotlinFieldBreakpointType : JavaBreakpointType<KotlinPropertyBreakp
result = when (psiClass) { result = when (psiClass) {
is KtLightClassForFacade -> { is KtLightClassForFacade -> {
psiClass.files.asSequence().map { createBreakpointIfPropertyExists(it, it, className, fieldName) }.filterNotNull().firstOrNull() psiClass.files.asSequence().mapNotNull { createBreakpointIfPropertyExists(it, it, className, fieldName) }.firstOrNull()
} }
is KtLightClassForExplicitDeclaration -> { is KtLightClassForExplicitDeclaration -> {
val jetClass = psiClass.getOrigin() val jetClass = psiClass.getOrigin()
@@ -89,8 +89,7 @@ public class KotlinFindUsagesHandlerFactory(project: Project) : FindUsagesHandle
assert(parameterIndex < parametersCount) assert(parameterIndex < parametersCount)
val overridingParameters = OverridingMethodsSearch.search(psiMethod, true) val overridingParameters = OverridingMethodsSearch.search(psiMethod, true)
.filter { it.parameterList.parametersCount == parametersCount } .filter { it.parameterList.parametersCount == parametersCount }
.map { it.parameterList.parameters[parameterIndex].unwrapped } .mapNotNull { it.parameterList.parameters[parameterIndex].unwrapped }
.filterNotNull()
return handlerForMultiple(element, listOf(element) + overridingParameters) return handlerForMultiple(element, listOf(element) + overridingParameters)
} }
} }
@@ -169,7 +169,7 @@ public class ConflictingExtensionPropertyInspection : AbstractKotlinInspection()
object : IntentionWrapper(MarkHiddenAndDeprecatedAction(property), property.containingFile), LowPriorityAction {} object : IntentionWrapper(MarkHiddenAndDeprecatedAction(property), property.containingFile), LowPriorityAction {}
else else
null null
listOf(fix1, fix2).filterNotNull().toTypedArray() listOfNotNull(fix1, fix2).toTypedArray()
} }
else { else {
emptyArray() emptyArray()
@@ -196,8 +196,7 @@ public class ConflictingExtensionPropertyInspection : AbstractKotlinInspection()
val searchScope = KotlinSourceFilterScope.sources(GlobalSearchScope.projectScope(project), project) val searchScope = KotlinSourceFilterScope.sources(GlobalSearchScope.projectScope(project), project)
ReferencesSearch.search(declaration, searchScope) ReferencesSearch.search(declaration, searchScope)
.filterIsInstance<KtSimpleNameReference>() .filterIsInstance<KtSimpleNameReference>()
.map { ref -> ref.expression.getStrictParentOfType<KtImportDirective>() } .mapNotNull { ref -> ref.expression.getStrictParentOfType<KtImportDirective>() }
.filterNotNull()
.filter { import -> !import.isAllUnder && import.targetDescriptors().size() == 1 } .filter { import -> !import.isAllUnder && import.targetDescriptors().size() == 1 }
} }
UIUtil.invokeLaterIfNeeded { UIUtil.invokeLaterIfNeeded {
@@ -63,8 +63,7 @@ class KotlinUnusedImportInspection : AbstractKotlinInspection() {
val directives = file.importDirectives val directives = file.importDirectives
val explicitlyImportedFqNames = directives val explicitlyImportedFqNames = directives
.asSequence() .asSequence()
.map { it.importPath } .mapNotNull { it.importPath }
.filterNotNull()
.filter { !it.isAllUnder && !it.hasAlias() } .filter { !it.isAllUnder && !it.hasAlias() }
.map { it.fqnPart() } .map { it.fqnPart() }
.toSet() .toSet()
@@ -106,8 +106,7 @@ public class UnusedSymbolInspection : AbstractKotlinInspection() {
val annotationsPresent = annotated.getAnnotations() val annotationsPresent = annotated.getAnnotations()
.map { it.getType() } .map { it.getType() }
.filter { !it.isError() } .filter { !it.isError() }
.map { it.getConstructor().getDeclarationDescriptor()?.let { DescriptorUtils.getFqName(it).asString() } } .mapNotNull { it.getConstructor().getDeclarationDescriptor()?.let { DescriptorUtils.getFqName(it).asString() } }
.filterNotNull()
if (annotationsPresent.isEmpty()) return false if (annotationsPresent.isEmpty()) return false
@@ -31,7 +31,7 @@ public class SwapBinaryExpressionIntention : SelfTargetingIntention<KtBinaryExpr
companion object { companion object {
private val SUPPORTED_OPERATIONS = setOf(PLUS, MUL, OROR, ANDAND, EQEQ, EXCLEQ, EQEQEQ, EXCLEQEQEQ, GT, LT, GTEQ, LTEQ) private val SUPPORTED_OPERATIONS = setOf(PLUS, MUL, OROR, ANDAND, EQEQ, EXCLEQ, EQEQEQ, EXCLEQEQEQ, GT, LT, GTEQ, LTEQ)
private val SUPPORTED_OPERATION_NAMES = SUPPORTED_OPERATIONS.map { OperatorConventions.BINARY_OPERATION_NAMES[it]?.asString() }.toSet().filterNotNull() + private val SUPPORTED_OPERATION_NAMES = SUPPORTED_OPERATIONS.mapNotNull { OperatorConventions.BINARY_OPERATION_NAMES[it]?.asString() }.toSet() +
setOf("xor", "or", "and", "equals", "identityEquals") setOf("xor", "or", "and", "equals", "identityEquals")
} }
@@ -65,8 +65,8 @@ public class MergeWhenIntention : SelfTargetingRangeIntention<KtWhenExpression>(
private fun KtWhenEntry.declarationNames(): Set<String> = private fun KtWhenEntry.declarationNames(): Set<String> =
getExpression()?.blockExpressionsOrSingle() getExpression()?.blockExpressionsOrSingle()
?.filter { it is KtNamedDeclaration } ?.filter { it is KtNamedDeclaration }
?.map { it.getName() } ?.mapNotNull { it.getName() }
?.filterNotNull()?.toSet() ?: emptySet() ?.toSet() ?: emptySet()
override fun applyTo(element: KtWhenExpression, editor: Editor) { override fun applyTo(element: KtWhenExpression, editor: Editor) {
val nextWhen = PsiTreeUtil.skipSiblingsForward(element, javaClass<PsiWhiteSpace>()) as KtWhenExpression val nextWhen = PsiTreeUtil.skipSiblingsForward(element, javaClass<PsiWhiteSpace>()) as KtWhenExpression
@@ -41,8 +41,7 @@ public class JoinDeclarationAndAssignmentHandler : JoinRawLinesHandlerDelegate {
?.firstOrNull { !isToSkip(it) } ?: return -1 ?.firstOrNull { !isToSkip(it) } ?: return -1
val pair = element.parentsWithSelf val pair = element.parentsWithSelf
.map { getPropertyAndAssignment(it) } .mapNotNull { getPropertyAndAssignment(it) }
.filterNotNull()
.firstOrNull() ?: return -1 .firstOrNull() ?: return -1
val (property, assignment) = pair val (property, assignment) = pair
@@ -75,8 +75,7 @@ class AnonymousSuperMacro : Macro() {
return resolutionScope return resolutionScope
.collectDescriptorsFiltered(DescriptorKindFilter.NON_SINGLETON_CLASSIFIERS) .collectDescriptorsFiltered(DescriptorKindFilter.NON_SINGLETON_CLASSIFIERS)
.filter { it is ClassDescriptor && it.modality.isOverridable && (it.kind == ClassKind.CLASS || it.kind == ClassKind.INTERFACE) } .filter { it is ClassDescriptor && it.modality.isOverridable && (it.kind == ClassKind.CLASS || it.kind == ClassKind.INTERFACE) }
.map { DescriptorToSourceUtils.descriptorToDeclaration(it) as PsiNamedElement? } .mapNotNull { DescriptorToSourceUtils.descriptorToDeclaration(it) as PsiNamedElement? }
.filterNotNull()
.toTypedArray() .toTypedArray()
} }
} }
@@ -119,7 +119,7 @@ class AddFunctionToSupertypeFix private constructor(
if (descriptors.isEmpty()) return null if (descriptors.isEmpty()) return null
val project = diagnostic.psiFile.project val project = diagnostic.psiFile.project
val functionData = descriptors.map { createFunctionData(it, project) }.filterNotNull() val functionData = descriptors.mapNotNull { createFunctionData(it, project) }
if (functionData.isEmpty()) return null if (functionData.isEmpty()) return null
return AddFunctionToSupertypeFix(function, functionData) return AddFunctionToSupertypeFix(function, functionData)
@@ -169,9 +169,7 @@ class AddFunctionToSupertypeFix private constructor(
} }
}) })
return supertypes return supertypes.mapNotNull { it.constructor.declarationDescriptor as? ClassDescriptor }
.map { it.constructor.declarationDescriptor as? ClassDescriptor }
.filterNotNull()
} }
private fun generateFunctionSignatureForType(functionDescriptor: FunctionDescriptor, typeDescriptor: ClassDescriptor): FunctionDescriptor { private fun generateFunctionSignatureForType(functionDescriptor: FunctionDescriptor, typeDescriptor: ClassDescriptor): FunctionDescriptor {
@@ -83,7 +83,7 @@ public class AddGenericUpperBoundFix(
val resultingSubstitutor = successfulConstraintSystem.resultingSubstitutor val resultingSubstitutor = successfulConstraintSystem.resultingSubstitutor
return inferenceData.descriptor.typeParameters.map factory@{ return inferenceData.descriptor.typeParameters.mapNotNull factory@{
typeParameterDescriptor -> typeParameterDescriptor ->
if (ConstraintsUtil.checkUpperBoundIsSatisfied( if (ConstraintsUtil.checkUpperBoundIsSatisfied(
@@ -96,7 +96,7 @@ public class AddGenericUpperBoundFix(
?: return@factory null ?: return@factory null
createAction(argument, upperBound) createAction(argument, upperBound)
}.filterNotNull() }
} }
private fun createAction(argument: KotlinType, upperBound: KotlinType): IntentionAction? { private fun createAction(argument: KotlinType, upperBound: KotlinType): IntentionAction? {
@@ -665,9 +665,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
} }
val expandedValueParameters = declaration.getValueParameters() val expandedValueParameters = declaration.getValueParameters()
parameterIndicesToShorten.asSequence() parameterIndicesToShorten.mapNotNullTo(typeRefsToShorten) { expandedValueParameters[it].getTypeReference() }
.map { expandedValueParameters[it].getTypeReference() }
.filterNotNullTo(typeRefsToShorten)
return typeRefsToShorten return typeRefsToShorten
} }
@@ -84,9 +84,9 @@ internal class ParameterNameExpression(
} }
// remember other parameter names for later use // remember other parameter names for later use
val parameterNames = parameterList.getParameters().asSequence().map { jetParameter -> val parameterNames = parameterList.getParameters().mapNotNullTo(HashSet<String>()) { jetParameter ->
if (jetParameter == parameter) null else jetParameter.getName() if (jetParameter == parameter) null else jetParameter.getName()
}.filterNotNullTo(HashSet<String>()) }
// add fallback parameter name // add fallback parameter name
if (names.isEmpty()) { if (names.isEmpty()) {
@@ -207,14 +207,14 @@ fun KtExpression.guessTypes(
} }
private fun KtNamedDeclaration.guessType(context: BindingContext): Array<KotlinType> { private fun KtNamedDeclaration.guessType(context: BindingContext): Array<KotlinType> {
val expectedTypes = SearchUtils.findAllReferences(this, getUseScope())!!.asSequence().map { ref -> val expectedTypes = SearchUtils.findAllReferences(this, getUseScope())!!.mapNotNullTo(HashSet<KotlinType>()) { ref ->
if (ref is KtSimpleNameReference) { if (ref is KtSimpleNameReference) {
context[BindingContext.EXPECTED_EXPRESSION_TYPE, ref.expression] context[BindingContext.EXPECTED_EXPRESSION_TYPE, ref.expression]
} }
else { else {
null null
} }
}.filterNotNullTo(HashSet<KotlinType>()) }
if (expectedTypes.isEmpty() || expectedTypes.any { expectedType -> ErrorUtils.containsErrorType(expectedType) }) { if (expectedTypes.isEmpty() || expectedTypes.any { expectedType -> ErrorUtils.containsErrorType(expectedType) }) {
return arrayOf() return arrayOf()
@@ -257,7 +257,7 @@ internal fun KotlinType.substitute(substitution: KotlinTypeSubstitution, varianc
fun KtExpression.getExpressionForTypeGuess() = getAssignmentByLHS()?.getRight() ?: this fun KtExpression.getExpressionForTypeGuess() = getAssignmentByLHS()?.getRight() ?: this
fun KtCallElement.getTypeInfoForTypeArguments(): List<TypeInfo> { fun KtCallElement.getTypeInfoForTypeArguments(): List<TypeInfo> {
return getTypeArguments().map { it.getTypeReference()?.let { TypeInfo(it, Variance.INVARIANT) } }.filterNotNull() return getTypeArguments().mapNotNull { it.getTypeReference()?.let { TypeInfo(it, Variance.INVARIANT) } }
} }
fun KtCallExpression.getParameterInfos(): List<ParameterInfo> { fun KtCallExpression.getParameterInfos(): List<ParameterInfo> {
@@ -151,8 +151,7 @@ public abstract class CreateCallableFromUsageFixBase<E : KtElement>(
val receiverTypeCandidates = callableBuilder.computeTypeCandidates(callableInfo.receiverTypeInfo) val receiverTypeCandidates = callableBuilder.computeTypeCandidates(callableInfo.receiverTypeInfo)
if (receiverTypeCandidates.isNotEmpty()) { if (receiverTypeCandidates.isNotEmpty()) {
val containers = receiverTypeCandidates val containers = receiverTypeCandidates
.map { candidate -> getDeclarationIfApplicable(project, candidate)?.let { candidate to it } } .mapNotNull { candidate -> getDeclarationIfApplicable(project, candidate)?.let { candidate to it } }
.filterNotNull()
chooseContainerElementIfNecessary(containers, editor, popupTitle, false, { it.second }) { chooseContainerElementIfNecessary(containers, editor, popupTitle, false, { it.second }) {
runBuilder(CallablePlacement.WithReceiver(it.first)) runBuilder(CallablePlacement.WithReceiver(it.first))
@@ -78,9 +78,7 @@ public object CreateClassFromCallWithConstructorCalleeActionFactory : CreateClas
val typeArgumentInfos = when { val typeArgumentInfos = when {
isAnnotation -> Collections.emptyList<TypeInfo>() isAnnotation -> Collections.emptyList<TypeInfo>()
else -> element.typeArguments else -> element.typeArguments.mapNotNull { it.typeReference?.let { TypeInfo(it, Variance.INVARIANT) } }
.map { it.typeReference?.let { TypeInfo(it, Variance.INVARIANT) } }
.filterNotNull()
} }
return ClassInfo( return ClassInfo(
@@ -175,7 +175,7 @@ public abstract class CallableRefactoring<T: CallableDescriptor>(
} }
fun getAffectedCallables(project: Project, descriptorsForChange: Collection<CallableDescriptor>): List<PsiElement> { fun getAffectedCallables(project: Project, descriptorsForChange: Collection<CallableDescriptor>): List<PsiElement> {
val baseCallables = descriptorsForChange.map { DescriptorToSourceUtilsIde.getAnyDeclaration(project, it) }.filterNotNull() val baseCallables = descriptorsForChange.mapNotNull { DescriptorToSourceUtilsIde.getAnyDeclaration(project, it) }
return baseCallables + baseCallables.flatMap { it.toLightMethods() }.flatMapTo(HashSet<PsiElement>()) { psiMethod -> return baseCallables + baseCallables.flatMap { it.toLightMethods() }.flatMapTo(HashSet<PsiElement>()) { psiMethod ->
val overrides = OverridingMethodsSearch.search(psiMethod).findAll() val overrides = OverridingMethodsSearch.search(psiMethod).findAll()
overrides.map { method -> method.namedUnwrappedElement ?: method} overrides.map { method -> method.namedUnwrappedElement ?: method}
@@ -373,8 +373,7 @@ public open class KotlinChangeInfo(
else else
PsiModifier.PACKAGE_LOCAL PsiModifier.PACKAGE_LOCAL
val propagationTargets = primaryPropagationTargets.asSequence() val propagationTargets = primaryPropagationTargets.asSequence()
.map { it.getRepresentativeLightMethod() } .mapNotNull { it.getRepresentativeLightMethod() }
.filterNotNull()
.toSet() .toSet()
val javaChangeInfo = ChangeSignatureProcessor( val javaChangeInfo = ChangeSignatureProcessor(
getMethod().getProject(), getMethod().getProject(),
@@ -413,7 +412,7 @@ public open class KotlinChangeInfo(
val oldParameterCount = originalPsiMethod.parameterList.parametersCount val oldParameterCount = originalPsiMethod.parameterList.parametersCount
var indexInCurrentPsiMethod = 0 var indexInCurrentPsiMethod = 0
return newParameterList.withIndex() return newParameterList.withIndex()
.map { pair -> .mapNotNullTo(ArrayList()) map@ { pair ->
val (i, info) = pair val (i, info) = pair
if (info.defaultValueForParameter != null && defaultValuesRemained-- <= 0) return@map null if (info.defaultValueForParameter != null && defaultValuesRemained-- <= 0) return@map null
@@ -435,7 +434,6 @@ public open class KotlinChangeInfo(
val defaultValue = info.defaultValueForCall ?: info.defaultValueForParameter val defaultValue = info.defaultValueForCall ?: info.defaultValueForParameter
ParameterInfoImpl(javaOldIndex, info.getName(), type, defaultValue?.getText() ?: "") ParameterInfoImpl(javaOldIndex, info.getName(), type, defaultValue?.getText() ?: "")
} }
.filterNotNullTo(ArrayList())
} }
fun createJavaChangeInfoForFunctionOrGetter( fun createJavaChangeInfoForFunctionOrGetter(
@@ -470,7 +468,7 @@ public open class KotlinChangeInfo(
if (javaChangeInfos == null) { if (javaChangeInfos == null) {
val method = getMethod() val method = getMethod()
originalToCurrentMethods = matchOriginalAndCurrentMethods(method.toLightMethods()) originalToCurrentMethods = matchOriginalAndCurrentMethods(method.toLightMethods())
javaChangeInfos = originalToCurrentMethods.entries.map { javaChangeInfos = originalToCurrentMethods.entries.mapNotNull {
val (originalPsiMethod, currentPsiMethod) = it val (originalPsiMethod, currentPsiMethod) = it
when (method) { when (method) {
@@ -488,7 +486,7 @@ public open class KotlinChangeInfo(
} }
else -> null else -> null
} }
}.filterNotNull() }
} }
return javaChangeInfos return javaChangeInfos
@@ -178,7 +178,7 @@ public class KotlinChangeSignature(project: Project,
override fun performRefactoring(descriptorsForChange: Collection<CallableDescriptor>) { override fun performRefactoring(descriptorsForChange: Collection<CallableDescriptor>) {
val adjustedDescriptor = adjustDescriptor(descriptorsForChange) ?: return val adjustedDescriptor = adjustDescriptor(descriptorsForChange) ?: return
val affectedFunctions = adjustedDescriptor.affectedCallables.map { it.getElement() }.filterNotNull() val affectedFunctions = adjustedDescriptor.affectedCallables.mapNotNull { it.getElement() }
if (affectedFunctions.any { !checkModifiable(it) }) return if (affectedFunctions.any { !checkModifiable(it) }) return
if (configuration.performSilently(affectedFunctions) || ApplicationManager.getApplication()!!.isUnitTestMode()) { if (configuration.performSilently(affectedFunctions) || ApplicationManager.getApplication()!!.isUnitTestMode()) {
@@ -111,14 +111,14 @@ public class KotlinChangeSignatureData(
lightMethods.flatMap { baseMethod -> lightMethods.flatMap { baseMethod ->
OverridingMethodsSearch OverridingMethodsSearch
.search(baseMethod) .search(baseMethod)
.map { overridingMethod -> .mapNotNullTo(HashSet<UsageInfo>()) { overridingMethod ->
if (overridingMethod is KtLightMethod) { if (overridingMethod is KtLightMethod) {
val overridingDeclaration = overridingMethod.namedUnwrappedElement as KtNamedDeclaration val overridingDeclaration = overridingMethod.namedUnwrappedElement as KtNamedDeclaration
val overridingDescriptor = overridingDeclaration.resolveToDescriptor() as CallableDescriptor val overridingDescriptor = overridingDeclaration.resolveToDescriptor() as CallableDescriptor
KotlinCallableDefinitionUsage<PsiElement>(overridingDeclaration, overridingDescriptor, primaryFunction, null) KotlinCallableDefinitionUsage<PsiElement>(overridingDeclaration, overridingDescriptor, primaryFunction, null)
} }
else OverriderUsageInfo(overridingMethod, baseMethod, true, true, true) else OverriderUsageInfo(overridingMethod, baseMethod, true, true, true)
}.filterNotNullTo(HashSet<UsageInfo>()) }
} }
} }
} }
@@ -154,11 +154,11 @@ private fun List<Instruction>.getResultTypeAndExpressions(
} }
} }
val resultTypes = map(::instructionToType).filterNotNull() val resultTypes = mapNotNull(::instructionToType)
var commonSupertype = if (resultTypes.isNotEmpty()) CommonSupertypes.commonSupertype(resultTypes) else module.builtIns.defaultReturnType val commonSupertype = if (resultTypes.isNotEmpty()) CommonSupertypes.commonSupertype(resultTypes) else module.builtIns.defaultReturnType
val resultType = if (options.allowSpecialClassNames) commonSupertype else commonSupertype.approximateWithResolvableType(targetScope, false) val resultType = if (options.allowSpecialClassNames) commonSupertype else commonSupertype.approximateWithResolvableType(targetScope, false)
val expressions = map { instructionToExpression(it, false) }.filterNotNull() val expressions = mapNotNull { instructionToExpression(it, false) }
return resultType to expressions return resultType to expressions
} }
@@ -420,13 +420,9 @@ fun KtTypeParameter.collectRelevantConstraints(): List<KtTypeConstraint> {
fun TypeParameter.collectReferencedTypes(bindingContext: BindingContext): List<KotlinType> { fun TypeParameter.collectReferencedTypes(bindingContext: BindingContext): List<KotlinType> {
val typeRefs = ArrayList<KtTypeReference>() val typeRefs = ArrayList<KtTypeReference>()
originalDeclaration.extendsBound?.let { typeRefs.add(it) } originalDeclaration.extendsBound?.let { typeRefs.add(it) }
originalConstraints originalConstraints.mapNotNullTo(typeRefs) { it.boundTypeReference }
.map { it.boundTypeReference }
.filterNotNullTo(typeRefs)
return typeRefs return typeRefs.mapNotNull { bindingContext[BindingContext.TYPE, it] }
.map { bindingContext[BindingContext.TYPE, it] }
.filterNotNull()
} }
private fun KotlinType.isExtractable(targetScope: LexicalScope?): Boolean { private fun KotlinType.isExtractable(targetScope: LexicalScope?): Boolean {
@@ -812,9 +808,9 @@ fun ExtractableCodeDescriptor.validate(): ExtractableCodeDescriptorWithConflicts
for ((originalOffset, resolveResult) in extractionData.refOffsetToDeclaration) { for ((originalOffset, resolveResult) in extractionData.refOffsetToDeclaration) {
if (resolveResult.declaration.isInsideOf(extractionData.originalElements)) continue if (resolveResult.declaration.isInsideOf(extractionData.originalElements)) continue
val currentRefExprs = result.nameByOffset[originalOffset].map { val currentRefExprs = result.nameByOffset[originalOffset].mapNotNull {
(it as? KtThisExpression)?.instanceReference ?: it as? KtSimpleNameExpression (it as? KtThisExpression)?.instanceReference ?: it as? KtSimpleNameExpression
}.filterNotNull() }
currentRefExprs.forEach { processReference(resolveResult, it) } currentRefExprs.forEach { processReference(resolveResult, it) }
} }
@@ -212,11 +212,10 @@ fun ExtractableCodeDescriptor.findDuplicates(): List<DuplicateInfo> {
.match(scopeElement, unifier) .match(scopeElement, unifier)
.asSequence() .asSequence()
.filter { !(it.range.getTextRange() intersects originalTextRange) } .filter { !(it.range.getTextRange() intersects originalTextRange) }
.map { match -> .mapNotNull { match ->
val controlFlow = getControlFlowIfMatched(match) val controlFlow = getControlFlowIfMatched(match)
controlFlow?.let { DuplicateInfo(match.range, it, unifierParameters.map { match.result.substitution[it]!!.text!! }) } controlFlow?.let { DuplicateInfo(match.range, it, unifierParameters.map { match.result.substitution[it]!!.text!! }) }
} }
.filterNotNull()
.toList() .toList()
} }
@@ -421,7 +420,7 @@ fun ExtractionGeneratorConfiguration.generateDeclaration(
fun getReturnArguments(resultExpression: KtExpression?): List<String> { fun getReturnArguments(resultExpression: KtExpression?): List<String> {
return descriptor.controlFlow.outputValues return descriptor.controlFlow.outputValues
.map { .mapNotNull {
when (it) { when (it) {
is ExpressionValue -> resultExpression?.text is ExpressionValue -> resultExpression?.text
is Jump -> if (it.conditional) "false" else null is Jump -> if (it.conditional) "false" else null
@@ -430,7 +429,6 @@ fun ExtractionGeneratorConfiguration.generateDeclaration(
else -> throw IllegalArgumentException("Unknown output value: $it") else -> throw IllegalArgumentException("Unknown output value: $it")
} }
} }
.filterNotNull()
} }
fun replaceWithReturn( fun replaceWithReturn(
@@ -525,7 +523,7 @@ fun ExtractionGeneratorConfiguration.generateDeclaration(
for ((expr, originalOffset) in originalOffsetByExpr) { for ((expr, originalOffset) in originalOffsetByExpr) {
if (expr.isValid) { if (expr.isValid) {
val replacements = exprReplacementMap[expr].map { it?.invoke(descriptor, expr) }.filterNotNull() val replacements = exprReplacementMap[expr].mapNotNull { it?.invoke(descriptor, expr) }
nameByOffset.put(originalOffset, if (replacements.isEmpty()) arrayListOf(expr) else replacements) nameByOffset.put(originalOffset, if (replacements.isEmpty()) arrayListOf(expr) else replacements)
} }
} }
@@ -55,8 +55,7 @@ public class KotlinInplaceParameterIntroducer(
null, null,
originalDescriptor.originalRange.elements.single() as KtExpression, originalDescriptor.originalRange.elements.single() as KtExpression,
originalDescriptor.occurrencesToReplace originalDescriptor.occurrencesToReplace
.map { it.elements.single() as KtExpression } .mapNotNull { it.elements.single() as KtExpression }
.filterNotNull()
.toTypedArray(), .toTypedArray(),
INTRODUCE_PARAMETER, INTRODUCE_PARAMETER,
project, project,
@@ -249,7 +249,7 @@ public open class KotlinIntroduceParameterHandler(
val textRange = it.range.getTextRange() val textRange = it.range.getTextRange()
forbiddenRanges.any { it.intersects(textRange) } forbiddenRanges.any { it.intersects(textRange) }
} }
.map { .mapNotNull {
val matchedElement = it.range.elements.singleOrNull() val matchedElement = it.range.elements.singleOrNull()
when (matchedElement) { when (matchedElement) {
is KtExpression -> matchedElement is KtExpression -> matchedElement
@@ -257,7 +257,6 @@ public open class KotlinIntroduceParameterHandler(
else -> null else -> null
} as? KtExpression } as? KtExpression
} }
.filterNotNull()
.map { it.toRange() } .map { it.toRange() }
project.executeCommand( project.executeCommand(
@@ -120,13 +120,12 @@ public class MoveKotlinTopLevelDeclarationsProcessor(
val projectScope = lightElement.getProject().projectScope() val projectScope = lightElement.getProject().projectScope()
val results = ReferencesSearch val results = ReferencesSearch
.search(lightElement, projectScope, false) .search(lightElement, projectScope, false)
.mapTo(ArrayList<UsageInfo?>()) { ref -> .mapNotNullTo(ArrayList()) { ref ->
if (foundReferences.add(ref) && elementsToMove.all { !it.isAncestor(ref.getElement())}) { if (foundReferences.add(ref) && elementsToMove.all { !it.isAncestor(ref.getElement())}) {
createMoveUsageInfoIfPossible(ref, lightElement, true) createMoveUsageInfoIfPossible(ref, lightElement, true)
} }
else null else null
} }
.filterNotNull()
val name = lightElement.getKotlinFqName()?.asString() val name = lightElement.getKotlinFqName()?.asString()
if (name != null) { if (name != null) {
@@ -74,7 +74,7 @@ public class PackageNameInfo(val oldPackageName: FqName, val newPackageName: FqN
public fun KtElement.getInternalReferencesToUpdateOnPackageNameChange(packageNameInfo: PackageNameInfo): List<UsageInfo> { public fun KtElement.getInternalReferencesToUpdateOnPackageNameChange(packageNameInfo: PackageNameInfo): List<UsageInfo> {
val file = getContainingFile() as? KtFile ?: return listOf() val file = getContainingFile() as? KtFile ?: return listOf()
val importPaths = file.getImportDirectives().map { it.getImportPath() }.filterNotNull() val importPaths = file.getImportDirectives().mapNotNull { it.getImportPath() }
tailrec fun isImported(descriptor: DeclarationDescriptor): Boolean { tailrec fun isImported(descriptor: DeclarationDescriptor): Boolean {
val fqName = DescriptorUtils.getFqName(descriptor).let { if (it.isSafe()) it.toSafe() else return@isImported false } val fqName = DescriptorUtils.getFqName(descriptor).let { if (it.isSafe()) it.toSafe() else return@isImported false }
@@ -78,8 +78,7 @@ public class JavaToKotlinPreconversionPullUpHelper(
setter?.let { dummyAccessorByName[setterName] = dummyTargetClass.add(it) as PsiMethod } setter?.let { dummyAccessorByName[setterName] = dummyTargetClass.add(it) as PsiMethod }
fieldsToUsages[member] = ReferencesSearch fieldsToUsages[member] = ReferencesSearch
.search(member) .search(member)
.map { helper.createUsage(encapsulateFieldsDescriptor, fieldDescriptor, it) } .mapNotNull { helper.createUsage(encapsulateFieldsDescriptor, fieldDescriptor, it) }
.filterNotNull()
} }
override fun move(info: MemberInfo, substitutor: PsiSubstitutor) { override fun move(info: MemberInfo, substitutor: PsiSubstitutor) {
@@ -114,7 +114,7 @@ public class KotlinPullUpDialog(
val targetPsiClass = targetClass as? PsiClass ?: (targetClass as KtClass).toLightClass() val targetPsiClass = targetClass as? PsiClass ?: (targetClass as KtClass).toLightClass()
return PullUpProcessor(sourceClass.toLightClass(), return PullUpProcessor(sourceClass.toLightClass(),
targetPsiClass, targetPsiClass,
memberInfos.map { it.toJavaMemberInfo() }.filterNotNull().toTypedArray(), memberInfos.mapNotNull { it.toJavaMemberInfo() }.toTypedArray(),
DocCommentPolicy<PsiComment>(JavaRefactoringSettings.getInstance().PULL_UP_MEMBERS_JAVADOC)) DocCommentPolicy<PsiComment>(JavaRefactoringSettings.getInstance().PULL_UP_MEMBERS_JAVADOC))
} }
} }
@@ -74,15 +74,12 @@ public class KotlinPullUpHandler : AbstractPullPushMembersHandler(
val classDescriptor = classOrObject.resolveToDescriptor() as ClassDescriptor val classDescriptor = classOrObject.resolveToDescriptor() as ClassDescriptor
val superClasses = classDescriptor.defaultType val superClasses = classDescriptor.defaultType
.supertypes() .supertypes()
.asSequence() .mapNotNull {
.map {
val descriptor = it.constructor.declarationDescriptor val descriptor = it.constructor.declarationDescriptor
val declaration = descriptor?.let { DescriptorToSourceUtilsIde.getAnyDeclaration(project, it) } val declaration = descriptor?.let { DescriptorToSourceUtilsIde.getAnyDeclaration(project, it) }
if ((declaration is KtClass || declaration is PsiClass) if ((declaration is KtClass || declaration is PsiClass)
&& declaration.canRefactor()) declaration as PsiNamedElement else null && declaration.canRefactor()) declaration as PsiNamedElement else null
} }
.filterNotNull()
.asIterable()
.sortedBy { it.qualifiedClassNameForRendering() } .sortedBy { it.qualifiedClassNameForRendering() }
if (superClasses.isEmpty()) { if (superClasses.isEmpty()) {
@@ -38,8 +38,7 @@ public class KotlinPullUpHelperFactory : PullUpHelperFactory {
val sourceClass = sourceClass.unwrapped as? KtClassOrObject ?: return null val sourceClass = sourceClass.unwrapped as? KtClassOrObject ?: return null
val targetClass = targetClass.unwrapped as? PsiNamedElement ?: return null val targetClass = targetClass.unwrapped as? PsiNamedElement ?: return null
val membersToMove = membersToMove val membersToMove = membersToMove
.map { it.namedUnwrappedElement as? KtNamedDeclaration } .mapNotNull { it.namedUnwrappedElement as? KtNamedDeclaration }
.filterNotNull()
.sortedBy { it.startOffset } .sortedBy { it.startOffset }
return KotlinPullUpData(sourceClass, targetClass, membersToMove) return KotlinPullUpData(sourceClass, targetClass, membersToMove)
} }
@@ -51,7 +51,7 @@ fun checkConflicts(project: Project,
val pullUpData = KotlinPullUpData(sourceClass, val pullUpData = KotlinPullUpData(sourceClass,
targetClass, targetClass,
memberInfos.map { it.member }.filterNotNull()) memberInfos.mapNotNull { it.member })
with(pullUpData) { with(pullUpData) {
for (memberInfo in memberInfos) { for (memberInfo in memberInfos) {
@@ -112,8 +112,7 @@ private fun KotlinPullUpData.checkAccidentalOverrides(
.searchInheritors() .searchInheritors()
.asSequence() .asSequence()
.filterNot { it.unwrapped == sourceClass || it.unwrapped == targetClass } .filterNot { it.unwrapped == sourceClass || it.unwrapped == targetClass }
.map { it.unwrapped as? KtClassOrObject } .mapNotNull { it.unwrapped as? KtClassOrObject }
.filterNotNull()
.forEach { .forEach {
val subClassDescriptor = resolutionFacade.resolveToDescriptor(it) as ClassDescriptor val subClassDescriptor = resolutionFacade.resolveToDescriptor(it) as ClassDescriptor
val substitutor = getTypeSubstitutor(targetClassDescriptor.defaultType, val substitutor = getTypeSubstitutor(targetClassDescriptor.defaultType,
@@ -94,14 +94,13 @@ public class KotlinPushDownProcessor(
} }
override fun getAfterData(usages: Array<out UsageInfo>) = RefactoringEventData().apply { override fun getAfterData(usages: Array<out UsageInfo>) = RefactoringEventData().apply {
addElements(usages.map { it.element as? KtClassOrObject }.filterNotNull()) addElements(usages.mapNotNull { it.element as? KtClassOrObject })
} }
override fun findUsages(): Array<out UsageInfo> { override fun findUsages(): Array<out UsageInfo> {
return HierarchySearchRequest(context.sourceClass, context.sourceClass.useScope, false) return HierarchySearchRequest(context.sourceClass, context.sourceClass.useScope, false)
.searchInheritors() .searchInheritors()
.map { it.unwrapped } .mapNotNull { it.unwrapped }
.filterNotNull()
.map { SubclassUsage(it) } .map { SubclassUsage(it) }
.toTypedArray() .toTypedArray()
} }
@@ -44,7 +44,7 @@ import java.util.ArrayList
fun analyzePushDownConflicts(context: KotlinPushDownContext, fun analyzePushDownConflicts(context: KotlinPushDownContext,
usages: Array<out UsageInfo>): MultiMap<PsiElement, String> { usages: Array<out UsageInfo>): MultiMap<PsiElement, String> {
val targetClasses = usages.map { it.element?.unwrapped }.filterNotNull() val targetClasses = usages.mapNotNull { it.element?.unwrapped }
val conflicts = MultiMap<PsiElement, String>() val conflicts = MultiMap<PsiElement, String>()
@@ -73,7 +73,7 @@ public class KotlinSafeDeleteProcessor : JavaSafeDeleteProcessor() {
val javaUsages = ArrayList<UsageInfo>() val javaUsages = ArrayList<UsageInfo>()
val searchInfo = super.findUsages(element, allElementsToDelete, javaUsages) val searchInfo = super.findUsages(element, allElementsToDelete, javaUsages)
javaUsages.map { usageInfo -> javaUsages.mapNotNullTo(usages) { usageInfo ->
when (usageInfo) { when (usageInfo) {
is SafeDeleteOverridingMethodUsageInfo -> is SafeDeleteOverridingMethodUsageInfo ->
usageInfo.getSmartPointer().getElement()?.let { usageElement -> usageInfo.getSmartPointer().getElement()?.let { usageElement ->
@@ -102,15 +102,14 @@ public class KotlinSafeDeleteProcessor : JavaSafeDeleteProcessor() {
else -> usageInfo else -> usageInfo
} }
}.filterNotNull().toCollection(usages) }
return searchInfo return searchInfo
} }
fun findUsagesByJavaProcessor(elements: Sequence<PsiElement>, insideDeleted: Condition<PsiElement>): Condition<PsiElement> = fun findUsagesByJavaProcessor(elements: Sequence<PsiElement>, insideDeleted: Condition<PsiElement>): Condition<PsiElement> =
elements elements
.map { element -> findUsagesByJavaProcessor(element, true)?.getInsideDeletedCondition() } .mapNotNull { element -> findUsagesByJavaProcessor(element, true)?.getInsideDeletedCondition() }
.filterNotNull()
.fold(insideDeleted) { condition1, condition2 -> Conditions.or(condition1, condition2) } .fold(insideDeleted) { condition1, condition2 -> Conditions.or(condition1, condition2) }
fun findUsagesByJavaProcessor(ktDeclaration: KtDeclaration): NonCodeUsageSearchInfo { fun findUsagesByJavaProcessor(ktDeclaration: KtDeclaration): NonCodeUsageSearchInfo {
@@ -47,8 +47,7 @@ public open class KotlinDirectInheritorsSearcher() : QueryExecutorBase<PsiClass,
runReadAction { runReadAction {
val noLibrarySourceScope = KotlinSourceFilterScope.sourceAndClassFiles(scope, baseClass.getProject()) val noLibrarySourceScope = KotlinSourceFilterScope.sourceAndClassFiles(scope, baseClass.getProject())
KotlinSuperClassIndex.getInstance().get(name, baseClass.getProject(), noLibrarySourceScope).asSequence() KotlinSuperClassIndex.getInstance().get(name, baseClass.getProject(), noLibrarySourceScope).asSequence()
.map { candidate -> SourceNavigationHelper.getOriginalPsiClassOrCreateLightClass(candidate)} .mapNotNull { candidate -> SourceNavigationHelper.getOriginalPsiClassOrCreateLightClass(candidate)}
.filterNotNull()
.filter { candidate -> candidate.isInheritor(baseClass, false) } .filter { candidate -> candidate.isInheritor(baseClass, false) }
.forEach { candidate -> consumer.process(candidate) } .forEach { candidate -> consumer.process(candidate) }
} }
@@ -238,7 +238,7 @@ public class ImportInsertHelperImpl(private val project: Project) : ImportInsert
val scopeToImport = getMemberScope(parentFqName, moduleDescriptor) ?: return ImportDescriptorResult.FAIL val scopeToImport = getMemberScope(parentFqName, moduleDescriptor) ?: return ImportDescriptorResult.FAIL
val importedScopes = imports val importedScopes = imports
.filter { it.isAllUnder () } .filter { it.isAllUnder () }
.map { .mapNotNull {
val importPath = it.getImportPath() val importPath = it.getImportPath()
if (importPath != null) { if (importPath != null) {
val fqName = importPath.fqnPart() val fqName = importPath.fqnPart()
@@ -248,7 +248,6 @@ public class ImportInsertHelperImpl(private val project: Project) : ImportInsert
null null
} }
} }
.filterNotNull()
val filePackage = moduleDescriptor.getPackage(file.getPackageFqName()) val filePackage = moduleDescriptor.getPackage(file.getPackageFqName())
@@ -266,7 +265,7 @@ public class ImportInsertHelperImpl(private val project: Project) : ImportInsert
val topLevelScope = resolutionFacade.getFileResolutionScope(file) val topLevelScope = resolutionFacade.getFileResolutionScope(file)
val conflictCandidates: List<ClassifierDescriptor> = classNamesToImport val conflictCandidates: List<ClassifierDescriptor> = classNamesToImport
.flatMap { .flatMap {
importedScopes.map { scope -> scope.getContributedClassifier(it, NoLookupLocation.FROM_IDE) }.filterNotNull() importedScopes.mapNotNull { scope -> scope.getContributedClassifier(it, NoLookupLocation.FROM_IDE) }
} }
.filter { importedClass -> .filter { importedClass ->
isVisible(importedClass) isVisible(importedClass)
@@ -708,7 +708,7 @@ public class KotlinPsiUnifier(
} }
private fun ASTNode.getChildrenRange(): KotlinPsiRange = private fun ASTNode.getChildrenRange(): KotlinPsiRange =
getChildren(null).map { it.getPsi() }.filterNotNull().toRange() getChildren(null).mapNotNull { it.getPsi() }.toRange()
private fun PsiElement.unwrapWeakly(): KtElement? { private fun PsiElement.unwrapWeakly(): KtElement? {
return when { return when {

Some files were not shown because too many files have changed in this diff Show More