[FE 1.0] Remove usages of safeAs and cast from most of FE 1.0 modules:

- :core:descriptors
- :core:descriptors.jvm
- :core:deserialization
- :compiler:cli
- :compiler:frontend
- :compiler:frontend:cfg
- :compiler:frontend.java
- :compiler:frontend.common.jvm
- :compiler:psi
- :compiler:resolution
- :compiler:resolution.common
- :compiler:resolution.common.jvm
- :kotlin-reflect-api
This commit is contained in:
Dmitriy Novozhilov
2022-10-11 15:26:45 +03:00
committed by Space Team
parent 6afceb1e84
commit d423782fac
65 changed files with 156 additions and 241 deletions
-13
View File
@@ -386,25 +386,12 @@ val projectsWithOptInToUnsafeCastFunctionsFromAddToStdLib by extra {
":compiler:backend.jvm.codegen",
":compiler:backend.jvm.entrypoint",
":compiler:backend.jvm.lower",
":compiler:cli",
":compiler:frontend:cfg",
":compiler:frontend.common.jvm",
":compiler:frontend.java",
":compiler:frontend",
":compiler:ir.backend.common",
":compiler:ir.psi2ir",
":compiler:ir.serialization.jvm",
":compiler:ir.tree",
":compiler:light-classes",
":compiler:psi",
":compiler:resolution.common.jvm",
":compiler:resolution.common",
":compiler:resolution",
":core:descriptors.jvm",
":core:descriptors",
":core:deserialization",
":core:reflection.jvm",
":kotlin-reflect-api",
":jps:jps-common",
":jps:jps-common",
":js:js.tests",
@@ -21,7 +21,6 @@ import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics
import org.jetbrains.kotlin.utils.addToStdlib.cast
private val JAVA_API_STUB = Key.create<CachedValue<Diagnostics>>("JAVA_API_STUB")
@@ -48,7 +47,7 @@ object CliExtraDiagnosticsProvider {
.findFilesForFacade(facadeFqName, GlobalSearchScope.allScope(project))
.ifEmpty { return Diagnostics.EMPTY }
val context = LightClassGenerationSupport.getInstance(project).cast<CliLightClassGenerationSupport>().context
val context = (LightClassGenerationSupport.getInstance(project) as CliLightClassGenerationSupport).context
val (_, _, diagnostics) = extraJvmDiagnosticsFromBackend(
facadeFqName.parent(),
facadeCollection,
@@ -20,7 +20,6 @@ import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics
import org.jetbrains.kotlin.utils.addToStdlib.cast
import org.jetbrains.org.objectweb.asm.Type
internal class LightClassDataProviderForClassOrObject(
@@ -29,7 +28,7 @@ internal class LightClassDataProviderForClassOrObject(
private fun computeLightClassData(): Diagnostics {
val file = classOrObject.containingKtFile
val packageFqName = file.packageFqName
val cliSupport = LightClassGenerationSupport.getInstance(classOrObject.project).cast<CliLightClassGenerationSupport>()
val cliSupport = LightClassGenerationSupport.getInstance(classOrObject.project) as CliLightClassGenerationSupport
//force resolve companion for light class generation
cliSupport.traceHolder.bindingContext.get(BindingContext.CLASS, classOrObject)?.companionObjectDescriptor
@@ -16,7 +16,6 @@ import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ConflictingJvmDeclarationsData
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm.*
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOriginKind.*
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
fun getJvmSignatureDiagnostics(element: PsiElement, otherDiagnostics: Diagnostics): Diagnostics? {
fun getDiagnosticsForClass(ktClassOrObject: KtClassOrObject): Diagnostics {
@@ -25,7 +24,7 @@ fun getJvmSignatureDiagnostics(element: PsiElement, otherDiagnostics: Diagnostic
}
fun doGetDiagnostics(): Diagnostics? {
if (element.containingFile.safeAs<KtFile>()?.safeIsScript() == true) return null
if ((element.containingFile as? KtFile)?.safeIsScript() == true) return null
var parent = element.parent
if (element is KtPropertyAccessor) {
@@ -18,7 +18,6 @@ import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedMemberDescriptor
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
object JvmFileClassUtil {
val JVM_NAME: FqName = FqName("kotlin.jvm.JvmName")
@@ -90,7 +89,7 @@ object JvmFileClassUtil {
val stringTemplateExpression = annotation.valueArguments.firstOrNull()?.run {
when (this) {
is KtValueArgument -> stringTemplateExpression
else -> getArgumentExpression().safeAs<KtStringTemplateExpression>()
else -> getArgumentExpression() as? KtStringTemplateExpression
}
} ?: return null
@@ -20,18 +20,13 @@ import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.load.java.lazy.descriptors.LazyJavaPackageFragment
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedCallableMemberDescriptor
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedClassDescriptor
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
fun CallableDescriptor.getContainingKotlinJvmBinaryClass(): KotlinJvmBinaryClass? {
if (this !is DeserializedCallableMemberDescriptor) return null
val container = containingDeclaration
return when (container) {
is DeserializedClassDescriptor ->
container.source.safeAs<KotlinJvmBinarySourceElement>()?.binaryClass
is LazyJavaPackageFragment ->
container.source.safeAs<KotlinJvmBinaryPackageSourceElement>()?.getRepresentativeBinaryClass()
return when (val container = containingDeclaration) {
is DeserializedClassDescriptor -> (container.source as? KotlinJvmBinarySourceElement)?.binaryClass
is LazyJavaPackageFragment -> (container.source as? KotlinJvmBinaryPackageSourceElement)?.getRepresentativeBinaryClass()
else -> null
}
}
@@ -128,7 +128,7 @@ object RuntimeAssertionsOnExtensionReceiverCallChecker : CallChecker {
private fun checkReceiver(receiverParameter: ReceiverParameterDescriptor?, receiverValue: ReceiverValue?, context: CallCheckerContext) {
if (receiverParameter == null || receiverValue == null) return
val expressionReceiverValue = receiverValue.safeAs<ExpressionReceiver>() ?: return
val expressionReceiverValue = receiverValue as? ExpressionReceiver ?: return
val receiverExpression = expressionReceiverValue.expression
val c = context.resolutionContext
@@ -22,7 +22,6 @@ import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.BindingContextUtils.variableDescriptorForDeclaration
import org.jetbrains.kotlin.util.javaslang.*
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingContext: BindingContext) {
private val containsDoWhile = pseudocode.rootPseudocode.containsDoWhile
@@ -118,12 +117,12 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon
private fun isValWithTrivialInitializer(variableDeclarationElement: KtDeclaration, descriptor: VariableDescriptor) =
variableDeclarationElement is KtParameter || variableDeclarationElement is KtObjectDeclaration ||
variableDeclarationElement.safeAs<KtVariableDeclaration>()?.isVariableWithTrivialInitializer(descriptor) == true
(variableDeclarationElement as? KtVariableDeclaration)?.isVariableWithTrivialInitializer(descriptor) == true
private fun KtVariableDeclaration.isVariableWithTrivialInitializer(descriptor: VariableDescriptor): Boolean {
if (descriptor.isPropertyWithoutBackingField()) return true
if (isVar) return false
return initializer != null || safeAs<KtProperty>()?.delegate != null || this is KtDestructuringDeclarationEntry
return initializer != null || (this as? KtProperty)?.delegate != null || this is KtDestructuringDeclarationEntry
}
private fun VariableDescriptor.isPropertyWithoutBackingField(): Boolean {
@@ -16,7 +16,6 @@
package org.jetbrains.kotlin.contracts.parsing
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.contracts.parsing.ContractsDslNames.CALLS_IN_PLACE
@@ -34,7 +33,6 @@ import org.jetbrains.kotlin.resolve.calls.model.ExpressionValueArgument
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.types.typeUtil.isBoolean
import org.jetbrains.kotlin.types.typeUtil.isNullableAny
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
object ContractsDslNames {
@@ -91,6 +89,6 @@ fun DeclarationDescriptor.isEqualsDescriptor(): Boolean =
this.returnType?.isBoolean() == true && this.valueParameters.singleOrNull()?.type?.isNullableAny() == true // signature matches
internal fun ResolvedCall<*>.firstArgumentAsExpressionOrNull(): KtExpression? =
this.valueArgumentsByIndex?.firstOrNull()?.safeAs<ExpressionValueArgument>()?.valueArgument?.getArgumentExpression()
(this.valueArgumentsByIndex?.firstOrNull() as? ExpressionValueArgument)?.valueArgument?.getArgumentExpression()
private fun DeclarationDescriptor.equalsDslDescriptor(dslName: Name): Boolean = this.name == dslName && this.isFromContractDsl()
private fun DeclarationDescriptor.equalsDslDescriptor(dslName: Name): Boolean = this.name == dslName && this.isFromContractDsl()
@@ -22,7 +22,6 @@ import org.jetbrains.kotlin.contracts.parsing.*
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
internal class PsiConditionalEffectParser(
collector: ContractParsingDiagnosticsCollector,
@@ -33,11 +32,11 @@ internal class PsiConditionalEffectParser(
val resolvedCall = expression.getResolvedCall(callContext.bindingContext) ?: return null
if (!resolvedCall.resultingDescriptor.isImpliesCallDescriptor()) return null
val effect = contractParserDispatcher.parseEffect(resolvedCall.dispatchReceiver.safeAs<ExpressionReceiver>()?.expression)
?: return null
val effect = contractParserDispatcher.parseEffect((resolvedCall.dispatchReceiver as? ExpressionReceiver)?.expression)
?: return null
val condition = contractParserDispatcher.parseCondition(resolvedCall.firstArgumentAsExpressionOrNull())
?: return null
?: return null
return ConditionalEffectDeclaration(effect, condition)
}
}
}
@@ -48,7 +48,6 @@ import org.jetbrains.kotlin.types.typeUtil.constituentTypes
import org.jetbrains.kotlin.types.typeUtil.contains
import org.jetbrains.kotlin.types.typeUtil.isArrayOfNothing
import org.jetbrains.kotlin.types.typeUtil.isNothing
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
internal class DeclarationsCheckerBuilder(
private val descriptorResolver: DescriptorResolver,
@@ -415,7 +414,7 @@ class DeclarationsChecker(
declaration
}
if (descriptor.containingDeclaration.safeAs<MemberDescriptor>()?.isInlineOnly() == true) return
if ((descriptor.containingDeclaration as? MemberDescriptor)?.isInlineOnly() == true) return
trace.report(BOUNDS_NOT_ALLOWED_IF_BOUNDED_BY_TYPE_PARAMETER.on(reportOn))
}
@@ -42,7 +42,6 @@ import org.jetbrains.kotlin.resolve.calls.util.isOrOverridesSynthesized
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.checker.KotlinTypeRefiner
import org.jetbrains.kotlin.types.checker.NewKotlinTypeCheckerImpl
import org.jetbrains.kotlin.utils.addToStdlib.assertedCast
import java.util.*
class OverrideResolver(
@@ -863,9 +862,8 @@ class OverrideResolver(
if (overriddenDescriptors.isEmpty()) {
val containingDeclaration = declared.containingDeclaration
val declaringClass = containingDeclaration.assertedCast<ClassDescriptor> {
"Overrides may only be resolved in a class, but $declared comes from $containingDeclaration"
}
val declaringClass = containingDeclaration as? ClassDescriptor
?: error("Overrides may only be resolved in a class, but $declared comes from $containingDeclaration")
val invisibleOverriddenDescriptor =
findInvisibleOverriddenDescriptor(
@@ -15,23 +15,20 @@ import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.psiUtil.isContractDescriptionCallPsiCheck
import org.jetbrains.kotlin.psi.psiUtil.isFirstStatement
import org.jetbrains.kotlin.resolve.scopes.LexicalScope
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
/*
* See KT-26386 and KT-30410
*/
fun disableContractsInsideContractsBlock(call: Call, descriptor: CallableDescriptor?, scope: LexicalScope, trace: BindingTrace) {
call.callElement.safeAs<KtExpression>()?.let { callExpression ->
(call.callElement as? KtExpression)?.let { callExpression ->
if (callExpression.isFirstStatement() && callExpression.isContractDescriptionCallPsiCheck()) {
if (descriptor?.isContractCallDescriptor() != true) {
scope.ownerDescriptor
.safeAs<FunctionDescriptor>()
?.getUserData(ContractProviderKey)
?.safeAs<LazyContractProvider>()
?.setContractDescription(null)
val functionDescriptor = scope.ownerDescriptor as? FunctionDescriptor
val contractProvider = functionDescriptor?.getUserData(ContractProviderKey) as? LazyContractProvider
contractProvider?.setContractDescription(null)
} else {
trace.record(BindingContext.IS_CONTRACT_DECLARATION_BLOCK, callExpression, true)
}
}
}
}
}
@@ -62,7 +62,6 @@ import org.jetbrains.kotlin.types.error.ErrorScope
import org.jetbrains.kotlin.types.error.ThrowingScope
import org.jetbrains.kotlin.types.extensions.TypeAttributeTranslators
import org.jetbrains.kotlin.types.typeUtil.*
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import kotlin.math.min
class TypeResolver(
@@ -416,7 +415,7 @@ class TypeResolver(
for (parametersGroup in parametersByName.values) {
if (parametersGroup.size < 2) continue
for (parameter in parametersGroup) {
val ktParameter = parameter.source.getPsi()?.safeAs<KtParameter>() ?: continue
val ktParameter = (parameter.source.getPsi() as? KtParameter) ?: continue
c.trace.report(DUPLICATE_PARAMETER_NAME_IN_FUNCTION_TYPE.on(ktParameter))
}
}
@@ -50,7 +50,6 @@ import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.error.ErrorScopeKind
import org.jetbrains.kotlin.types.error.ErrorUtils
import org.jetbrains.kotlin.types.expressions.DataFlowAnalyzer
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import java.util.*
class CallCompleter(
@@ -113,7 +112,7 @@ class CallCompleter(
missingSupertypesResolver: MissingSupertypesResolver
) {
val call = context.call
val explicitReceiver = call.explicitReceiver.safeAs<ReceiverValue>() ?: return
val explicitReceiver = call.explicitReceiver as? ReceiverValue ?: return
MissingDependencySupertypeChecker.checkSupertypes(
explicitReceiver.type, call.callElement, context.trace, missingSupertypesResolver
@@ -329,7 +328,7 @@ class CallCompleter(
}
private fun createTypeForConvertableConstant(constant: CompileTimeConstant<*>): SimpleType? {
val value = constant.getValue(TypeUtils.NO_EXPECTED_TYPE).safeAs<Number>()?.toLong() ?: return null
val value = (constant.getValue(TypeUtils.NO_EXPECTED_TYPE) as? Number)?.toLong() ?: return null
val typeConstructor = IntegerValueTypeConstructor(value, moduleDescriptor, constant.parameters)
return KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope(
TypeAttributes.Empty, typeConstructor, emptyList(), false,
@@ -51,8 +51,6 @@ import org.jetbrains.kotlin.types.model.freshTypeConstructor
import org.jetbrains.kotlin.types.typeUtil.contains
import org.jetbrains.kotlin.types.typeUtil.isNullableNothing
import org.jetbrains.kotlin.types.typeUtil.makeNullable
import org.jetbrains.kotlin.utils.addToStdlib.cast
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
@@ -184,7 +182,7 @@ class DiagnosticReporterByTrackingStrategy(
override fun onCallReceiver(callReceiver: SimpleKotlinCallArgument, diagnostic: KotlinCallDiagnostic) {
when (diagnostic.javaClass) {
UnsafeCallError::class.java -> {
val unsafeCallErrorDiagnostic = diagnostic.cast<UnsafeCallError>()
val unsafeCallErrorDiagnostic = diagnostic as UnsafeCallError
val isForImplicitInvoke = when (callReceiver) {
is ReceiverExpressionKotlinCallArgument -> callReceiver.isForImplicitInvoke
else -> unsafeCallErrorDiagnostic.isForImplicitInvoke
@@ -248,8 +246,8 @@ class DiagnosticReporterByTrackingStrategy(
trace.report(MIXING_NAMED_AND_POSITIONED_ARGUMENTS.on(callArgument.psiCallArgument.valueArgument.asElement()))
NoneCallableReferenceCallCandidates::class.java -> {
val expression = diagnostic.cast<NoneCallableReferenceCallCandidates>()
.argument.safeAs<CallableReferenceKotlinCallArgumentImpl>()?.ktCallableReferenceExpression
val argument = (diagnostic as? NoneCallableReferenceCallCandidates)?.argument
val expression = (argument as? CallableReferenceKotlinCallArgumentImpl)?.ktCallableReferenceExpression
if (expression != null) {
trace.report(UNRESOLVED_REFERENCE.on(expression.callableReference, expression.callableReference))
}
@@ -260,7 +258,7 @@ class DiagnosticReporterByTrackingStrategy(
val expression = when (val psiExpression = ambiguityDiagnostic.argument.psiExpression) {
is KtPsiUtil.KtExpressionWrapper -> psiExpression.baseExpression
else -> psiExpression
}.safeAs<KtCallableReferenceExpression>()
} as? KtCallableReferenceExpression
val candidates = ambiguityDiagnostic.candidates.map { it.candidate }
if (expression != null) {
@@ -380,8 +378,8 @@ class DiagnosticReporterByTrackingStrategy(
override fun onCallArgumentSpread(callArgument: KotlinCallArgument, diagnostic: KotlinCallDiagnostic) {
when (diagnostic.javaClass) {
NonVarargSpread::class.java -> {
val castedPsiCallArgument = callArgument.safeAs<PSIKotlinCallArgument>()
val castedCallArgument = callArgument.safeAs<ExpressionKotlinCallArgumentImpl>()
val castedPsiCallArgument = callArgument as? PSIKotlinCallArgument
val castedCallArgument = callArgument as? ExpressionKotlinCallArgumentImpl
if (castedCallArgument != null) {
val spreadElement = castedCallArgument.valueArgument.getSpreadElement()
@@ -488,7 +486,7 @@ class DiagnosticReporterByTrackingStrategy(
val typeMismatchDiagnostic = if (isWarning) TYPE_MISMATCH_WARNING else TYPE_MISMATCH
val report = if (isWarning) trace::reportDiagnosticOnce else trace::report
argument?.let {
it.safeAs<LambdaKotlinCallArgument>()?.let lambda@{ lambda ->
(it as? LambdaKotlinCallArgument)?.let lambda@{ lambda ->
val parameterTypes = lambda.parametersTypes?.toList() ?: return@lambda
val index = parameterTypes.indexOf(error.upperKotlinType.unwrap())
val lambdaExpression = lambda.psiExpression as? KtLambdaExpression ?: return@lambda
@@ -516,7 +514,7 @@ class DiagnosticReporterByTrackingStrategy(
}
(position as? ExpectedTypeConstraintPositionImpl)?.let {
val call = it.topLevelCall.psiKotlinCall.psiCall.callElement.safeAs<KtExpression>()
val call = it.topLevelCall.psiKotlinCall.psiCall.callElement as? KtExpression
val inferredType =
if (!error.lowerKotlinType.isNullableNothing()) error.lowerKotlinType
else error.upperKotlinType.makeNullable()
@@ -549,7 +547,7 @@ class DiagnosticReporterByTrackingStrategy(
}
if (morePreciseDiagnosticExists) return
val call = it.resolvedAtom?.atom?.safeAs<PSIKotlinCall>()?.psiCall ?: call
val call = (it.resolvedAtom?.atom as? PSIKotlinCall)?.psiCall ?: call
val expression = call.calleeExpression ?: return
trace.reportDiagnosticOnce(typeMismatchDiagnostic.on(expression, error.upperKotlinType, error.lowerKotlinType))
@@ -566,9 +564,8 @@ class DiagnosticReporterByTrackingStrategy(
error as CapturedTypeFromSubtyping
val position = error.position
val argumentPosition: ArgumentConstraintPositionImpl? =
position.safeAs<ArgumentConstraintPositionImpl>()
?: position.safeAs<IncorporationConstraintPosition>()
?.from.safeAs<ArgumentConstraintPositionImpl>()
position as? ArgumentConstraintPositionImpl
?: (position as? IncorporationConstraintPosition)?.from as? ArgumentConstraintPositionImpl
argumentPosition?.let {
val expression = it.argument.psiExpression ?: return
@@ -689,7 +686,7 @@ class DiagnosticReporterByTrackingStrategy(
}
private fun reportNullabilityMismatchDiagnostic(callArgument: KotlinCallArgument, diagnostic: ArgumentNullabilityMismatchDiagnostic) {
val expression = callArgument.safeAs<PSIKotlinCallArgument>()?.valueArgument?.getArgumentExpression()?.let {
val expression = (callArgument as? PSIKotlinCallArgument)?.valueArgument?.getArgumentExpression()?.let {
KtPsiUtil.deparenthesize(it) ?: it
}
if (expression != null) {
@@ -17,7 +17,6 @@ import org.jetbrains.kotlin.resolve.scopes.receivers.ExtensionReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.getAbbreviation
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
object DslMarkerUtils {
@@ -33,13 +32,12 @@ object DslMarkerUtils {
fun extractDslMarkerFqNames(receiver: ReceiverValue): DslMarkersFromReceiver {
val errorLevel = extractDslMarkerFqNames(receiver.type)
val deprecationLevel =
receiver.safeAs<ExtensionReceiver>()
?.declarationDescriptor
?.safeAs<FunctionDescriptor>()
?.getUserData(FunctionTypeAnnotationsKey)
?.let(Annotations::extractDslMarkerFqNames)
?.toSet() ?: emptySet()
val functionDescriptor = (receiver as? ExtensionReceiver)?.declarationDescriptor as? FunctionDescriptor
val deprecationLevel = functionDescriptor
?.getUserData(FunctionTypeAnnotationsKey)
?.let(Annotations::extractDslMarkerFqNames)
?.toSet()
?: emptySet()
return DslMarkersFromReceiver(errorLevel, deprecationLevel)
}
@@ -51,7 +49,7 @@ object DslMarkerUtils {
kotlinType.getAbbreviation()?.constructor?.declarationDescriptor?.run {
result.addAll(annotations.extractDslMarkerFqNames())
safeAs<TypeAliasDescriptor>()?.run {
(this as? TypeAliasDescriptor)?.run {
result.addAll(extractDslMarkerFqNames(this.underlyingType))
}
}
@@ -48,7 +48,6 @@ import org.jetbrains.kotlin.types.TypeUtils.DONT_CARE
import org.jetbrains.kotlin.types.expressions.ControlStructureTypingUtils.ResolveConstruct
import org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils
import org.jetbrains.kotlin.types.typeUtil.makeNullable
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
val SPECIAL_FUNCTION_NAMES = ResolveConstruct.values().map { it.specialFunctionName }.toSet()
@@ -133,7 +132,7 @@ class GenericCandidateResolver(
if (context.candidateCall is VariableAsFunctionResolvedCall) return
val candidateDescriptor = context.candidateCall.candidateDescriptor.safeAs<FunctionDescriptor>() ?: return
val candidateDescriptor = context.candidateCall.candidateDescriptor as? FunctionDescriptor ?: return
val binaryParent = context.call.calleeExpression?.getBinaryWithTypeParent() ?: return
val operationType = binaryParent.operationReference.getReferencedNameElementType().takeIf {
@@ -531,4 +530,4 @@ private fun KotlinType.isApplicableExpectedTypeForCallableReference(): Boolean {
ReflectionTypes.isBaseTypeForNumberedReferenceTypes(this) ||
ReflectionTypes.isNumberedKFunctionOrKSuspendFunction(this) ||
ReflectionTypes.isNumberedKPropertyOrKMutablePropertyType(this)
}
}
@@ -6,7 +6,6 @@
package org.jetbrains.kotlin.resolve.calls.checkers
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.calls.util.isInfixCall
@@ -15,7 +14,6 @@ import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.serialization.deserialization.KOTLIN_SUSPEND_BUILT_IN_FUNCTION_FQ_NAME
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
object LambdaWithSuspendModifierCallChecker : CallChecker {
@@ -23,7 +21,7 @@ object LambdaWithSuspendModifierCallChecker : CallChecker {
val descriptor = resolvedCall.candidateDescriptor
val call = resolvedCall.call
val calleeName = call.referencedName()
val variableCalleeName = resolvedCall.safeAs<VariableAsFunctionResolvedCall>()?.variableCall?.call?.referencedName()
val variableCalleeName = (resolvedCall as? VariableAsFunctionResolvedCall)?.variableCall?.call?.referencedName()
if (calleeName != "suspend" && variableCalleeName != "suspend" && descriptor.name.asString() != "suspend") return
@@ -48,22 +46,19 @@ object LambdaWithSuspendModifierCallChecker : CallChecker {
}
}
private fun Call.hasFormOfSuspendModifierForLambdaOrFun() =
private fun Call.hasFormOfSuspendModifierForLambdaOrFun(): Boolean =
!isCallableReference()
&& typeArguments.isEmpty()
&& (hasNoArgumentListButDanglingLambdas() || isInfixWithRightLambda() || isInfixWithRightFun())
private fun Call.referencedName() =
calleeExpression?.safeAs<KtSimpleNameExpression>()?.getReferencedName()
private fun Call.referencedName(): String? = (calleeExpression as? KtSimpleNameExpression)?.getReferencedName()
private fun Call.hasNoArgumentListButDanglingLambdas() =
private fun Call.hasNoArgumentListButDanglingLambdas(): Boolean =
valueArgumentList?.leftParenthesis == null && functionLiteralArguments.isNotEmpty()
private fun Call.isInfixWithRightLambda() =
isInfixCall(this)
&& callElement.safeAs<KtBinaryExpression>()?.right is KtLambdaExpression
private fun Call.isInfixWithRightLambda(): Boolean =
isInfixCall(this) && (callElement as? KtBinaryExpression)?.right is KtLambdaExpression
private fun Call.isInfixWithRightFun() =
isInfixCall(this)
&& callElement.safeAs<KtBinaryExpression>()?.right is KtNamedFunction
private fun Call.isInfixWithRightFun(): Boolean =
isInfixCall(this) && (callElement as? KtBinaryExpression)?.right is KtNamedFunction
}
@@ -18,7 +18,6 @@ import org.jetbrains.kotlin.resolve.calls.tower.SimplePSIKotlinCallArgument
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValueWithSmartCastInfo
import org.jetbrains.kotlin.types.FlexibleType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
object NullableVarargArgumentCallChecker : CallChecker {
override fun check(resolvedCall: ResolvedCall<*>, reportOn: PsiElement, context: CallCheckerContext) {
@@ -33,7 +32,7 @@ object NullableVarargArgumentCallChecker : CallChecker {
if (!arg.isSpread || arg !is SimplePSIKotlinCallArgument) continue
val spreadElement = arg.valueArgument.getSpreadElement() ?: continue
val receiver = arg.receiver.safeAs<ReceiverValueWithSmartCastInfo>() ?: continue
val receiver = (arg.receiver as? ReceiverValueWithSmartCastInfo) ?: continue
val type = if (receiver.stableType.constructor is TypeVariableTypeConstructor) {
context.trace.bindingContext[EXPRESSION_TYPE_INFO, arg.valueArgument.getArgumentExpression()]?.type
@@ -48,4 +47,4 @@ object NullableVarargArgumentCallChecker : CallChecker {
}
}
}
}
}
@@ -31,8 +31,6 @@ import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.resolve.scopes.utils.parentsWithSelf
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.supertypes
import org.jetbrains.kotlin.utils.addToStdlib.cast
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
val COROUTINE_CONTEXT_FQ_NAME =
StandardNames.COROUTINES_PACKAGE_FQ_NAME.child(Name.identifier("coroutineContext"))
@@ -48,10 +46,12 @@ fun PropertyDescriptor.isBuiltInCoroutineContext() =
private val ALLOWED_SCOPE_KINDS = setOf(LexicalScopeKind.FUNCTION_INNER_SCOPE, LexicalScopeKind.FUNCTION_HEADER_FOR_DESTRUCTURING)
fun findEnclosingSuspendFunction(context: CallCheckerContext): FunctionDescriptor? =
context.scope.parentsWithSelf.firstOrNull {
it is LexicalScope && it.kind in ALLOWED_SCOPE_KINDS && it.ownerDescriptor.safeAs<FunctionDescriptor>()?.isSuspend == true
}?.cast<LexicalScope>()?.ownerDescriptor?.cast()
fun findEnclosingSuspendFunction(context: CallCheckerContext): FunctionDescriptor? {
val scope = context.scope.parentsWithSelf.firstOrNull {
it is LexicalScope && it.kind in ALLOWED_SCOPE_KINDS && (it.ownerDescriptor as? FunctionDescriptor)?.isSuspend == true
} as LexicalScope?
return scope?.ownerDescriptor as FunctionDescriptor?
}
object CoroutineSuspendCallChecker : CallChecker {
override fun check(resolvedCall: ResolvedCall<*>, reportOn: PsiElement, context: CallCheckerContext) {
@@ -39,7 +39,6 @@ import org.jetbrains.kotlin.types.model.safeSubstitute
import org.jetbrains.kotlin.types.typeUtil.asTypeProjection
import org.jetbrains.kotlin.types.typeUtil.contains
import org.jetbrains.kotlin.types.typeUtil.shouldBeUpdated
import org.jetbrains.kotlin.utils.addToStdlib.cast
class BuilderInferenceSession(
psiCallResolver: PSICallResolver,
@@ -218,7 +217,7 @@ class BuilderInferenceSession(
fun getUsedStubTypes(): Set<StubTypeForBuilderInference> = stubsForPostponedVariables.values.toSet()
fun getCurrentSubstitutor(): NewTypeSubstitutor =
commonSystem.buildCurrentSubstitutor().cast<NewTypeSubstitutor>().takeIf { !it.isEmpty } ?: EmptySubstitutor
(commonSystem.buildCurrentSubstitutor() as NewTypeSubstitutor).takeIf { !it.isEmpty } ?: EmptySubstitutor
private fun arePostponedVariablesInferred() = commonSystem.notFixedTypeVariables.isEmpty()
@@ -267,7 +266,8 @@ class BuilderInferenceSession(
updateAllCalls(resultingSubstitutor)
}
return commonSystem.fixedTypeVariables.cast() // TODO: SUB
@Suppress("UNCHECKED_CAST")
return commonSystem.fixedTypeVariables as Map<TypeConstructor, UnwrappedType> // TODO: SUB
}
private fun getNestedBuilderInferenceSessions() = buildList {
@@ -495,8 +495,9 @@ class BuilderInferenceSession(
val resultingCallSubstitutor = storage.fixedTypeVariables.entries
.associate { it.key to nonFixedTypesToResultSubstitutor.safeSubstitute(it.value as UnwrappedType) } // TODO: SUB
@Suppress("UNCHECKED_CAST")
val resultingSubstitutor =
NewTypeSubstitutorByConstructorMap((resultingCallSubstitutor + nonFixedTypesToResult).cast()) // TODO: SUB
NewTypeSubstitutorByConstructorMap((resultingCallSubstitutor + nonFixedTypesToResult) as Map<TypeConstructor, UnwrappedType>) // TODO: SUB
val atomCompleter = createResolvedAtomCompleter(
resultingSubstitutor,
@@ -42,7 +42,6 @@ import org.jetbrains.kotlin.types.model.requireOrDescribe
import org.jetbrains.kotlin.types.typeUtil.builtIns
import org.jetbrains.kotlin.types.typeUtil.defaultProjections
import org.jetbrains.kotlin.types.typeUtil.isDefaultBound
import org.jetbrains.kotlin.utils.addToStdlib.cast
import java.util.*
open class ConstraintSystemBuilderImpl(private val mode: Mode = ConstraintSystemBuilderImpl.Mode.INFERENCE) : ConstraintSystem.Builder {
@@ -432,8 +431,10 @@ open class ConstraintSystemBuilderImpl(private val mode: Mode = ConstraintSystem
get() = SimpleClassicTypeSystemContext
var counter = 0
override fun registerTypeVariables(typeParameters: Collection<TypeParameterMarker>) =
registerTypeVariables(CallHandle.NONE, typeParameters.cast())
override fun registerTypeVariables(typeParameters: Collection<TypeParameterMarker>): TypeSubstitutor {
@Suppress("UNCHECKED_CAST")
return registerTypeVariables(CallHandle.NONE, typeParameters as Collection<TypeParameterDescriptor>)
}
override fun addSubtypeConstraint(subType: KotlinTypeMarker, superType: KotlinTypeMarker) {
requireOrDescribe(subType is UnwrappedType, subType)
@@ -53,7 +53,6 @@ import org.jetbrains.kotlin.types.expressions.ExpressionTypingServices
import org.jetbrains.kotlin.types.expressions.KotlinTypeInfo
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.types.typeUtil.makeNullable
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
data class LambdaContextInfo(
var typeInfo: KotlinTypeInfo? = null,
@@ -310,7 +309,7 @@ class KotlinResolutionCallbacksImpl(
val returnType = descriptor.returnType ?: return false
if (!isPrimitiveTypeOrNullablePrimitiveType(returnType) || !isPrimitiveTypeOrNullablePrimitiveType(expectedType)) return false
val callElement = resolvedAtom.atom.psiKotlinCall.psiCall.callElement.safeAs<KtExpression>() ?: return false
val callElement = (resolvedAtom.atom.psiKotlinCall.psiCall.callElement as? KtExpression) ?: return false
val expression = findCommonParent(callElement, resolvedAtom.atom.psiKotlinCall.explicitReceiver)
val temporaryBindingTrace = TemporaryBindingTrace.create(
@@ -327,7 +326,7 @@ class KotlinResolutionCallbacksImpl(
override fun getExpectedTypeFromAsExpressionAndRecordItInTrace(resolvedAtom: ResolvedCallAtom): UnwrappedType? {
val candidateDescriptor = resolvedAtom.candidateDescriptor as? FunctionDescriptor ?: return null
val call = resolvedAtom.atom.safeAs<PSIKotlinCall>()?.psiCall ?: return null
val call = (resolvedAtom.atom as? PSIKotlinCall)?.psiCall ?: return null
if (call.typeArgumentList != null || !candidateDescriptor.isFunctionForExpectTypeFromCastFeature()) return null
val binaryParent = call.calleeExpression?.getBinaryWithTypeParent() ?: return null
@@ -17,7 +17,6 @@
package org.jetbrains.kotlin.resolve.calls.tower
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.config.AnalysisFlags
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
@@ -29,7 +28,7 @@ import org.jetbrains.kotlin.resolve.calls.util.isInfixCall
import org.jetbrains.kotlin.resolve.calls.util.isSuperOrDelegatingConstructorCall
import org.jetbrains.kotlin.resolve.calls.components.KotlinResolutionCallbacks
import org.jetbrains.kotlin.resolve.calls.components.KotlinResolutionStatelessCallbacks
import org.jetbrains.kotlin.resolve.calls.inference.ConstraintSystemBuilderImpl
import org.jetbrains.kotlin.resolve.calls.components.candidate.ResolutionCandidate
import org.jetbrains.kotlin.resolve.calls.inference.components.ConstraintInjector
import org.jetbrains.kotlin.resolve.calls.inference.components.SimpleConstraintSystemImpl
import org.jetbrains.kotlin.resolve.calls.inference.isBuilderInferenceCall
@@ -40,10 +39,8 @@ import org.jetbrains.kotlin.resolve.calls.model.SimpleKotlinCallArgument
import org.jetbrains.kotlin.resolve.calls.results.SimpleConstraintSystem
import org.jetbrains.kotlin.resolve.deprecation.DeprecationResolver
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.KotlinTypeRefinerImpl
import org.jetbrains.kotlin.types.TypeIntersector
import org.jetbrains.kotlin.types.checker.KotlinTypeRefiner
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class KotlinResolutionStatelessCallbacksImpl(
private val deprecationResolver: DeprecationResolver,
@@ -92,8 +89,8 @@ class KotlinResolutionStatelessCallbacksImpl(
override fun getScopeTowerForCallableReferenceArgument(argument: CallableReferenceKotlinCallArgument): ImplicitScopeTower =
(argument as CallableReferenceKotlinCallArgumentImpl).scopeTowerForResolution
override fun getVariableCandidateIfInvoke(functionCall: KotlinCall) =
functionCall.safeAs<PSIKotlinCallForInvoke>()?.variableCall
override fun getVariableCandidateIfInvoke(functionCall: KotlinCall): ResolutionCandidate? =
(functionCall as? PSIKotlinCallForInvoke)?.variableCall
override fun isBuilderInferenceCall(argument: KotlinCallArgument, parameter: ValueParameterDescriptor): Boolean =
isBuilderInferenceCall(parameter, argument.psiCallArgument.valueArgument, languageVersionSettings)
@@ -43,7 +43,6 @@ import org.jetbrains.kotlin.types.expressions.DoubleColonExpressionResolver
import org.jetbrains.kotlin.types.expressions.ExpressionTypingServices
import org.jetbrains.kotlin.types.expressions.ExpressionTypingUtils
import org.jetbrains.kotlin.types.model.TypeSystemInferenceExtensionContextDelegate
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class KotlinToResolvedCallTransformer(
private val callCheckers: Iterable<CallChecker>,
@@ -170,7 +169,7 @@ class KotlinToResolvedCallTransformer(
): NewAbstractResolvedCall<D> {
val result = transformToResolvedCall<D>(candidate, trace, substitutor, diagnostics)
val psiKotlinCall = candidate.atom.psiKotlinCall
val tracing = psiKotlinCall.safeAs<PSIKotlinCallForInvoke>()?.baseCall?.tracingStrategy ?: psiKotlinCall.tracingStrategy
val tracing = (psiKotlinCall as? PSIKotlinCallForInvoke)?.baseCall?.tracingStrategy ?: psiKotlinCall.tracingStrategy
tracing.bindReference(trace, result)
tracing.bindResolvedCall(trace, result)
@@ -393,7 +392,7 @@ class KotlinToResolvedCallTransformer(
}
private fun createTypeForConvertableConstant(constant: CompileTimeConstant<*>): SimpleType? {
val value = constant.getValue(TypeUtils.NO_EXPECTED_TYPE).safeAs<Number>()?.toLong() ?: return null
val value = (constant.getValue(TypeUtils.NO_EXPECTED_TYPE) as? Number)?.toLong() ?: return null
val typeConstructor = IntegerLiteralTypeConstructor(value, moduleDescriptor, constant.parameters)
return KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope(
TypeAttributes.Empty, typeConstructor, emptyList(), false,
@@ -462,8 +461,8 @@ class KotlinToResolvedCallTransformer(
}
internal fun bind(trace: BindingTrace, resolvedCall: ResolvedCall<*>) {
resolvedCall.safeAs<NewAbstractResolvedCall<*>>()?.let { bind(trace, it) }
resolvedCall.safeAs<NewVariableAsFunctionResolvedCallImpl>()?.let { bind(trace, it) }
(resolvedCall as? NewAbstractResolvedCall<*>)?.let { bind(trace, it) }
(resolvedCall as? NewVariableAsFunctionResolvedCallImpl)?.let { bind(trace, it) }
}
fun reportDiagnostics(
@@ -30,7 +30,6 @@ import org.jetbrains.kotlin.types.error.ErrorTypeKind
import org.jetbrains.kotlin.types.error.ErrorUtils
import org.jetbrains.kotlin.types.UnwrappedType
import org.jetbrains.kotlin.types.expressions.KotlinTypeInfo
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class SimpleTypeArgumentImpl(
val typeProjection: KtTypeProjection,
@@ -60,8 +59,8 @@ val KotlinCallArgument.psiCallArgument: PSIKotlinCallArgument
val KotlinCallArgument.psiExpression: KtExpression?
get() {
return when (this) {
is ReceiverExpressionKotlinCallArgument -> receiver.receiverValue.safeAs<ExpressionReceiver>()?.expression
is QualifierReceiverKotlinCallArgument -> receiver.safeAs<Qualifier>()?.expression
is ReceiverExpressionKotlinCallArgument -> (receiver.receiverValue as? ExpressionReceiver)?.expression
is QualifierReceiverKotlinCallArgument -> (receiver as? Qualifier)?.expression
is EmptyLabeledReturn -> returnExpression
else -> psiCallArgument.valueArgument.getArgumentExpression()
}
@@ -21,7 +21,6 @@ import org.jetbrains.kotlin.resolve.scopes.receivers.CastImplicitClassReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class NewResolvedCallImpl<D : CallableDescriptor>(
override val resolvedCallAtom: ResolvedCallAtom,
@@ -228,7 +227,7 @@ class NewResolvedCallImpl<D : CallableDescriptor>(
else -> null
} as? ArgumentConstraintPositionImpl ?: return@forEach
val argument = position.argument.safeAs<PSIKotlinCallArgument>()?.valueArgument ?: return@forEach
val argument = (position.argument as? PSIKotlinCallArgument)?.valueArgument ?: return@forEach
result += argument to it
}
@@ -14,13 +14,12 @@ import org.jetbrains.kotlin.resolve.calls.model.ResolvedValueArgument
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeApproximator
import org.jetbrains.kotlin.utils.addToStdlib.cast
class NewVariableAsFunctionResolvedCallImpl(
override val variableCall: NewAbstractResolvedCall<VariableDescriptor>,
override val functionCall: NewAbstractResolvedCall<FunctionDescriptor>,
) : VariableAsFunctionResolvedCall, NewAbstractResolvedCall<FunctionDescriptor>() {
val baseCall: PSIKotlinCallImpl = functionCall.psiKotlinCall.cast<PSIKotlinCallForInvoke>().baseCall
val baseCall: PSIKotlinCallImpl = (functionCall.psiKotlinCall as PSIKotlinCallForInvoke).baseCall
override val resolvedCallAtom: ResolvedCallAtom? = functionCall.resolvedCallAtom
override val psiKotlinCall: PSIKotlinCall = functionCall.psiKotlinCall
@@ -240,7 +240,7 @@ class ResolvedAtomCompleter(
?: return (subResolvedAtoms!!.single() as ResolvedLambdaAtom).isCoercedToUnit
val returnTypes =
resultArgumentsInfo.nonErrorArguments.map {
val type = it.safeAs<SimpleKotlinCallArgument>()?.receiver?.receiverValue?.type ?: return@map null
val type = (it as? SimpleKotlinCallArgument)?.receiver?.receiverValue?.type ?: return@map null
val unwrappedType = when (type) {
is WrappedType -> type.unwrap()
is UnwrappedType -> type
@@ -30,7 +30,6 @@ import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.typeUtil.asTypeProjection
import org.jetbrains.kotlin.types.typeUtil.contains
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.kotlin.utils.sure
// resolved call
@@ -279,11 +278,11 @@ fun ResolvedCall<*>.getFirstArgumentExpression(): KtExpression? =
valueArgumentsByIndex?.run { get(0).arguments[0].getArgumentExpression() }
fun ResolvedCall<*>.getReceiverExpression(): KtExpression? =
extensionReceiver.safeAs<ExpressionReceiver>()?.expression ?: dispatchReceiver.safeAs<ExpressionReceiver>()?.expression
(extensionReceiver as? ExpressionReceiver)?.expression ?: (dispatchReceiver as? ExpressionReceiver)?.expression
val KtLambdaExpression.isTrailingLambdaOnNewLIne
get(): Boolean {
parent?.safeAs<KtLambdaArgument>()?.let { lambdaArgument ->
(parent as? KtLambdaArgument)?.let { lambdaArgument ->
var prevSibling = lambdaArgument.prevSibling
while (prevSibling != null && prevSibling !is KtElement) {
@@ -21,7 +21,6 @@ import org.jetbrains.kotlin.resolve.constants.StringValue
import org.jetbrains.kotlin.resolve.deprecation.getSinceVersion
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
object DeprecatedSinceKotlinAnnotationChecker : DeclarationChecker {
override fun check(declaration: KtDeclaration, descriptor: DeclarationDescriptor, context: DeclarationCheckerContext) {
@@ -91,7 +90,7 @@ object DeprecatedSinceKotlinAnnotationChecker : DeclarationChecker {
context: DeclarationCheckerContext,
reportOn: PsiElement
) {
val argumentValue = argumentValue(name).safeAs<StringValue>()?.value
val argumentValue = (argumentValue(name) as? StringValue)?.value
if (argumentValue != null && (parsedVersion == null || !argumentValue.matches(RequireKotlinConstants.VERSION_REGEX))) {
context.trace.reportDiagnosticOnce(
Errors.ILLEGAL_KOTLIN_VERSION_STRING_VALUE.on(
@@ -35,7 +35,6 @@ import org.jetbrains.kotlin.resolve.multiplatform.ExpectActualCompatibility.*
import org.jetbrains.kotlin.resolve.source.KotlinSourceElement
import org.jetbrains.kotlin.resolve.source.PsiSourceFile
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import java.io.File
class ExpectedActualDeclarationChecker(
@@ -196,7 +195,7 @@ class ExpectedActualDeclarationChecker(
private fun reportMissingActualModifier(actual: MemberDescriptor, reportOn: KtNamedDeclaration?, trace: BindingTrace) {
if (actual.isActual) return
@Suppress("NAME_SHADOWING")
val reportOn = reportOn ?: actual.source.safeAs<KotlinSourceElement>()?.psi.safeAs<KtNamedDeclaration>() ?: return
val reportOn = reportOn ?: (actual.source as? KotlinSourceElement)?.psi as? KtNamedDeclaration ?: return
if (requireActualModifier(actual)) {
trace.report(Errors.ACTUAL_MISSING.on(reportOn))
@@ -222,11 +221,10 @@ class ExpectedActualDeclarationChecker(
}
}
private fun sourceFile(descriptor: MemberDescriptor): File? =
descriptor.source
.containingFile
.safeAs<PsiSourceFile>()
?.run { VfsUtilCore.virtualToIoFile(psiFile.virtualFile) }
private fun sourceFile(descriptor: MemberDescriptor): File? {
val containingFile = descriptor.source.containingFile as? PsiSourceFile ?: return null
return VfsUtilCore.virtualToIoFile(containingFile.psiFile.virtualFile)
}
private fun checkActualDeclarationHasExpected(
reportOn: KtNamedDeclaration,
@@ -22,7 +22,6 @@ import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.isNothing
import org.jetbrains.kotlin.types.typeUtil.isTypeParameter
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
private val javaLangCloneable = FqNameUnsafe("java.lang.Cloneable")
@@ -92,7 +91,7 @@ object InlineClassDeclarationChecker : DeclarationChecker {
}
var baseParametersOk = true
val baseParameterTypes = descriptor.safeAs<ClassDescriptor>()?.defaultType?.substitutedUnderlyingTypes() ?: emptyList()
val baseParameterTypes = (descriptor as? ClassDescriptor)?.defaultType?.substitutedUnderlyingTypes() ?: emptyList()
for ((baseParameter, baseParameterType) in primaryConstructor.valueParameters zip baseParameterTypes) {
if (!isParameterAcceptableForInlineClass(baseParameter)) {
@@ -27,7 +27,6 @@ import org.jetbrains.kotlin.resolve.constants.KClassValue
import org.jetbrains.kotlin.resolve.descriptorUtil.annotationClass
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.descriptorUtil.getAnnotationRetention
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class OptInMarkerDeclarationAnnotationChecker(private val module: ModuleDescriptor) : AdditionalAnnotationChecker {
override fun checkEntries(
@@ -43,9 +42,8 @@ class OptInMarkerDeclarationAnnotationChecker(private val module: ModuleDescript
val annotation = trace.bindingContext.get(BindingContext.ANNOTATION, entry) ?: continue
when (annotation.fqName) {
OptInNames.OPT_IN_FQ_NAME -> {
val annotationClasses =
annotation.allValueArguments[OptInNames.OPT_IN_ANNOTATION_CLASS]
.safeAs<ArrayValue>()?.value.orEmpty()
val annotationClasses = (annotation.allValueArguments[OptInNames.OPT_IN_ANNOTATION_CLASS] as? ArrayValue)
?.value.orEmpty()
checkOptInUsage(annotationClasses, trace, entry)
}
OptInNames.SUBCLASS_OPT_IN_REQUIRED_FQ_NAME -> {
@@ -19,7 +19,6 @@ import org.jetbrains.kotlin.resolve.constants.EnumValue
import org.jetbrains.kotlin.resolve.constants.StringValue
import org.jetbrains.kotlin.resolve.deprecation.DeprecationLevelValue.*
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
internal sealed class DeprecatedByAnnotation(
val annotation: AnnotationDescriptor,
@@ -27,12 +26,12 @@ internal sealed class DeprecatedByAnnotation(
override val propagatesToOverrides: Boolean
) : DescriptorBasedDeprecationInfo() {
override val message: String?
get() = annotation.argumentValue("message")?.safeAs<StringValue>()?.value
get() = (annotation.argumentValue("message") as? StringValue)?.value
internal val replaceWithValue: String?
get() {
val replaceWithAnnotation = annotation.argumentValue(Deprecated::replaceWith.name)?.safeAs<AnnotationValue>()?.value
return replaceWithAnnotation?.argumentValue(ReplaceWith::expression.name)?.safeAs<StringValue>()?.value
val replaceWithAnnotation = (annotation.argumentValue(Deprecated::replaceWith.name) as? AnnotationValue)?.value
return (replaceWithAnnotation?.argumentValue(ReplaceWith::expression.name) as? StringValue)?.value
}
class StandardDeprecated(
@@ -41,7 +40,7 @@ internal sealed class DeprecatedByAnnotation(
propagatesToOverrides: Boolean
) : DeprecatedByAnnotation(annotation, target, propagatesToOverrides) {
override val deprecationLevel: DeprecationLevelValue
get() = when (annotation.argumentValue("level")?.safeAs<EnumValue>()?.enumEntryName?.asString()) {
get() = when ((annotation.argumentValue("level") as? EnumValue)?.enumEntryName?.asString()) {
"WARNING" -> WARNING
"ERROR" -> ERROR
"HIDDEN" -> HIDDEN
@@ -29,7 +29,6 @@ import org.jetbrains.kotlin.storage.StorageManager
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.utils.SmartList
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
@@ -270,7 +269,7 @@ class DeprecationResolver(
languageVersionSettings.apiVersion < ApiVersion.KOTLIN_1_3
private fun getDeprecationFromUserData(target: DeclarationDescriptor): DescriptorBasedDeprecationInfo? =
target.safeAs<CallableDescriptor>()?.getUserData(DEPRECATED_FUNCTION_KEY)
(target as? CallableDescriptor)?.getUserData(DEPRECATED_FUNCTION_KEY)
private fun getDeprecationByVersionRequirement(target: DeclarationDescriptor): List<DeprecatedByVersionRequirement> {
fun createVersion(version: String): MavenComparableVersion? = try {
@@ -17,7 +17,6 @@ import org.jetbrains.kotlin.metadata.ProtoBuf
import org.jetbrains.kotlin.resolve.annotations.argumentValue
import org.jetbrains.kotlin.resolve.constants.StringValue
import org.jetbrains.kotlin.resolve.deprecation.DeprecationLevelValue.*
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
fun DescriptorBasedDeprecationInfo.deprecatedByOverriddenMessage(): String? = (this as? DeprecatedByOverridden)?.additionalMessage()
@@ -25,7 +24,7 @@ fun DescriptorBasedDeprecationInfo.deprecatedByAnnotationReplaceWithExpression()
// The function extracts value of warningSince/errorSince/hiddenSince from DeprecatedSinceKotlin annotation
fun AnnotationDescriptor.getSinceVersion(name: String): ApiVersion? =
argumentValue(name)?.safeAs<StringValue>()?.value?.takeUnless(String::isEmpty)?.let(ApiVersion.Companion::parse)
(argumentValue(name) as? StringValue)?.value?.takeUnless(String::isEmpty)?.let(ApiVersion.Companion::parse)
fun computeLevelForDeprecatedSinceKotlin(annotation: AnnotationDescriptor, apiVersion: ApiVersion): DeprecationLevelValue? {
val hiddenSince = annotation.getSinceVersion("hiddenSince")
@@ -22,7 +22,6 @@ import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.stubs.KotlinClassOrObjectStub
import org.jetbrains.kotlin.types.expressions.OperatorConventions
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import java.util.*
// NOTE: in this file we collect only Kotlin-specific methods working with PSI and not modifying it
@@ -674,7 +673,7 @@ fun isTopLevelInFileOrScript(element: PsiElement): Boolean {
fun KtFile.getFileOrScriptDeclarations() = if (isScript()) script!!.declarations else declarations
fun KtExpression.getBinaryWithTypeParent(): KtBinaryExpressionWithTypeRHS? {
val callExpression = parent.safeAs<KtCallExpression>() ?: return null
val callExpression = parent as? KtCallExpression ?: return null
val possibleQualifiedExpression = callExpression.parent
val targetExpression = if (possibleQualifiedExpression is KtQualifiedExpression) {
@@ -21,7 +21,6 @@ import org.jetbrains.kotlin.load.java.structure.impl.classFiles.BinaryJavaAnnota
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.org.objectweb.asm.*
import java.lang.reflect.Array
@@ -66,7 +65,7 @@ internal class AnnotationsAndParameterCollectorMethodVisitor(
override fun visitAnnotationDefault(): AnnotationVisitor =
BinaryJavaAnnotationVisitor(context, signatureParser) {
member.safeAs<BinaryJavaMethod>()?.annotationParameterDefaultValue = it
(member as? BinaryJavaMethod)?.annotationParameterDefaultValue = it
}
override fun visitParameter(name: String?, access: Int) {
@@ -114,7 +113,7 @@ internal class AnnotationsAndParameterCollectorMethodVisitor(
}
val (annotationOwner, isFreshlySupportedAnnotation) = when (typeReference.sort) {
TypeReference.METHOD_RETURN -> getTargetType(member.safeAs<BinaryJavaMethod>()?.returnType ?: return null)
TypeReference.METHOD_RETURN -> getTargetType((member as? BinaryJavaMethod)?.returnType ?: return null)
TypeReference.METHOD_TYPE_PARAMETER -> member.typeParameters[typeReference.typeParameterIndex] to true
TypeReference.METHOD_FORMAL_PARAMETER -> getTargetType(member.valueParameters[typeReference.formalParameterIndex].type)
TypeReference.METHOD_TYPE_PARAMETER_BOUND -> getTargetType(
@@ -215,7 +214,7 @@ class BinaryJavaAnnotation private constructor(
}
override val classId: ClassId
get() = classifierResolutionResult.classifier.safeAs<JavaClass>()?.classId
get() = (classifierResolutionResult.classifier as? JavaClass)?.classId
?: ClassId.topLevel(FqName(classifierResolutionResult.qualifiedName))
override fun resolve() = classifierResolutionResult.classifier as? JavaClass
@@ -19,7 +19,6 @@ package org.jetbrains.kotlin.load.java.structure.impl.classFiles
import org.jetbrains.kotlin.builtins.PrimitiveType
import org.jetbrains.kotlin.load.java.structure.*
import org.jetbrains.kotlin.utils.SmartList
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
internal abstract class JavaPlainType : ListBasedJavaAnnotationOwner, MutableJavaAnnotationOwner {
override val annotations: MutableCollection<JavaAnnotation> = SmartList()
@@ -42,7 +41,7 @@ internal class PlainJavaClassifierType(
override val classifier get() = classifierResolverResult.classifier
override val isRaw
get() = typeArguments.isEmpty() &&
classifierResolverResult.classifier?.safeAs<JavaClass>()?.typeParameters?.isNotEmpty() == true
(classifierResolverResult.classifier as? JavaClass)?.typeParameters?.isNotEmpty() == true
override val classifierQualifiedName: String
get() = classifierResolverResult.qualifiedName
@@ -11,7 +11,6 @@ import org.jetbrains.kotlin.resolve.calls.inference.model.*
import org.jetbrains.kotlin.resolve.calls.model.*
import org.jetbrains.kotlin.types.model.*
import org.jetbrains.kotlin.utils.SmartSet
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import java.util.*
private typealias Context = ConstraintSystemCompletionContext
@@ -530,7 +529,7 @@ class PostponedArgumentInputTypesResolver(
dependencyProvider: TypeVariableDependencyInformationProvider,
resolvedAtomProvider: ResolvedAtomProvider
): Boolean = with(c) {
val expectedType = argument.run { safeAs<PostponedAtomWithRevisableExpectedType>()?.revisedExpectedType ?: expectedType }
val expectedType = argument.run { (this as? PostponedAtomWithRevisableExpectedType)?.revisedExpectedType ?: expectedType }
if (expectedType != null && expectedType.isFunctionOrKFunctionWithAnySuspendability()) {
val wasFixedSomeVariable = c.fixNextReadyVariableForParameterType(
@@ -34,7 +34,6 @@ import org.jetbrains.kotlin.types.checker.prepareArgumentTypeRegardingCaptureTyp
import org.jetbrains.kotlin.types.typeUtil.isNullableNothing
import org.jetbrains.kotlin.types.typeUtil.makeNullable
import org.jetbrains.kotlin.utils.DFS
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
internal fun unexpectedArgument(argument: KotlinCallArgument): Nothing =
error("Unexpected argument type: $argument, ${argument.javaClass.canonicalName}.")
@@ -90,11 +89,11 @@ internal fun KotlinCallArgument.getExpectedType(parameter: ParameterDescriptor,
) {
parameter.type.unwrap()
} else {
parameter.safeAs<ValueParameterDescriptor>()?.varargElementType?.unwrap() ?: parameter.type.unwrap()
(parameter as? ValueParameterDescriptor)?.varargElementType?.unwrap() ?: parameter.type.unwrap()
}
val ValueParameterDescriptor.isVararg: Boolean get() = varargElementType != null
val ParameterDescriptor.isVararg: Boolean get() = this.safeAs<ValueParameterDescriptor>()?.isVararg ?: false
val ParameterDescriptor.isVararg: Boolean get() = (this as? ValueParameterDescriptor)?.isVararg ?: false
/**
* @return `true` iff the parameter has a default value, i.e. declares it, inherits it by overriding a parameter which has a default value,
@@ -17,7 +17,6 @@ import org.jetbrains.kotlin.resolve.calls.inference.model.TypeVariableTypeConstr
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.checker.*
import org.jetbrains.kotlin.types.model.*
import org.jetbrains.kotlin.utils.addToStdlib.cast
class ClassicTypeSystemContextForCS(
override val builtIns: KotlinBuiltIns,
@@ -59,7 +58,8 @@ class ClassicTypeSystemContextForCS(
override fun typeSubstitutorByTypeConstructor(map: Map<TypeConstructorMarker, KotlinTypeMarker>): TypeSubstitutorMarker {
if (map.isEmpty()) return createEmptySubstitutor()
return NewTypeSubstitutorByConstructorMap(map.cast())
@Suppress("UNCHECKED_CAST")
return NewTypeSubstitutorByConstructorMap(map as Map<TypeConstructor, UnwrappedType>)
}
override fun createEmptySubstitutor(): TypeSubstitutorMarker {
@@ -26,7 +26,6 @@ import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.error.ErrorUtils
import org.jetbrains.kotlin.types.error.ErrorTypeKind
import org.jetbrains.kotlin.types.typeUtil.builtIns
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
fun resolveKtPrimitive(
csBuilder: ConstraintSystemBuilder,
@@ -102,7 +101,7 @@ private fun extraLambdaInfo(
val isSuspend = expectedType?.isSuspendFunctionType ?: false
val isFunctionSupertype = expectedType != null && KotlinBuiltIns.isNotNullOrNullableFunctionSupertype(expectedType)
val argumentAsFunctionExpression = argument.safeAs<FunctionExpression>()
val argumentAsFunctionExpression = argument as? FunctionExpression
val typeVariable = TypeVariableForLambdaReturnType(builtIns, "_L")
@@ -153,7 +152,7 @@ private fun extractLambdaInfoFromFunctionalType(
val expectedParameters = expectedType.getValueParameterTypesFromFunctionType()
val expectedReceiver = expectedType.getReceiverTypeFromFunctionType()?.unwrap()
val expectedContextReceivers = expectedType.getContextReceiverTypesFromFunctionType().map { it.unwrap() }.toTypedArray()
val argumentAsFunctionExpression = argument.safeAs<FunctionExpression>()
val argumentAsFunctionExpression = argument as? FunctionExpression
val receiverFromExpected = argumentAsFunctionExpression?.receiverType == null && expectedReceiver != null
@@ -14,12 +14,13 @@ import org.jetbrains.kotlin.resolve.calls.inference.addSubsystemFromArgument
import org.jetbrains.kotlin.resolve.calls.inference.components.ConstraintSystemCompletionMode
import org.jetbrains.kotlin.resolve.calls.inference.model.BuilderInferencePosition
import org.jetbrains.kotlin.resolve.calls.inference.model.LambdaArgumentConstraintPositionImpl
import org.jetbrains.kotlin.resolve.calls.inference.model.NewTypeVariable
import org.jetbrains.kotlin.resolve.calls.model.*
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.StubTypeForBuilderInference
import org.jetbrains.kotlin.types.UnwrappedType
import org.jetbrains.kotlin.types.model.*
import org.jetbrains.kotlin.types.typeUtil.builtIns
import org.jetbrains.kotlin.utils.addToStdlib.cast
class PostponedArgumentsAnalyzer(
private val callableReferenceArgumentResolver: CallableReferenceArgumentResolver,
@@ -128,6 +129,7 @@ class PostponedArgumentsAnalyzer(
else FilteredAnnotations(annotations, true) { it != StandardNames.FqNames.extensionFunctionType }
}
@Suppress("UNCHECKED_CAST")
val returnArgumentsAnalysisResult = resolutionCallbacks.analyzeAndGetLambdaReturnArguments(
lambda.atom,
lambda.isSuspend,
@@ -136,7 +138,7 @@ class PostponedArgumentsAnalyzer(
parameters,
expectedTypeForReturnArguments,
convertedAnnotations ?: Annotations.EMPTY,
substitutorAndStubsForLambdaAnalysis.stubsForPostponedVariables.cast(),
substitutorAndStubsForLambdaAnalysis.stubsForPostponedVariables as Map<NewTypeVariable, StubTypeForBuilderInference>,
)
applyResultsOfAnalyzedLambdaToCandidateSystem(c, lambda, returnArgumentsAnalysisResult, completionMode, diagnosticHolder, substitute)
return returnArgumentsAnalysisResult
@@ -29,9 +29,7 @@ import org.jetbrains.kotlin.types.error.ErrorUtils
import org.jetbrains.kotlin.types.model.*
import org.jetbrains.kotlin.types.typeUtil.*
import org.jetbrains.kotlin.utils.SmartList
import org.jetbrains.kotlin.utils.addToStdlib.cast
import org.jetbrains.kotlin.utils.addToStdlib.compactIfPossible
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
internal object CheckVisibility : ResolutionPart() {
override fun ResolutionCandidate.process(workIndex: Int) {
@@ -851,7 +849,7 @@ internal object ErrorDescriptorResolutionPart : ResolutionPart() {
resolvedCall.knownParametersSubstitutor = EmptySubstitutor
resolvedCall.argumentToCandidateParameter = emptyMap()
kotlinCall.explicitReceiver?.safeAs<SimpleKotlinCallArgument>()?.let {
(kotlinCall.explicitReceiver as? SimpleKotlinCallArgument)?.let {
resolveKotlinArgument(it, null, ReceiverInfo.notReceiver)
}
for (argument in kotlinCall.argumentsInParenthesis) {
@@ -918,8 +916,10 @@ internal object CheckIncompatibleTypeVariableUpperBounds : ResolutionPart() {
* Check if the candidate was already discriminated by `CompatibilityOfTypeVariableAsIntersectionTypePart` resolution part
* If it's true we shouldn't mark the candidate with warning, but should mark with error, to repeat the existing proper behaviour
*/
private fun ResolutionCandidate.wasPreviouslyDiscriminated(upperTypes: List<KotlinTypeMarker>) =
callComponents.statelessCallbacks.isOldIntersectionIsEmpty(upperTypes.cast())
private fun ResolutionCandidate.wasPreviouslyDiscriminated(upperTypes: List<KotlinTypeMarker>): Boolean {
@Suppress("UNCHECKED_CAST")
return callComponents.statelessCallbacks.isOldIntersectionIsEmpty(upperTypes as List<KotlinType>)
}
override fun ResolutionCandidate.process(workIndex: Int) = with(getSystem().asConstraintSystemCompleterContext()) {
val constraintSystem = getSystem()
@@ -16,7 +16,6 @@ import org.jetbrains.kotlin.resolve.calls.model.SubKotlinCallArgument
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.model.TypeSystemInferenceExtensionContext
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
fun ConstraintStorage.buildResultingSubstitutor(
context: TypeSystemInferenceExtensionContext,
@@ -75,7 +74,7 @@ fun PostponedArgumentsAnalyzerContext.addSubsystemFromArgument(argument: KotlinC
}
is CallableReferenceKotlinCallArgument -> {
addSubsystemFromArgument(argument.lhsResult.safeAs<LHSResult.Expression>()?.lshCallArgument)
addSubsystemFromArgument((argument.lhsResult as? LHSResult.Expression)?.lshCallArgument)
}
else -> false
@@ -20,8 +20,6 @@ import org.jetbrains.kotlin.types.model.TypeVariableTypeConstructorMarker
import org.jetbrains.kotlin.types.model.safeSubstitute
import org.jetbrains.kotlin.types.typeUtil.asTypeProjection
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.utils.addToStdlib.cast
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class KotlinConstraintSystemCompleter(
private val resultTypeResolver: ResultTypeResolver,
@@ -291,8 +289,8 @@ class KotlinConstraintSystemCompleter(
argument: PostponedAtomWithRevisableExpectedType,
diagnosticsHolder: KotlinDiagnosticsHolder
): Boolean = with(c) {
val revisedExpectedType: UnwrappedType =
argument.revisedExpectedType?.takeIf { it.isFunctionOrKFunctionWithAnySuspendability() }?.cast() ?: return false
val revisedExpectedType: UnwrappedType = argument.revisedExpectedType
?.takeIf { it.isFunctionOrKFunctionWithAnySuspendability() } as UnwrappedType? ?: return false
when (argument) {
is PostponedCallableReferenceAtom ->
@@ -488,7 +486,7 @@ class KotlinConstraintSystemCompleter(
companion object {
fun getOrderedNotAnalyzedPostponedArguments(topLevelAtoms: List<ResolvedAtom>): List<PostponedResolvedAtom> {
fun ResolvedAtom.process(to: MutableList<PostponedResolvedAtom>) {
to.addIfNotNull(this.safeAs<PostponedResolvedAtom>()?.takeUnless { it.analyzed })
to.addIfNotNull((this as? PostponedResolvedAtom)?.takeUnless { it.analyzed })
if (analyzed) {
subResolvedAtoms?.forEach { it.process(to) }
@@ -6,7 +6,6 @@
package org.jetbrains.kotlin.resolve.calls.model
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
interface KotlinCall : ResolutionAtom {
@@ -42,8 +41,8 @@ fun KotlinCall.checkCallInvariants() {
"Lambda argument or callable reference is not allowed as explicit receiver: $explicitReceiver"
}
explicitReceiver.safeAs<SimpleKotlinCallArgument>()?.checkReceiverInvariants()
dispatchReceiverForInvokeExtension.safeAs<SimpleKotlinCallArgument>()?.checkReceiverInvariants()
(explicitReceiver as? SimpleKotlinCallArgument)?.checkReceiverInvariants()
(dispatchReceiverForInvokeExtension as? SimpleKotlinCallArgument)?.checkReceiverInvariants()
when (callKind) {
KotlinCallKind.FUNCTION, KotlinCallKind.INVOKE -> {
@@ -28,7 +28,6 @@ import org.jetbrains.kotlin.types.UnwrappedType
import org.jetbrains.kotlin.types.model.KotlinTypeMarker
import org.jetbrains.kotlin.types.typeUtil.unCapture
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
/**
* Call, Callable reference, lambda & function expression, collection literal.
@@ -281,7 +280,7 @@ sealed class CallResolutionResult(
return diagnostics.map {
val error = it.constraintSystemError ?: return@map it
if (error !is NewConstraintMismatch) return@map it
val lowerType = error.lowerType.safeAs<KotlinType>()?.unwrap() ?: return@map it
val lowerType = (error.lowerType as? KotlinType)?.unwrap() ?: return@map it
val newLowerType = substitutor.safeSubstitute(lowerType.unCapture())
when (error) {
is NewConstraintError -> NewConstraintError(newLowerType, error.upperType, error.position).asDiagnostic()
@@ -20,7 +20,6 @@ import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.incremental.components.LookupLocation
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.utils.Printer
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class LexicalWritableScope(
parent: LexicalScope,
@@ -84,8 +83,7 @@ class LexicalWritableScope(
name: Name,
location: LookupLocation
): DescriptorWithDeprecation<ClassifierDescriptor>? {
return variableOrClassDescriptorByName(name, descriptorLimit)
?.safeAs<ClassifierDescriptor>()
return (variableOrClassDescriptorByName(name, descriptorLimit) as? ClassifierDescriptor)
?.let { DescriptorWithDeprecation.createNonDeprecated(it) }
}
@@ -24,7 +24,6 @@ import org.jetbrains.kotlin.test.KotlinTestUtils
import org.jetbrains.kotlin.test.TestCaseWithTmpdir
import org.jetbrains.kotlin.test.util.KtTestUtil
import org.jetbrains.kotlin.utils.PathUtil
import org.jetbrains.kotlin.utils.addToStdlib.cast
import java.io.File
import java.util.concurrent.TimeUnit
@@ -81,11 +80,13 @@ class LauncherScriptTest : TestCaseWithTmpdir() {
}
}
private fun quoteIfNeeded(args: Array<out String>): Array<String> =
if (SystemInfo.isWindows) args.map {
private fun quoteIfNeeded(args: Array<out String>): Array<String> {
@Suppress("UNCHECKED_CAST")
return if (SystemInfo.isWindows) args.map {
if (it.contains('=') || it.contains(" ") || it.contains(";") || it.contains(",")) "\"$it\"" else it
}.toTypedArray()
else args.cast()
else args as Array<String>
}
private val testDataDirectory: String
get() = KtTestUtil.getTestDataPathBase() + "/launcher"
@@ -38,7 +38,6 @@ import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.checker.KotlinTypeRefiner
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class LazyJavaClassDescriptor(
val outerContext: LazyJavaResolverContext,
@@ -187,7 +186,7 @@ class LazyJavaClassDescriptor(
// Check if any of the super-interfaces contain too many methods to be a SAM
return typeConstructor.supertypes.any {
it.constructor.declarationDescriptor.safeAs<LazyJavaClassDescriptor>()?.isDefinitelyNotSamInterface == true
(it.constructor.declarationDescriptor as? LazyJavaClassDescriptor)?.isDefinitelyNotSamInterface == true
}
}
@@ -35,7 +35,6 @@ import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.storage.NullableLazyValue
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.kotlin.utils.alwaysTrue
import java.util.*
@@ -76,8 +75,7 @@ class LazyJavaPackageScope(
request.javaClass ?: c.components.finder.findClass(
JavaClassFinder.Request(
requestClassId,
kotlinClassOrClassFileContent?.safeAs<KotlinClassFinder.Result.ClassFileContent>()
?.content
(kotlinClassOrClassFileContent as? KotlinClassFinder.Result.ClassFileContent)?.content
)
)
@@ -23,7 +23,6 @@ import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.SimpleType
import org.jetbrains.kotlin.types.TypeConstructor
import org.jetbrains.kotlin.types.checker.KotlinTypeRefiner
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class SyntheticJavaClassDescriptor(
@@ -121,7 +120,7 @@ class SyntheticJavaClassDescriptor(
// Check if any of the super-interfaces contain too many methods to be a SAM
return typeConstructor.supertypes.any {
it.constructor.declarationDescriptor.safeAs<SyntheticJavaClassDescriptor>()?.isDefinitelyNotSamInterface == true
(it.constructor.declarationDescriptor as? SyntheticJavaClassDescriptor)?.isDefinitelyNotSamInterface == true
}
}
@@ -27,7 +27,6 @@ import org.jetbrains.kotlin.load.java.descriptors.JavaCallableMemberDescriptor
import org.jetbrains.kotlin.load.java.descriptors.JavaMethodDescriptor
import org.jetbrains.kotlin.load.java.descriptors.JavaPropertyDescriptor
import org.jetbrains.kotlin.load.java.descriptors.PossiblyExternalAnnotationDescriptor
import org.jetbrains.kotlin.load.java.lazy.JavaResolverComponents
import org.jetbrains.kotlin.load.java.lazy.LazyJavaResolverContext
import org.jetbrains.kotlin.load.java.lazy.copyWithNewDefaultTypeQualifiers
import org.jetbrains.kotlin.load.java.lazy.descriptors.LazyJavaAnnotationDescriptor
@@ -50,7 +49,6 @@ import org.jetbrains.kotlin.types.model.KotlinTypeMarker
import org.jetbrains.kotlin.types.model.TypeParameterMarker
import org.jetbrains.kotlin.types.model.TypeSystemInferenceExtensionContext
import org.jetbrains.kotlin.types.typeUtil.contains
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class SignatureEnhancement(private val typeEnhancement: JavaTypeEnhancement) {
fun <D : CallableMemberDescriptor> enhanceSignatures(c: LazyJavaResolverContext, platformSignatures: Collection<D>): Collection<D> {
@@ -92,7 +90,7 @@ class SignatureEnhancement(private val typeEnhancement: JavaTypeEnhancement) {
val receiverTypeEnhancement =
if (extensionReceiverParameter != null)
enhanceValueParameter(
parameterDescriptor = annotationOwnerForMember.safeAs<FunctionDescriptor>()
parameterDescriptor = (annotationOwnerForMember as? FunctionDescriptor)
?.getUserData(JavaMethodDescriptor.ORIGINAL_VALUE_PARAMETER_FOR_EXTENSION_RECEIVER),
methodContext = memberContext,
predefined = null,
@@ -128,7 +126,7 @@ class SignatureEnhancement(private val typeEnhancement: JavaTypeEnhancement) {
typeContainer = annotationOwnerForMember, isCovariant = true,
containerContext = memberContext,
containerApplicabilityType =
if (this.safeAs<PropertyDescriptor>()?.isJavaField == true)
if ((this as? PropertyDescriptor)?.isJavaField == true)
AnnotationQualifierApplicabilityType.FIELD
else
AnnotationQualifierApplicabilityType.METHOD_RETURN_TYPE,
@@ -13,7 +13,6 @@ import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeSubstitutor
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
val JVM_INLINE_ANNOTATION_FQ_NAME = FqName("kotlin.jvm.JvmInline")
val JVM_INLINE_ANNOTATION_CLASS_ID = ClassId.topLevel(JVM_INLINE_ANNOTATION_FQ_NAME)
@@ -28,10 +27,10 @@ fun DeclarationDescriptor.isMultiFieldValueClass(): Boolean =
fun DeclarationDescriptor.isValueClass(): Boolean = isInlineClass() || isMultiFieldValueClass()
fun KotlinType.unsubstitutedUnderlyingType(): KotlinType? =
constructor.declarationDescriptor.safeAs<ClassDescriptor>()?.inlineClassRepresentation?.underlyingType
(constructor.declarationDescriptor as? ClassDescriptor)?.inlineClassRepresentation?.underlyingType
fun KotlinType.unsubstitutedUnderlyingTypes(): List<KotlinType> {
val declarationDescriptor = constructor.declarationDescriptor.safeAs<ClassDescriptor>() ?: return emptyList()
val declarationDescriptor = constructor.declarationDescriptor as? ClassDescriptor ?: return emptyList()
return when {
declarationDescriptor.isInlineClass() -> listOfNotNull(unsubstitutedUnderlyingType())
declarationDescriptor.isMultiFieldValueClass() ->
@@ -19,7 +19,6 @@ import org.jetbrains.kotlin.types.checker.REFINER_CAPABILITY
import org.jetbrains.kotlin.types.checker.TypeRefinementSupport
import org.jetbrains.kotlin.types.model.KotlinTypeMarker
import org.jetbrains.kotlin.utils.DFS
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
@OptIn(TypeRefinement::class)
class KotlinTypeRefinerImpl(
@@ -203,8 +202,8 @@ private val TypeConstructor.allDependentTypeConstructors: Collection<TypeConstru
else -> supertypes.map { it.constructor }
}
private fun TypeConstructor.isExpectClass() =
declarationDescriptor?.safeAs<ClassDescriptor>()?.isExpect == true
private fun TypeConstructor.isExpectClass(): Boolean =
(declarationDescriptor as? ClassDescriptor)?.isExpect == true
private fun KotlinType.restoreAdditionalTypeInformation(prototype: KotlinType): KotlinType {
return TypeUtils.makeNullableAsSpecified(this, prototype.isMarkedNullable).replace(prototype.arguments)
@@ -28,7 +28,6 @@ import org.jetbrains.kotlin.types.checker.*
import org.jetbrains.kotlin.types.error.ErrorType
import org.jetbrains.kotlin.types.model.TypeArgumentMarker
import org.jetbrains.kotlin.types.model.TypeVariableTypeConstructorMarker
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.kotlin.types.error.ErrorUtils
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
@@ -337,7 +336,7 @@ fun SimpleType.unCapture(): UnwrappedType {
}
fun unCaptureProjection(projection: TypeProjection): TypeProjection {
val unCapturedProjection = projection.type.constructor.safeAs<NewCapturedTypeConstructor>()?.projection ?: projection
val unCapturedProjection = (projection.type.constructor as? NewCapturedTypeConstructor)?.projection ?: projection
if (unCapturedProjection.isStarProjection || unCapturedProjection.type is ErrorType) return unCapturedProjection
val newArguments = unCapturedProjection.type.arguments.map(::unCaptureProjection)
@@ -30,7 +30,6 @@ import org.jetbrains.kotlin.types.model.*
import org.jetbrains.kotlin.types.typeUtil.*
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.kotlin.types.typeUtil.isSignedOrUnsignedNumberType as classicIsSignedOrUnsignedNumberType
import org.jetbrains.kotlin.types.typeUtil.isStubType as isSimpleTypeStubType
import org.jetbrains.kotlin.types.typeUtil.isStubTypeForBuilderInference as isSimpleTypeStubTypeForBuilderInference
@@ -837,7 +836,7 @@ interface ClassicTypeSystemContext : TypeSystemInferenceExtensionContext, TypeSy
require(firstCandidate is KotlinType, this::errorMessage)
require(secondCandidate is KotlinType, this::errorMessage)
firstCandidate.constructor.safeAs<IntersectionTypeConstructor>()?.let { intersectionConstructor ->
(firstCandidate.constructor as? IntersectionTypeConstructor)?.let { intersectionConstructor ->
val intersectionTypeWithAlternative = intersectionConstructor.setAlternative(secondCandidate).createType()
return if (firstCandidate.isMarkedNullable) intersectionTypeWithAlternative.makeNullableAsSpecified(true)
else intersectionTypeWithAlternative
@@ -16,7 +16,6 @@ import org.jetbrains.kotlin.types.TypeProjection
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.types.typeUtil.contains
import org.jetbrains.kotlin.types.typeUtil.isUnresolvedType
import org.jetbrains.kotlin.utils.addToStdlib.cast
object ErrorUtils {
val errorModule: ModuleDescriptor = ErrorModuleDescriptor
@@ -110,6 +109,6 @@ object ErrorUtils {
fun unresolvedTypeAsItIs(type: KotlinType): String {
assert(isUnresolvedType(type))
return type.constructor.cast<ErrorTypeConstructor>().getParam(0)
return (type.constructor as ErrorTypeConstructor).getParam(0)
}
}
@@ -54,7 +54,6 @@ import org.jetbrains.kotlin.util.OperatorNameConventions.SIMPLE_UNARY_OPERATION_
import org.jetbrains.kotlin.util.ReturnsCheck.*
import org.jetbrains.kotlin.util.ValueParameterCountCheck.NoValueParameters
import org.jetbrains.kotlin.util.ValueParameterCountCheck.SingleValueParameter
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
sealed class CheckResult(val isSuccess: Boolean) {
class IllegalSignature(val error: String) : CheckResult(false)
@@ -241,8 +240,7 @@ object OperatorChecks : AbstractModifierChecks() {
val potentialActualAliasId = classDescriptor.classId ?: return false
val actualReceiverTypeAlias =
classDescriptor.module.findClassifierAcrossModuleDependencies(potentialActualAliasId).safeAs<TypeAliasDescriptor>()
?: return false
classDescriptor.module.findClassifierAcrossModuleDependencies(potentialActualAliasId) as? TypeAliasDescriptor ?: return false
returnType?.let { returnType ->
return returnType.isSubtypeOf(actualReceiverTypeAlias.expandedType)
@@ -21,7 +21,6 @@ import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.error.ErrorUtils
import org.jetbrains.kotlin.types.error.ErrorTypeKind
import org.jetbrains.kotlin.types.typeUtil.builtIns
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import java.util.*
private val EXPERIMENTAL_CONTINUATION_FQ_NAME = FqName("kotlin.coroutines.experimental.Continuation")
@@ -232,7 +231,7 @@ class TypeDeserializer(
val suspendReturnType = continuationArgumentType.arguments.single().type
// Load kotlin.suspend as accepting and returning suspend function type independent of its version requirement
if (c.containingDeclaration.safeAs<CallableDescriptor>()?.fqNameOrNull() == KOTLIN_SUSPEND_BUILT_IN_FUNCTION_FQ_NAME) {
if ((c.containingDeclaration as? CallableDescriptor)?.fqNameOrNull() == KOTLIN_SUSPEND_BUILT_IN_FUNCTION_FQ_NAME) {
return createSimpleSuspendFunctionType(funType, suspendReturnType)
}
@@ -23,7 +23,6 @@ import org.jetbrains.kotlin.descriptors.runtime.components.ReflectKotlinClass
import org.jetbrains.kotlin.load.kotlin.JvmPackagePartSource
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedMemberDescriptor
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import kotlin.jvm.internal.TypeParameterReference
import kotlin.reflect.KType
import kotlin.reflect.KTypeParameter
@@ -74,9 +73,11 @@ internal class KTypeParameterImpl(
toJavaClass()?.kotlin as KClassImpl<*>?
?: throw KotlinReflectionInternalError("Type parameter container is not resolved: $containingDeclaration")
private fun DeserializedMemberDescriptor.getContainerClass(): Class<*> =
containerSource.safeAs<JvmPackagePartSource>()?.knownJvmBinaryClass.safeAs<ReflectKotlinClass>()?.klass
private fun DeserializedMemberDescriptor.getContainerClass(): Class<*> {
val jvmPackagePartSource = containerSource as? JvmPackagePartSource
return (jvmPackagePartSource?.knownJvmBinaryClass as? ReflectKotlinClass)?.klass
?: throw KotlinReflectionInternalError("Container of deserialized member is not resolved: $this")
}
override fun equals(other: Any?) =
other is KTypeParameterImpl && container == other.container && name == other.name