Fix "Should be replaced with Kotlin function" warnings

This commit is contained in:
Dmitry Gridin
2019-04-16 12:12:06 +07:00
parent d738a12b86
commit 3bed360c98
77 changed files with 161 additions and 99 deletions
@@ -129,7 +129,7 @@ class KotlinCompilerAdapter : Javac13() {
}
companion object {
private val KOTLIN_EXTENSIONS = Arrays.asList("kt", "kts")
private val KOTLIN_EXTENSIONS = listOf("kt", "kts")
private fun filterOutKotlinSources(files: Array<File>): Array<File> {
return files.filterNot {
@@ -19,6 +19,7 @@ package org.jetbrains.kotlin.incremental.testingUtils
import com.intellij.openapi.util.io.FileUtil
import java.io.File
import java.util.*
import kotlin.math.max
private val COMMANDS = listOf("new", "touch", "delete")
private val COMMANDS_AS_REGEX_PART = COMMANDS.joinToString("|")
@@ -166,7 +167,7 @@ class TouchFile(path: String, private val touchPolicy: TouchPolicy) : Modificati
TouchPolicy.TIMESTAMP -> {
val oldLastModified = file.lastModified()
//Mac OS and some versions of Linux truncate timestamp to nearest second
file.setLastModified(Math.max(System.currentTimeMillis(), oldLastModified + 1000))
file.setLastModified(max(System.currentTimeMillis(), oldLastModified + 1000))
}
TouchPolicy.CHECKSUM -> {
file.appendText(" ")
@@ -34,6 +34,7 @@ import org.jetbrains.org.objectweb.asm.tree.*
import org.jetbrains.org.objectweb.asm.tree.analysis.Frame
import org.jetbrains.org.objectweb.asm.tree.analysis.SourceInterpreter
import org.jetbrains.org.objectweb.asm.tree.analysis.SourceValue
import kotlin.math.max
private const val COROUTINES_DEBUG_METADATA_VERSION = 1
@@ -628,7 +629,7 @@ class CoroutineTransformerMethodVisitor(
spilledToVariableMapping.add(spilledToVariable)
varsCountByType.forEach {
maxVarsCountByType[it.key] = Math.max(maxVarsCountByType[it.key] ?: 0, it.value)
maxVarsCountByType[it.key] = max(maxVarsCountByType[it.key] ?: 0, it.value)
}
}
@@ -27,6 +27,7 @@ import org.jetbrains.org.objectweb.asm.tree.*
import org.jetbrains.org.objectweb.asm.tree.analysis.BasicValue
import org.jetbrains.org.objectweb.asm.tree.analysis.Frame
import org.jetbrains.org.objectweb.asm.tree.analysis.Interpreter
import kotlin.math.max
/**
* In cases like:
@@ -135,7 +136,7 @@ class UninitializedStoresProcessor(
nextVarIndex += type.size
storedTypes.add(type)
}
methodNode.maxLocals = Math.max(methodNode.maxLocals, nextVarIndex)
methodNode.maxLocals = max(methodNode.maxLocals, nextVarIndex)
methodNode.instructions.insertBefore(insn, insnListOf(
TypeInsnNode(Opcodes.NEW, newInsn.desc),
@@ -22,6 +22,7 @@ import org.jetbrains.org.objectweb.asm.tree.*
import java.util.*
import kotlin.collections.HashSet
import kotlin.collections.LinkedHashSet
import kotlin.math.max
abstract class CoveringTryCatchNodeProcessor(parameterSize: Int) {
val tryBlocksMetaInfo: IntervalMetaInfo<TryCatchBlockNodeInfo> = IntervalMetaInfo(this)
@@ -42,7 +43,7 @@ abstract class CoveringTryCatchNodeProcessor(parameterSize: Int) {
if (curInstr is VarInsnNode || curInstr is IincInsnNode) {
val argSize = getLoadStoreArgSize(curInstr.opcode)
val varIndex = if (curInstr is VarInsnNode) curInstr.`var` else (curInstr as IincInsnNode).`var`
nextFreeLocalIndex = Math.max(nextFreeLocalIndex, varIndex + argSize)
nextFreeLocalIndex = max(nextFreeLocalIndex, varIndex + argSize)
}
if (curInstr is LabelNode) {
@@ -51,6 +51,7 @@ import org.jetbrains.org.objectweb.asm.commons.Method
import org.jetbrains.org.objectweb.asm.tree.*
import java.util.*
import kotlin.collections.HashSet
import kotlin.math.max
abstract class InlineCodegen<out T : BaseExpressionCodegen>(
protected val codegen: T,
@@ -340,9 +341,9 @@ abstract class InlineCodegen<out T : BaseExpressionCodegen>(
var marker = -1
val intervals = processor.localVarsMetaInfo.currentIntervals
for (interval in intervals) {
marker = Math.max(interval.node.index + 1, marker)
marker = max(interval.node.index + 1, marker)
}
while (frameMap.currentSize < Math.max(processor.nextFreeLocalIndex, offsetForFinallyLocalVar + marker)) {
while (frameMap.currentSize < max(processor.nextFreeLocalIndex, offsetForFinallyLocalVar + marker)) {
frameMap.enterTemp(Type.INT_TYPE)
}
@@ -38,6 +38,7 @@ import org.jetbrains.org.objectweb.asm.tree.*
import org.jetbrains.org.objectweb.asm.tree.analysis.*
import org.jetbrains.org.objectweb.asm.util.Printer
import java.util.*
import kotlin.math.max
class MethodInliner(
private val node: MethodNode,
@@ -259,7 +260,7 @@ class MethodInliner(
val erasedInvokeFunction = ClosureCodegen.getErasedInvokeFunction(actualInvokeDescriptor)
val invokeParameters = erasedInvokeFunction.valueParameters
val valueParamShift = Math.max(nextLocalIndex, markerShift)//NB: don't inline cause it changes
val valueParamShift = max(nextLocalIndex, markerShift)//NB: don't inline cause it changes
putStackValuesIntoLocalsForLambdaOnInvoke(
listOf(*info.invokeMethod.argumentTypes), valueParameters, invokeParameters, valueParamShift, this, coroutineDesc
)
@@ -32,6 +32,7 @@ import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
import org.jetbrains.org.objectweb.asm.tree.*
import kotlin.math.max
class ReificationArgument(
val parameterName: String, val nullable: Boolean, private val arrayDepth: Int
@@ -194,7 +195,7 @@ class ReifiedTypeInliner(
instructions.remove(stubCheckcast)
// TODO: refine max stack calculation (it's not always as big as +4)
maxStackSize = Math.max(maxStackSize, 4)
maxStackSize = max(maxStackSize, 4)
return true
}
@@ -214,7 +215,7 @@ class ReifiedTypeInliner(
instructions.remove(stubInstanceOf)
// TODO: refine max stack calculation (it's not always as big as +2)
maxStackSize = Math.max(maxStackSize, 2)
maxStackSize = max(maxStackSize, 2)
return true
}
@@ -229,7 +230,7 @@ class ReifiedTypeInliner(
instructions.insert(insn, newMethodNode.instructions)
instructions.remove(stubConstNull)
maxStackSize = Math.max(maxStackSize, stackSize)
maxStackSize = max(maxStackSize, stackSize)
return true
}
@@ -24,6 +24,7 @@ import org.jetbrains.kotlin.codegen.inline.SMAP.Companion.FILE_SECTION
import org.jetbrains.kotlin.codegen.inline.SMAP.Companion.LINE_SECTION
import org.jetbrains.kotlin.codegen.inline.SMAP.Companion.STRATA_SECTION
import java.util.*
import kotlin.math.max
const val KOTLIN_STRATA_NAME = "Kotlin"
const val KOTLIN_DEBUG_STRATA_NAME = "KotlinDebug"
@@ -217,7 +218,7 @@ open class DefaultSourceMapper(val sourceInfo: SourceInfo) : SourceMapper {
val newFileMapping = getOrRegisterNewSource(fileMapping.name, fileMapping.path)
fileMapping.lineMappings.forEach {
newFileMapping.mapNewInterval(it.source, it.dest, it.range)
maxUsedValue = Math.max(it.maxDest, maxUsedValue)
maxUsedValue = max(it.maxDest, maxUsedValue)
}
}
}
@@ -47,6 +47,8 @@ import org.jetbrains.org.objectweb.asm.util.Textifier
import org.jetbrains.org.objectweb.asm.util.TraceMethodVisitor
import java.io.PrintWriter
import java.io.StringWriter
import kotlin.math.max
import kotlin.math.min
const val GENERATE_SMAP = true
const val NUMBERED_FUNCTION_PREFIX = "kotlin/jvm/functions/Function"
@@ -121,8 +123,8 @@ internal fun getMethodNode(
return object : MethodNode(Opcodes.API_VERSION, access, name, desc, signature, exceptions) {
override fun visitLineNumber(line: Int, start: Label) {
super.visitLineNumber(line, start)
lines[0] = Math.min(lines[0], line)
lines[1] = Math.max(lines[1], line)
lines[0] = min(lines[0], line)
lines[1] = max(lines[1], line)
}
}.also {
node = it
@@ -509,7 +511,7 @@ private fun getIndexAfterLastMarker(node: MethodNode): Int {
var result = -1
for (variable in node.localVariables) {
if (isFakeLocalVariableForInline(variable.name)) {
result = Math.max(result, variable.index + 1)
result = max(result, variable.index + 1)
}
}
return result
@@ -31,6 +31,7 @@ import org.jetbrains.org.objectweb.asm.tree.MethodNode
import org.jetbrains.org.objectweb.asm.tree.analysis.BasicValue
import org.jetbrains.org.objectweb.asm.tree.analysis.Frame
import org.jetbrains.org.objectweb.asm.tree.analysis.Interpreter
import kotlin.math.max
internal class FixStackAnalyzer(
owner: String,
@@ -133,7 +134,7 @@ internal class FixStackAnalyzer(
super.push(value)
} else {
extraStack.add(value)
maxExtraStackSize = Math.max(maxExtraStackSize, extraStack.size)
maxExtraStackSize = max(maxExtraStackSize, extraStack.size)
}
}
@@ -19,6 +19,7 @@ package org.jetbrains.kotlin.codegen.optimization.fixStack
import org.jetbrains.org.objectweb.asm.tree.AbstractInsnNode
import org.jetbrains.org.objectweb.asm.tree.MethodNode
import org.jetbrains.org.objectweb.asm.tree.analysis.BasicValue
import kotlin.math.max
internal class LocalVariablesManager(val context: FixStackContext, val methodNode: MethodNode) {
private class AllocatedHandle(val savedStackDescriptor: SavedStackDescriptor, var numRestoreMarkers: Int) {
@@ -35,7 +36,7 @@ internal class LocalVariablesManager(val context: FixStackContext, val methodNod
private val allocatedHandles = hashMapOf<AbstractInsnNode, AllocatedHandle>()
private fun updateMaxLocals(newValue: Int) {
methodNode.maxLocals = Math.max(methodNode.maxLocals, newValue)
methodNode.maxLocals = max(methodNode.maxLocals, newValue)
}
fun allocateVariablesForSaveStackMarker(saveStackMarker: AbstractInsnNode, savedStackValues: List<BasicValue>): SavedStackDescriptor {
@@ -67,7 +68,7 @@ internal class LocalVariablesManager(val context: FixStackContext, val methodNod
private fun getFirstUnusedLocalVariableIndex(): Int =
allocatedHandles.values.fold(initialMaxLocals) { index, handle ->
Math.max(index, handle.savedStackDescriptor.firstUnusedLocalVarIndex)
max(index, handle.savedStackDescriptor.firstUnusedLocalVarIndex)
}
fun markRestoreStackMarkerEmitted(restoreStackMarker: AbstractInsnNode) {
@@ -20,6 +20,7 @@ import java.io.File
import java.io.FileNotFoundException
import java.net.URL
import java.util.*
import kotlin.system.exitProcess
object Main {
private val KOTLIN_HOME: File
@@ -28,7 +29,7 @@ object Main {
val home = System.getProperty("kotlin.home")
if (home == null) {
System.err.println("error: no kotlin.home system property was passed")
System.exit(1)
exitProcess(1)
}
KOTLIN_HOME = File(home)
}
@@ -120,7 +121,7 @@ object Main {
}
catch (e: RunnerException) {
System.err.println("error: " + e.message)
System.exit(1)
exitProcess(1)
}
}
@@ -143,7 +144,7 @@ where command may be one of:
-version Display Kotlin version
-help (-h) Print a synopsis of options
""")
System.exit(0)
exitProcess(0)
}
private fun printVersionAndExit() {
@@ -155,6 +156,6 @@ where command may be one of:
}
println("Kotlin version " + version + " (JRE " + System.getProperty("java.runtime.version") + ")")
System.exit(0)
exitProcess(0)
}
}
@@ -33,6 +33,7 @@ import java.io.PrintStream
import java.net.URL
import java.net.URLConnection
import java.util.function.Predicate
import kotlin.system.exitProcess
abstract class CLITool<A : CommonToolArguments> {
fun exec(errStream: PrintStream, vararg args: String): ExitCode {
@@ -205,7 +206,7 @@ abstract class CLITool<A : CommonToolArguments> {
}
val exitCode = doMainNoExit(compiler, args)
if (exitCode != ExitCode.OK) {
System.exit(exitCode.code)
exitProcess(exitCode.code)
}
}
@@ -18,6 +18,7 @@ import org.jetbrains.kotlin.js.sourceMap.SourceMap3Builder
import org.jetbrains.kotlin.js.util.TextOutputImpl
import java.io.File
import java.io.StringReader
import kotlin.system.exitProcess
fun main(args: Array<String>) {
val outputFile = File(args[0])
@@ -55,7 +56,7 @@ private fun mergeStdlibParts(outputFile: File, wrapperFile: File, baseDir: File,
when (sourceMapParse) {
is SourceMapError -> {
System.err.println("Error parsing source map file $sourceMapFile: ${sourceMapParse.message}")
System.exit(1)
exitProcess(1)
}
is SourceMapSuccess -> {
val sourceMap = sourceMapParse.value
@@ -33,6 +33,7 @@ import java.util.*
import java.util.jar.Manifest
import java.util.logging.*
import kotlin.concurrent.schedule
import kotlin.system.exitProcess
val DAEMON_PERIODIC_CHECK_INTERVAL_MS = 1000L
val DAEMON_PERIODIC_SELDOM_CHECK_INTERVAL_MS = 60000L
@@ -153,7 +154,7 @@ object KotlinCompileDaemon {
timer.schedule(daemonOptions.forceShutdownTimeoutMilliseconds) {
cancel()
log.info("force JVM shutdown")
System.exit(0)
exitProcess(0)
}
}
else {
@@ -48,7 +48,7 @@ class ConditionalJumpInstruction(
}
override val nextInstructions: Collection<Instruction>
get() = Arrays.asList(nextOnFalse, nextOnTrue)
get() = listOf(nextOnFalse, nextOnTrue)
override val inputValues: List<PseudoValue>
get() = listOfNotNull(conditionValue)
@@ -56,6 +56,7 @@ import org.jetbrains.kotlin.types.typeUtil.containsTypeAliasParameters
import org.jetbrains.kotlin.types.typeUtil.containsTypeAliases
import org.jetbrains.kotlin.types.typeUtil.isArrayOfNothing
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import kotlin.math.min
class TypeResolver(
private val annotationResolver: AnnotationResolver,
@@ -699,7 +700,7 @@ class TypeResolver(
var wasStatic = false
val result = SmartList<KtTypeProjection>()
val classifierChainLastIndex = Math.min(classifierDescriptorChain.size, reversedQualifierParts.size) - 1
val classifierChainLastIndex = min(classifierDescriptorChain.size, reversedQualifierParts.size) - 1
for (index in 0..classifierChainLastIndex) {
val qualifierPart = reversedQualifierParts[index]
@@ -729,7 +730,7 @@ class TypeResolver(
val nonClassQualifierParts =
reversedQualifierParts.subList(
Math.min(classifierChainLastIndex + 1, reversedQualifierParts.size),
min(classifierChainLastIndex + 1, reversedQualifierParts.size),
reversedQualifierParts.size
)
@@ -45,6 +45,7 @@ import org.jetbrains.kotlin.types.expressions.DoubleColonExpressionResolver
import org.jetbrains.kotlin.types.typeUtil.containsTypeProjectionsInTopLevelArguments
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
import java.util.*
import kotlin.math.min
class CandidateResolver(
private val argumentTypeResolver: ArgumentTypeResolver,
@@ -591,7 +592,7 @@ class CandidateResolver(
}
val typeParameters = functionDescriptor.typeParameters
for (i in 0..Math.min(typeParameters.size, ktTypeArguments.size) - 1) {
for (i in 0..min(typeParameters.size, ktTypeArguments.size) - 1) {
val typeParameterDescriptor = typeParameters[i]
val typeArgument = typeArguments[i]
val typeReference = ktTypeArguments[i].typeReference
@@ -686,7 +687,7 @@ class CandidateResolver(
// TODO do not perform substitution for type arguments multiple times
val substitutedTypeArguments = typeAliasParametersSubstitutor.safeSubstitute(unsubstitutedType, Variance.INVARIANT).arguments
for (i in 0..Math.min(typeParameters.size, substitutedTypeArguments.size) - 1) {
for (i in 0..min(typeParameters.size, substitutedTypeArguments.size) - 1) {
val substitutedTypeProjection = substitutedTypeArguments[i]
if (substitutedTypeProjection.isStarProjection) continue
@@ -42,6 +42,8 @@ import org.jetbrains.kotlin.resolve.calls.model.*
import org.jetbrains.kotlin.resolve.scopes.receivers.*
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeSubstitutor
import kotlin.math.max
import kotlin.math.min
fun StatementGenerator.generateReceiverOrNull(ktDefaultElement: KtElement, receiver: ReceiverValue?): IntermediateValue? =
receiver?.let { generateReceiver(ktDefaultElement, receiver) }
@@ -220,10 +222,10 @@ fun StatementGenerator.generateVarargExpressionUsing(
}
val varargStartOffset = varargArgument.arguments.fold(Int.MAX_VALUE) { minStartOffset, argument ->
Math.min(minStartOffset, argument.asElement().startOffsetSkippingComments)
min(minStartOffset, argument.asElement().startOffsetSkippingComments)
}
val varargEndOffset = varargArgument.arguments.fold(Int.MIN_VALUE) { maxEndOffset, argument ->
Math.max(maxEndOffset, argument.asElement().endOffset)
max(maxEndOffset, argument.asElement().endOffset)
}
val varargElementType =
@@ -21,6 +21,7 @@ import com.intellij.psi.LiteralTextEscaper
import gnu.trove.TIntArrayList
import org.jetbrains.kotlin.psi.psiUtil.getContentRange
import org.jetbrains.kotlin.psi.psiUtil.isSingleQuoted
import kotlin.math.min
class KotlinStringLiteralTextEscaper(host: KtStringTemplateExpression) : LiteralTextEscaper<KtStringTemplateExpression>(host) {
private var sourceOffsets: IntArray? = null
@@ -70,7 +71,7 @@ class KotlinStringLiteralTextEscaper(host: KtStringTemplateExpression) : Literal
override fun getOffsetInHost(offsetInDecoded: Int, rangeInsideHost: TextRange): Int {
val offsets = sourceOffsets
if (offsets == null || offsetInDecoded >= offsets.size) return -1
return Math.min(offsets[offsetInDecoded], rangeInsideHost.length) + rangeInsideHost.startOffset
return min(offsets[offsetInDecoded], rangeInsideHost.length) + rangeInsideHost.startOffset
}
override fun getRelevantTextRange(): TextRange {
@@ -33,7 +33,7 @@ class KtClassBody : KtElementImplStub<KotlinPlaceHolderStub<KtClassBody>>, KtDec
override fun getParent() = parentByStub
override fun getDeclarations() = Arrays.asList(*getStubOrPsiChildren(DECLARATION_TYPES, KtDeclaration.ARRAY_FACTORY))
override fun getDeclarations() = listOf(*getStubOrPsiChildren(DECLARATION_TYPES, KtDeclaration.ARRAY_FACTORY))
override fun <R, D> accept(visitor: KtVisitor<R, D>, data: D) = visitor.visitClassBody(this, data)
@@ -25,6 +25,7 @@ import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.checker.NewCapturedType
import org.jetbrains.kotlin.types.model.*
import java.util.*
import kotlin.math.max
class ConstraintInjector(val constraintIncorporator: ConstraintIncorporator, val typeApproximator: TypeApproximator) {
private val ALLOWED_DEPTH_DELTA_FOR_INCORPORATION = 1
@@ -85,7 +86,7 @@ class ConstraintInjector(val constraintIncorporator: ConstraintIncorporator, val
}
private fun updateAllowedTypeDepth(c: Context, initialType: KotlinTypeMarker) = with(c) {
c.maxTypeDepthFromInitialConstraints = Math.max(c.maxTypeDepthFromInitialConstraints, initialType.typeDepth())
c.maxTypeDepthFromInitialConstraints = max(c.maxTypeDepthFromInitialConstraints, initialType.typeDepth())
}
private fun Context.shouldWeSkipConstraint(typeVariable: TypeVariableMarker, constraint: Constraint): Boolean {
@@ -21,6 +21,7 @@ import org.jetbrains.kotlin.types.checker.NewCapturedTypeConstructor
import org.jetbrains.kotlin.types.model.*
import org.jetbrains.kotlin.utils.SmartList
import org.jetbrains.kotlin.utils.addToStdlib.cast
import kotlin.math.max
class NewConstraintSystemImpl(
private val constraintInjector: ConstraintInjector,
@@ -173,7 +174,7 @@ class NewConstraintSystemImpl(
}
storage.initialConstraints.addAll(otherSystem.initialConstraints)
storage.maxTypeDepthFromInitialConstraints =
Math.max(storage.maxTypeDepthFromInitialConstraints, otherSystem.maxTypeDepthFromInitialConstraints)
max(storage.maxTypeDepthFromInitialConstraints, otherSystem.maxTypeDepthFromInitialConstraints)
storage.errors.addAll(otherSystem.errors)
storage.fixedTypeVariables.putAll(otherSystem.fixedTypeVariables)
storage.postponedTypeVariables.addAll(otherSystem.postponedTypeVariables)
@@ -23,8 +23,8 @@ private val BEGIN_MARKER = "<~BEGIN~>"
private val END_MARKER = "<~END~>"
fun CharSequence.substringWithContext(beginIndex: Int, endIndex: Int, range: Int): String {
val start = Math.max(0, beginIndex - range)
val end = Math.min(this.length, endIndex + range)
val start = kotlin.math.max(0, beginIndex - range)
val end = kotlin.math.min(this.length, endIndex + range)
val notFromBegin = start != 0
val notToEnd = end != this.length
@@ -202,7 +202,7 @@ object JavaToKotlinClassMap : PlatformToKotlinClassMap {
val kotlinMutableAnalogFqName = readOnlyToMutable[kotlinAnalog.fqNameUnsafe] ?: return setOf(kotlinAnalog)
return Arrays.asList(kotlinAnalog, builtIns.getBuiltInClassByFqName(kotlinMutableAnalogFqName))
return listOf(kotlinAnalog, builtIns.getBuiltInClassByFqName(kotlinMutableAnalogFqName))
}
override fun mapPlatformClass(classDescriptor: ClassDescriptor): Collection<ClassDescriptor> {
@@ -91,7 +91,7 @@ class CharValue(value: Char) : IntegerValueConstant<Char>(value) {
//TODO: KT-8507
12.toChar() -> "\\f"
'\r' -> "\\r"
else -> if (isPrintableUnicode(c)) Character.toString(c) else "?"
else -> if (isPrintableUnicode(c)) c.toString() else "?"
}
private fun isPrintableUnicode(c: Char): Boolean {
@@ -18,6 +18,7 @@ import org.jetbrains.kotlin.types.model.*
import org.jetbrains.kotlin.types.model.CaptureStatus
import org.jetbrains.kotlin.types.typeUtil.asTypeProjection
import org.jetbrains.kotlin.types.typeUtil.contains
import kotlin.math.max
interface ClassicTypeSystemContext : TypeSystemInferenceExtensionContext {
override fun TypeConstructorMarker.isDenotable(): Boolean {
@@ -470,7 +471,7 @@ private fun singleBestRepresentative(collection: Collection<KotlinType>) = colle
internal fun UnwrappedType.typeDepthInternal() =
when (this) {
is SimpleType -> typeDepthInternal()
is FlexibleType -> Math.max(lowerBound.typeDepthInternal(), upperBound.typeDepthInternal())
is FlexibleType -> max(lowerBound.typeDepthInternal(), upperBound.typeDepthInternal())
}
internal fun SimpleType.typeDepthInternal(): Int {
@@ -21,6 +21,7 @@ import com.intellij.execution.util.ExecUtil
import com.intellij.util.LineSeparator
import java.io.File
import java.util.regex.Pattern
import kotlin.system.exitProcess
// This file generates protobuf classes from formal description.
// To run it, you'll need protoc (protobuf compiler) 2.6.1 installed.
@@ -86,7 +87,7 @@ fun main(args: Array<String>) {
}
finally {
// Workaround for JVM hanging: IDEA's process handler creates thread pool
System.exit(0)
exitProcess(0)
}
}
@@ -29,6 +29,7 @@ import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.idea.util.requireNode
import org.jetbrains.kotlin.lexer.KtTokens
import java.util.*
import kotlin.math.max
fun CommonCodeStyleSettings.createSpaceBeforeRBrace(numSpacesOtherwise: Int, textRange: TextRange): Spacing? {
return Spacing.createDependentLFSpacing(numSpacesOtherwise, numSpacesOtherwise, textRange,
@@ -107,7 +108,7 @@ class KotlinSpacingBuilder(val commonCodeStyleSettings: CommonCodeStyleSettings,
val dependentSpacingRule = DependentSpacingRule(Trigger.HAS_LINE_FEEDS).registerData(Anchor.MIN_LINE_FEEDS, emptyLines + 1)
spacingBuilderUtil.createLineFeedDependentSpacing(numSpacesOtherwise,
numSpacesOtherwise,
if (leftEndsWithComment) Math.max(1, numberOfLineFeedsOtherwise) else numberOfLineFeedsOtherwise,
if (leftEndsWithComment) max(1, numberOfLineFeedsOtherwise) else numberOfLineFeedsOtherwise,
commonCodeStyleSettings.KEEP_LINE_BREAKS,
commonCodeStyleSettings.KEEP_BLANK_LINES_IN_DECLARATIONS,
left.textRange,
@@ -38,7 +38,7 @@ object JsLibraryStdDetectionUtil {
if (library !is LibraryEx || library.isDisposed) return false
if (!ignoreKind && library.effectiveKind(project) !is JSLibraryKind) return false
val classes = Arrays.asList(*library.getFiles(OrderRootType.CLASSES))
val classes = listOf(*library.getFiles(OrderRootType.CLASSES))
return getJsStdLibJar(classes) != null
}
@@ -42,6 +42,7 @@ import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.bindingContextUtil.getReferenceTargets
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import kotlin.math.max
var KtFile.doNotComplete: Boolean? by UserDataProperty(Key.create("DO_NOT_COMPLETE"))
@@ -71,7 +72,7 @@ class KotlinCompletionContributor : CompletionContributor() {
context.replacementOffset = context.replacementOffset
val offset = context.startOffset
val tokenBefore = psiFile.findElementAt(Math.max(0, offset - 1))
val tokenBefore = psiFile.findElementAt(max(0, offset - 1))
if (offset > 0 && tokenBefore!!.node.elementType == KtTokens.REGULAR_STRING_PART && tokenBefore.text.startsWith(".")) {
val prev = tokenBefore.parent.prevSibling
@@ -104,7 +105,7 @@ class KotlinCompletionContributor : CompletionContributor() {
?: DEFAULT_DUMMY_IDENTIFIER
}
val tokenAt = psiFile.findElementAt(Math.max(0, offset))
val tokenAt = psiFile.findElementAt(max(0, offset))
if (tokenAt != null) {
if (context.completionType == CompletionType.SMART && !isAtEndOfLine(offset, context.editor.document) /* do not use parent expression if we are at the end of line - it's probably parsed incorrectly */) {
var parent = tokenAt.parent
@@ -29,6 +29,7 @@ import org.jetbrains.kotlin.idea.completion.handlers.WithExpressionPrefixInsertH
import org.jetbrains.kotlin.idea.completion.handlers.WithTailInsertHandler
import org.jetbrains.kotlin.idea.core.completion.DeclarationLookupObject
import java.util.*
import kotlin.math.max
class LookupElementsCollector(
private val onFlush: () -> Unit,
@@ -157,7 +158,7 @@ class LookupElementsCollector(
}
val matchingDegree = RealPrefixMatchingWeigher.getBestMatchingDegree(result, prefixMatcher)
bestMatchingDegree = Math.max(bestMatchingDegree, matchingDegree)
bestMatchingDegree = max(bestMatchingDegree, matchingDegree)
}
// used to avoid insertion of spaces before/after ',', '=' on just typing
@@ -21,6 +21,7 @@ import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import kotlin.math.min
class ToFromOriginalFileMapper private constructor(
val originalFile: KtFile,
@@ -49,7 +50,7 @@ class ToFromOriginalFileMapper private constructor(
syntheticLength = syntheticText.length
originalLength = originalText.length
val minLength = Math.min(originalLength, syntheticLength)
val minLength = min(originalLength, syntheticLength)
tailLength = (0..minLength-1).firstOrNull {
syntheticText[syntheticLength - it - 1] != originalText[originalLength - it - 1]
} ?: minLength
@@ -22,6 +22,7 @@ import com.intellij.codeInsight.lookup.WeighingContext
import com.intellij.openapi.util.Key
import com.intellij.psi.codeStyle.NameUtil
import org.jetbrains.kotlin.idea.core.ExpectedInfo
import kotlin.math.min
val NAME_SIMILARITY_KEY = Key<Int>("NAME_SIMILARITY_KEY")
@@ -49,7 +50,7 @@ private fun calcNameSimilarity(name: String, expectedName: String): Int {
val nonNumberWords2 = words2.filter(::isNonNumber)
// count number of words matched at the end (but ignore number words - they are less important)
val minWords = Math.min(nonNumberWords1.size, nonNumberWords2.size)
val minWords = min(nonNumberWords1.size, nonNumberWords2.size)
val matchedTailLength = (0..minWords-1).firstOrNull {
i -> nonNumberWords1[nonNumberWords1.size - i - 1] != nonNumberWords2[nonNumberWords2.size - i - 1]
} ?: minWords
@@ -34,6 +34,7 @@ import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.siblings
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.utils.ifEmpty
import kotlin.math.min
fun moveCaretIntoGeneratedElement(editor: Editor, element: PsiElement) {
val project = element.project
@@ -120,7 +121,7 @@ private fun moveCaretIntoGeneratedElementDocumentUnblocked(editor: Editor, eleme
val start = firstInBlock.textRange!!.startOffset
val end = lastInBlock.textRange!!.endOffset
editor.moveCaret(Math.min(start, end))
editor.moveCaret(min(start, end))
if (start < end) {
editor.selectionModel.setSelection(start, end)
@@ -261,7 +261,7 @@ abstract class AbstractGradleMultiplatformWizardTest : ProjectWizardTestCase<Abs
addSdk(SimpleJavaSdkType().createJdk("_other", javaHome))
println("ProjectWizardTestCase.configureJdk:")
println(Arrays.asList(*ProjectJdkTable.getInstance().allJdks))
println(listOf(*ProjectJdkTable.getInstance().allJdks))
FileTypeManager.getInstance().associateExtension(GroovyFileType.GROOVY_FILE_TYPE, "gradle")
}
@@ -278,7 +278,7 @@ abstract class GradleImportingTestCase : ExternalSystemImportingTestCase() {
@JvmStatic
@Parameterized.Parameters(name = "{index}: with Gradle-{0}")
fun data(): Collection<Array<Any>> {
return Arrays.asList(*AbstractModelBuilderTest.SUPPORTED_GRADLE_VERSIONS)
return listOf(*AbstractModelBuilderTest.SUPPORTED_GRADLE_VERSIONS)
}
fun wrapperJar(): File {
@@ -67,7 +67,7 @@ abstract class KotlinWithLibraryConfigurator protected constructor() : KotlinPro
var nonConfiguredModules = if (!ApplicationManager.getApplication().isUnitTestMode)
getCanBeConfiguredModules(project, this)
else
Arrays.asList(*ModuleManager.getInstance(project).modules)
listOf(*ModuleManager.getInstance(project).modules)
nonConfiguredModules -= excludeModules
var modulesToConfigure = nonConfiguredModules
@@ -40,6 +40,8 @@ import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import java.util.*
import kotlin.math.max
import kotlin.math.min
class KotlinFrameExtraVariablesProvider : FrameExtraVariablesProvider {
override fun isAvailable(sourcePosition: SourcePosition, evalContext: EvaluationContext): Boolean {
@@ -70,12 +72,12 @@ private fun findAdditionalExpressions(position: SourcePosition): Set<TextWithImp
val limit = getLineRangeForElement(containingElement, doc)
var startLine = Math.max(limit.startOffset, line)
var startLine = max(limit.startOffset, line)
while (startLine - 1 > limit.startOffset && shouldSkipLine(file, doc, startLine - 1)) {
startLine--
}
var endLine = Math.min(limit.endOffset, line)
var endLine = min(limit.endOffset, line)
while (endLine + 1 < limit.endOffset && shouldSkipLine(file, doc, endLine + 1)) {
endLine++
}
@@ -59,6 +59,8 @@ import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCallIm
import org.jetbrains.kotlin.resolve.inline.InlineUtil
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.utils.keysToMap
import kotlin.math.max
import kotlin.math.min
class KotlinSteppingCommandProvider : JvmSteppingCommandProvider() {
override fun getStepOverCommand(
@@ -268,7 +270,7 @@ private fun findCallsOnPosition(sourcePosition: SourcePosition, filter: (KtCallE
return allFilteredCalls.filter {
val shouldInclude = it.getLineNumber() in linesRange
if (shouldInclude) {
linesRange = Math.min(linesRange.start, it.getLineNumber())..Math.max(linesRange.endInclusive, it.getLineNumber(false))
linesRange = min(linesRange.start, it.getLineNumber())..max(linesRange.endInclusive, it.getLineNumber(false))
}
shouldInclude
}
@@ -53,6 +53,7 @@ import java.util.*
import javax.swing.JButton
import javax.swing.JCheckBox
import javax.swing.JPanel
import kotlin.math.min
sealed class BytecodeGenerationResult {
data class Bytecode(val text: String) : BytecodeGenerationResult()
@@ -154,10 +155,10 @@ class KotlinBytecodeToolWindow(private val myProject: Project, private val toolW
val byteCodeDocument = myEditor.document
val linesRange = mapLines(byteCodeDocument.text, startLine, endLine)
val endSelectionLineIndex = Math.min(linesRange.second + 1, byteCodeDocument.lineCount)
val endSelectionLineIndex = min(linesRange.second + 1, byteCodeDocument.lineCount)
val startOffset = byteCodeDocument.getLineStartOffset(linesRange.first)
val endOffset = Math.min(byteCodeDocument.getLineStartOffset(endSelectionLineIndex), byteCodeDocument.textLength)
val endOffset = min(byteCodeDocument.getLineStartOffset(endSelectionLineIndex), byteCodeDocument.textLength)
myEditor.caretModel.moveToOffset(endOffset)
myEditor.scrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE)
@@ -308,7 +308,7 @@ class LiveTemplatesTest : KotlinLightCodeInsightFixtureTestCase() {
}
private fun assertStringItems(@NonNls vararg items: String) {
TestCase.assertEquals(Arrays.asList(*items), Arrays.asList(*itemStringsSorted))
TestCase.assertEquals(listOf(*items), listOf(*itemStringsSorted))
}
private val itemStrings: Array<String>
@@ -23,6 +23,8 @@ import com.intellij.openapi.editor.ex.util.EditorUtil
import com.intellij.openapi.project.Project
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import kotlin.math.max
import kotlin.math.min
class HistoryKeyListener(
private val project: Project, private val consoleEditor: EditorEx, private val history: CommandHistory
@@ -73,7 +75,7 @@ class HistoryKeyListener(
unfinishedCommand = document.text
}
historyPos = Math.max(historyPos - 1, 0)
historyPos = max(historyPos - 1, 0)
WriteCommandAction.runWriteCommandAction(project) {
document.setText(history[historyPos].entryText)
EditorUtil.scrollToTheEnd(consoleEditor)
@@ -89,7 +91,7 @@ class HistoryKeyListener(
return
}
historyPos = Math.min(historyPos + 1, history.size)
historyPos = min(historyPos + 1, history.size)
WriteCommandAction.runWriteCommandAction(project) {
document.setText(if (historyPos == history.size) unfinishedCommand else history[historyPos].entryText)
prevCaretOffset = document.textLength
@@ -35,6 +35,7 @@ import org.jetbrains.kotlin.console.gutter.ConsoleErrorRenderer
import org.jetbrains.kotlin.console.gutter.ConsoleIndicatorRenderer
import org.jetbrains.kotlin.console.gutter.ReplIcons
import org.jetbrains.kotlin.diagnostics.Severity
import kotlin.math.max
class ReplOutputProcessor(
private val runner: KotlinConsoleRunner
@@ -123,7 +124,7 @@ class ReplOutputProcessor(
}.values.map { messages ->
val highlighters = messages.map { message ->
val cmdStart = lastCommandStartOffset + message.range.startOffset
val cmdEnd = lastCommandStartOffset + Math.max(message.range.endOffset, message.range.startOffset + 1)
val cmdEnd = lastCommandStartOffset + max(message.range.endOffset, message.range.startOffset + 1)
val textAttributes = getAttributesForSeverity(cmdStart, cmdEnd, message.severity)
historyMarkup.addRangeHighlighter(
@@ -24,6 +24,7 @@ import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtCatchClause
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import kotlin.math.min
class KotlinCatchParameterFixer : SmartEnterProcessorWithFixers.Fixer<KotlinSmartEnterHandler>() {
override fun apply(editor: Editor, processor: KotlinSmartEnterHandler, psiElement: PsiElement) {
@@ -33,7 +34,7 @@ class KotlinCatchParameterFixer : SmartEnterProcessorWithFixers.Fixer<KotlinSmar
val parameterList = psiElement.parameterList
if (parameterList == null || parameterList.node.findChildByType(KtTokens.RPAR) == null) {
val endOffset = Math.min(psiElement.endOffset, psiElement.catchBody?.startOffset ?: Int.MAX_VALUE)
val endOffset = min(psiElement.endOffset, psiElement.catchBody?.startOffset ?: Int.MAX_VALUE)
val parameter = parameterList?.parameters?.firstOrNull()?.text ?: ""
editor.document.replaceString(catchEnd, endOffset, "($parameter)")
processor.registerUnresolvedError(endOffset - 1)
@@ -21,6 +21,7 @@ import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.editor.KotlinSmartEnterHandler
import org.jetbrains.kotlin.psi.KtNamedFunction
import kotlin.math.max
class KotlinFunctionParametersFixer : SmartEnterProcessorWithFixers.Fixer<KotlinSmartEnterHandler>() {
@@ -32,7 +33,7 @@ class KotlinFunctionParametersFixer : SmartEnterProcessorWithFixers.Fixer<Kotlin
val identifier = psiElement.nameIdentifier ?: return
// Insert () after name or after type parameters list when it placed after name
val offset = Math.max(identifier.range.end, psiElement.typeParameterList?.range?.end ?: psiElement.range.start)
val offset = max(identifier.range.end, psiElement.typeParameterList?.range?.end ?: psiElement.range.start)
editor.document.insertString(offset, "()")
processor.registerUnresolvedError(offset + 1)
} else {
@@ -20,6 +20,7 @@ import com.intellij.lang.SmartEnterProcessorWithFixers
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.editor.KotlinSmartEnterHandler
import kotlin.math.min
abstract class MissingConditionFixer<T : PsiElement> : SmartEnterProcessorWithFixers.Fixer<KotlinSmartEnterHandler>() {
override fun apply(editor: Editor, processor: KotlinSmartEnterHandler, element: PsiElement) {
@@ -35,10 +36,10 @@ abstract class MissingConditionFixer<T : PsiElement> : SmartEnterProcessorWithFi
var stopOffset = doc.getLineEndOffset(doc.getLineNumber(workElement.range.start))
val then = getBody(workElement)
if (then != null) {
stopOffset = Math.min(stopOffset, then.range.start)
stopOffset = min(stopOffset, then.range.start)
}
stopOffset = Math.min(stopOffset, workElement.range.end)
stopOffset = min(stopOffset, workElement.range.end)
doc.replaceString(workElement.range.start, stopOffset, "$keyword ()")
processor.registerUnresolvedError(workElement.range.start + "$keyword (".length)
@@ -30,6 +30,7 @@ import javax.swing.*
import javax.swing.table.AbstractTableModel
import javax.swing.table.TableCellEditor
import javax.swing.table.TableCellRenderer
import kotlin.math.max
class KotlinFacetCompilerPluginsTab(
private val configuration: KotlinFacetConfiguration,
@@ -154,7 +155,7 @@ class KotlinFacetCompilerPluginsTab(
val component = super.prepareRenderer(renderer, row, column)
val rendererWidth = component.preferredSize.width
with(getColumnModel().getColumn(column)) {
preferredWidth = Math.max(rendererWidth + intercellSpacing.width, preferredWidth)
preferredWidth = max(rendererWidth + intercellSpacing.width, preferredWidth)
}
return component
}
@@ -42,6 +42,7 @@ import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
import org.jetbrains.kotlin.utils.ifEmpty
import java.util.*
import kotlin.math.min
object RenameUnresolvedReferenceActionFactory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
@@ -134,7 +135,7 @@ class RenameUnresolvedReferenceFix(element: KtNameReferenceExpression): KotlinQu
private class HammingComparator<T>(private val referenceString: String, private val asString: T.() -> String) : Comparator<T> {
private fun countDifference(s1: String): Int {
return (0..Math.min(s1.lastIndex, referenceString.lastIndex)).count { s1[it] != referenceString[it] }
return (0..min(s1.lastIndex, referenceString.lastIndex)).count { s1[it] != referenceString[it] }
}
override fun compare(lookupItem1: T, lookupItem2: T): Int {
@@ -33,6 +33,7 @@ import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.isUnsignedNumberType
import kotlin.math.floor
private val valueRanges = mapOf(
KotlinBuiltIns.FQ_NAMES._byte to Byte.MIN_VALUE.toLong()..Byte.MAX_VALUE.toLong(),
@@ -85,7 +86,7 @@ class WrongPrimitiveLiteralFix(element: KtConstantExpression, type: KotlinType)
if (constValue is Float || constValue is Double) {
val value = constValue.toDouble()
if (value != Math.floor(value)) return false
if (value != floor(value)) return false
if (value !in Long.MIN_VALUE.toDouble()..Long.MAX_VALUE.toDouble()) return false
}
@@ -79,6 +79,7 @@ import org.jetbrains.kotlin.types.typeUtil.isAnyOrNullableAny
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.types.typeUtil.makeNullable
import java.util.*
import kotlin.math.max
/**
* Represents a single choice for a type (e.g. parameter type or return type).
@@ -1062,7 +1063,7 @@ internal fun <D : KtNamedDeclaration> placeDeclarationInContainer(
else -> 1
}
return Math.max(lineBreaksNeeded - lineBreaksPresent, 0)
return max(lineBreaksNeeded - lineBreaksPresent, 0)
}
val actualContainer = (container as? KtClassOrObject)?.getOrCreateBody() ?: container
@@ -98,7 +98,7 @@ object CreateClassFromReferenceExpressionActionFactory : CreateClassFromUsageFac
val targetParents = getTargetParentsByCall(call, context).ifEmpty { return emptyList() }
if (isInnerClassExpected(call)) return Collections.emptyList()
val allKinds = Arrays.asList(ClassKind.OBJECT, ClassKind.ENUM_ENTRY)
val allKinds = listOf(ClassKind.OBJECT, ClassKind.ENUM_ENTRY)
val expectedType = fullCallExpr.guessTypeForClass(context, moduleDescriptor)
@@ -49,6 +49,7 @@ import java.awt.Font
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
import kotlin.math.max
// Based on com.intellij.refactoring.copy.CopyClassDialog
class CopyKotlinDeclarationDialog(
@@ -97,7 +98,7 @@ class CopyKotlinDeclarationDialog(
override fun createNorthPanel(): JComponent? {
val qualifiedName = qualifiedName
packageNameField = PackageNameReferenceEditorCombo(qualifiedName, project, RECENTS_KEY, RefactoringBundle.message("choose.destination.package"))
packageNameField.setTextFieldPreferredWidth(Math.max(qualifiedName.length + 5, 40))
packageNameField.setTextFieldPreferredWidth(max(qualifiedName.length + 5, 40))
packageLabel.text = RefactoringBundle.message("destination.package")
packageLabel.labelFor = packageNameField
@@ -42,6 +42,7 @@ import java.util.*
import javax.swing.DefaultListCellRenderer
import javax.swing.DefaultListModel
import javax.swing.JList
import kotlin.math.min
@Throws(IntroduceRefactoringException::class)
fun selectElement(
@@ -237,7 +238,7 @@ private fun smartSelectElement(
fun getExpressionShortText(element: KtElement): String {
val text = element.renderTrimmed()
val firstNewLinePos = text.indexOf('\n')
var trimmedText = text.substring(0, if (firstNewLinePos != -1) firstNewLinePos else Math.min(100, text.length))
var trimmedText = text.substring(0, if (firstNewLinePos != -1) firstNewLinePos else min(100, text.length))
if (trimmedText.length != text.length) trimmedText += " ..."
return trimmedText
}
@@ -74,6 +74,7 @@ import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.utils.ifEmpty
import org.jetbrains.kotlin.utils.sure
import java.util.*
import kotlin.math.min
object KotlinIntroduceVariableHandler : RefactoringActionHandler {
val INTRODUCE_VARIABLE = KotlinRefactoringBundle.message("introduce.variable")
@@ -331,7 +332,7 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler {
private fun calculateAnchor(commonParent: PsiElement, commonContainer: PsiElement, allReplaces: List<KtExpression>): PsiElement? {
if (commonParent != commonContainer) return commonParent.parentsWithSelf.firstOrNull { it.parent == commonContainer }
val startOffset = allReplaces.fold(commonContainer.endOffset) { offset, expr -> Math.min(offset, expr.substringContextOrThis.startOffset) }
val startOffset = allReplaces.fold(commonContainer.endOffset) { offset, expr -> min(offset, expr.substringContextOrThis.startOffset) }
return commonContainer.allChildren.lastOrNull { it.textRange.contains(startOffset) } ?: return null
}
@@ -30,6 +30,8 @@ import java.awt.event.ActionEvent
import java.awt.event.KeyEvent
import javax.swing.*
import javax.swing.table.AbstractTableModel
import kotlin.math.max
import kotlin.math.min
abstract class AbstractParameterTablePanel<Param, UIParam : AbstractParameterTablePanel.AbstractParameterInfo<Param>> : JPanel(BorderLayout()) {
companion object {
@@ -165,7 +167,7 @@ abstract class AbstractParameterTablePanel<Param, UIParam : AbstractParameterTab
parameterInfos[oldIndex] = parameterInfos[newIndex]
parameterInfos[newIndex] = old
fireTableRowsUpdated(Math.min(oldIndex, newIndex), Math.max(oldIndex, newIndex))
fireTableRowsUpdated(min(oldIndex, newIndex), max(oldIndex, newIndex))
updateSignature()
}
@@ -100,6 +100,7 @@ import java.io.File
import java.lang.annotation.Retention
import java.util.*
import javax.swing.Icon
import kotlin.math.min
const val CHECK_SUPER_METHODS_YES_NO_DIALOG = "CHECK_SUPER_METHODS_YES_NO_DIALOG"
@@ -776,7 +777,7 @@ fun <ListType : KtElement> replaceListPsiAndKeepDelimiters(
val oldCount = oldParameters.size
val newCount = newParameters.size
val commonCount = Math.min(oldCount, newCount)
val commonCount = min(oldCount, newCount)
for (i in 0 until commonCount) {
oldParameters[i] = oldParameters[i].replace(newParameters[i]) as KtElement
}
@@ -92,7 +92,7 @@ enum class LibraryJarDescriptor(
RUNTIME_JAR(PathUtil.KOTLIN_JAVA_STDLIB_JAR, OrderRootType.CLASSES, true, { it.stdlibPath }) {
override fun findExistingJar(library: Library): VirtualFile? {
if (isExternalLibrary(library)) return null
return JavaRuntimeDetectionUtil.getRuntimeJar(Arrays.asList(*library.getFiles(OrderRootType.CLASSES)))
return JavaRuntimeDetectionUtil.getRuntimeJar(listOf(*library.getFiles(OrderRootType.CLASSES)))
}
},
@@ -132,7 +132,7 @@ enum class LibraryJarDescriptor(
open fun findExistingJar(library: Library): VirtualFile? {
if (isExternalLibrary(library)) return null
return LibraryUtils.getJarFile(Arrays.asList(*library.getFiles(orderRootType)), jarName)
return LibraryUtils.getJarFile(listOf(*library.getFiles(orderRootType)), jarName)
}
fun getPathInPlugin() = getPath(PathUtil.kotlinPathsForIdeaPlugin)
@@ -16,6 +16,7 @@ import com.intellij.openapi.util.text.StringUtilRt
import com.intellij.openapi.vfs.CharsetToolkit
import org.junit.Assert
import java.io.File
import kotlin.math.min
internal class KotlinOutputChecker(
private val testDir: String,
@@ -79,7 +80,7 @@ internal class KotlinOutputChecker(
println("actual:")
println(actual)
val len = Math.min(expected.length, actual.length)
val len = min(expected.length, actual.length)
if (expected.length != actual.length) {
println("Text sizes differ: expected " + expected.length + " but actual: " + actual.length)
}
@@ -67,7 +67,7 @@ abstract class AbstractScratchRunActionTest : FileEditorManagerTestCase() {
val outputDir = createTempDir(dirName)
if (javaFiles.isNotEmpty()) {
val options = Arrays.asList("-d", outputDir.path)
val options = listOf("-d", outputDir.path)
KotlinTestUtils.compileJavaFiles(javaFiles, options)
}
@@ -27,6 +27,7 @@ import org.jetbrains.kotlin.j2k.ast.SpacesInheritance
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import java.util.*
import kotlin.math.max
fun <T> CodeBuilder.buildList(generators: Collection<() -> T>, separator: String, prefix: String = "", suffix: String = ""): CodeBuilder {
if (generators.isNotEmpty()) {
@@ -192,7 +193,7 @@ class CodeBuilder(private val topElement: PsiElement?, private var docConverter:
return when {
isEmpty() -> other
other.isEmpty() -> this
else -> Prefix(elements + other.elements, Math.max(lineBreaksBefore, other.lineBreaksBefore))
else -> Prefix(elements + other.elements, max(lineBreaksBefore, other.lineBreaksBefore))
}
}
@@ -22,6 +22,7 @@ import com.intellij.util.IncorrectOperationException
import org.jetbrains.kotlin.j2k.ast.*
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.psi.psiUtil.siblings
import kotlin.math.abs
class ForConverter(
private val statement: PsiForStatement,
@@ -278,7 +279,7 @@ class ForConverter(
val converted = codeConverter.convertExpression(bound)
val sign = if (correction > 0) JavaTokenType.PLUS else JavaTokenType.MINUS
return BinaryExpression(converted, LiteralExpression(Math.abs(correction).toString()).assignNoPrototype(), Operator(sign).assignPrototype(bound)).assignNoPrototype()
return BinaryExpression(converted, LiteralExpression(abs(correction).toString()).assignNoPrototype(), Operator(sign).assignPrototype(bound)).assignNoPrototype()
}
private fun PsiStatement.toContinuedLoop(): PsiLoopStatement? {
@@ -29,6 +29,7 @@ import org.jetbrains.kotlin.resolve.calls.util.FakeCallableDescriptorForObject
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.resolve.descriptorUtil.isEnumValueOfMethod
import java.util.*
import kotlin.math.abs
/**
* This class is responsible for generating names for declarations. It does not produce fully-qualified JS name, instead
@@ -339,7 +340,7 @@ class NameSuggestion {
}
private fun mangledId(forCalculateId: String): String {
val absHashCode = Math.abs(forCalculateId.hashCode())
val absHashCode = abs(forCalculateId.hashCode())
return if (absHashCode != 0) absHashCode.toString(Character.MAX_RADIX) else ""
}
@@ -51,7 +51,7 @@ actual fun <T : Throwable> assertFailsWith(exceptionClass: KClass<T>, message: S
*/
@InlineOnly
actual inline fun todo(@Suppress("UNUSED_PARAMETER") block: () -> Unit) {
System.out.println("TODO at " + currentStackTrace()[0])
println("TODO at " + currentStackTrace()[0])
}
/**
@@ -306,7 +306,7 @@ abstract class BaseGradleIT {
} catch (t: Throwable) {
// to prevent duplication of output
if (!options.forceOutputToStdout) {
System.out.println(result.output)
println(result.output)
}
throw t
}
@@ -37,7 +37,7 @@ fun runProcess(
val sb = StringBuilder()
process.inputStream!!.bufferedReader().forEachLine {
if (options?.forceOutputToStdout ?: false) {
System.out.println(it)
println(it)
}
sb.appendln(it)
}
@@ -1,7 +1,7 @@
package projB
fun main(vararg args: String) {
System.out.println(projA.getInfo())
println(projA.getInfo())
}
@@ -76,7 +76,7 @@ internal class GradleKotlinCompilerWork @Inject constructor(
companion object {
init {
if (System.getProperty("org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.trace.loading") == "true") {
System.out.println("Loaded GradleKotlinCompilerWork")
println("Loaded GradleKotlinCompilerWork")
}
}
}
@@ -93,7 +93,7 @@ internal fun runToolInSeparateProcess(
}
} else {
process.inputStream!!.bufferedReader().forEachLine {
System.out.println(it)
println(it)
}
}
@@ -31,6 +31,7 @@ import org.jetbrains.kotlin.gradle.report.configureBuildReporter
import org.jetbrains.kotlin.gradle.utils.relativeToRoot
import org.jetbrains.kotlin.utils.addToStdlib.sumByLong
import java.lang.management.ManagementFactory
import kotlin.math.max
internal class KotlinGradleBuildServices private constructor(
private val gradle: Gradle
@@ -132,7 +133,7 @@ internal class KotlinGradleBuildServices private constructor(
}
private fun getGcCount(): Long =
ManagementFactory.getGarbageCollectorMXBeans().sumByLong { Math.max(0, it.collectionCount) }
ManagementFactory.getGarbageCollectorMXBeans().sumByLong { max(0, it.collectionCount) }
private var loadedInProjectPath: String? = null
@@ -6,6 +6,7 @@ import com.google.gson.stream.JsonWriter
import com.google.gson.stream.MalformedJsonException
import org.slf4j.LoggerFactory
import java.io.*
import kotlin.math.min
open class RewriteSourceMapFilterReader(
val input: Reader
@@ -175,7 +176,7 @@ open class RewriteSourceMapFilterReader(
}
}
val toRead = Math.min(todo, bufferAvailable)
val toRead = min(todo, bufferAvailable)
buffer.getChars(bufferReadPos, bufferReadPos + toRead, dest, destOffset)
bufferReadPos += toRead
destOffset += toRead
@@ -201,7 +202,7 @@ open class RewriteSourceMapFilterReader(
}
}
val toRead = Math.min(todo, bufferAvailable)
val toRead = min(todo, bufferAvailable)
bufferReadPos += toRead
todo -= toRead
}
@@ -7,6 +7,7 @@ package org.jetbrains.kotlin.kotlinp
import java.io.File
import java.io.IOException
import kotlin.system.exitProcess
object Main {
private fun run(args: Array<String>) {
@@ -60,7 +61,7 @@ object Main {
run(args)
} catch (e: KotlinpException) {
System.err.println("error: " + e.message)
System.exit(1)
exitProcess(1)
}
}
@@ -75,7 +76,7 @@ where possible options include:
-help (-h) Print a synopsis of options
"""
)
System.exit(0)
exitProcess(0)
}
private fun printVersionAndExit() {
@@ -83,6 +84,6 @@ where possible options include:
val version = "@snapshot@"
println("Kotlin version " + version + " (JRE " + System.getProperty("java.runtime.version") + ")")
System.exit(0)
exitProcess(0)
}
}
@@ -13,6 +13,7 @@ import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.nj2k.*
import org.jetbrains.kotlin.nj2k.tree.*
import org.jetbrains.kotlin.nj2k.tree.impl.*
import kotlin.math.abs
class ForConversion(private val context: ConversionContext) : RecursiveApplicableConversionBase() {
@@ -199,7 +200,7 @@ class ForConversion(private val context: ConversionContext) : RecursiveApplicabl
val sign = if (correction > 0) KtTokens.PLUS else KtTokens.MINUS
return kotlinBinaryExpression(
bound,
JKKtLiteralExpressionImpl(Math.abs(correction).toString(), JKLiteralExpression.LiteralType.INT),
JKKtLiteralExpressionImpl(abs(correction).toString(), JKLiteralExpression.LiteralType.INT),
JKKtSingleValueOperatorToken(sign),
context.symbolProvider
)!!
+2 -1
View File
@@ -17,6 +17,7 @@ import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler
import org.jetbrains.kotlin.cli.jvm.modules.isAtLeastJava9
import org.jetbrains.kotlin.kapt.cli.CliToolOption.Format.*
import java.io.File
import kotlin.system.exitProcess
fun main(args: Array<String>) {
val messageCollector = PrintingMessageCollector(System.err, MessageRenderer.PLAIN_RELATIVE_PATHS, false)
@@ -29,7 +30,7 @@ fun main(args: Array<String>) {
val kaptTransformed = transformArgs(args.asList(), messageCollector, false)
if (messageCollector.hasErrors()) {
System.exit(ExitCode.COMPILATION_ERROR.code)
exitProcess(ExitCode.COMPILATION_ERROR.code)
return
}
@@ -28,6 +28,7 @@ import javax.annotation.processing.RoundEnvironment
import javax.lang.model.element.ElementKind
import javax.lang.model.element.ExecutableElement
import javax.lang.model.element.TypeElement
import kotlin.system.exitProcess
class KotlinKapt3IntegrationTests : AbstractKotlinKapt3IntegrationTest(), Java9TestLauncher {
override fun test(
@@ -149,7 +150,7 @@ internal class SingleJUnitTestRunner {
val (className, methodName) = args.single().split('#')
val request = Request.method(Class.forName(className), methodName)
val result = JUnitCore().run(request)
System.exit(if (result.wasSuccessful()) 0 else 1)
exitProcess(if (result.wasSuccessful()) 0 else 1)
}
}
}
@@ -150,7 +150,7 @@ class ReplFromTerminal(
companion object {
private fun splitCommand(command: String): List<String> {
return Arrays.asList(*command.split(" ".toRegex()).dropLastWhile(String::isEmpty).toTypedArray())
return listOf(*command.split(" ".toRegex()).dropLastWhile(String::isEmpty).toTypedArray())
}
fun run(disposable: Disposable, configuration: CompilerConfiguration) {