Compare commits

...

2 Commits

Author SHA1 Message Date
Ilya Gorbunov
64174d5371 Preview: rename check to verifyOrNull 2017-01-12 05:00:06 +03:00
Ilya Gorbunov
c236697977 New scope functions: supply and verifyOrNull 2017-01-12 04:57:38 +03:00
54 changed files with 143 additions and 126 deletions

View File

@@ -26,7 +26,7 @@ import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.serialization.deserialization.MetadataPackageFragment
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import java.io.InputStream
class JvmCliVirtualFileFinder(
@@ -61,6 +61,6 @@ class JvmCliVirtualFileFinder(
private fun findBinaryClass(classId: ClassId, fileName: String): VirtualFile? =
index.findClass(classId, acceptedRootTypes = JavaRoot.OnlyBinary) { dir, _ ->
dir.findChild(fileName)?.check(VirtualFile::isValid)
}?.check { it in scope }
dir.findChild(fileName)?.verifyOrNull(VirtualFile::isValid)
}?.verifyOrNull { it in scope }
}

View File

@@ -32,7 +32,7 @@ import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.jvm.KotlinCliJavaFileManager
import org.jetbrains.kotlin.util.PerformanceCounter
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import java.util.*
import kotlin.properties.Delegates
@@ -50,7 +50,7 @@ class KotlinCliJavaFileManagerImpl(private val myPsiManager: PsiManager) : CoreJ
val classNameWithInnerClasses = classId.relativeClassName.asString()
index.findClass(classId) { dir, type ->
findClassGivenPackage(allScope, dir, classNameWithInnerClasses, type)
}?.check { it.containingFile.virtualFile in searchScope }
}?.verifyOrNull { it.containingFile.virtualFile in searchScope }
}
}

View File

@@ -21,7 +21,7 @@ import net.rubygrapefruit.platform.ProcessLauncher
import org.jetbrains.kotlin.daemon.common.*
import org.jetbrains.kotlin.load.kotlin.incremental.components.IncrementalCompilationComponents
import org.jetbrains.kotlin.progress.CompilationCanceledStatus
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import java.io.File
import java.io.OutputStream
import java.io.PrintStream
@@ -54,9 +54,9 @@ object KotlinCompilerClient {
): CompileService? {
val flagFile = System.getProperty(COMPILE_DAEMON_CLIENT_ALIVE_PATH_PROPERTY)
?.let(String::trimQuotes)
?.check { !it.isBlank() }
?.verifyOrNull { !it.isBlank() }
?.let(::File)
?.check(File::exists)
?.verifyOrNull(File::exists)
?: makeAutodeletingFlagFile()
return connectToCompileService(compilerId, flagFile, daemonJVMOptions, daemonOptions, reportingTargets, autostart)
}
@@ -255,7 +255,7 @@ object KotlinCompilerClient {
.sortedWith(compareByDescending(DaemonJVMOptionsMemoryComparator(), { it.second.get() }))
val optsCopy = daemonJVMOptions.copy()
// if required options fit into fattest running daemon - return the daemon and required options with memory params set to actual ones in the daemon
return aliveWithOpts.firstOrNull()?.check { daemonJVMOptions memorywiseFitsInto it.second.get() }?.let {
return aliveWithOpts.firstOrNull()?.verifyOrNull { daemonJVMOptions memorywiseFitsInto it.second.get() }?.let {
Pair(it.first, optsCopy.updateMemoryUpperBounds(it.second.get()))
}
// else combine all options from running daemon to get fattest option for a new daemon to run

View File

@@ -45,7 +45,7 @@ import org.jetbrains.kotlin.modules.Module
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.progress.CompilationCanceledStatus
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import java.io.BufferedOutputStream
import java.io.ByteArrayOutputStream
import java.io.File
@@ -543,7 +543,7 @@ class CompileServiceImpl(
if (fattestOpts memorywiseFitsInto daemonJVMOptions && !(daemonJVMOptions memorywiseFitsInto fattestOpts)) {
// all others are smaller that me, take overs' clients and shut them down
aliveWithOpts.forEach {
it.first.getClients().check { it.isGood }?.let {
it.first.getClients().verifyOrNull { it.isGood }?.let {
it.get().forEach { registerClient(it) }
}
it.first.scheduleShutdown(true)
@@ -553,7 +553,7 @@ class CompileServiceImpl(
// there is at least one bigger, handover my clients to it and shutdown
scheduleShutdown(true)
aliveWithOpts.first().first.let { fattest ->
getClients().check { it.isGood }?.let {
getClients().verifyOrNull { it.isGood }?.let {
it.get().forEach { fattest.registerClient(it) }
}
}

View File

@@ -21,7 +21,7 @@ import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.types.replace
import org.jetbrains.kotlin.types.typeUtil.asTypeProjection
import org.jetbrains.kotlin.types.typeUtil.contains
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
// If type 'samType' contains no projection, then it's non-projection parametrization is 'samType' itself
// Else each projection type argument 'out/in A_i' (but star projections) is replaced with it's bound 'A_i'
@@ -43,7 +43,7 @@ internal fun nonProjectionParametrization(samType: SimpleType): SimpleType? {
projection.projectionKind == Variance.INVARIANT -> projection
projection.isStarProjection ->
parameter.upperBounds.first().check {
parameter.upperBounds.first().verifyOrNull {
t -> !t.contains { it.constructor.declarationDescriptor in parametersSet }
}?.asTypeProjection() ?: return@nonProjectionParametrization null

View File

@@ -28,7 +28,7 @@ import com.intellij.testFramework.LightVirtualFile
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import java.util.*
abstract class KtCodeFragment(
@@ -175,7 +175,7 @@ abstract class KtCodeFragment(
private fun initImports(imports: String?) {
if (imports != null && !imports.isEmpty()) {
val importsWithPrefix = imports.split(IMPORT_SEPARATOR).map { it.check { it.startsWith("import ") } ?: "import ${it.trim()}" }
val importsWithPrefix = imports.split(IMPORT_SEPARATOR).map { it.verifyOrNull { it.startsWith("import ") } ?: "import ${it.trim()}" }
importsWithPrefix.forEach {
addImport(it)
}

View File

@@ -37,7 +37,7 @@ import org.jetbrains.kotlin.resolve.source.KotlinSourceElement
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
import org.jetbrains.kotlin.types.typeUtil.*
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import java.util.*
internal class DeclarationsCheckerBuilder(
@@ -182,7 +182,7 @@ class DeclarationsChecker(
private fun getUsedTypeAliasParameters(type: KotlinType, typeAlias: TypeAliasDescriptor): Set<TypeParameterDescriptor> =
type.constituentTypes().mapNotNullTo(HashSet()) {
val descriptor = it.constructor.declarationDescriptor as? TypeParameterDescriptor
descriptor?.check { it.containingDeclaration == typeAlias }
descriptor?.verifyOrNull { it.containingDeclaration == typeAlias }
}
private class TypeAliasDeclarationCheckingReportStrategy(

View File

@@ -37,7 +37,7 @@ import org.jetbrains.kotlin.resolve.source.KotlinSourceElement
import org.jetbrains.kotlin.types.expressions.ExpressionTypingContext
import org.jetbrains.kotlin.types.expressions.isWithoutValueArguments
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
class QualifiedExpressionResolver {
fun resolvePackageHeader(
@@ -230,7 +230,7 @@ class QualifiedExpressionResolver {
}
val importedDescriptors = candidates.filter { isVisible(it, packageFragmentForVisibilityCheck, position = QualifierPosition.IMPORT) }.
check { it.isNotEmpty() } ?: candidates
verifyOrNull { it.isNotEmpty() } ?: candidates
return SingleImportScope(aliasName, importedDescriptors)
}
@@ -455,12 +455,12 @@ class QualifiedExpressionResolver {
val qualifierDescriptor = when (receiver) {
is PackageQualifier -> {
val childPackageFQN = receiver.descriptor.fqName.child(name)
receiver.descriptor.module.getPackage(childPackageFQN).check { !it.isEmpty() } ?:
receiver.descriptor.module.getPackage(childPackageFQN).verifyOrNull { !it.isEmpty() } ?:
receiver.descriptor.memberScope.getContributedClassifier(name, location)
}
is ClassQualifier -> receiver.staticScope.getContributedClassifier(name, location)
null -> context.scope.findClassifier(name, location) ?:
context.scope.ownerDescriptor.module.getPackage(FqName.ROOT.child(name)).check { !it.isEmpty() }
context.scope.ownerDescriptor.module.getPackage(FqName.ROOT.child(name)).verifyOrNull { !it.isEmpty() }
is ReceiverValue -> receiver.type.memberScope.memberScopeAsImportingScope().findClassifier(name, location)
else -> null
}

View File

@@ -56,7 +56,7 @@ import org.jetbrains.kotlin.types.ErrorUtils
import org.jetbrains.kotlin.types.expressions.OperatorConventions
import org.jetbrains.kotlin.types.isDynamic
import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import org.jetbrains.kotlin.utils.sure
import java.lang.IllegalStateException
import java.util.*
@@ -451,7 +451,7 @@ class NewResolutionOldInference(
functionContext.tracing.bindReference(variable.resolvedCall.trace, variable.resolvedCall)
// todo hacks
val functionCall = CallTransformer.CallForImplicitInvoke(
basicCallContext.call.explicitReceiver?.check { useExplicitReceiver },
basicCallContext.call.explicitReceiver?.verifyOrNull { useExplicitReceiver },
variableReceiver, basicCallContext.call, true)
val tracingForInvoke = TracingStrategyForInvoke(calleeExpression, functionCall, variableReceiver.type)
val basicCallResolutionContext = basicCallContext.replaceBindingTrace(variable.resolvedCall.trace)

View File

@@ -30,7 +30,7 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.storage.StorageManager
import org.jetbrains.kotlin.storage.getValue
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
class DefaultImportProvider(
storageManager: StorageManager,
@@ -56,7 +56,7 @@ class DefaultImportProvider(
defaultImports
.filter { it.isAllUnder }
.mapNotNull {
it.fqnPart().check { !it.isSubpackageOf(KotlinBuiltIns.BUILT_INS_PACKAGE_FQ_NAME) }
it.fqnPart().verifyOrNull { !it.isSubpackageOf(KotlinBuiltIns.BUILT_INS_PACKAGE_FQ_NAME) }
}
val nonKotlinAliasedTypeFqNames =
builtinTypeAliases

View File

@@ -40,7 +40,7 @@ import org.jetbrains.kotlin.storage.StorageManager
import org.jetbrains.kotlin.storage.getValue
import org.jetbrains.kotlin.types.TypeSubstitutor
import org.jetbrains.kotlin.utils.Printer
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
data class FileScopes(val lexicalScope: LexicalScope, val importingScope: ImportingScope, val importResolver: ImportResolver)
@@ -176,7 +176,7 @@ class FileScopeFactory(
if (name in excludedNames) return null
val classifier = scope.getContributedClassifier(name, location) ?: return null
val visible = Visibilities.isVisibleIgnoringReceiver(classifier as DeclarationDescriptorWithVisibility, fromDescriptor)
return classifier.check { filteringKind == if (visible) FilteringKind.VISIBLE_CLASSES else FilteringKind.INVISIBLE_CLASSES }
return classifier.verifyOrNull { filteringKind == if (visible) FilteringKind.VISIBLE_CLASSES else FilteringKind.INVISIBLE_CLASSES }
}
override fun getContributedVariables(name: Name, location: LookupLocation): Collection<PropertyDescriptor> {

View File

@@ -24,14 +24,14 @@ import org.jetbrains.kotlin.resolve.calls.tasks.ExplicitReceiverKind
import org.jetbrains.kotlin.resolve.scopes.receivers.DetailedReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.QualifierReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValueWithSmartCastInfo
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
class KnownResultProcessor<out C>(
val result: Collection<C>
): ScopeTowerProcessor<C> {
override fun process(data: TowerData)
= if (data == TowerData.Empty) listOfNotNull(result.check { it.isNotEmpty() }) else emptyList()
= if (data == TowerData.Empty) listOfNotNull(result.verifyOrNull { it.isNotEmpty() }) else emptyList()
}
class CompositeScopeTowerProcessor<out C>(
@@ -46,7 +46,7 @@ internal abstract class AbstractSimpleScopeTowerProcessor<D : CallableDescriptor
protected abstract fun simpleProcess(data: TowerData): Collection<C>
override fun process(data: TowerData): List<Collection<C>> = listOfNotNull(simpleProcess(data).check { it.isNotEmpty() })
override fun process(data: TowerData): List<Collection<C>> = listOfNotNull(simpleProcess(data).verifyOrNull { it.isNotEmpty() })
}
private typealias CandidatesCollector<D> =

View File

@@ -25,7 +25,7 @@ import org.jetbrains.kotlin.resolve.scopes.ImportingScope
import org.jetbrains.kotlin.resolve.scopes.LexicalScope
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValueWithSmartCastInfo
import org.jetbrains.kotlin.resolve.scopes.utils.parentsWithSelf
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import java.util.*
interface Candidate<out D : CallableDescriptor> {
@@ -235,11 +235,11 @@ class TowerResolver {
override fun getSuccessfulCandidates(): Collection<C>? = getResolved()
fun getResolved() = currentCandidates.check { currentLevel == ResolutionCandidateApplicability.RESOLVED }
fun getResolved() = currentCandidates.verifyOrNull { currentLevel == ResolutionCandidateApplicability.RESOLVED }
fun getResolvedLowPriority() = currentCandidates.check { currentLevel == ResolutionCandidateApplicability.RESOLVED_LOW_PRIORITY }
fun getResolvedLowPriority() = currentCandidates.verifyOrNull { currentLevel == ResolutionCandidateApplicability.RESOLVED_LOW_PRIORITY }
fun getErrors() = currentCandidates.check {
fun getErrors() = currentCandidates.verifyOrNull {
currentLevel == null || currentLevel!! > ResolutionCandidateApplicability.RESOLVED_LOW_PRIORITY
}

View File

@@ -16,7 +16,7 @@
package org.jetbrains.kotlin.utils
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
import kotlin.reflect.*
import kotlin.reflect.full.isSubclassOf
@@ -106,7 +106,7 @@ private fun <T> tryCreateCallableMapping(callable: KCallable<*>, args: Iterator<
}
ArgsTraversalState.NAMED -> {
assert(arg.name != null)
val parIdx = unboundParams.indexOfFirst { it.name == arg.name }.check { it >= 0 }
val parIdx = unboundParams.indexOfFirst { it.name == arg.name }.verifyOrNull { it >= 0 }
?: return null // failed to match: no matching named parameter found
val par = unboundParams.removeAt(parIdx)
val cvtRes = converter.tryConvertSingle(par, arg)
@@ -184,7 +184,7 @@ private class StringArgsConverter : ArgsConverter<String> {
DoubleArray::class -> args.map { it?.toDoubleOrNull() }
BooleanArray::class -> args.map { it?.toBoolean() }
else -> null
}?.toList()?.check { list -> list.none { it == null } }?.toTypedArray()
}?.toList()?.verifyOrNull { list -> list.none { it == null } }?.toTypedArray()
val parameterType = parameter.type
if (parameterType.jvmErasure.java.isArray) {

View File

@@ -48,7 +48,7 @@ import org.jetbrains.kotlin.serialization.deserialization.NotFoundClasses
import org.jetbrains.kotlin.storage.getValue
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import org.jetbrains.kotlin.utils.toReadOnlyList
import java.util.*
@@ -188,7 +188,7 @@ class LazyJavaClassDescriptor(
}
private fun getPurelyImplementedSupertype(): KotlinType? {
val annotatedPurelyImplementedFqName = getPurelyImplementsFqNameFromAnnotation()?.check {
val annotatedPurelyImplementedFqName = getPurelyImplementsFqNameFromAnnotation()?.verifyOrNull {
!it.isRoot && it.toUnsafe().startsWith(KotlinBuiltIns.BUILT_INS_PACKAGE_NAME)
}

View File

@@ -57,7 +57,7 @@ import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
import org.jetbrains.kotlin.utils.*
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
import java.util.*
@@ -209,7 +209,7 @@ class LazyJavaClassMemberScope(
descriptor ->
if (descriptor.valueParameters.size != 0) return@factory null
descriptor.check { KotlinTypeChecker.DEFAULT.isSubtypeOf(descriptor.returnType ?: return@check false, type) }
descriptor.verifyOrNull { KotlinTypeChecker.DEFAULT.isSubtypeOf(descriptor.returnType ?: return@verifyOrNull false, type) }
}
}
@@ -221,7 +221,7 @@ class LazyJavaClassMemberScope(
if (descriptor.valueParameters.size != 1) return@factory null
if (!KotlinBuiltIns.isUnit(descriptor.returnType ?: return@factory null)) return@factory null
descriptor.check { KotlinTypeChecker.DEFAULT.equalTypes(descriptor.valueParameters.single().type, type) }
descriptor.verifyOrNull { KotlinTypeChecker.DEFAULT.equalTypes(descriptor.valueParameters.single().type, type) }
}
}

View File

@@ -33,7 +33,7 @@ import org.jetbrains.kotlin.platform.JavaToKotlinClassMap
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.typeUtil.createProjection
import org.jetbrains.kotlin.types.typeUtil.isTypeParameter
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import org.jetbrains.kotlin.utils.toReadOnlyList
// The index in the lambda is the position of the type component:
@@ -52,7 +52,7 @@ private enum class TypeComponentPosition {
}
private open class Result(open val type: KotlinType, val subtreeSize: Int, val wereChanges: Boolean) {
val typeIfChanged: KotlinType? get() = type.check { wereChanges }
val typeIfChanged: KotlinType? get() = type.verifyOrNull { wereChanges }
}
private class SimpleResult(override val type: SimpleType, subtreeSize: Int, wereChanges: Boolean): Result(type, subtreeSize, wereChanges)

View File

@@ -27,7 +27,7 @@ import org.jetbrains.kotlin.serialization.deserialization.DeserializationCompone
import org.jetbrains.kotlin.serialization.deserialization.IncompatibleVersionErrorData
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedPackageMemberScope
import org.jetbrains.kotlin.serialization.jvm.JvmProtoBufUtil
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import javax.inject.Inject
class DeserializedDescriptorResolver {
@@ -80,7 +80,7 @@ class DeserializedDescriptorResolver {
internal fun readData(kotlinClass: KotlinJvmBinaryClass, expectedKinds: Set<KotlinClassHeader.Kind>): Array<String>? {
val header = kotlinClass.classHeader
return (header.data ?: header.incompatibleData)?.check { header.kind in expectedKinds }
return (header.data ?: header.incompatibleData)?.verifyOrNull { header.kind in expectedKinds }
}
private inline fun <T : Any> parseProto(klass: KotlinJvmBinaryClass, block: () -> T): T? {

View File

@@ -51,7 +51,7 @@ import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.LazyWrappedType
import org.jetbrains.kotlin.utils.DFS
import org.jetbrains.kotlin.utils.SmartSet
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import org.jetbrains.kotlin.utils.addToStdlib.singletonList
import java.io.Serializable
import java.util.*
@@ -285,7 +285,7 @@ open class JvmBuiltInsSettings(
// No additional members should be added to Any
if (isAny) return null
val fqName = fqNameUnsafe.check { it.isSafe }?.toSafe() ?: return null
val fqName = fqNameUnsafe.verifyOrNull { it.isSafe }?.toSafe() ?: return null
val javaAnalogueFqName = j2kClassMap.mapKotlinToJava(fqName.toUnsafe())?.asSingleFqName() ?: return null
return ownerModuleDescriptor.resolveClassByFqName(javaAnalogueFqName, NoLookupLocation.FROM_BUILTINS) as? LazyJavaClassDescriptor

View File

@@ -38,7 +38,7 @@ import org.jetbrains.kotlin.types.typeUtil.asTypeProjection
import org.jetbrains.kotlin.types.typeUtil.replaceAnnotations
import org.jetbrains.kotlin.utils.DFS
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import java.util.*
private fun KotlinType.isTypeOrSubtypeOf(predicate: (KotlinType) -> Boolean): Boolean =
@@ -150,7 +150,7 @@ fun KotlinType.extractParameterNameFromFunctionTypeArgument(): Name? {
val annotation = annotations.findAnnotation(KotlinBuiltIns.FQ_NAMES.parameterName) ?: return null
val name = (annotation.allValueArguments.values.singleOrNull() as? StringValue)
?.value
?.check { Name.isValidIdentifier(it) }
?.verifyOrNull { Name.isValidIdentifier(it) }
?: return null
return Name.identifier(name)
}
@@ -167,7 +167,7 @@ fun getFunctionTypeArgumentProjections(
arguments.addIfNotNull(receiverType?.asTypeProjection())
parameterTypes.mapIndexedTo(arguments) { index, type ->
val name = parameterNames?.get(index)?.check { !it.isSpecial }
val name = parameterNames?.get(index)?.verifyOrNull { !it.isSpecial }
val typeToUse = if (name != null) {
val annotationClass = builtIns.getBuiltInClassByName(KotlinBuiltIns.FQ_NAMES.parameterName.shortName())
val nameValue = ConstantValueFactory(builtIns).createStringValue(name.asString())

View File

@@ -39,7 +39,7 @@ import org.jetbrains.kotlin.types.typeUtil.isAnyOrNullableAny
import org.jetbrains.kotlin.types.typeUtil.makeNullable
import org.jetbrains.kotlin.utils.DFS
import org.jetbrains.kotlin.utils.SmartList
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
fun ClassDescriptor.getClassObjectReferenceTarget(): ClassDescriptor = companionObjectDescriptor ?: this
@@ -220,7 +220,7 @@ val DeclarationDescriptor.parents: Sequence<DeclarationDescriptor>
val CallableMemberDescriptor.propertyIfAccessor: CallableMemberDescriptor
get() = if (this is PropertyAccessorDescriptor) correspondingProperty else this
fun CallableDescriptor.fqNameOrNull(): FqName? = fqNameUnsafe.check { it.isSafe }?.toSafe()
fun CallableDescriptor.fqNameOrNull(): FqName? = fqNameUnsafe.verifyOrNull { it.isSafe }?.toSafe()
fun CallableMemberDescriptor.firstOverridden(
useOriginal: Boolean = false,

View File

@@ -26,7 +26,7 @@ import org.jetbrains.kotlin.types.checker.TypeCheckerContext.SupertypesPolicy
import org.jetbrains.kotlin.types.typeUtil.asTypeProjection
import org.jetbrains.kotlin.types.typeUtil.makeNullable
import org.jetbrains.kotlin.utils.SmartList
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
object StrictEqualityTypeChecker {
/**
@@ -102,7 +102,7 @@ object NewKotlinTypeChecker : KotlinTypeChecker {
fun transformToNewType(type: SimpleType): SimpleType {
if (type is CapturedType) {
val lowerType = type.typeProjection.check { it.projectionKind == Variance.IN_VARIANCE }?.type?.unwrap()
val lowerType = type.typeProjection.verifyOrNull { it.projectionKind == Variance.IN_VARIANCE }?.type?.unwrap()
// it is incorrect calculate this type directly because of recursive star projections
if (type.constructor.newTypeConstructor == null) {
@@ -188,7 +188,7 @@ object NewKotlinTypeChecker : KotlinTypeChecker {
val newArguments = superConstructor.parameters.mapIndexed { index, parameterDescriptor ->
val allProjections = supertypesWithSameConstructor.map {
it.arguments.getOrNull(index)?.check { it.projectionKind == Variance.INVARIANT }?.type?.unwrap()
it.arguments.getOrNull(index)?.verifyOrNull { it.projectionKind == Variance.INVARIANT }?.type?.unwrap()
?: error("Incorrect type: $it, subType: $subType, superType: $superType")
}

View File

@@ -18,7 +18,7 @@ package org.jetbrains.kotlin.types.checker
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.utils.SmartSet
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import java.util.*
open class TypeCheckerContext(val errorTypeEqualsToAnything: Boolean) {
@@ -85,7 +85,7 @@ open class TypeCheckerContext(val errorTypeEqualsToAnything: Boolean) {
return true
}
val policy = supertypesPolicy(current).check { it != SupertypesPolicy.None } ?: continue
val policy = supertypesPolicy(current).verifyOrNull { it != SupertypesPolicy.None } ?: continue
for (supertype in current.constructor.supertypes) deque.add(policy.transformType(supertype))
}

View File

@@ -76,7 +76,10 @@ fun <T> sequenceOfLazyValues(vararg elements: () -> T): Sequence<T> = elements.a
fun <T1, T2> Pair<T1, T2>.swap(): Pair<T2, T1> = Pair(second, first)
fun <T: Any> T.check(predicate: (T) -> Boolean): T? = if (predicate(this)) this else null
fun <T> T.verifyOrNull(predicate: (T) -> Boolean): T? = if (predicate(this)) this else null
@Deprecated("Use verifyOrNull instead", ReplaceWith("this.verifyOrNull(predicate)"))
fun <T: Any> T.check(predicate: (T) -> Boolean): T? = verifyOrNull(predicate)
inline fun <reified T : Any> Any?.safeAs(): T? = this as? T
inline fun <reified T : Any> Any?.cast(): T = this as T

View File

@@ -42,7 +42,7 @@ import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.expressions.DoubleColonLHS
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import java.util.*
class ReferenceVariantsHelper(
@@ -277,7 +277,7 @@ class ReferenceVariantsHelper(
val qualifier = bindingContext[BindingContext.QUALIFIER, receiverExpression] ?: return emptyList()
val staticDescriptors = qualifier.staticScope.getDescriptorsFiltered(kindFilter, nameFilter)
val objectDescriptor = (qualifier as? ClassQualifier)?.descriptor?.check { it.kind == ClassKind.OBJECT } ?: return staticDescriptors
val objectDescriptor = (qualifier as? ClassQualifier)?.descriptor?.verifyOrNull { it.kind == ClassKind.OBJECT } ?: return staticDescriptors
return staticDescriptors + objectDescriptor.defaultType.memberScope.getDescriptorsFiltered(kindFilter, nameFilter)
}

View File

@@ -27,7 +27,7 @@ import org.jetbrains.kotlin.resolve.calls.inference.constraintPosition.Constrain
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.checker.StrictEqualityTypeChecker
import org.jetbrains.kotlin.types.typeUtil.*
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import java.util.*
fun CallableDescriptor.fuzzyReturnType() = returnType?.toFuzzyType(typeParameters)
@@ -182,7 +182,7 @@ class FuzzyType(
valueTransform = {
val typeProjection = TypeProjectionImpl(Variance.INVARIANT, it.defaultType)
val substitutedProjection = substitutorToKeepCapturedTypes.substitute(typeProjection)
substitutedProjection?.check { !ErrorUtils.containsUninferredParameter(it.type) } ?: typeProjection
substitutedProjection?.verifyOrNull { !ErrorUtils.containsUninferredParameter(it.type) } ?: typeProjection
})
return TypeConstructorSubstitution.createByConstructorsMap(substitutionMap, approximateCapturedTypes = true).buildSubstitutor()
}

View File

@@ -48,7 +48,7 @@ import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.expressions.OperatorConventions
import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.kotlin.util.isValidOperator
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import java.util.*
abstract class OperatorReferenceSearcher<TReferenceElement : KtElement>(
@@ -227,7 +227,7 @@ abstract class OperatorReferenceSearcher<TReferenceElement : KtElement>(
}
private fun extractReceiverType(): FuzzyType? {
val descriptor = resolveTargetToDescriptor()?.check { it.isValidOperator() } ?: return null
val descriptor = resolveTargetToDescriptor()?.verifyOrNull { it.isValidOperator() } ?: return null
return if (descriptor.isExtension) {
descriptor.fuzzyExtensionReceiverType()!!

View File

@@ -41,7 +41,7 @@ import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.OverridingUtil
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
val KtDeclaration.descriptor: DeclarationDescriptor?
get() = this.analyze().get(BindingContext.DECLARATION_TO_DESCRIPTOR, this)
@@ -163,7 +163,7 @@ private fun processInheritorsDelegatingCallToSpecifiedConstructor(
): Boolean {
return HierarchySearchRequest(klass, scope, false).searchInheritors().all {
runReadAction {
val unwrapped = it.check { it.isValid }?.unwrapped
val unwrapped = it.verifyOrNull { it.isValid }?.unwrapped
if (unwrapped is KtClass)
processClassDelegationCallsToSpecifiedConstructor(unwrapped, descriptor, process)
else

View File

@@ -51,7 +51,7 @@ import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindExclude
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.util.supertypesWithAny
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import java.util.*
@@ -347,8 +347,8 @@ class BasicCompletionSession(
if (userType != typeRef.typeElement) return null
val parent = typeRef.parent
return when (parent) {
is KtNamedFunction -> parent.check { typeRef == it.receiverTypeReference }
is KtProperty -> parent.check { typeRef == it.receiverTypeReference }
is KtNamedFunction -> parent.verifyOrNull { typeRef == it.receiverTypeReference }
is KtProperty -> parent.verifyOrNull { typeRef == it.receiverTypeReference }
else -> null
}
}

View File

@@ -46,7 +46,7 @@ import org.jetbrains.kotlin.resolve.inline.InlineUtil
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.TypeNullability
import org.jetbrains.kotlin.types.typeUtil.nullability
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import java.util.*
tailrec fun <T : Any> LookupElement.putUserDataDeep(key: Key<T>, value: T?) {
@@ -413,7 +413,7 @@ fun ImportableFqNameClassifier.isImportableDescriptorImported(descriptor: Declar
fun OffsetMap.tryGetOffset(key: OffsetKey): Int? {
try {
return getOffset(key).check { it != -1 } // prior to IDEA 2016.3 getOffset() returned -1 if not found, now it throws exception
return getOffset(key).verifyOrNull { it != -1 } // prior to IDEA 2016.3 getOffset() returned -1 if not found, now it throws exception
}
catch(e: Exception) {
return null

View File

@@ -45,7 +45,7 @@ import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.typeUtil.isBooleanOrNullableBoolean
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import org.jetbrains.kotlin.utils.addToStdlib.singletonList
import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptySet
import java.util.*
@@ -94,7 +94,7 @@ class SmartCompletion(
val descriptorFilter: ((DeclarationDescriptor, AbstractLookupElementFactory) -> Collection<LookupElement>)? =
{ descriptor: DeclarationDescriptor, factory: AbstractLookupElementFactory ->
filterDescriptor(descriptor, factory).map { postProcess(it) }
}.check { expectedInfos.isNotEmpty() }
}.verifyOrNull { expectedInfos.isNotEmpty() }
fun additionalItems(lookupElementFactory: LookupElementFactory): Pair<Collection<LookupElement>, InheritanceItemsSearcher?> {
val (items, inheritanceSearcher) = additionalItemsNoPostProcess(lookupElementFactory)

View File

@@ -40,7 +40,7 @@ import org.jetbrains.kotlin.types.TypeSubstitutor
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.types.typeUtil.*
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptyList
import java.util.*
@@ -582,7 +582,7 @@ class ExpectedInfos(
val loopVar = forExpression.loopParameter
val loopVarType = if (loopVar != null && loopVar.typeReference != null)
(bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, loopVar] as VariableDescriptor).type.check { !it.isError }
(bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, loopVar] as VariableDescriptor).type.verifyOrNull { !it.isError }
else
null
@@ -624,7 +624,7 @@ class ExpectedInfos(
?: property.dispatchReceiverParameter?.type?.toFuzzyType(emptyList())
?: property.builtIns.nullableNothingType.toFuzzyType(emptyList())
val explicitPropertyType = property.fuzzyReturnType()?.check { propertyDeclaration.typeReference != null }
val explicitPropertyType = property.fuzzyReturnType()?.verifyOrNull { propertyDeclaration.typeReference != null }
?: property.overriddenDescriptors.singleOrNull()?.fuzzyReturnType() // for override properties use super property type as explicit (if not specified)
val typesWithGetDetector = TypesWithGetValueDetector(scope, indicesHelper, propertyOwnerType, explicitPropertyType)
val typesWithSetDetector = if (property.isVar) TypesWithSetValueDetector(scope, indicesHelper, propertyOwnerType) else null

View File

@@ -21,7 +21,7 @@ import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
class ClassUsageReplacementStrategy(
typeReplacement: KtUserType?,
@@ -31,7 +31,7 @@ class ClassUsageReplacementStrategy(
private val factory = KtPsiFactory(project)
private val typeReplacement = typeReplacement?.check { it.referenceExpression != null }
private val typeReplacement = typeReplacement?.verifyOrNull { it.referenceExpression != null }
private val typeReplacementQualifierAsExpression = typeReplacement?.qualifier?.let { factory.createExpression(it.text) }
private val constructorReplacementStrategy = constructorReplacement?.let(::CallableUsageReplacementStrategy)

View File

@@ -35,7 +35,7 @@ import org.jetbrains.kotlin.resolve.scopes.LexicalScope
import org.jetbrains.kotlin.resolve.scopes.utils.findLocalVariable
import org.jetbrains.kotlin.types.ErrorUtils
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
/**
* Modifies [MutableCodeToInline] introducing a variable initialized by [value] and replacing all of [usages] with its use.
@@ -93,7 +93,7 @@ internal fun MutableCodeToInline.introduceValue(
val declaration = psiFactory.createDeclarationByPattern<KtVariableDeclaration>("val $0 = $1", name, value)
statementsBefore.add(0, declaration)
val explicitType = valueType?.check {
val explicitType = valueType?.verifyOrNull {
variableNeedsExplicitType(value, valueType, expressionToBeReplaced, resolutionScope, bindingContext)
}
if (explicitType != null) {

View File

@@ -44,7 +44,7 @@ import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import org.jetbrains.kotlin.utils.addToStdlib.ifNotEmpty
import java.awt.datatransfer.DataFlavor
import java.awt.datatransfer.Transferable
@@ -168,7 +168,7 @@ class ConvertTextJavaCopyPasteProcessor : CopyPastePostProcessor<TextBlockTransf
if (isParsedAsKotlinCode(text, pasteContext, project)) return null
fun JavaContext.check(): JavaContext? {
return check { isParsedAsJavaCode(text, it, project) }
return verifyOrNull { isParsedAsJavaCode(text, it, project) }
}
when (pasteContext) {

View File

@@ -39,7 +39,7 @@ import org.jetbrains.kotlin.idea.refactoring.getLineStartOffset
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import java.util.*
class KotlinFrameExtraVariablesProvider : FrameExtraVariablesProvider {
@@ -64,7 +64,7 @@ private fun findAdditionalExpressions(position: SourcePosition): Set<TextWithImp
return emptySet()
}
val offset = file.getLineStartOffset(line)?.check { it > 0 } ?: return emptySet()
val offset = file.getLineStartOffset(line)?.verifyOrNull { it > 0 } ?: return emptySet()
val elem = file.findElementAt(offset)
val containingElement = getContainingElement(elem!!) ?: elem ?: return emptySet()

View File

@@ -46,7 +46,7 @@ import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import org.jetbrains.kotlin.utils.getOrPutNullable
import org.jetbrains.org.objectweb.asm.*
import java.io.File
@@ -174,7 +174,7 @@ private fun readClassFileImpl(project: Project,
}
private fun findClassFileByPath(packageName: String, className: String, outputDir: VirtualFile): File? {
val outDirFile = File(outputDir.path).check(File::exists) ?: return null
val outDirFile = File(outputDir.path).verifyOrNull(File::exists) ?: return null
val parentDirectory = File(outDirFile, packageName.replace(".", File.separator))
if (!parentDirectory.exists()) return null

View File

@@ -57,7 +57,7 @@ import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.makeNullable
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import java.util.concurrent.atomic.AtomicReference
class KotlinCodeFragmentFactory: CodeFragmentFactory() {
@@ -323,7 +323,7 @@ class KotlinCodeFragmentFactory: CodeFragmentFactory() {
return containingFile
}
private fun KtElement?.check(): Boolean = this != null && this.check { KotlinEditorTextProvider.isAcceptedAsCodeFragmentContext(it) } != null
private fun KtElement?.check(): Boolean = this != null && this.verifyOrNull { KotlinEditorTextProvider.isAcceptedAsCodeFragmentContext(it) } != null
//internal for tests
fun createCodeFragmentForLabeledObjects(project: Project, markupMap: Map<*, ValueMarkup>): Pair<String, Map<String, Value>> {
@@ -398,7 +398,7 @@ class KotlinCodeFragmentFactory: CodeFragmentFactory() {
val sb = StringBuilder()
javaFile?.packageName?.check { !it.isBlank() }?.let {
javaFile?.packageName?.verifyOrNull { !it.isBlank() }?.let {
sb.append("package ").append(it.quoteIfNeeded()).append("\n")
}

View File

@@ -51,7 +51,7 @@ import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.findOriginalTopMostOverriddenDescriptors
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
abstract class KotlinFindMemberUsagesHandler<T : KtNamedDeclaration>
protected constructor(declaration: T, elementsToSearch: Collection<PsiElement>, factory: KotlinFindUsagesHandlerFactory)
@@ -164,7 +164,7 @@ abstract class KotlinFindMemberUsagesHandler<T : KtNamedDeclaration>
addTask {
val overriders = HierarchySearchRequest(element, options.searchScope, true).searchOverriders()
overriders.all {
val element = runReadAction { it.check { it.isValid }?.navigationElement } ?: return@all true
val element = runReadAction { it.verifyOrNull { it.isValid }?.navigationElement } ?: return@all true
KotlinFindUsagesHandler.processUsage(uniqueProcessor, element)
}
}

View File

@@ -47,7 +47,7 @@ import org.jetbrains.kotlin.resolve.scopes.SyntheticScopes
import org.jetbrains.kotlin.resolve.scopes.collectSyntheticMemberFunctions
import org.jetbrains.kotlin.synthetic.SamAdapterExtensionFunctionDescriptor
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import org.jetbrains.kotlin.utils.addToStdlib.singletonList
class RedundantSamConstructorInspection : AbstractKotlinInspection() {
@@ -179,7 +179,7 @@ class RedundantSamConstructorInspection : AbstractKotlinInspection() {
for (staticFunWithSameName in containingClass.staticScope.getContributedFunctions(functionResolvedCall.resultingDescriptor.name, NoLookupLocation.FROM_IDE)) {
if (staticFunWithSameName is SamAdapterDescriptor<*>) {
if (isSamAdapterSuitableForCall(staticFunWithSameName, originalFunctionDescriptor, samConstructorCallArguments.size)) {
return samConstructorCallArguments.check { canBeReplaced(functionCall, it) } ?: emptyList()
return samConstructorCallArguments.verifyOrNull { canBeReplaced(functionCall, it) } ?: emptyList()
}
}
}
@@ -193,7 +193,7 @@ class RedundantSamConstructorInspection : AbstractKotlinInspection() {
for (syntheticExtension in syntheticExtensions) {
val samAdapter = syntheticExtension as? SamAdapterExtensionFunctionDescriptor ?: continue
if (isSamAdapterSuitableForCall(samAdapter, originalFunctionDescriptor, samConstructorCallArguments.size)) {
return samConstructorCallArguments.check { canBeReplaced(functionCall, it) } ?: emptyList()
return samConstructorCallArguments.verifyOrNull { canBeReplaced(functionCall, it) } ?: emptyList()
}
}
@@ -204,7 +204,7 @@ class RedundantSamConstructorInspection : AbstractKotlinInspection() {
= argument.toCallExpression()?.samConstructorValueArgument() != null
private fun KtCallExpression.samConstructorValueArgument(): KtValueArgument? {
return valueArguments.singleOrNull()?.check { it.getArgumentExpression() is KtLambdaExpression }
return valueArguments.singleOrNull()?.verifyOrNull { it.getArgumentExpression() is KtLambdaExpression }
}
private fun ValueArgument.toCallExpression(): KtCallExpression? {

View File

@@ -28,7 +28,7 @@ import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
class ConvertAssertToIfWithThrowIntention : SelfTargetingIntention<KtCallExpression>(KtCallExpression::class.java, "Replace 'assert' with 'if' statement"), LowPriorityAction {
override fun isApplicableTo(element: KtCallExpression, caretOffset: Int): Boolean {
@@ -93,7 +93,7 @@ class ConvertAssertToIfWithThrowIntention : SelfTargetingIntention<KtCallExpress
private fun extractMessageSingleExpression(functionLiteral: KtLambdaExpression, bindingContext: BindingContext): KtExpression? {
return functionLiteral.bodyExpression?.statements?.singleOrNull()?.let { singleStatement ->
singleStatement.check { it.isUsedAsExpression(bindingContext) }
singleStatement.verifyOrNull { it.isUsedAsExpression(bindingContext) }
}
}

View File

@@ -30,7 +30,7 @@ import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
class ConvertToExpressionBodyIntention(
val convertEmptyToUnit: Boolean = true
@@ -62,7 +62,7 @@ class ConvertToExpressionBodyIntention(
val deleteTypeHandler: (KtCallableDeclaration) -> Unit = {
it.deleteChildRange(it.colon!!, it.typeReference!!)
}
applyTo(declaration, deleteTypeHandler.check { canDeleteTypeRef })
applyTo(declaration, deleteTypeHandler.verifyOrNull { canDeleteTypeRef })
}
private fun applyTo(declaration: KtDeclarationWithBody, deleteTypeHandler: ((KtCallableDeclaration) -> Unit)?) {

View File

@@ -19,7 +19,7 @@ package org.jetbrains.kotlin.idea.intentions.branchedTransformations
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.lastBlockStatementOrThis
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
object BranchedFoldingUtils {
fun getFoldableBranchedAssignment(branch: KtExpression?): KtBinaryExpression? {
@@ -36,11 +36,11 @@ object BranchedFoldingUtils {
return true
}
return (branch?.lastBlockStatementOrThis() as? KtBinaryExpression)?.check(::checkAssignment)
return (branch?.lastBlockStatementOrThis() as? KtBinaryExpression)?.verifyOrNull(::checkAssignment)
}
fun getFoldableBranchedReturn(branch: KtExpression?): KtReturnExpression? {
return (branch?.lastBlockStatementOrThis() as? KtReturnExpression)?.check { it.returnedExpression != null }
return (branch?.lastBlockStatementOrThis() as? KtReturnExpression)?.verifyOrNull { it.returnedExpression != null }
}
fun checkAssignmentsMatch(a1: KtBinaryExpression, a2: KtBinaryExpression): Boolean {

View File

@@ -35,7 +35,7 @@ import org.jetbrains.kotlin.resolve.DescriptorUtils.isSubtypeOfClass
import org.jetbrains.kotlin.resolve.calls.smartcasts.ExplicitSmartCasts
import org.jetbrains.kotlin.resolve.calls.smartcasts.ImplicitSmartCasts
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
object MatcherRegistrar {
val matchers: Collection<TransformationMatcher> = listOf(
@@ -138,7 +138,7 @@ fun match(loop: KtForExpression, useLazySequence: Boolean): MatchResult? {
return MatchResult(sequenceExpression, result, state.initializationStatementsToDelete)
.check { checkSmartCastsPreserved(loop, it) }
.verifyOrNull { checkSmartCastsPreserved(loop, it) }
}
}
}

View File

@@ -28,7 +28,7 @@ import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.PsiChildRange
import org.jetbrains.kotlin.types.typeUtil.TypeNullability
import org.jetbrains.kotlin.types.typeUtil.nullability
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
/**
* Matches:
@@ -361,8 +361,8 @@ object FindTransformationMatcher : TransformationMatcher {
if (this !is KtBinaryExpression) return null
if (operationToken != KtTokens.EQEQ) return null
return when {
left.isVariableReference(inputVariable) -> right?.check { it.isStableInLoop(loop, false) }
right.isVariableReference(inputVariable) -> left?.check { it.isStableInLoop(loop, false) }
left.isVariableReference(inputVariable) -> right?.verifyOrNull { it.isStableInLoop(loop, false) }
right.isVariableReference(inputVariable) -> left?.verifyOrNull { it.isStableInLoop(loop, false) }
else -> null
}
}

View File

@@ -44,7 +44,7 @@ import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import java.util.*
fun generateLambda(inputVariable: KtCallableDeclaration, expression: KtExpression): KtLambdaExpression {
@@ -166,7 +166,7 @@ fun KtExpression?.findVariableInitializationBeforeLoop(
for (statement in prevStatements) {
val variableInitialization = extractVariableInitialization(statement, variable)
if (variableInitialization != null) {
return variableInitialization.check {
return variableInitialization.verifyOrNull {
statementsBetween.all { canSwapExecutionOrder(variableInitialization.initializationStatement, it) }
}
}

View File

@@ -45,7 +45,7 @@ import org.jetbrains.kotlin.types.ErrorUtils
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import java.util.*
abstract class ChangeCallableReturnTypeFix(
@@ -75,7 +75,7 @@ abstract class ChangeCallableReturnTypeFix(
val name = element.name
if (name != null) {
val container = element.resolveToDescriptor().containingDeclaration as? ClassDescriptor
val containerName = container?.name?.check { !it.isSpecial }?.asString()
val containerName = container?.name?.verifyOrNull { !it.isSpecial }?.asString()
val fullName = if (containerName != null) "'$containerName.$name'" else "'$name'"
if (element is KtParameter) {
return "property $fullName"

View File

@@ -45,7 +45,7 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.setSingleOverridden
import org.jetbrains.kotlin.resolve.findMemberWithMaxVisibility
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
import org.jetbrains.kotlin.types.typeUtil.supertypes
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import java.util.*
/**
@@ -252,7 +252,7 @@ class ChangeMemberFunctionSignatureFix private constructor(
object MatchNames : ParameterChooser {
override fun choose(parameter: ValueParameterDescriptor, superParameter: ValueParameterDescriptor): ValueParameterDescriptor? {
return superParameter.check { parameter.name == superParameter.name }
return superParameter.verifyOrNull { parameter.name == superParameter.name }
}
}

View File

@@ -36,7 +36,7 @@ import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.types.ErrorUtils
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import java.util.*
open class ChangeVariableTypeFix(element: KtVariableDeclaration, type: KotlinType) : KotlinQuickFixAction<KtVariableDeclaration>(element) {
@@ -49,7 +49,7 @@ open class ChangeVariableTypeFix(element: KtVariableDeclaration, type: KotlinTyp
val name = element.name
if (name != null) {
val container = element.resolveToDescriptor().containingDeclaration as? ClassDescriptor
val containerName = container?.name?.check { !it.isSpecial }?.asString()
val containerName = container?.name?.verifyOrNull { !it.isSpecial }?.asString()
return if (containerName != null) "'$containerName.$name'" else "'$name'"
}
else {

View File

@@ -19,7 +19,7 @@ package org.jetbrains.kotlin.j2k
import com.intellij.psi.*
import com.intellij.psi.CommonClassNames.*
import org.jetbrains.kotlin.j2k.ast.*
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
class CodeConverter(
val converter: Converter,
@@ -81,7 +81,7 @@ class CodeConverter(
fun convertLocalVariable(variable: PsiLocalVariable): LocalVariable {
val isVal = canChangeType(variable)
val type = typeConverter.convertVariableType(variable)
val explicitType = type.check { settings.specifyLocalVariableTypeByDefault || converter.shouldDeclareVariableType(variable, type, isVal) }
val explicitType = type.verifyOrNull { settings.specifyLocalVariableTypeByDefault || converter.shouldDeclareVariableType(variable, type, isVal) }
return LocalVariable(variable.declarationIdentifier(),
converter.convertAnnotations(variable),
converter.convertModifiers(variable, false),

View File

@@ -21,7 +21,7 @@ import com.intellij.psi.CommonClassNames.JAVA_LANG_OBJECT
import com.intellij.psi.CommonClassNames.JAVA_LANG_STRING
import com.intellij.psi.impl.PsiExpressionEvaluator
import org.jetbrains.kotlin.j2k.ast.*
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import java.io.PrintStream
import java.util.*
@@ -346,7 +346,7 @@ enum class SpecialMethod(val qualifiedClassName: String?, val methodName: String
STRING_GET_BYTES(JAVA_LANG_STRING, "getBytes", null) {
override fun ConvertCallData.convertCall(): MethodCallExpression {
val charsetArg = arguments.lastOrNull()?.check { it.type?.canonicalText == JAVA_LANG_STRING }
val charsetArg = arguments.lastOrNull()?.verifyOrNull { it.type?.canonicalText == JAVA_LANG_STRING }
val convertedArguments = codeConverter.convertExpressionsInList(arguments).map {
if (charsetArg != null && it.prototypes?.singleOrNull()?.element == charsetArg)
MethodCallExpression.buildNonNull(null, "charset", ArgumentList.withNoPrototype(it)).assignNoPrototype()
@@ -523,7 +523,7 @@ enum class SpecialMethod(val qualifiedClassName: String?, val methodName: String
val candidates = valuesByName[method.name] ?: return null
return candidates
.firstOrNull { it.matches(method, services.superMethodsSearcher) }
?.check { it.parameterCount == null || it.parameterCount == argumentCount } // if parameterCount is specified we should make sure that argument count is correct
?.verifyOrNull { it.parameterCount == null || it.parameterCount == argumentCount } // if parameterCount is specified we should make sure that argument count is correct
}
}
}

View File

@@ -28,7 +28,7 @@ import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
import java.util.*
class PropertyInfo(
@@ -227,7 +227,7 @@ private class PropertyDetector(
converter.convertModifiers(field, false).accessModifier()
else
propertyAccess
val specialSetterAccess = setterAccess?.check { it != propertyAccess }
val specialSetterAccess = setterAccess?.verifyOrNull { it != propertyAccess }
val propertyInfo = PropertyInfo(Identifier.withNoPrototype(propertyName),
isVar,

View File

@@ -25,10 +25,10 @@ import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.addToStdlib.check
import org.jetbrains.kotlin.utils.addToStdlib.verifyOrNull
val KotlinType.nameIfStandardType: Name?
get() = constructor.declarationDescriptor?.check(KotlinBuiltIns::isBuiltIn)?.name
get() = constructor.declarationDescriptor?.verifyOrNull(KotlinBuiltIns::isBuiltIn)?.name
fun KotlinType.getJetTypeFqName(printTypeArguments: Boolean): String {
val declaration = requireNotNull(constructor.declarationDescriptor)

View File

@@ -48,12 +48,26 @@ public inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block
@kotlin.internal.InlineOnly
public inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this }
/**
* Calls the specified function [block] supplying `this` value as its argument and returns `this` value.
*/
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.supply(block: (T) -> Unit): T { block(this); return this }
/**
* Calls the specified function [block] with `this` value as its argument and returns its result.
*/
@kotlin.internal.InlineOnly
public inline fun <T, R> T.let(block: (T) -> R): R = block(this)
/**
* Verifies whether the given [predicate] holds for `this` value and returns `this` value if it does, or `null` otherwise.
*/
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.verifyOrNull(predicate: (T) -> Boolean): T? = if (predicate(this)) this else null
/**
* Executes the given function [action] specified number of [times].