Cleanup RC deprecations in compiler and plugin.

This commit is contained in:
Ilya Gorbunov
2016-01-26 21:53:07 +03:00
parent c7a0375c25
commit 744a7a83f7
68 changed files with 92 additions and 86 deletions
@@ -40,7 +40,7 @@ abstract class ArgumentGenerator {
val actualArgsWithDeclIndex = actualArgs.filter { it !is DefaultValueArgument }.map {
ArgumentAndDeclIndex(it, arg2Index[it]!!)
}.toArrayList()
}.toMutableList()
valueArgumentsByIndex.withIndex().forEach {
if (it.value is DefaultValueArgument) {
@@ -38,7 +38,7 @@ class DefaultImplsClassContext(
override fun getAccessors(): Collection<AccessorForCallableDescriptor<*>> {
val accessors = super.getAccessors()
val alreadyExistKeys = accessors.map ({ Pair(it.calleeDescriptor, it.superCallTarget) })
val filtered = interfaceContext.accessors.toMapBy({ Pair(it.calleeDescriptor, it.superCallTarget) }, { it }) - alreadyExistKeys
val filtered = interfaceContext.accessors.associateByTo(linkedMapOf()) { Pair(it.calleeDescriptor, it.superCallTarget) }.apply { keys -= alreadyExistKeys }
return accessors + filtered.values
}
}
@@ -38,7 +38,7 @@ object PluginCliParser {
javaClass.classLoader
)
val componentRegistrars = ServiceLoader.load(ComponentRegistrar::class.java, classLoader).toArrayList()
val componentRegistrars = ServiceLoader.load(ComponentRegistrar::class.java, classLoader).toMutableList()
componentRegistrars.addAll(BundledCompilerPlugins.componentRegistrars)
configuration.addAll(ComponentRegistrar.PLUGIN_COMPONENT_REGISTRARS, componentRegistrars)
@@ -55,11 +55,11 @@ object PluginCliParser {
it.pluginId
} ?: mapOf()
val commandLineProcessors = ServiceLoader.load(CommandLineProcessor::class.java, classLoader).toArrayList()
val commandLineProcessors = ServiceLoader.load(CommandLineProcessor::class.java, classLoader).toMutableList()
commandLineProcessors.addAll(BundledCompilerPlugins.commandLineProcessors)
for (processor in commandLineProcessors) {
val declaredOptions = processor.pluginOptions.toMapBy { it.name }
val declaredOptions = processor.pluginOptions.associateBy { it.name }
val optionsToValues = MultiMap<CliOption, CliOptionValue>()
for (optionValue in optionValuesByPlugin[processor.pluginId].orEmpty()) {
@@ -47,7 +47,7 @@ interface Conditional {
companion object {
val ANNOTATIONS: Map<String, Parser> = listOf<Parser>(JvmVersion, JsVersion, TargetName).toMapBy { it.name }
val ANNOTATIONS: Map<String, Parser> = listOf<Parser>(JvmVersion, JsVersion, TargetName).associateBy { it.name }
}
}
@@ -25,7 +25,7 @@ data class Modification(val range: TextRange, val apply: (String) -> String)
class CollectModificationsVisitor(evaluators: List<Evaluator>) : KtTreeVisitorVoid() {
val elementModifications: Map<Evaluator, MutableList<Modification>> =
evaluators.toMapBy(selector = { it }, transform = { arrayListOf<Modification>() })
evaluators.associateBy(keySelector = { it }, valueTransform = { arrayListOf<Modification>() })
override fun visitDeclaration(declaration: KtDeclaration) {
super.visitDeclaration(declaration)
@@ -36,7 +36,7 @@ fun createJvmProfile(targetRoot: File, version: Int): Profile = Profile("JVM$ver
fun createJsProfile(targetRoot: File): Profile = Profile("JS", JsPlatformEvaluator(), File(targetRoot, "js"))
val profileEvaluators: Map<String, () -> Evaluator> =
listOf(6, 7, 8).toMapBy({ version -> "JVM$version" }, { version -> { JvmPlatformEvaluator(version) } }) + ("JS" to { JsPlatformEvaluator() })
listOf(6, 7, 8).associateBy({ version -> "JVM$version" }, { version -> { JvmPlatformEvaluator(version) } }) + ("JS" to { JsPlatformEvaluator() })
fun createProfile(name: String, targetRoot: File): Profile {
val (profileName, evaluator) = profileEvaluators.entries.firstOrNull { it.key.equals(name, ignoreCase = true) } ?: throw IllegalArgumentException("Profile with name '$name' is not supported")
@@ -102,7 +102,7 @@ private fun collectInterfacesRecursive(type: Type, result: MutableSet<Type>) {
private fun getRegistrations(klass: Class<*>): List<Type> {
val registrations = ArrayList<Type>()
val superClasses = sequence<Type>(klass) {
val superClasses = generateSequence<Type>(klass) {
when (it) {
is Class<*> -> it.genericSuperclass
is ParameterizedType -> (it.rawType as? Class<*>)?.genericSuperclass
@@ -28,6 +28,7 @@ import java.io.PrintStream
import java.rmi.server.UnicastRemoteObject
import java.util.concurrent.Semaphore
import java.util.concurrent.TimeUnit
import kotlin.comparisons.*
import kotlin.concurrent.thread
@@ -216,7 +217,7 @@ object KotlinCompilerClient {
val memBefore = daemon.getUsedMemory().get() / 1024
val startTime = System.nanoTime()
val res = daemon.remoteCompile(CompileService.NO_SESSION, CompileService.TargetPlatform.JVM, filteredArgs.toArrayList().toTypedArray(), servicesFacade, outStrm, CompileService.OutputFormat.PLAIN, outStrm, null)
val res = daemon.remoteCompile(CompileService.NO_SESSION, CompileService.TargetPlatform.JVM, filteredArgs.toList().toTypedArray(), servicesFacade, outStrm, CompileService.OutputFormat.PLAIN, outStrm, null)
val endTime = System.nanoTime()
println("Compilation result code: $res")
@@ -39,6 +39,7 @@ import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.locks.ReentrantReadWriteLock
import java.util.logging.Level
import java.util.logging.Logger
import kotlin.comparisons.*
import kotlin.concurrent.read
import kotlin.concurrent.schedule
import kotlin.concurrent.write
@@ -303,7 +304,7 @@ class CompileServiceImpl(
synchronized(state.sessions) {
// 2. check if any session hanged - clean
// making copy of the list before calling release
state.sessions.filterValues { !it.isAlive }.keys.toArrayList()
state.sessions.filterValues { !it.isAlive }.keys.toList()
}.forEach { releaseCompileSession(it) }
// 3. check if in graceful shutdown state and all sessions are closed
@@ -47,7 +47,7 @@ class LazyClasspathWatcher(classpath: Iterable<String>,
private data class FileId(val file: File, val lastModified: Long, val digest: ByteArray)
private val fileIdsLock = Semaphore(1) // a barrier for ensuring ids are initialized, using semaphore to allow modifications from another thread
private var fileIds: ArrayList<FileId>? = null
private var fileIds: List<FileId>? = null
private val lastChangedStatus = AtomicBoolean(false)
private val lastUpdate = AtomicLong(0)
private val lastDigestUpdate = AtomicLong(0)
@@ -63,7 +63,7 @@ class LazyClasspathWatcher(classpath: Iterable<String>,
.asSequence()
.flatMap { it.walk().filter(::isClasspathFile) }
.map { FileId(it, it.lastModified(), it.md5Digest()) }
.toArrayList()
.toList()
val nowMs = TimeUnit.MILLISECONDS.toMillis(System.nanoTime())
lastUpdate.set(nowMs)
lastDigestUpdate.set(nowMs)
@@ -108,7 +108,7 @@ class SamAdapterFunctionsScope(storageManager: StorageManager) : SyntheticScope
sourceFunction.original.source)
descriptor.sourceFunction = sourceFunction
val sourceTypeParams = (sourceFunction.typeParameters).toArrayList()
val sourceTypeParams = (sourceFunction.typeParameters).toMutableList()
val ownerClass = sourceFunction.containingDeclaration as ClassDescriptor
//TODO: should we go up parents for getters/setters too?
//TODO: non-inner classes
@@ -69,7 +69,7 @@ fun KtSimpleNameExpression.getQualifiedElement(): KtElement {
}
fun KtSimpleNameExpression.getTopmostParentQualifiedExpressionForSelector(): KtQualifiedExpression? {
return sequence<KtExpression>(this) {
return generateSequence<KtExpression>(this) {
val parentQualified = it.parent as? KtQualifiedExpression
if (parentQualified?.selectorExpression == it) parentQualified else null
}.last() as? KtQualifiedExpression
@@ -60,7 +60,7 @@ fun PsiElement.siblings(forward: Boolean = true, withItself: Boolean = true): Se
}
val PsiElement.parentsWithSelf: Sequence<PsiElement>
get() = sequence(this) { if (it is PsiFile) null else it.parent }
get() = generateSequence(this) { if (it is PsiFile) null else it.parent }
val PsiElement.parents: Sequence<PsiElement>
get() = parentsWithSelf.drop(1)
@@ -72,10 +72,10 @@ fun PsiElement.nextLeaf(skipEmptyElements: Boolean = false): PsiElement?
= PsiTreeUtil.nextLeaf(this, skipEmptyElements)
val PsiElement.prevLeafs: Sequence<PsiElement>
get() = sequence({ prevLeaf() }, { it.prevLeaf() })
get() = generateSequence({ prevLeaf() }, { it.prevLeaf() })
val PsiElement.nextLeafs: Sequence<PsiElement>
get() = sequence({ nextLeaf() }, { it.nextLeaf() })
get() = generateSequence({ nextLeaf() }, { it.nextLeaf() })
fun PsiElement.prevLeaf(filter: (PsiElement) -> Boolean): PsiElement? {
var leaf = prevLeaf()
@@ -45,7 +45,7 @@ fun KtReturnExpression.getTargetFunctionDescriptor(context: BindingContext): Fun
val containingFunctionDescriptor = DescriptorUtils.getParentOfType(declarationDescriptor, FunctionDescriptor::class.java, false)
if (containingFunctionDescriptor == null) return null
return sequence(containingFunctionDescriptor) { DescriptorUtils.getParentOfType(it, FunctionDescriptor::class.java) }
return generateSequence(containingFunctionDescriptor) { DescriptorUtils.getParentOfType(it, FunctionDescriptor::class.java) }
.dropWhile { it is AnonymousFunctionDescriptor }
.firstOrNull()
}
@@ -481,7 +481,7 @@ class TypeResolver(
}
private fun ClassifierDescriptor?.classDescriptorChain(): List<ClassDescriptor>
= sequence({ this as? ClassDescriptor }, { it.containingDeclaration as? ClassDescriptor }).toList()
= generateSequence({ this as? ClassDescriptor }, { it.containingDeclaration as? ClassDescriptor }).toList()
private fun TypeParameterDescriptor.isDeclaredInScope(c: TypeResolutionContext): Boolean {
assert(containingDeclaration is ClassDescriptor) { "This function is implemented for classes only, but $containingDeclaration was given" }
@@ -499,7 +499,7 @@ class TypeResolver(
}
private fun DeclarationDescriptor.isInsideOfClass(classDescriptor: ClassDescriptor)
= sequence(this, { it.containingDeclaration }).any { it.original == classDescriptor }
= generateSequence(this, { it.containingDeclaration }).any { it.original == classDescriptor }
private fun resolveTypeProjectionsWithErrorConstructor(
@@ -105,7 +105,7 @@ fun Call.getValueArgumentForExpression(expression: KtExpression): ValueArgument?
else -> null
}
}
fun KtElement.isParenthesizedExpression() = sequence(this) { it.deparenthesizeStructurally() }.any { it == expression }
fun KtElement.isParenthesizedExpression() = generateSequence(this) { it.deparenthesizeStructurally() }.any { it == expression }
return valueArguments.firstOrNull { it?.getArgumentExpression()?.isParenthesizedExpression() ?: false }
}
@@ -27,7 +27,7 @@ import org.jetbrains.kotlin.util.collectionUtils.concat
import org.jetbrains.kotlin.utils.Printer
val HierarchicalScope.parentsWithSelf: Sequence<HierarchicalScope>
get() = sequence(this) { it.parent }
get() = generateSequence(this) { it.parent }
val HierarchicalScope.parents: Sequence<HierarchicalScope>
get() = parentsWithSelf.drop(1)
@@ -34,7 +34,7 @@ class TestStdlibWithDxTest {
private fun doTest(file: File) {
val zip = ZipInputStream(FileInputStream(file))
zip.use {
sequence { zip.nextEntry }.forEach {
generateSequence { zip.nextEntry }.forEach {
if (it.name.endsWith(".class")) {
DxChecker.checkFileWithDx(zip.readBytes(), it.name)
}
@@ -67,7 +67,7 @@ interface AbstractSMAPBaseTest {
}.map {
val smap = it.value.mapNotNull { it.smap?.replaceHash() }.joinToString("\n")
SMAPAndFile(if (smap.isNotEmpty()) smap else null, it.key)
}.toMapBy { it.sourceFile }
}.associateBy { it.sourceFile }
for (source in sourceData) {
val data = compiledData[source.sourceFile]
@@ -80,7 +80,7 @@ class LazyJavaAnnotationDescriptor(
val constructors = getAnnotationClass().constructors
if (constructors.isEmpty()) return mapOf()
val nameToArg = javaAnnotation.arguments.toMapBy { it.name }
val nameToArg = javaAnnotation.arguments.associateBy { it.name }
return constructors.first().valueParameters.keysToMapExceptNulls { valueParameter ->
var javaAnnotationArgument = nameToArg[valueParameter.getName()]
@@ -604,11 +604,11 @@ class LazyJavaClassMemberScope(
}
private val nestedClassIndex = c.storageManager.createLazyValue {
jClass.innerClasses.toMapBy { c -> c.name }
jClass.innerClasses.associateBy { c -> c.name }
}
private val enumEntryIndex = c.storageManager.createLazyValue {
jClass.fields.filter { it.isEnumEntry }.toMapBy { f -> f.name }
jClass.fields.filter { it.isEnumEntry }.associateBy { f -> f.name }
}
private val nestedClasses = c.storageManager.createMemoizedFunctionWithNullableValues {
@@ -58,7 +58,7 @@ open class ClassMemberIndex(val jClass: JavaClass, val memberFilter: (JavaMember
}
private val methods = jClass.methods.asSequence().filter(methodFilter).groupBy { m -> m.name }
private val fields = jClass.fields.asSequence().filter(memberFilter).toMapBy { m -> m.name }
private val fields = jClass.fields.asSequence().filter(memberFilter).associateBy { m -> m.name }
override fun findMethodsByName(name: Name): Collection<JavaMethod> = methods[name] ?: listOf()
override fun getMethodNames(nameFilter: (Name) -> Boolean): Collection<Name> =
@@ -131,7 +131,7 @@ class JvmNameResolver(
"kotlin/collections/ListIterator", "kotlin/collections/MutableListIterator"
)
private val PREDEFINED_STRINGS_MAP = PREDEFINED_STRINGS.withIndex().toMapBy({ it.value }, { it.index })
private val PREDEFINED_STRINGS_MAP = PREDEFINED_STRINGS.withIndex().associateBy({ it.value }, { it.index })
fun getPredefinedStringIndex(string: String): Int? = PREDEFINED_STRINGS_MAP[string]
}
@@ -37,7 +37,7 @@ class KotlinClassHeader(
MULTIFILE_CLASS_PART(5);
companion object {
private val entryById = values().toMapBy(Kind::id)
private val entryById = values().associateBy(Kind::id)
@JvmStatic
fun getById(id: Int) = entryById[id] ?: UNKNOWN
@@ -45,7 +45,7 @@ class ReflectJavaClassifierType(public override val type: Type) : ReflectJavaTyp
override fun isRaw(): Boolean = with(type) { this is Class<*> && getTypeParameters().isNotEmpty() }
override fun getTypeArguments(): List<JavaType> {
return sequence({type as? ParameterizedType}, { it.ownerType as? ParameterizedType }).flatMap {
return generateSequence({type as? ParameterizedType}, { it.ownerType as? ParameterizedType }).flatMap {
it.actualTypeArguments.asSequence().map { ReflectJavaType.create(it) }
}.toList()
}
@@ -52,7 +52,7 @@ class BuiltinsPackageFragment(
override val nameResolver = NameResolverImpl(builtinsMessage.strings, builtinsMessage.qualifiedNames)
override val classIdToProto =
builtinsMessage.classList.toMapBy { klass ->
builtinsMessage.classList.associateBy { klass ->
nameResolver.getClassId(klass.fqName)
}
@@ -192,7 +192,7 @@ fun Annotated.getAnnotationRetention(): KotlinRetention? {
}
val DeclarationDescriptor.parentsWithSelf: Sequence<DeclarationDescriptor>
get() = sequence(this, { it.containingDeclaration })
get() = generateSequence(this, { it.containingDeclaration })
val DeclarationDescriptor.parents: Sequence<DeclarationDescriptor>
get() = parentsWithSelf.drop(1)
@@ -127,6 +127,8 @@ open class DelegatingFlexibleType protected constructor(
if (lowerBound == upperBound) return lowerBound
return DelegatingFlexibleType(lowerBound, upperBound, extraCapabilities)
}
internal val ASSERTIONS_ENABLED = DelegatingFlexibleType::class.java.desiredAssertionStatus()
}
// These assertions are needed for checking invariants of flexible types.
@@ -49,7 +49,7 @@ class AnnotationDeserializer(private val module: ModuleDescriptor) {
if (proto.argumentCount != 0 && !ErrorUtils.isError(annotationClass) && DescriptorUtils.isAnnotationClass(annotationClass)) {
val constructor = annotationClass.constructors.singleOrNull()
if (constructor != null) {
val parameterByName = constructor.valueParameters.toMapBy { it.name }
val parameterByName = constructor.valueParameters.associateBy { it.name }
arguments = proto.argumentList.map { resolveArgument(it, parameterByName, nameResolver) }.filterNotNull().toMap()
}
}
@@ -287,7 +287,7 @@ class DeserializedClassDescriptor(
}
private inner class EnumEntryClassDescriptors {
private val enumEntryProtos = classProto.enumEntryList.toMapBy { c.nameResolver.getName(it.name) }
private val enumEntryProtos = classProto.enumEntryList.associateBy { c.nameResolver.getName(it.name) }
private val protoContainer =
ProtoContainer.Class(classProto, c.nameResolver, c.typeTable, (containingDeclaration as? ClassDescriptor)?.kind)
@@ -19,7 +19,7 @@ package org.jetbrains.kotlin.utils
import java.util.*
fun <K, V> Iterable<K>.keysToMap(value: (K) -> V): Map<K, V> {
return toMapBy({ it }, value)
return associateBy({ it }, value)
}
fun <K, V: Any> Iterable<K>.keysToMapExceptNulls(value: (K) -> V?): Map<K, V> {
@@ -63,7 +63,7 @@ class GenerateProtoBufCompare {
private val extensionsMap = DebugJvmProtoBuf.getDescriptor().extensions.groupBy { it.containingType }
private val allMessages: MutableSet<Descriptors.Descriptor> = linkedSetOf()
private val messagesToProcess: Queue<Descriptors.Descriptor> = linkedListOf()
private val messagesToProcess: Queue<Descriptors.Descriptor> = LinkedList()
private val repeatedFields: MutableSet<Descriptors.FieldDescriptor> = linkedSetOf()
fun generate(): String {
@@ -73,7 +73,7 @@ class ExtractableSubstringInfo(
get() = contentRange.shiftRight(-template.startOffset)
val entries: Sequence<KtStringTemplateEntry>
get() = sequence(startEntry) { if (it != endEntry) it.nextSiblingOfSameType() else null }
get() = generateSequence(startEntry) { if (it != endEntry) it.nextSiblingOfSameType() else null }
fun createExpression(): KtExpression {
val quote = template.firstChild.text
@@ -142,7 +142,7 @@ class FuzzyType(
if (otherSubstitutedType.isError) return null
if (!substitutedType.checkInheritance(otherSubstitutedType)) return null
val substitution = constraintSystem.typeVariables.map { it.originalTypeParameter }.toMapBy({ it.typeConstructor }) {
val substitution = constraintSystem.typeVariables.map { it.originalTypeParameter }.associateBy({ it.typeConstructor }) {
val type = it.defaultType
val solution = substitutor.substitute(type, Variance.INVARIANT)
TypeProjectionImpl(if (solution != null && !ErrorUtils.containsUninferredParameter(solution)) solution else type)
@@ -883,7 +883,7 @@ class KotlinPsiUnifier(
}
}
private val descriptorToParameter = parameters.toMapBy { (it.descriptor as? DeclarationDescriptorWithSource)?.source?.getPsi() }
private val descriptorToParameter = parameters.associateBy { (it.descriptor as? DeclarationDescriptorWithSource)?.source?.getPsi() }
private fun PsiElement.unwrap(): PsiElement? {
return when (this) {
@@ -88,7 +88,7 @@ class TypeClsStubBuilder(private val c: ClsStubBuilderContext) {
return
}
createTypeAnnotationStubs(parent, annotations)
val outerTypeChain = sequence(type) { it.outerType(c.typeTable) }.toList()
val outerTypeChain = generateSequence(type) { it.outerType(c.typeTable) }.toList()
createStubForTypeName(classId, parent) {
userTypeStub, index ->
@@ -110,7 +110,7 @@ private fun setupFileStub(fileStub: KotlinFileStubImpl, packageFqName: FqName) {
}
fun createStubForPackageName(packageDirectiveStub: KotlinPlaceHolderStubImpl<KtPackageDirective>, packageFqName: FqName) {
val segments = packageFqName.pathSegments().toArrayList()
val segments = packageFqName.pathSegments()
val iterator = segments.listIterator(segments.size)
fun recCreateStubForPackageName(current: StubElement<out PsiElement>) {
@@ -26,6 +26,7 @@ import org.jetbrains.kotlin.resolve.calls.inference.InferenceErrorData
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ConflictingJvmDeclarationsData
import org.jetbrains.kotlin.types.KotlinType
import kotlin.comparisons.*
object IdeRenderers {
@@ -43,8 +44,7 @@ object IdeRenderers {
@JvmField val HTML_NONE_APPLICABLE_CALLS: Renderer<Collection<ResolvedCall<*>>> = Renderer {
calls: Collection<ResolvedCall<*>> ->
// TODO: compareBy(comparator, selector) in stdlib
val comparator = comparator<ResolvedCall<*>> { c1, c2 -> MemberComparator.INSTANCE.compare(c1.resultingDescriptor, c2.resultingDescriptor) }
val comparator = compareBy(MemberComparator.INSTANCE) { c: ResolvedCall<*> -> c.resultingDescriptor }
calls
.sortedWith(comparator)
.joinToString("") { "<li>" + renderResolvedCall(it) + "</li>" }
@@ -59,7 +59,7 @@ abstract class SelfTargetingIntention<TElement : KtElement>(
val leaf2 = file.findElementAt(offset - 1)
val commonParent = if (leaf1 != null && leaf2 != null) PsiTreeUtil.findCommonParent(leaf1, leaf2) else null
var elementsToCheck: Sequence<PsiElement> = sequence { null }
var elementsToCheck: Sequence<PsiElement> = emptySequence()
if (leaf1 != null) {
elementsToCheck += leaf1.parentsWithSelf.takeWhile { it != commonParent }
}
@@ -55,22 +55,22 @@ class CommentSaver(originalElements: PsiChildRange, private val saveLineBreaks:
var lastChild: TreeElement? = null
val children: Sequence<TreeElement>
get() = sequence({ firstChild }, { it.next })
get() = generateSequence({ firstChild }, { it.next })
val reverseChildren: Sequence<TreeElement>
get() = sequence({ lastChild }, { it.prev })
get() = generateSequence({ lastChild }, { it.prev })
val prevSiblings: Sequence<TreeElement>
get() = sequence({ prev }, { it.prev })
get() = generateSequence({ prev }, { it.prev })
val nextSiblings: Sequence<TreeElement>
get() = sequence({ next }, { it.next })
get() = generateSequence({ next }, { it.next })
val parents: Sequence<TreeElement>
get() = sequence({ parent }, { it.parent })
get() = generateSequence({ parent }, { it.parent })
val parentsWithSelf: Sequence<TreeElement>
get() = sequence(this, { it.parent })
get() = generateSequence(this, { it.parent })
val firstLeafInside: TreeElement
get() {
@@ -101,10 +101,10 @@ class CommentSaver(originalElements: PsiChildRange, private val saveLineBreaks:
}
val prevLeafs: Sequence<TreeElement>
get() = sequence({ prevLeaf }, { it.prevLeaf })
get() = generateSequence({ prevLeaf }, { it.prevLeaf })
val nextLeafs: Sequence<TreeElement>
get() = sequence({ nextLeaf }, { it.nextLeaf })
get() = generateSequence({ nextLeaf }, { it.nextLeaf })
fun withDescendants(leftToRight: Boolean): Sequence<TreeElement> {
val children = if (leftToRight) children else reverseChildren
@@ -462,7 +462,7 @@ class KotlinCompletionContributor : CompletionContributor() {
private fun isInUnclosedSuperQualifier(tokenBefore: PsiElement?): Boolean {
if (tokenBefore == null) return false
val tokensToSkip = TokenSet.orSet(TokenSet.create(KtTokens.IDENTIFIER, KtTokens.DOT ), KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET)
val tokens = sequence(tokenBefore) { it.prevLeaf() }
val tokens = generateSequence(tokenBefore) { it.prevLeaf() }
val ltToken = tokens.firstOrNull { it.node.elementType !in tokensToSkip } ?: return false
if (ltToken.node.elementType != KtTokens.LT) return false
val superToken = ltToken.prevLeaf { it !is PsiWhiteSpace && it !is PsiComment }
@@ -52,7 +52,7 @@ fun Call.mapArgumentsToParameters(targetDescriptor: CallableDescriptor): Map<Val
if (parameters.isEmpty()) return emptyMap()
val map = HashMap<ValueArgument, ValueParameterDescriptor>()
val parametersByName = parameters.toMapBy { it.name }
val parametersByName = parameters.associateBy { it.name }
var positionalArgumentIndex: Int? = 0
@@ -26,7 +26,7 @@ import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
class KotlinExpressionTypeProvider : ExpressionTypeProvider<KtExpression>() {
override fun getExpressionsAt(elementAt: PsiElement): List<KtExpression> =
elementAt.parentsWithSelf.filterIsInstance<KtExpression>().filterNot { it.shouldSkip() }.toArrayList()
elementAt.parentsWithSelf.filterIsInstance<KtExpression>().filterNot { it.shouldSkip() }.toList()
private fun KtExpression.shouldSkip(): Boolean {
return this is KtStatementExpression && this !is KtFunction
@@ -130,7 +130,7 @@ class KotlinUnusedImportInspection : AbstractKotlinInspection() {
val optimizedImports = KotlinImportOptimizer.prepareOptimizedImports(file, descriptorsToImport) ?: return // return if already optimized
// unwrap progress indicator
val progress = sequence(ProgressManager.getInstance().progressIndicator) {
val progress = generateSequence(ProgressManager.getInstance().progressIndicator) {
(it as? ProgressWrapper)?.originalProgressIndicator
}.last() as DaemonProgressIndicator
val highlightingSession = HighlightingSessionImpl.getHighlightingSession(file, progress)
@@ -44,7 +44,7 @@ open class AddStarProjectionsFix private constructor(element: KtUserType,
public override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val diagnosticWithParameters = Errors.NO_TYPE_ARGUMENTS_ON_RHS.cast(diagnostic)
val typeElement: KtTypeElement = diagnosticWithParameters.psiElement.typeElement ?: return null
val unwrappedType = sequence(typeElement) { (it as? KtNullableType)?.innerType }.lastOrNull() as? KtUserType ?: return null
val unwrappedType = generateSequence(typeElement) { (it as? KtNullableType)?.innerType }.lastOrNull() as? KtUserType ?: return null
return AddStarProjectionsFix(unwrappedType, diagnosticWithParameters.a)
}
}
@@ -83,7 +83,7 @@ open class KotlinChangeInfo(
field = value
}
private val newParameters = parameterInfos.toArrayList()
private val newParameters = parameterInfos.toMutableList()
private val originalPsiMethods = method.toLightMethods()
private val originalParameters = (method as? KtFunction)?.valueParameters ?: emptyList()
@@ -323,7 +323,7 @@ open class KotlinChangeInfo(
val defaultValueCount = parameters.count { getDefaultValue(it) != null }
if (psiMethods.size != defaultValueCount + 1) return emptyList()
val mandatoryParams = parameters.toArrayList()
val mandatoryParams = parameters.toMutableList()
val defaultValues = ArrayList<KtExpression>()
return psiMethods.map {
JvmOverloadSignature(it, mandatoryParams.map(getPsi).toSet(), defaultValues.toSet()).apply {
@@ -360,7 +360,7 @@ open class KotlinChangeInfo(
currentPsiMethods.singleOrNull()?.let { method -> return originalPsiMethods.keysToMap { method } }
val currentSignatures = initCurrentSignatures(currentPsiMethods)
return originalSignatures.toMapBy({ it.method }) { originalSignature ->
return originalSignatures.associateBy({ it.method }) { originalSignature ->
var constrainedCurrentSignatures = currentSignatures.map { it.constrainBy(originalSignature) }
val maxMandatoryCount = constrainedCurrentSignatures.maxBy { it.mandatoryParams.size }!!.mandatoryParams.size
constrainedCurrentSignatures = constrainedCurrentSignatures.filter { it.mandatoryParams.size == maxMandatoryCount }
@@ -602,7 +602,7 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor {
caller: KtNamedDeclaration,
callerDescriptor: DeclarationDescriptor) {
val valueParameters = caller.getValueParameters()
val existingParameters = valueParameters.toMapBy { it.name }
val existingParameters = valueParameters.associateBy { it.name }
val signature = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_IN_TYPES.render(callerDescriptor)
for (parameterInfo in changeInfo.getNonReceiverParameters()) {
if (!(parameterInfo.isNewParameter)) continue
@@ -85,7 +85,7 @@ class KotlinMethodNode(
is PsiMethod -> myMethod.getJavaMethodDescriptor() ?: return
else -> throw AssertionError("Invalid declaration: ${myMethod.getElementTextWithContext()}")
}
val containerName = sequence<DeclarationDescriptor>(descriptor) { it.containingDeclaration }
val containerName = generateSequence<DeclarationDescriptor>(descriptor) { it.containingDeclaration }
.firstOrNull { it is ClassDescriptor }
?.name
@@ -123,7 +123,7 @@ fun ExtractionGeneratorConfiguration.getDeclarationPattern(
return buildSignature(this, descriptorRenderer).let { builder ->
builder.transform {
for (i in sequence(indexOf('$')) { indexOf('$', it + 2) }) {
for (i in generateSequence(indexOf('$')) { indexOf('$', it + 2) }) {
if (i < 0) break
insert(i + 1, '$')
}
@@ -286,7 +286,7 @@ private fun makeCall(
else -> calleeName
}
val anchorInBlock = sequence(anchor) { it.parent }.firstOrNull { it.parent is KtBlockExpression }
val anchorInBlock = generateSequence(anchor) { it.parent }.firstOrNull { it.parent is KtBlockExpression }
val block = (anchorInBlock?.parent as? KtBlockExpression) ?: anchorParent
val psiFactory = KtPsiFactory(anchor.project)
@@ -64,7 +64,7 @@ private fun getApplicableComponentFunctions(
val psiFactory = KtPsiFactory(contextExpression)
@Suppress("UNCHECKED_CAST")
return sequence(1) { it + 1 }
return generateSequence(1) { it + 1 }
.map {
val componentCallExpr = psiFactory.createExpressionByPattern("$0.$1", receiverExpression ?: contextExpression, "component$it()")
val newContext = componentCallExpr.analyzeInContext(scope, contextExpression)
@@ -698,7 +698,7 @@ fun <ListType : KtElement> replaceListPsiAndKeepDelimiters(
): ListType {
originalList.children.takeWhile { it is PsiErrorElement }.forEach { it.delete() }
val oldParameters = originalList.itemsFun().toArrayList()
val oldParameters = originalList.itemsFun().toMutableList()
val newParameters = newList.itemsFun()
val oldCount = oldParameters.size
val newCount = newParameters.size
@@ -348,7 +348,7 @@ class MoveKotlinDeclarationsProcessor(
}
try {
val usageList = usages.toArrayList()
val usageList = usages.toList()
descriptor.delegate.preprocessUsages(project, usageList)
@@ -160,7 +160,7 @@ private fun KotlinPullUpData.checkVisibility(
}
val member = memberInfo.member
val childrenToCheck = member.allChildren.toArrayList()
val childrenToCheck = member.allChildren.toMutableList()
if (memberInfo.isToAbstract && member is KtCallableDeclaration) {
when (member) {
is KtNamedFunction -> childrenToCheck.remove(member.bodyExpression as PsiElement?)
@@ -103,7 +103,7 @@ class KotlinCreateTestIntention : SelfTargetingRangeIntention<KtNamedDeclaration
private fun getTempJavaClassName(project: Project, kotlinFile: VirtualFile): String {
val baseName = kotlinFile.nameWithoutExtension
val psiDir = kotlinFile.parent!!.toPsiDirectory(project)!!
return sequence(0) { it + 1 }
return generateSequence(0) { it + 1 }
.map { "$baseName$it" }
.first { psiDir.findFile("$it.java") == null && findTestClass(psiDir, it) == null }
}
@@ -350,7 +350,7 @@ class ImportInsertHelperImpl(private val project: Project) : ImportInsertHelper(
private fun detectNeededImports(importedClasses: Collection<ClassifierDescriptor>): Set<ClassifierDescriptor> {
if (importedClasses.isEmpty()) return setOf()
val classesToCheck = importedClasses.map { it.name to it }.toMap().toLinkedMap()
val classesToCheck = importedClasses.associateByTo(mutableMapOf()) { it.name }
val result = LinkedHashSet<ClassifierDescriptor>()
file.accept(object : KtVisitorVoid() {
override fun visitElement(element: PsiElement) {
@@ -77,7 +77,7 @@ abstract class AbstractInspectionTest : KotlinLightCodeInsightFixtureTestCase()
null
}
else if (file.extension != "kt") {
val filePath = file.relativeToFile(srcDir).invariantSeparatorsPath
val filePath = file.relativeTo(srcDir).invariantSeparatorsPath
configureByFile(filePath)
}
else {
@@ -61,7 +61,7 @@ abstract class AbstractMemberPullPushTest : KotlinLightCodeInsightFixtureTestCas
val extraFiles = mainFile.parentFile.listFiles { file, name ->
name != mainFileName && name.startsWith("$mainFileBaseName.") && (name.endsWith(".kt") || name.endsWith(".java"))
}
val extraFilesToPsi = extraFiles.toMapBy { fixture.configureByFile(it.name) }
val extraFilesToPsi = extraFiles.associateBy { fixture.configureByFile(it.name) }
val file = fixture.configureByFile(mainFileName)
val addKotlinRuntime = InTextDirectivesUtils.findStringWithPrefixes(file.text, "// WITH_RUNTIME") != null
@@ -44,7 +44,7 @@ abstract class AbstractInlineTest : KotlinLightCodeInsightFixtureTestCase() {
val extraFiles = mainFile.parentFile.listFiles { file, name ->
name != mainFileName && name.startsWith("$mainFileBaseName.") && (name.endsWith(".kt") || name.endsWith(".java"))
}
val extraFilesToPsi = extraFiles.toMapBy { fixture.configureByFile(path.replace(mainFileName, it.name)) }
val extraFilesToPsi = extraFiles.associateBy { fixture.configureByFile(path.replace(mainFileName, it.name)) }
val file = myFixture.configureByFile(path)
val afterFileExists = afterFile.exists()
@@ -319,7 +319,7 @@ abstract class AbstractExtractionTest() : KotlinLightCodeInsightFixtureTestCase(
val extraFiles = mainFile.parentFile.listFiles { file, name ->
name != mainFileName && name.startsWith("$mainFileBaseName.") && (name.endsWith(".kt") || name.endsWith(".java"))
}
val extraFilesToPsi = extraFiles.toMapBy { fixture.configureByFile(it.name) }
val extraFilesToPsi = extraFiles.associateBy { fixture.configureByFile(it.name) }
val file = fixture.configureByFile(mainFileName)
val addKotlinRuntime = InTextDirectivesUtils.findStringWithPrefixes(file.text, "// WITH_RUNTIME") != null
@@ -107,7 +107,7 @@ class JavaToKotlinConverter(
val intermediateResults = processor.processItems(0.25, inputElements) { inputElement ->
Converter.create(inputElement, settings, services, ::inConversionScope, usageProcessingCollector).convert()
}.toArrayList()
}.toMutableList()
val results = processor.processItems(0.25, intermediateResults.withIndex()) { pair ->
val (i, result) = pair
@@ -830,7 +830,7 @@ private fun withSubtypes(
typeFqName: FqName,
caches: Sequence<IncrementalCacheImpl<*>>
): Set<FqName> {
val types = linkedListOf(typeFqName)
val types = LinkedList(listOf(typeFqName))
val subtypes = hashSetOf<FqName>()
while (types.isNotEmpty()) {
@@ -81,7 +81,7 @@ class JpsIncrementalCacheImpl(
private inner class DirtyInlineFunctionsMap(storageFile: File) : BasicStringMap<Collection<String>>(storageFile, StringCollectionExternalizer) {
fun getEntries(): Map<JvmClassName, Collection<String>> =
storage.keys.toMapBy(JvmClassName::byInternalName) { storage[it]!! }
storage.keys.associateBy(JvmClassName::byInternalName) { storage[it]!! }
fun put(className: JvmClassName, changedFunctions: List<String>) {
storage[className.internalName] = changedFunctions
@@ -53,7 +53,7 @@ abstract class AbstractLookupTrackerTest : AbstractIncrementalJpsTest(
fail("File $actualFile unexpectedly contains multiline comments. In range ${matchResult.range} found: ${matchResult.value} in $text")
}
val lines = text.lines().toArrayList()
val lines = text.lines().toMutableList()
for ((line, lookupsFromLine) in lookupsFromFile.groupBy { it.position.line }) {
val columnToLookups = lookupsFromLine.groupBy { it.position.column }.toList().sortedBy { it.first }
@@ -36,6 +36,8 @@ import java.io.File
import java.io.PrintWriter
import java.io.StringWriter
import java.util.*
import kotlin.comparisons.*
// Set this to true if you want to dump all bytecode (test will fail in this case)
val DUMP_ALL = System.getProperty("comparison.dump.all") == "true"
@@ -53,7 +55,7 @@ fun getDirectoryString(dir: File, interestingPaths: List<String>): String {
val listFiles = dir.listFiles()
assertNotNull(listFiles)
val children = listFiles!!.sortedWith(compareBy ({ it.isDirectory }, { it.name } ))
val children = listFiles!!.sortedWith(compareBy({ it.isDirectory }, { it.name }))
for (child in children) {
if (child.isDirectory) {
p.println(child.name)
@@ -37,8 +37,8 @@ abstract class AbstractProtoComparisonTest : UsefulTestCase() {
val oldClassFiles = compileFileAndGetClasses(testDataPath, testDir, "old")
val newClassFiles = compileFileAndGetClasses(testDataPath, testDir, "new")
val oldClassMap = oldClassFiles.toMapBy { it.name }
val newClassMap = newClassFiles.toMapBy { it.name }
val oldClassMap = oldClassFiles.associateBy { it.name }
val newClassMap = newClassFiles.associateBy { it.name }
val sb = StringBuilder()
val p = Printer(sb)
@@ -21,7 +21,7 @@ import com.google.dart.compiler.backend.js.ast.*
import java.util.Stack
class ScopeContext(scope: JsScope) {
private val rootScope = sequence(scope) { it.parent }.first { it is JsRootScope }
private val rootScope = generateSequence(scope) { it.parent }.first { it is JsRootScope }
private val scopes = Stack<JsScope>();
init {
@@ -59,7 +59,7 @@ class AndroidCommandLineProcessor : CommandLineProcessor {
override fun processOption(option: CliOption, value: String, configuration: CompilerConfiguration) {
when (option) {
VARIANT_OPTION -> {
val paths = configuration.getList(AndroidConfigurationKeys.VARIANT).toArrayList()
val paths = configuration.getList(AndroidConfigurationKeys.VARIANT).toMutableList()
paths.add(value)
configuration.put(AndroidConfigurationKeys.VARIANT, paths)
}
@@ -43,7 +43,7 @@ class StubProducerExtension(val stubsOutputDir: File) : AnalysisCompletedHandler
StubClassBuilderFactory(),
module,
bindingContext,
files.toArrayList(),
files.toList(),
disableCallAssertions = false,
disableParamAssertions = false)