Replace sort with sorted.

This commit is contained in:
Ilya Gorbunov
2015-09-30 21:27:31 +03:00
parent 389ea1b230
commit 37a0347669
50 changed files with 76 additions and 75 deletions
@@ -45,8 +45,8 @@ public object CodegenUtilKt {
return descriptor.getDefaultType().getMemberScope().getDescriptors().asSequence() return descriptor.getDefaultType().getMemberScope().getDescriptors().asSequence()
.filterIsInstance<CallableMemberDescriptor>() .filterIsInstance<CallableMemberDescriptor>()
.filter { it.getKind() == CallableMemberDescriptor.Kind.DELEGATION } .filter { it.getKind() == CallableMemberDescriptor.Kind.DELEGATION }
.toList() .asIterable()
.sortBy(MemberComparator.INSTANCE as Comparator<CallableMemberDescriptor>) // Workaround for KT-6030 .sortedWith(MemberComparator.INSTANCE)
.keysToMapExceptNulls { .keysToMapExceptNulls {
delegatingMember -> delegatingMember ->
@@ -243,7 +243,7 @@ class SMAP(val fileMappings: List<FileMapping>) {
val default: FileMapping val default: FileMapping
get() = fileMappings.first() get() = fileMappings.first()
val intervals = fileMappings.flatMap { it.lineMappings }.sortBy(RangeMapping.Comparator) val intervals = fileMappings.flatMap { it.lineMappings }.sortedWith(RangeMapping.Comparator)
val sourceInfo: SourceInfo val sourceInfo: SourceInfo
init { init {
@@ -131,7 +131,7 @@ public class KotlinCoreEnvironment private constructor(
message -> message ->
report(ERROR, message) report(ERROR, message)
})) }))
sourceFiles.sortBy(object : Comparator<JetFile> { sourceFiles.sortedWith(object : Comparator<JetFile> {
override fun compare(o1: JetFile, o2: JetFile): Int { override fun compare(o1: JetFile, o2: JetFile): Int {
return o1.getVirtualFile().getPath().compareTo(o2.getVirtualFile().getPath(), ignoreCase = true) return o1.getVirtualFile().getPath().compareTo(o2.getVirtualFile().getPath(), ignoreCase = true)
} }
@@ -91,7 +91,7 @@ public fun getExpectedTypePredicate(
val candidates = callee.getReferenceTargets(bindingContext) val candidates = callee.getReferenceTargets(bindingContext)
.filterIsInstance<FunctionDescriptor>() .filterIsInstance<FunctionDescriptor>()
.sortBy { DescriptorRenderer.DEBUG_TEXT.render(it) } .sortedBy { DescriptorRenderer.DEBUG_TEXT.render(it) }
if (candidates.isEmpty()) return null if (candidates.isEmpty()) return null
val explicitReceiver = call.getExplicitReceiver() val explicitReceiver = call.getExplicitReceiver()
@@ -106,9 +106,9 @@ public object Renderers {
public val AMBIGUOUS_CALLS: Renderer<Collection<ResolvedCall<*>>> = Renderer { public val AMBIGUOUS_CALLS: Renderer<Collection<ResolvedCall<*>>> = Renderer {
calls: Collection<ResolvedCall<*>> -> calls: Collection<ResolvedCall<*>> ->
calls calls
.map { it.getResultingDescriptor() } .map { it.getResultingDescriptor() }
.sortBy(MemberComparator.INSTANCE) .sortedWith(MemberComparator.INSTANCE)
.joinToString(separator = "\n", prefix = "\n") { DescriptorRenderer.FQ_NAMES_IN_TYPES.render(it) } .joinToString(separator = "\n", prefix = "\n") { DescriptorRenderer.FQ_NAMES_IN_TYPES.render(it) }
} }
@@ -142,7 +142,7 @@ public fun <TElement : JetElement> createByPattern(pattern: String, vararg args:
.flatMap { it.value } .flatMap { it.value }
.map { it.range } .map { it.range }
.filterNot { it.isEmpty() } .filterNot { it.isEmpty() }
.sortBy { -it.getStartOffset() } .sortedBy { -it.getStartOffset() }
// reformat whole text except for String arguments (as they can contain user's formatting to be preserved) // reformat whole text except for String arguments (as they can contain user's formatting to be preserved)
if (stringPlaceholderRanges.none()) { if (stringPlaceholderRanges.none()) {
@@ -40,7 +40,7 @@ public open class KotlinStubBaseImpl<T : JetElementImplStub<*>>(parent: StubElem
} }
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().sort() return collectProperties(stubInterface).map { property -> renderProperty(property) }.filterNotNull().sorted()
} }
private fun collectProperties(stubInterface: Class<*>): Collection<Method> { private fun collectProperties(stubInterface: Class<*>): Collection<Method> {
@@ -69,7 +69,7 @@ public abstract class AbstractPseudoValueTest : AbstractPseudocodeTest() {
.map { (it as? InstructionWithValue)?.outputValue } .map { (it as? InstructionWithValue)?.outputValue }
.filterNotNull() .filterNotNull()
.filter { it.element == null } .filter { it.element == null }
.toSortedListBy { it.debugName } .sortedBy { it.debugName }
val allValues = elementToValues.values() + unboundValues val allValues = elementToValues.values() + unboundValues
if (allValues.isEmpty()) return if (allValues.isEmpty()) return
@@ -68,7 +68,7 @@ class LazyOperationsLog(
return groupedByOwner.map { return groupedByOwner.map {
val (owner, records) = it val (owner, records) = it
renderOwner(owner, records) renderOwner(owner, records)
}.sortBy(stringSanitizer).join("\n").renumberObjects() }.sortedBy(stringSanitizer).join("\n").renumberObjects()
} }
/** /**
@@ -97,7 +97,7 @@ class LazyOperationsLog(
with (Printer(sb)) { with (Printer(sb)) {
println(render(owner), " {") println(render(owner), " {")
indent { indent {
records.map { renderRecord(it) }.sortBy(stringSanitizer).forEach { records.map { renderRecord(it) }.sortedBy(stringSanitizer).forEach {
println(it) println(it)
} }
} }
@@ -58,6 +58,6 @@ private fun checkSorted(descriptors: Collection<DeclarationDescriptor>, declarat
UsefulTestCase.assertOrderedEquals( UsefulTestCase.assertOrderedEquals(
"Members of $declaration should be sorted by serialization.", "Members of $declaration should be sorted by serialization.",
descriptors, descriptors,
descriptors.sortBy(MemberComparator.INSTANCE) descriptors.sortedWith(MemberComparator.INSTANCE)
) )
} }
@@ -383,15 +383,15 @@ internal class DescriptorRendererImpl(
} ?: emptyList() } ?: emptyList()
val defaultList = parameterDescriptorsWithDefaultValue.filter { !allValueArguments.containsKey(it) }.map { val defaultList = parameterDescriptorsWithDefaultValue.filter { !allValueArguments.containsKey(it) }.map {
"${it.getName().asString()} = ..." "${it.getName().asString()} = ..."
}.sort() }.sorted()
val argumentList = allValueArguments.entrySet() val argumentList = allValueArguments.entrySet()
.map { entry -> .map { entry ->
val name = entry.key.getName().asString() val name = entry.key.getName().asString()
val value = if (!parameterDescriptorsWithDefaultValue.contains(entry.key)) renderConstant(entry.value) else "..." val value = if (!parameterDescriptorsWithDefaultValue.contains(entry.key)) renderConstant(entry.value) else "..."
"$name = $value" "$name = $value"
} }
.sort() .sorted()
return (defaultList + argumentList).sort() return (defaultList + argumentList).sorted()
} }
private fun renderConstant(value: ConstantValue<*>): String { private fun renderConstant(value: ConstantValue<*>): String {
@@ -32,7 +32,7 @@ public object IdeRenderers {
calls: Collection<ResolvedCall<*>> -> calls: Collection<ResolvedCall<*>> ->
calls calls
.map { it.getResultingDescriptor() } .map { it.getResultingDescriptor() }
.sortBy(MemberComparator.INSTANCE) .sortedWith(MemberComparator.INSTANCE)
.joinToString("") { "<li>" + DescriptorRenderer.HTML.render(it) + "</li>" } .joinToString("") { "<li>" + DescriptorRenderer.HTML.render(it) + "</li>" }
} }
@@ -45,7 +45,7 @@ public object IdeRenderers {
// TODO: compareBy(comparator, selector) in stdlib // TODO: compareBy(comparator, selector) in stdlib
val comparator = comparator<ResolvedCall<*>> { c1, c2 -> MemberComparator.INSTANCE.compare(c1.getResultingDescriptor(), c2.getResultingDescriptor()) } val comparator = comparator<ResolvedCall<*>> { c1, c2 -> MemberComparator.INSTANCE.compare(c1.getResultingDescriptor(), c2.getResultingDescriptor()) }
calls calls
.sortBy(comparator) .sortedWith(comparator)
.joinToString("") { "<li>" + renderResolvedCall(it) + "</li>" } .joinToString("") { "<li>" + renderResolvedCall(it) + "</li>" }
} }
@@ -80,7 +80,7 @@ public object IdeRenderers {
val conflicts = data.signatureOrigins val conflicts = data.signatureOrigins
.map { it.descriptor } .map { it.descriptor }
.filterNotNull() .filterNotNull()
.sortBy(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" }
"The following declarations have the same JVM signature (<code>${data.signature.name}${data.signature.desc}</code>):<br/>\n<ul>\n$conflicts</ul>" "The following declarations have the same JVM signature (<code>${data.signature.name}${data.signature.desc}</code>):<br/>\n<ul>\n$conflicts</ul>"
@@ -273,7 +273,7 @@ public object ExpectedCompletionUtils {
val map = HashMap<String, String?>() val map = HashMap<String, String?>()
map.put(CompletionProposal.LOOKUP_STRING, item.lookupString) map.put(CompletionProposal.LOOKUP_STRING, item.lookupString)
map.put(CompletionProposal.ALL_LOOKUP_STRINGS, item.allLookupStrings.sort().joinToString()) map.put(CompletionProposal.ALL_LOOKUP_STRINGS, item.allLookupStrings.sorted().joinToString())
if (presentation.itemText != null) { if (presentation.itemText != null) {
map.put(CompletionProposal.PRESENTATION_ITEM_TEXT, presentation.itemText) map.put(CompletionProposal.PRESENTATION_ITEM_TEXT, presentation.itemText)
@@ -30,12 +30,12 @@ public object DirectiveBasedActionUtils {
return return
} }
val expectedErrors = InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.getText(), "// ERROR:").sort() val expectedErrors = InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.getText(), "// ERROR:").sorted()
val actualErrors = file.analyzeFully().getDiagnostics() val actualErrors = file.analyzeFully().getDiagnostics()
.filter { it.getSeverity() == Severity.ERROR } .filter { it.getSeverity() == Severity.ERROR }
.map { IdeErrorMessages.render(it) } .map { IdeErrorMessages.render(it) }
.sort() .sorted()
UsefulTestCase.assertOrderedEquals("All actual errors should be mentioned in test data with // ERROR: directive. But no unnecessary errors should be me mentioned", UsefulTestCase.assertOrderedEquals("All actual errors should be mentioned in test data with // ERROR: directive. But no unnecessary errors should be me mentioned",
actualErrors, actualErrors,
@@ -43,12 +43,12 @@ public object DirectiveBasedActionUtils {
} }
public fun checkAvailableActionsAreExpected(file: JetFile, availableActions: Collection<IntentionAction>) { public fun checkAvailableActionsAreExpected(file: JetFile, availableActions: Collection<IntentionAction>) {
val expectedActions = InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.getText(), "// ACTION:").sort() val expectedActions = InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.getText(), "// ACTION:").sorted()
UsefulTestCase.assertEmpty("Irrelevant actions should not be specified in ACTION directive for they are not checked anyway", UsefulTestCase.assertEmpty("Irrelevant actions should not be specified in ACTION directive for they are not checked anyway",
expectedActions.filter { isIrrelevantAction(it) }) expectedActions.filter { isIrrelevantAction(it) })
val actualActions = availableActions.map { it.getText() }.sort() val actualActions = availableActions.map { it.getText() }.sorted()
UsefulTestCase.assertOrderedEquals("Some unexpected actions available at current position. Use // ACTION: directive", UsefulTestCase.assertOrderedEquals("Some unexpected actions available at current position. Use // ACTION: directive",
filterOutIrrelevantActions(actualActions), filterOutIrrelevantActions(actualActions),
@@ -72,7 +72,7 @@ public class KotlinAddImportAction(
val descriptorToImport: DeclarationDescriptor val descriptorToImport: DeclarationDescriptor
get() { get() {
return descriptors.singleOrNull() return descriptors.singleOrNull()
?: descriptors.sortBy { if (it is ClassDescriptor) 0 else 1 }.first() ?: descriptors.sortedBy { if (it is ClassDescriptor) 0 else 1 }.first()
} }
val declarationToImport = DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptorToImport) val declarationToImport = DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptorToImport)
@@ -81,7 +81,7 @@ public class KotlinAddImportAction(
private val variants = candidates private val variants = candidates
.groupBy { it.importableFqName!! } .groupBy { it.importableFqName!! }
.map { Variant(it.key, it.value) } .map { Variant(it.key, it.value) }
.sortBy { it.priority } .sortedBy { it.priority }
public val highestPriorityFqName: FqName public val highestPriorityFqName: FqName
get() = variants.first().fqName get() = variants.first().fqName
@@ -55,7 +55,7 @@ data class DataForConversion private constructor(
} }
private fun clipTextIfNeeded(file: PsiJavaFile, fileText: String, startOffsets: IntArray, endOffsets: IntArray): String? { private fun clipTextIfNeeded(file: PsiJavaFile, fileText: String, startOffsets: IntArray, endOffsets: IntArray): String? {
val ranges = startOffsets.indices.map { TextRange(startOffsets[it], endOffsets[it]) }.sortBy { it.start } val ranges = startOffsets.indices.map { TextRange(startOffsets[it], endOffsets[it]) }.sortedBy { it.start }
fun canDropRange(range: TextRange) = ranges.all { range !in it } fun canDropRange(range: TextRange) = ranges.all { range !in it }
@@ -189,8 +189,8 @@ class KotlinEvaluator(val codeFragment: JetCodeFragment,
val classFileFactory = createClassFileFactory(codeFragment, extractedFunction, context, parametersDescriptor) val classFileFactory = createClassFileFactory(codeFragment, extractedFunction, context, parametersDescriptor)
val outputFiles = classFileFactory.asList().filterClassFiles() val outputFiles = classFileFactory.asList().filterClassFiles()
.filter { it.relativePath != "$packageInternalName.class" } .filter { it.relativePath != "$packageInternalName.class" }
.sortBy { it.relativePath.length() } .sortedBy { it.relativePath.length() }
val funName = runReadAction { extractedFunction.name } val funName = runReadAction { extractedFunction.name }
if (funName == null) { if (funName == null) {
@@ -90,7 +90,7 @@ public class KotlinClassWithDelegatedPropertyRenderer : ClassRenderer() {
} }
if (XDebuggerSettingsManager.getInstance()!!.getDataViewSettings().isSortValues()) { if (XDebuggerSettingsManager.getInstance()!!.getDataViewSettings().isSortValues()) {
children.sortBy(NodeManagerImpl.getNodeComparator()) children.sortedWith(NodeManagerImpl.getNodeComparator())
} }
builder.setChildren(children) builder.setChildren(children)
@@ -80,7 +80,7 @@ public fun getOverriddenMethodTooltip(method: PsiMethod): String? {
val comparator = MethodCellRenderer(false).getComparator() val comparator = MethodCellRenderer(false).getComparator()
val overridingJavaMethods = processor.getCollection().filter { it !is KotlinLightMethodForTraitFakeOverride } sortBy(comparator) val overridingJavaMethods = processor.getCollection().filter { it !is KotlinLightMethodForTraitFakeOverride } sortedWith (comparator)
if (overridingJavaMethods.isEmpty()) return null if (overridingJavaMethods.isEmpty()) return null
val start = if (isAbstract) DaemonBundle.message("method.is.implemented.header") else DaemonBundle.message("method.is.overriden.header") val start = if (isAbstract) DaemonBundle.message("method.is.implemented.header") else DaemonBundle.message("method.is.overriden.header")
@@ -109,7 +109,7 @@ public fun navigateToOverriddenMethod(e: MouseEvent?, method: PsiMethod) {
val showMethodNames = !PsiUtil.allMethodsHaveSameSignature(overridingJavaMethods.toTypedArray()) val showMethodNames = !PsiUtil.allMethodsHaveSameSignature(overridingJavaMethods.toTypedArray())
val renderer = MethodCellRenderer(showMethodNames) val renderer = MethodCellRenderer(showMethodNames)
overridingJavaMethods = overridingJavaMethods.sortBy(renderer.getComparator()) overridingJavaMethods = overridingJavaMethods.sortedWith(renderer.comparator)
val methodsUpdater = OverridingMethodsUpdater(method, renderer) val methodsUpdater = OverridingMethodsUpdater(method, renderer)
PsiElementListNavigator.openTargets( PsiElementListNavigator.openTargets(
@@ -73,7 +73,7 @@ fun getOverriddenPropertyTooltip(property: JetProperty): String? {
JetBundle.message("property.is.overridden.header") JetBundle.message("property.is.overridden.header")
val pattern = "&nbsp;&nbsp;&nbsp;&nbsp;{0}" val pattern = "&nbsp;&nbsp;&nbsp;&nbsp;{0}"
return GutterIconTooltipHelper.composeText(collectedClasses.sortBy(PsiClassListCellRenderer().getComparator()), start, pattern) return GutterIconTooltipHelper.composeText(collectedClasses.sortedWith(PsiClassListCellRenderer().comparator), start, pattern)
} }
fun navigateToPropertyOverriddenDeclarations(e: MouseEvent?, property: JetProperty) { fun navigateToPropertyOverriddenDeclarations(e: MouseEvent?, property: JetProperty) {
@@ -105,7 +105,7 @@ fun navigateToPropertyOverriddenDeclarations(e: MouseEvent?, property: JetProper
val renderer = DefaultPsiElementCellRenderer() val renderer = DefaultPsiElementCellRenderer()
val navigatingOverrides = elementProcessor.getResults() val navigatingOverrides = elementProcessor.getResults()
.sortBy(renderer.getComparator()) .sortedWith(renderer.comparator)
.filterIsInstance<NavigatablePsiElement>() .filterIsInstance<NavigatablePsiElement>()
PsiElementListNavigator.openTargets(e, PsiElementListNavigator.openTargets(e,
@@ -60,7 +60,7 @@ object SuperDeclarationMarkerTooltip: Function<JetDeclaration, String> {
"${if (!isAbstract && isBaseAbstract) "Implements" else "Overrides"} $memberKind in '${renderer.render(declaration)}'" "${if (!isAbstract && isBaseAbstract) "Implements" else "Overrides"} $memberKind in '${renderer.render(declaration)}'"
} }
return containingStrings.sort().join(separator = "<br/>") return containingStrings.sorted().join(separator = "<br/>")
} }
} }
@@ -220,7 +220,7 @@ public class KotlinImportOptimizer() : ImportOptimizer {
//TODO: drop unused aliases? //TODO: drop unused aliases?
aliasImports.mapTo(importsToGenerate) { ImportPath(it.getValue(), false, it.getKey())} aliasImports.mapTo(importsToGenerate) { ImportPath(it.getValue(), false, it.getKey())}
val sortedImportsToGenerate = importsToGenerate.sortBy(importInsertHelper.importSortComparator) val sortedImportsToGenerate = importsToGenerate.sortedWith(importInsertHelper.importSortComparator)
// check if no changes to imports required // check if no changes to imports required
val oldImports = file.importDirectives val oldImports = file.importDirectives
@@ -171,7 +171,7 @@ internal class TypeParameterListExpression(private val mandatoryTypeParameters:
} }
val sortedRenderedTypeParameters = renderedTypeParameters.sortBy { if (it.fake) it.typeParameter.getIndex() else -1} val sortedRenderedTypeParameters = renderedTypeParameters.sortedBy { if (it.fake) it.typeParameter.getIndex() else -1 }
currentTypeParameters = sortedRenderedTypeParameters.map { it.typeParameter } currentTypeParameters = sortedRenderedTypeParameters.map { it.typeParameter }
return TextResult( return TextResult(
@@ -234,7 +234,7 @@ private fun ExtractionData.getLocalDeclarationsWithNonLocalUsages(
} }
} }
} }
return declarations.sortBy { it.getTextRange()!!.getStartOffset() } return declarations.sortedBy { it.getTextRange()!!.getStartOffset() }
} }
private fun ExtractionData.analyzeControlFlow( private fun ExtractionData.analyzeControlFlow(
@@ -314,12 +314,12 @@ private fun ExtractionData.analyzeControlFlow(
} }
if (declarationsToReport.isNotEmpty()) { if (declarationsToReport.isNotEmpty()) {
val localVarStr = declarationsToReport.map { it.renderForMessage(bindingContext)!! }.distinct().sort() val localVarStr = declarationsToReport.map { it.renderForMessage(bindingContext)!! }.distinct().sorted()
return controlFlow to ErrorMessage.DECLARATIONS_ARE_USED_OUTSIDE.addAdditionalInfo(localVarStr) return controlFlow to ErrorMessage.DECLARATIONS_ARE_USED_OUTSIDE.addAdditionalInfo(localVarStr)
} }
val outParameters = val outParameters =
parameters.filter { it.mirrorVarName != null && modifiedVarDescriptors[it.originalDescriptor] != null }.sortBy { it.nameForRef } parameters.filter { it.mirrorVarName != null && modifiedVarDescriptors[it.originalDescriptor] != null }.sortedBy { it.nameForRef }
val outDeclarations = val outDeclarations =
declarationsToCopy.filter { modifiedVarDescriptors[bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, it]] != null } declarationsToCopy.filter { modifiedVarDescriptors[bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, it]] != null }
val modifiedValueCount = outParameters.size() + outDeclarations.size() val modifiedValueCount = outParameters.size() + outDeclarations.size()
@@ -363,7 +363,7 @@ private fun ExtractionData.analyzeControlFlow(
if (!options.enableListBoxing) { if (!options.enableListBoxing) {
val outValuesStr = val outValuesStr =
(outParameters.map { it.originalDescriptor.renderForMessage() } (outParameters.map { it.originalDescriptor.renderForMessage() }
+ outDeclarations.map { it.renderForMessage(bindingContext)!! }).sort() + outDeclarations.map { it.renderForMessage(bindingContext)!! }).sorted()
return controlFlow to ErrorMessage.MULTIPLE_OUTPUT.addAdditionalInfo(outValuesStr) return controlFlow to ErrorMessage.MULTIPLE_OUTPUT.addAdditionalInfo(outValuesStr)
} }
OutputValueBoxer::AsList OutputValueBoxer::AsList
@@ -837,7 +837,7 @@ private fun ExtractionData.checkDeclarationsMovingOutOfScope(
) )
if (declarationsOutOfScope.isNotEmpty()) { if (declarationsOutOfScope.isNotEmpty()) {
val declStr = declarationsOutOfScope.map { it.renderForMessage(bindingContext)!! }.sort() val declStr = declarationsOutOfScope.map { it.renderForMessage(bindingContext)!! }.sorted()
return ErrorMessage.DECLARATIONS_OUT_OF_SCOPE.addAdditionalInfo(declStr) return ErrorMessage.DECLARATIONS_OUT_OF_SCOPE.addAdditionalInfo(declStr)
} }
@@ -909,7 +909,7 @@ fun ExtractionData.performAnalysis(): AnalysisResult {
returnType.processTypeIfExtractable(paramsInfo.typeParameters, paramsInfo.nonDenotableTypes, options, targetScope) returnType.processTypeIfExtractable(paramsInfo.typeParameters, paramsInfo.nonDenotableTypes, options, targetScope)
if (paramsInfo.nonDenotableTypes.isNotEmpty()) { if (paramsInfo.nonDenotableTypes.isNotEmpty()) {
val typeStr = paramsInfo.nonDenotableTypes.map {it.renderForMessage()}.sort() val typeStr = paramsInfo.nonDenotableTypes.map {it.renderForMessage()}.sorted()
return AnalysisResult( return AnalysisResult(
null, null,
Status.CRITICAL_ERROR, Status.CRITICAL_ERROR,
@@ -939,9 +939,9 @@ fun ExtractionData.performAnalysis(): AnalysisResult {
bindingContext, bindingContext,
suggestFunctionNames(returnType), suggestFunctionNames(returnType),
getDefaultVisibility(), getDefaultVisibility(),
adjustedParameters.sortBy { it.name }, adjustedParameters.sortedBy { it.name },
receiverParameter, receiverParameter,
paramsInfo.typeParameters.sortBy { it.originalDeclaration.getName()!! }, paramsInfo.typeParameters.sortedBy { it.originalDeclaration.getName()!! },
paramsInfo.replacementMap, paramsInfo.replacementMap,
if (messages.isEmpty()) controlFlow else controlFlow.toDefault(), if (messages.isEmpty()) controlFlow else controlFlow.toDefault(),
returnType returnType
@@ -482,7 +482,7 @@ fun ExtractionGeneratorConfiguration.generateDeclaration(
* Sort by descending position so that internals of value/type arguments in calls and qualified types are replaced * Sort by descending position so that internals of value/type arguments in calls and qualified types are replaced
* before calls/types themselves * before calls/types themselves
*/ */
for ((offsetInBody, resolveResult) in descriptor.extractionData.refOffsetToDeclaration.entrySet().sortDescendingBy { it.key }) { for ((offsetInBody, resolveResult) in descriptor.extractionData.refOffsetToDeclaration.entrySet().sortedByDescending { it.key }) {
val expr = file.findElementAt(bodyOffset + offsetInBody)?.getNonStrictParentOfType<JetSimpleNameExpression>() val expr = file.findElementAt(bodyOffset + offsetInBody)?.getNonStrictParentOfType<JetSimpleNameExpression>()
assert(expr != null) { "Couldn't find expression at $offsetInBody in '${body.getText()}'" } assert(expr != null) { "Couldn't find expression at $offsetInBody in '${body.getText()}'" }
@@ -134,7 +134,7 @@ fun IntroduceParameterDescriptor.performRefactoring() {
parameters.indexOf(it) + if (withReceiver) 1 else 0 parameters.indexOf(it) + if (withReceiver) 1 else 0
} else 0 } else 0
} }
.sortDescending() .sortedDescending()
.forEach { methodDescriptor.removeParameter(it) } .forEach { methodDescriptor.removeParameter(it) }
} }
@@ -65,7 +65,7 @@ public class KotlinIntroduceParameterMethodUsageProcessor : IntroduceParameterMe
val changeSignatureData = JetChangeSignatureData(psiMethodDescriptor, method, Collections.singletonList(psiMethodDescriptor)) val changeSignatureData = JetChangeSignatureData(psiMethodDescriptor, method, Collections.singletonList(psiMethodDescriptor))
val changeInfo = JetChangeInfo(methodDescriptor = changeSignatureData, context = method) val changeInfo = JetChangeInfo(methodDescriptor = changeSignatureData, context = method)
data.getParametersToRemove().toNativeArray().toList().sortDescending().forEach { changeInfo.removeParameter(it) } data.getParametersToRemove().toNativeArray().sortedDescending().forEach { changeInfo.removeParameter(it) }
// Temporarily assume that the new parameter is of Any type. Actual type is substituted during the signature update phase // Temporarily assume that the new parameter is of Any type. Actual type is substituted during the signature update phase
val defaultValueForCall = (data.getParameterInitializer().getExpression()!! as? PsiExpression)?.let { it.j2k() } val defaultValueForCall = (data.getParameterInitializer().getExpression()!! as? PsiExpression)?.let { it.j2k() }
@@ -241,7 +241,7 @@ fun postProcessMoveUsages(usages: List<UsageInfo>,
): List<NonCodeUsageInfo> { ): List<NonCodeUsageInfo> {
fun counterpart(e: PsiElement) = oldToNewElementsMapping[e] ?: e fun counterpart(e: PsiElement) = oldToNewElementsMapping[e] ?: e
val sortedUsages = usages.sortBy( val sortedUsages = usages.sortedWith(
object : Comparator<UsageInfo> { object : Comparator<UsageInfo> {
override fun compare(o1: UsageInfo, o2: UsageInfo): Int { override fun compare(o1: UsageInfo, o2: UsageInfo): Int {
val file1 = o1.getVirtualFile() val file1 = o1.getVirtualFile()
@@ -82,7 +82,8 @@ public class KotlinPullUpHandler : AbstractPullPushMembersHandler(
&& declaration.canRefactor()) declaration as PsiNamedElement else null && declaration.canRefactor()) declaration as PsiNamedElement else null
} }
.filterNotNull() .filterNotNull()
.toSortedListBy { it.qualifiedClassNameForRendering() } .asIterable()
.sortedBy { it.qualifiedClassNameForRendering() }
if (superClasses.isEmpty()) { if (superClasses.isEmpty()) {
val containingClass = classOrObject.getStrictParentOfType<JetClassOrObject>() val containingClass = classOrObject.getStrictParentOfType<JetClassOrObject>()
@@ -564,7 +564,7 @@ class KotlinPullUpHelper(
} }
for ((constructorElement, propertyToInitializerInfo) in targetConstructorToPropertyInitializerInfoMap.entrySet()) { for ((constructorElement, propertyToInitializerInfo) in targetConstructorToPropertyInitializerInfoMap.entrySet()) {
val properties = propertyToInitializerInfo.keySet().toArrayList().sortBy( val properties = propertyToInitializerInfo.keySet().sortedWith(
object : Comparator<JetProperty> { object : Comparator<JetProperty> {
override fun compare(property1: JetProperty, property2: JetProperty): Int { override fun compare(property1: JetProperty, property2: JetProperty): Int {
val info1 = propertyToInitializerInfo[property1]!! val info1 = propertyToInitializerInfo[property1]!!
@@ -40,7 +40,7 @@ public class KotlinPullUpHelperFactory : PullUpHelperFactory {
val membersToMove = membersToMove val membersToMove = membersToMove
.map { it.namedUnwrappedElement as? JetNamedDeclaration } .map { it.namedUnwrappedElement as? JetNamedDeclaration }
.filterNotNull() .filterNotNull()
.sortBy { it.startOffset } .sortedBy { it.startOffset }
return KotlinPullUpData(sourceClass, targetClass, membersToMove) return KotlinPullUpData(sourceClass, targetClass, membersToMove)
} }
@@ -382,7 +382,7 @@ public class JetPsiUnifier(
} }
private fun matchTypes(types1: Collection<JetType>, types2: Collection<JetType>): Boolean { private fun matchTypes(types1: Collection<JetType>, types2: Collection<JetType>): Boolean {
fun sortTypes(types: Collection<JetType>) = types.sortBy{ DescriptorRenderer.DEBUG_TEXT.renderType(it) } fun sortTypes(types: Collection<JetType>) = types.sortedBy { DescriptorRenderer.DEBUG_TEXT.renderType(it) }
if (types1.size() != types2.size()) return false if (types1.size() != types2.size()) return false
return (sortTypes(types1) zip sortTypes(types2)).all { matchTypes(it.first, it.second) == MATCHED } return (sortTypes(types1) zip sortTypes(types2)).all { matchTypes(it.first, it.second) == MATCHED }
@@ -591,11 +591,11 @@ public class JetPsiUnifier(
fun resolveAndSortDeclarationsByDescriptor(declarations: List<JetDeclaration>): List<Pair<JetDeclaration, DeclarationDescriptor?>> { fun resolveAndSortDeclarationsByDescriptor(declarations: List<JetDeclaration>): List<Pair<JetDeclaration, DeclarationDescriptor?>> {
return declarations return declarations
.map { it to it.bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, it] } .map { it to it.bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, it] }
.sortBy { it.second?.let { IdeDescriptorRenderers.SOURCE_CODE.render(it) } ?: "" } .sortedBy { it.second?.let { IdeDescriptorRenderers.SOURCE_CODE.render(it) } ?: "" }
} }
fun sortDeclarationsByElementType(declarations: List<JetDeclaration>): List<JetDeclaration> { fun sortDeclarationsByElementType(declarations: List<JetDeclaration>): List<JetDeclaration> {
return declarations.sortBy { it.getNode()?.getElementType()?.getIndex() ?: -1 } return declarations.sortedBy { it.getNode()?.getElementType()?.getIndex() ?: -1 }
} }
if (desc1.getKind() != desc2.getKind()) return UNMATCHED if (desc1.getKind() != desc2.getKind()) return UNMATCHED
@@ -49,7 +49,7 @@ public abstract class AbstractDataFlowValueRenderingTest: JetLightCodeInsightFix
val info = expression.analyze().getDataFlowInfo(expression) val info = expression.analyze().getDataFlowInfo(expression)
val allValues = (info.getCompleteTypeInfo().keySet() + info.getCompleteNullabilityInfo().keySet()).toSet() val allValues = (info.getCompleteTypeInfo().keySet() + info.getCompleteNullabilityInfo().keySet()).toSet()
val actual = allValues.map { renderDataFlowValue(it) }.filterNotNull().sort().joinToString("\n") val actual = allValues.map { renderDataFlowValue(it) }.filterNotNull().sorted().joinToString("\n")
JetTestUtils.assertEqualsToFile(File(FileUtil.getNameWithoutExtension(fileName) + ".txt"), actual) JetTestUtils.assertEqualsToFile(File(FileUtil.getNameWithoutExtension(fileName) + ".txt"), actual)
} }
@@ -160,7 +160,7 @@ public abstract class AbstractOverrideImplementTest : JetLightCodeInsightFixture
val classOrObject = PsiTreeUtil.getParentOfType(elementAtCaret, javaClass<JetClassOrObject>()) val classOrObject = PsiTreeUtil.getParentOfType(elementAtCaret, javaClass<JetClassOrObject>())
?: error("Caret should be inside class or object") ?: error("Caret should be inside class or object")
val chooserObjects = handler.collectMembersToGenerate(classOrObject).sortBy { it.descriptor.name.asString() + " in " + it.immediateSuper.containingDeclaration.name.asString() } val chooserObjects = handler.collectMembersToGenerate(classOrObject).sortedBy { it.descriptor.name.asString() + " in " + it.immediateSuper.containingDeclaration.name.asString() }
performGenerateCommand(classOrObject, chooserObjects) performGenerateCommand(classOrObject, chooserObjects)
} }
@@ -65,8 +65,8 @@ public abstract class AbstractSmartStepIntoTest : JetLightCodeInsightFixtureTest
val sb = StringBuilder() val sb = StringBuilder()
val maxExtStrSize = (expected.maxBy { it.length() }?.length() ?: 0) + 5 val maxExtStrSize = (expected.maxBy { it.length() }?.length() ?: 0) + 5
val longerList = (if (expected.size() < actual.size()) actual else expected).sort() val longerList = (if (expected.size() < actual.size()) actual else expected).sorted()
val shorterList = (if (expected.size() < actual.size()) expected else actual).sort() val shorterList = (if (expected.size() < actual.size()) expected else actual).sorted()
for ((i, element) in longerList.withIndex()) { for ((i, element) in longerList.withIndex()) {
sb.append(element) sb.append(element)
sb.append(" ".repeat(maxExtStrSize - element.length())) sb.append(" ".repeat(maxExtStrSize - element.length()))
@@ -86,7 +86,7 @@ public abstract class AbstractMemberPullPushTest : JetLightCodeInsightFixtureTes
} }
catch(e: Exception) { catch(e: Exception) {
val message = when (e) { val message = when (e) {
is BaseRefactoringProcessor.ConflictsInTestsException -> e.messages.sort().joinToString("\n") is BaseRefactoringProcessor.ConflictsInTestsException -> e.messages.sorted().joinToString("\n")
is CommonRefactoringUtil.RefactoringErrorHintException -> e.getMessage()!! is CommonRefactoringUtil.RefactoringErrorHintException -> e.getMessage()!!
else -> throw e else -> throw e
} }
@@ -339,7 +339,7 @@ public abstract class AbstractJetExtractionTest() : JetLightCodeInsightFixtureTe
} }
} }
catch(e: Exception) { catch(e: Exception) {
val message = if (e is ConflictsInTestsException) e.getMessages().sort().joinToString(" ") else e.getMessage() val message = if (e is ConflictsInTestsException) e.getMessages().sorted().joinToString(" ") else e.getMessage()
JetTestUtils.assertEqualsToFile(conflictFile, message?.replace("\n", " ") ?: e.javaClass.getName()) JetTestUtils.assertEqualsToFile(conflictFile, message?.replace("\n", " ") ?: e.javaClass.getName())
} }
finally { finally {
@@ -95,7 +95,7 @@ public abstract class AbstractJetMoveTest : KotlinMultiFileTestCase() {
assert(!conflictFile.exists()) assert(!conflictFile.exists())
} }
catch(e: ConflictsInTestsException) { catch(e: ConflictsInTestsException) {
JetTestUtils.assertEqualsToFile(conflictFile, e.getMessages().sort().joinToString("\n")) JetTestUtils.assertEqualsToFile(conflictFile, e.getMessages().sorted().joinToString("\n"))
} }
finally { finally {
PsiDocumentManager.getInstance(getProject()!!).commitAllDocuments() PsiDocumentManager.getInstance(getProject()!!).commitAllDocuments()
@@ -69,7 +69,7 @@ public class JetNameSuggesterTest : LightCodeInsightFixtureTestCase() {
try { try {
JetRefactoringUtil.selectExpression(myFixture.getEditor(), file, object : JetRefactoringUtil.SelectExpressionCallback { JetRefactoringUtil.selectExpression(myFixture.getEditor(), file, object : JetRefactoringUtil.SelectExpressionCallback {
override fun run(expression: JetExpression?) { override fun run(expression: JetExpression?) {
val names = KotlinNameSuggester.suggestNamesByExpressionAndType(expression!!, expression.analyze(BodyResolveMode.PARTIAL), { true }, "value").sort() val names = KotlinNameSuggester.suggestNamesByExpressionAndType(expression!!, expression.analyze(BodyResolveMode.PARTIAL), { true }, "value").sorted()
val result = StringUtil.join(names, "\n").trim() val result = StringUtil.join(names, "\n").trim()
assertEquals(expectedResultText, result) assertEquals(expectedResultText, result)
} }
@@ -105,7 +105,7 @@ public abstract class AbstractPartialBodyResolveTest : JetLightCodeInsightFixtur
val skippedStatements = set val skippedStatements = set
.filter { !it.parents.any { it in set } } // do not include skipped statements which are inside other skipped statement .filter { !it.parents.any { it in set } } // do not include skipped statements which are inside other skipped statement
.sortBy { it.getTextOffset() } .sortedBy { it.getTextOffset() }
myFixture.getProject().executeWriteCommand("") { myFixture.getProject().executeWriteCommand("") {
for (statement in skippedStatements) { for (statement in skippedStatements) {
@@ -81,7 +81,7 @@ public abstract class AbstractReferenceResolveTest : KotlinLightPlatformCodeInsi
actualResolvedTo.add(ReferenceUtils.renderAsGotoImplementation(result.getElement()!!)) actualResolvedTo.add(ReferenceUtils.renderAsGotoImplementation(result.getElement()!!))
} }
UsefulTestCase.assertOrderedEquals("Not matching for reference #$index", actualResolvedTo.sort(), expectedReferences.sort()) UsefulTestCase.assertOrderedEquals("Not matching for reference #$index", actualResolvedTo.sorted(), expectedReferences.sorted())
} }
} }
@@ -51,6 +51,6 @@ public class KotlinReferencesSearchTest(): AbstractSearcherTest() {
private inline fun doTest<reified T: PsiElement>(): List<PsiReference> { private inline fun doTest<reified T: PsiElement>(): List<PsiReference> {
myFixture.configureByFile(getFileName()) myFixture.configureByFile(getFileName())
val func = myFixture.getElementAtCaret().getParentOfType<T>(false)!! val func = myFixture.getElementAtCaret().getParentOfType<T>(false)!!
return ReferencesSearch.search(func).findAll().sortBy { it.getElement().getTextRange().getStartOffset() } return ReferencesSearch.search(func).findAll().sortedBy { it.getElement().getTextRange().getStartOffset() }
} }
} }
@@ -189,7 +189,7 @@ public class JavaToKotlinConverter(
private fun processUsages(refs: Collection<ReferenceInfo>) { private fun processUsages(refs: Collection<ReferenceInfo>) {
for (fileRefs in refs.groupBy { it.file }.values()) { // group by file for faster sorting for (fileRefs in refs.groupBy { it.file }.values()) { // group by file for faster sorting
ReferenceLoop@ ReferenceLoop@
for ((reference, target, file, processings) in fileRefs.sortBy(ReferenceComparator)) { for ((reference, target, file, processings) in fileRefs.sortedWith(ReferenceComparator)) {
val processors = when (reference.getElement().getLanguage()) { val processors = when (reference.getElement().getLanguage()) {
JavaLanguage.INSTANCE -> processings.map { it.javaCodeProcessor }.filterNotNull() JavaLanguage.INSTANCE -> processings.map { it.javaCodeProcessor }.filterNotNull()
KotlinLanguage.INSTANCE -> processings.map { it.kotlinCodeProcessor }.filterNotNull() KotlinLanguage.INSTANCE -> processings.map { it.kotlinCodeProcessor }.filterNotNull()
@@ -143,7 +143,7 @@ class OverloadReducer(
private fun dropOverloadsForDefaultValues(equivalenceMap: Map<PsiMethod, EquivalentOverloadInfo>) { private fun dropOverloadsForDefaultValues(equivalenceMap: Map<PsiMethod, EquivalentOverloadInfo>) {
val dropCandidates = equivalenceMap val dropCandidates = equivalenceMap
.map { it.key } .map { it.key }
.sortBy { -it.getParameterList().getParametersCount() } // we will try to drop them starting from ones with more parameters .sortedBy { -it.getParameterList().getParametersCount() } // we will try to drop them starting from ones with more parameters
DropCandidatesLoop@ DropCandidatesLoop@
for (method in dropCandidates) { for (method in dropCandidates) {
@@ -314,7 +314,7 @@ public abstract class AbstractIncrementalJpsTest(
val mapping = project.dataManager.getSourceToOutputMap(target) val mapping = project.dataManager.getSourceToOutputMap(target)
mapping.sources.forEach { mapping.sources.forEach {
val outputs = mapping.getOutputs(it)!!.sort() val outputs = mapping.getOutputs(it)!!.sorted()
if (outputs.isNotEmpty()) { if (outputs.isNotEmpty()) {
result.println("source $it -> $outputs") result.println("source $it -> $outputs")
} }
@@ -640,7 +640,7 @@ public class KotlinJpsBuildTest : AbstractKotlinJpsBuildTestCase() {
"""Classpath entry points to a non-existent location: TEST_PATH/some/test.class"""), """Classpath entry points to a non-existent location: TEST_PATH/some/test.class"""),
warnings.map { warnings.map {
it.messageText.replace(File("").absolutePath, "TEST_PATH").replace("\\", "/") it.messageText.replace(File("").absolutePath, "TEST_PATH").replace("\\", "/")
}.sort().toTypedArray() }.sorted().toTypedArray()
) )
} }
@@ -53,7 +53,7 @@ fun getDirectoryString(dir: File, interestingPaths: List<String>): String {
val listFiles = dir.listFiles() val listFiles = dir.listFiles()
assertNotNull(listFiles) assertNotNull(listFiles)
val children = listFiles!!.toList().sortBy { it.getName() }.sortBy { it.isDirectory() } val children = listFiles!!.toList().sortedBy { it.getName() }.sortedBy { it.isDirectory() }
for (child in children) { for (child in children) {
if (child.isDirectory()) { if (child.isDirectory()) {
p.println(child.name) p.println(child.name)
@@ -101,7 +101,7 @@ fun assertEqualDirectories(expected: File, actual: File, forgiveExtraFiles: Bool
val commonPaths = Sets.intersection(pathsInExpected, pathsInActual) val commonPaths = Sets.intersection(pathsInExpected, pathsInActual)
val changedPaths = commonPaths val changedPaths = commonPaths
.filter { DUMP_ALL || !Arrays.equals(File(expected, it).readBytes(), File(actual, it).readBytes()) } .filter { DUMP_ALL || !Arrays.equals(File(expected, it).readBytes(), File(actual, it).readBytes()) }
.sort() .sorted()
val expectedString = getDirectoryString(expected, changedPaths) val expectedString = getDirectoryString(expected, changedPaths)
val actualString = getDirectoryString(actual, changedPaths) val actualString = getDirectoryString(actual, changedPaths)
@@ -344,7 +344,7 @@ private fun Map<TypeParameterDescriptor, JetType>.addReifiedTypeArgsTo(
val reifiedTypeArguments = SmartList<JsExpression>() val reifiedTypeArguments = SmartList<JsExpression>()
val patternTranslator = PatternTranslator.newInstance(context) val patternTranslator = PatternTranslator.newInstance(context)
for (param in keySet().sortBy { it.getIndex() }) { for (param in keySet().sortedBy { it.getIndex() }) {
if (!param.isReified()) continue if (!param.isReified()) continue
val argumentType = get(param) val argumentType = get(param)
@@ -67,7 +67,7 @@ public abstract class AndroidLayoutXmlFileManager(val project: Project) {
val layoutNameToXmls = allLayoutPsiFiles val layoutNameToXmls = allLayoutPsiFiles
.groupBy { it.name.substringBeforeLast('.') } .groupBy { it.name.substringBeforeLast('.') }
.mapValues { it.getValue().sortBy { it.parent!!.name.length() } } .mapValues { it.getValue().sortedBy { it.parent!!.name.length() } }
return layoutNameToXmls return layoutNameToXmls
} }
@@ -19,7 +19,7 @@ package org.jetbrains.kotlin.android.synthetic.res
import org.jetbrains.kotlin.android.synthetic.AndroidConst import org.jetbrains.kotlin.android.synthetic.AndroidConst
public data class AndroidModuleInfo(val applicationPackage: String, resDirectories: List<String>) { public data class AndroidModuleInfo(val applicationPackage: String, resDirectories: List<String>) {
val resDirectories = resDirectories.sort() val resDirectories = resDirectories.sorted()
} }
public abstract class AndroidResource(val id: String) { public abstract class AndroidResource(val id: String) {