mirror of
https://github.com/jlengrand/kotlin.git
synced 2026-04-11 15:52:06 +00:00
Compare commits
6 Commits
get-script
...
fir-perfor
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c0c646a437 | ||
|
|
a64fb17266 | ||
|
|
545f6d4fd8 | ||
|
|
4c701616d6 | ||
|
|
b4cca74117 | ||
|
|
2de373f68e |
@@ -10,7 +10,8 @@ buildscript {
|
||||
extra["defaultSnapshotVersion"] = "1.3-SNAPSHOT"
|
||||
|
||||
// when updating please also update JPS artifacts configuration: https://jetbrains.quip.com/zzGUAYSJ6gv3/JPS-Build-update-bootstrap
|
||||
kotlinBootstrapFrom(BootstrapOption.TeamCity("1.3.40-dev-431", onlySuccessBootstrap = false))
|
||||
kotlinBootstrapFrom(BootstrapOption.Local(project.property("bootstrap.compiler.version").toString(), localPath=project.property("bootstrap.compiler.repository").toString()))
|
||||
|
||||
|
||||
repositories.withRedirector(project) {
|
||||
bootstrapKotlinRepo?.let(::maven)
|
||||
@@ -742,4 +743,9 @@ allprojects {
|
||||
repositories.redirect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tasks.withType<KotlinCompile> {
|
||||
kotlinOptions.freeCompilerArgs += "-Xdump-model=" + project.property("dump.model.output").toString()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -995,7 +995,7 @@ private fun findSafelyReachableReturns(methodNode: MethodNode, sourceFrames: Arr
|
||||
|
||||
if (!insn.isMeaningful || insn.opcode in SAFE_OPCODES || insn.isInvisibleInDebugVarInsn(methodNode) ||
|
||||
isInlineMarker(insn)) {
|
||||
setOf()
|
||||
setOf<Int>()
|
||||
} else null
|
||||
}
|
||||
|
||||
|
||||
@@ -171,7 +171,7 @@ class PsiSourceCompilerForInline(private val codegen: ExpressionCodegen, overrid
|
||||
codegen.parentCodegen.className
|
||||
else
|
||||
state.typeMapper.mapImplementationOwner(descriptor).internalName,
|
||||
if (isLambda) emptyList() else additionalInnerClasses,
|
||||
if (isLambda) emptyList<ClassDescriptor>() else additionalInnerClasses,
|
||||
isLambda
|
||||
)
|
||||
|
||||
|
||||
@@ -11,5 +11,5 @@ import org.jetbrains.kotlin.fir.expressions.FirBlock
|
||||
class FirEmptyExpressionBlock(
|
||||
session: FirSession
|
||||
) : FirAbstractBlock(session, null), FirBlock {
|
||||
override val statements = listOf()
|
||||
override val statements = listOf<FirStatement>()
|
||||
}
|
||||
@@ -508,7 +508,7 @@ class ControlFlowInformationProvider private constructor(
|
||||
}
|
||||
}
|
||||
if (descriptor == null) {
|
||||
val descriptors = trace.get(BindingContext.AMBIGUOUS_REFERENCE_TARGET, operationReference) ?: emptyList()
|
||||
val descriptors = trace.get(BindingContext.AMBIGUOUS_REFERENCE_TARGET, operationReference) ?: emptyList<DeclarationDescriptor>()
|
||||
for (referenceDescriptor in descriptors) {
|
||||
if ((referenceDescriptor as? FunctionDescriptor)?.returnType?.let { KotlinBuiltIns.isUnit(it) } == true) {
|
||||
hasReassignMethodReturningUnit = true
|
||||
|
||||
@@ -13,6 +13,8 @@ import org.jetbrains.kotlin.diagnostics.rendering.AbstractDiagnosticWithParamete
|
||||
import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages
|
||||
import org.jetbrains.kotlin.diagnostics.rendering.DiagnosticWithParameters1Renderer
|
||||
import org.jetbrains.kotlin.diagnostics.rendering.Renderers.TO_STRING
|
||||
import org.jetbrains.kotlin.diagnostics.rendering.DiagnosticRenderer
|
||||
import org.jetbrains.kotlin.diagnostics.Diagnostic
|
||||
import java.util.regex.Pattern
|
||||
|
||||
class TextDiagnostic(
|
||||
@@ -136,7 +138,7 @@ class TextDiagnostic(
|
||||
private fun asTextDiagnostic(actualDiagnostic: ActualDiagnostic): TextDiagnostic {
|
||||
val diagnostic = actualDiagnostic.diagnostic
|
||||
val renderer = when (diagnostic.factory) {
|
||||
is DebugInfoDiagnosticFactory1 -> DiagnosticWithParameters1Renderer("{0}", TO_STRING)
|
||||
is DebugInfoDiagnosticFactory1 -> DiagnosticWithParameters1Renderer("{0}", TO_STRING) as DiagnosticRenderer<Diagnostic>
|
||||
else -> DefaultErrorMessages.getRendererForDiagnostic(diagnostic)
|
||||
}
|
||||
val diagnosticName = actualDiagnostic.name
|
||||
|
||||
@@ -205,7 +205,7 @@ class KotlinResolutionCallbacksImpl(
|
||||
}
|
||||
|
||||
override fun bindStubResolvedCallForCandidate(candidate: ResolvedCallAtom) {
|
||||
kotlinToResolvedCallTransformer.createStubResolvedCallAndWriteItToTrace(candidate, trace, emptyList(), substitutor = null)
|
||||
kotlinToResolvedCallTransformer.createStubResolvedCallAndWriteItToTrace<CallableDescriptor>(candidate, trace, emptyList(), substitutor = null)
|
||||
}
|
||||
|
||||
override fun createReceiverWithSmartCastInfo(resolvedAtom: ResolvedCallAtom): ReceiverValueWithSmartCastInfo? {
|
||||
|
||||
@@ -108,7 +108,7 @@ class KotlinToResolvedCallTransformer(
|
||||
|
||||
val resultSubstitutor = baseResolvedCall.constraintSystem.buildResultingSubstitutor()
|
||||
if (context.inferenceSession.writeOnlyStubs()) {
|
||||
val stub = createStubResolvedCallAndWriteItToTrace(
|
||||
val stub = createStubResolvedCallAndWriteItToTrace<CallableDescriptor>(
|
||||
candidate,
|
||||
context.trace,
|
||||
baseResolvedCall.diagnostics,
|
||||
|
||||
@@ -261,7 +261,7 @@ open class WrappedTypeParameterDescriptor(
|
||||
|
||||
override val supertypeLoopChecker = SupertypeLoopChecker.EMPTY
|
||||
|
||||
override fun getParameters() = emptyList()
|
||||
override fun getParameters(): List<TypeParameterDescriptor> = emptyList()
|
||||
|
||||
override fun isFinal() = false
|
||||
|
||||
@@ -687,7 +687,7 @@ open class WrappedEnumEntryDescriptor(
|
||||
TODO("not implemented")
|
||||
}
|
||||
|
||||
override fun getDeclaredTypeParameters() = emptyList()
|
||||
override fun getDeclaredTypeParameters(): List<TypeParameterDescriptor> = emptyList()
|
||||
|
||||
override fun getSealedSubclasses(): Collection<ClassDescriptor> {
|
||||
TODO("not implemented")
|
||||
@@ -773,7 +773,7 @@ open class WrappedPropertyDescriptor(
|
||||
owner.setter?.descriptor as? PropertyAccessorDescriptor
|
||||
).toMutableList()
|
||||
|
||||
override fun getTypeParameters() = emptyList()
|
||||
override fun getTypeParameters(): List<TypeParameterDescriptor> = emptyList()
|
||||
|
||||
override fun getVisibility() = owner.visibility
|
||||
|
||||
@@ -877,7 +877,7 @@ open class WrappedFieldDescriptor(
|
||||
|
||||
override fun getAccessors(): MutableList<PropertyAccessorDescriptor> = mutableListOf()
|
||||
|
||||
override fun getTypeParameters() = emptyList()
|
||||
override fun getTypeParameters(): List<TypeParameterDescriptor> = emptyList()
|
||||
|
||||
override fun getVisibility() = owner.visibility
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid
|
||||
import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
|
||||
import org.jetbrains.kotlin.name.Name
|
||||
|
||||
val jvmDefaultArgumentStubPhase = makeIrFilePhase(
|
||||
val jvmDefaultArgumentStubPhase = makeIrFilePhase<CommonBackendContext>(
|
||||
{ context -> DefaultArgumentStubGenerator(context, false) },
|
||||
name = "DefaultArgumentsStubGenerator",
|
||||
description = "Generate synthetic stubs for functions with default parameter values"
|
||||
|
||||
@@ -32,7 +32,7 @@ import org.jetbrains.kotlin.name.Name
|
||||
|
||||
object SYNTHESIZED_INIT_BLOCK: IrStatementOriginImpl("SYNTHESIZED_INIT_BLOCK")
|
||||
|
||||
fun makeInitializersPhase(origin: IrDeclarationOrigin, clinitNeeded: Boolean)= makeIrFilePhase(
|
||||
fun makeInitializersPhase(origin: IrDeclarationOrigin, clinitNeeded: Boolean)= makeIrFilePhase<CommonBackendContext>(
|
||||
{ context -> InitializersLowering(context, origin, clinitNeeded) },
|
||||
name = "Initializers",
|
||||
description = "Handle initializer statements",
|
||||
|
||||
@@ -33,8 +33,9 @@ import org.jetbrains.kotlin.ir.visitors.*
|
||||
import org.jetbrains.kotlin.name.Name
|
||||
import org.jetbrains.kotlin.name.NameUtils
|
||||
import java.util.*
|
||||
import org.jetbrains.kotlin.backend.common.CommonBackendContext
|
||||
|
||||
val jvmLocalDeclarationsPhase = makeIrFilePhase(
|
||||
val jvmLocalDeclarationsPhase = makeIrFilePhase<CommonBackendContext>(
|
||||
{ context ->
|
||||
LocalDeclarationsLowering(context, object : LocalNameProvider {
|
||||
override fun localName(declaration: IrDeclarationWithName): String =
|
||||
|
||||
@@ -114,7 +114,7 @@ private class VarargTransformer(
|
||||
|
||||
// empty vararg => empty array literal
|
||||
if (segments.isEmpty()) {
|
||||
return emptyList().toArrayLiteral(primitiveExpressionType, primitiveElementType)
|
||||
return emptyList<IrExpression>().toArrayLiteral(primitiveExpressionType, primitiveElementType)
|
||||
}
|
||||
|
||||
// vararg with a single segment => no need to concatenate
|
||||
@@ -173,7 +173,7 @@ private class VarargTransformer(
|
||||
val argument = expression.getValueArgument(i)
|
||||
val parameter = expression.symbol.owner.valueParameters[i]
|
||||
if (argument == null && parameter.varargElementType != null) {
|
||||
expression.putValueArgument(i, emptyList().toArrayLiteral(parameter.type, parameter.varargElementType!!))
|
||||
expression.putValueArgument(i, emptyList<IrExpression>().toArrayLiteral(parameter.type, parameter.varargElementType!!))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -444,7 +444,7 @@ class StateMachineBuilder(
|
||||
|
||||
private fun transformArguments(arguments: Array<IrExpression?>): Array<IrExpression?> {
|
||||
|
||||
var suspendableCount = arguments.fold(0) { r, n -> if (n in suspendableNodes) r + 1 else r }
|
||||
var suspendableCount = arguments.fold(0) { r, n -> if (n != null && n in suspendableNodes) r + 1 else r }
|
||||
|
||||
val newArguments = arrayOfNulls<IrExpression>(arguments.size)
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ private val expectDeclarationsRemovingPhase = makeIrFilePhase(
|
||||
description = "Remove expect declaration from module fragment"
|
||||
)
|
||||
|
||||
private val propertiesPhase = makeIrFilePhase(
|
||||
private val propertiesPhase = makeIrFilePhase<CommonBackendContext>(
|
||||
{ context ->
|
||||
PropertiesLowering(context, JvmLoweredDeclarationOrigin.SYNTHETIC_METHOD_FOR_PROPERTY_ANNOTATIONS) { propertyName ->
|
||||
JvmAbi.getSyntheticMethodNameForAnnotatedProperty(propertyName)
|
||||
@@ -55,7 +55,7 @@ private val propertiesPhase = makeIrFilePhase(
|
||||
stickyPostconditions = setOf((PropertiesLowering)::checkNoProperties)
|
||||
)
|
||||
|
||||
val jvmPhases = namedIrFilePhase(
|
||||
val jvmPhases = namedIrFilePhase<JvmBackendContext> (
|
||||
name = "IrLowering",
|
||||
description = "IR lowering",
|
||||
lower = expectDeclarationsRemovingPhase then
|
||||
|
||||
@@ -157,7 +157,11 @@ private class AdditionalClassAnnotationLowering(private val context: JvmBackendC
|
||||
private fun generateRetentionAnnotation(irClass: IrClass) {
|
||||
if (irClass.hasAnnotation(FqName("java.lang.annotation.Retention"))) return
|
||||
val kotlinRetentionPolicy = irClass.getAnnotation(FqName("kotlin.annotation.Retention"))
|
||||
val javaRetentionPolicy = annotationRetentionMap[kotlinRetentionPolicy] ?: rpRuntime
|
||||
val javaRetentionPolicy = if (kotlinRetentionPolicy is KotlinRetention) {
|
||||
annotationRetentionMap[kotlinRetentionPolicy] ?: rpRuntime
|
||||
} else {
|
||||
rpRuntime
|
||||
}
|
||||
|
||||
irClass.annotations.add(
|
||||
IrCallImpl(
|
||||
|
||||
@@ -58,7 +58,7 @@ import org.jetbrains.org.objectweb.asm.Type
|
||||
|
||||
//Hack implementation to support CR java types in lower
|
||||
class CrIrType(val type: Type) : IrType {
|
||||
override val annotations = emptyList()
|
||||
override val annotations: List<IrCall> = emptyList()
|
||||
|
||||
override fun equals(other: Any?): Boolean =
|
||||
other is CrIrType && type == other.type
|
||||
@@ -595,7 +595,7 @@ internal class CallableReferenceLowering(val context: JvmBackendContext) : FileL
|
||||
private fun IrType.substitute(substitutionMap: Map<IrTypeParameter, IrType>): IrType {
|
||||
if (this !is IrSimpleType) return this
|
||||
|
||||
substitutionMap[classifier]?.let { return it }
|
||||
// substitutionMap[classifier]?.let { return it }
|
||||
|
||||
val newArguments = arguments.map {
|
||||
if (it is IrTypeProjection) {
|
||||
|
||||
@@ -60,8 +60,7 @@ internal class PropertyReferenceLowering(val context: JvmBackendContext) : Class
|
||||
get() = context.state.typeMapper.mapSignatureSkipGeneric(collectRealOverrides().first().descriptor).toString()
|
||||
|
||||
private val IrMemberAccessExpression.signature: String
|
||||
get() = localPropertyIndices[getter]?.let { "<v#$it>" }
|
||||
?: (getter?.owner as? IrSimpleFunction)?.signature
|
||||
get() = getter?.let { getter -> localPropertyIndices[getter]?.let { "<v#$it>" } }
|
||||
// Plain Java fields do not have a getter, but can be referenced nonetheless. The signature should be
|
||||
// the one that a getter would have, if it existed.
|
||||
?: TODO("plain Java field signature")
|
||||
|
||||
@@ -12,6 +12,7 @@ import org.jetbrains.kotlin.backend.common.push
|
||||
import org.jetbrains.kotlin.backend.jvm.JvmBackendContext
|
||||
import org.jetbrains.kotlin.ir.declarations.IrClass
|
||||
import org.jetbrains.kotlin.ir.declarations.IrDeclaration
|
||||
import org.jetbrains.kotlin.ir.declarations.IrDeclarationParent
|
||||
import org.jetbrains.kotlin.ir.declarations.IrSymbolOwner
|
||||
import org.jetbrains.kotlin.ir.expressions.*
|
||||
import org.jetbrains.kotlin.ir.expressions.impl.IrGetFieldImpl
|
||||
@@ -27,7 +28,7 @@ internal val singletonReferencesPhase = makeIrFilePhase(
|
||||
|
||||
private class SingletonReferencesLowering(val context: JvmBackendContext) : ClassLoweringPass, IrElementTransformerVoid() {
|
||||
private lateinit var containingClass: IrClass
|
||||
private val constructingEnums = arrayListOf()
|
||||
private val constructingEnums = arrayListOf<IrDeclarationParent>()
|
||||
|
||||
override fun lower(irClass: IrClass) {
|
||||
containingClass = irClass
|
||||
|
||||
@@ -76,11 +76,11 @@ class AllClassesCompletion(private val parameters: CompletionParameters,
|
||||
private fun collectClassesFromScope(scope: MemberScope, collector: (ClassDescriptor) -> Unit) {
|
||||
for (descriptor in scope.getDescriptorsFiltered(DescriptorKindFilter.CLASSIFIERS)) {
|
||||
if (descriptor is ClassDescriptor) {
|
||||
if (kindFilter(descriptor.kind) && prefixMatcher.prefixMatches(descriptor.name.asString())) {
|
||||
collector(descriptor)
|
||||
if (kindFilter((descriptor as ClassDescriptor).kind) && prefixMatcher.prefixMatches((descriptor as ClassDescriptor).name.asString())) {
|
||||
collector(descriptor as ClassDescriptor)
|
||||
}
|
||||
|
||||
collectClassesFromScope(descriptor.unsubstitutedInnerClassesScope, collector)
|
||||
collectClassesFromScope((descriptor as ClassDescriptor).unsubstitutedInnerClassesScope, collector)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -113,6 +113,6 @@ class AllClassesCompletion(private val parameters: CompletionParameters,
|
||||
private fun isNotToBeUsed(javaClass: PsiClass): Boolean {
|
||||
if (includeJavaClassesNotToBeUsed) return false
|
||||
val fqName = javaClass.getKotlinFqName()
|
||||
return fqName != null && isJavaClassNotToBeUsedInKotlin(fqName)
|
||||
return fqName != null && isJavaClassNotToBeUsedInKotlin(fqName!!)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,11 +116,11 @@ class BasicCompletionSession(
|
||||
if (OPERATOR_NAME.isApplicable())
|
||||
return OPERATOR_NAME
|
||||
|
||||
if (NamedArgumentCompletion.isOnlyNamedArgumentExpected(nameExpression)) {
|
||||
if (NamedArgumentCompletion.isOnlyNamedArgumentExpected(nameExpression!!)) {
|
||||
return NAMED_ARGUMENTS_ONLY
|
||||
}
|
||||
|
||||
if (nameExpression.getStrictParentOfType<KtSuperExpression>() != null) {
|
||||
if (nameExpression!!.getStrictParentOfType<KtSuperExpression>() != null) {
|
||||
return SUPER_QUALIFIER
|
||||
}
|
||||
|
||||
@@ -166,7 +166,7 @@ class BasicCompletionSession(
|
||||
|
||||
if (smartCompletion != null) {
|
||||
val smartCompletionInBasicWeigher =
|
||||
SmartCompletionInBasicWeigher(smartCompletion, callTypeAndReceiver, resolutionFacade, bindingContext)
|
||||
SmartCompletionInBasicWeigher(smartCompletion!!, callTypeAndReceiver, resolutionFacade, bindingContext)
|
||||
sorter = sorter.weighBefore(
|
||||
KindWeigher.toString(),
|
||||
smartCompletionInBasicWeigher,
|
||||
@@ -197,15 +197,15 @@ class BasicCompletionSession(
|
||||
override fun doComplete() {
|
||||
val declaration = isStartOfExtensionReceiverFor()
|
||||
if (declaration != null) {
|
||||
completeDeclarationNameFromUnresolvedOrOverride(declaration)
|
||||
completeDeclarationNameFromUnresolvedOrOverride(declaration!!)
|
||||
|
||||
if (declaration is KtProperty) {
|
||||
completeParameterOrVarNameAndType(declaration.modifierList?.hasModifier(KtTokens.LATEINIT_KEYWORD) == true)
|
||||
completeParameterOrVarNameAndType((declaration as KtProperty).modifierList?.hasModifier(KtTokens.LATEINIT_KEYWORD) == true)
|
||||
}
|
||||
|
||||
// no auto-popup on typing after "val", "var" and "fun" because it's likely the name of the declaration which is being typed by user
|
||||
if (parameters.invocationCount == 0) {
|
||||
val suppressOtherCompletion = when (declaration) {
|
||||
val suppressOtherCompletion = when (declaration!!) {
|
||||
is KtNamedFunction, is KtProperty -> prefixMatcher.prefix.let { it.isEmpty() || it[0].isLowerCase() /* function name usually starts with lower case letter */ }
|
||||
else -> true
|
||||
}
|
||||
@@ -215,7 +215,7 @@ class BasicCompletionSession(
|
||||
|
||||
fun completeWithSmartCompletion(lookupElementFactory: LookupElementFactory) {
|
||||
if (smartCompletion != null) {
|
||||
val (additionalItems, @Suppress("UNUSED_VARIABLE") inheritanceSearcher) = smartCompletion.additionalItems(
|
||||
val (additionalItems, @Suppress("UNUSED_VARIABLE") inheritanceSearcher) = smartCompletion!!.additionalItems(
|
||||
lookupElementFactory
|
||||
)
|
||||
|
||||
@@ -274,7 +274,7 @@ class BasicCompletionSession(
|
||||
JavaPsiFacade.getInstance(project).findPackage("")?.getSubPackages(searchScope)?.forEach { psiPackage ->
|
||||
val name = psiPackage.name
|
||||
if (Name.isValidIdentifier(name!!)) {
|
||||
packageNames.add(FqName(name))
|
||||
packageNames.add(FqName(name!!))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -290,7 +290,7 @@ class BasicCompletionSession(
|
||||
val contextVariablesProvider = RealContextVariablesProvider(referenceVariantsHelper, position)
|
||||
withContextVariablesProvider(contextVariablesProvider) { lookupElementFactory ->
|
||||
if (receiverTypes != null) {
|
||||
ExtensionFunctionTypeValueCompletion(receiverTypes, callTypeAndReceiver.callType, lookupElementFactory)
|
||||
ExtensionFunctionTypeValueCompletion(receiverTypes!!, callTypeAndReceiver.callType, lookupElementFactory)
|
||||
.processVariables(contextVariablesProvider)
|
||||
.forEach {
|
||||
val lookupElements =
|
||||
@@ -326,8 +326,8 @@ class BasicCompletionSession(
|
||||
if (isDebuggerContext) {
|
||||
val variantsAndFactory = getRuntimeReceiverTypeReferenceVariants(lookupElementFactory)
|
||||
if (variantsAndFactory != null) {
|
||||
val variants = variantsAndFactory.first
|
||||
@Suppress("NAME_SHADOWING") val lookupElementFactory = variantsAndFactory.second
|
||||
val variants = variantsAndFactory!!.first
|
||||
@Suppress("NAME_SHADOWING") val lookupElementFactory = variantsAndFactory!!.second
|
||||
collector.addDescriptorElements(variants.imported, lookupElementFactory, withReceiverCast = true)
|
||||
collector.addDescriptorElements(
|
||||
variants.notImportedExtensions,
|
||||
@@ -378,12 +378,12 @@ class BasicCompletionSession(
|
||||
BetterPrefixMatcher(prefixMatcher, collector.bestMatchingDegree)
|
||||
else
|
||||
prefixMatcher
|
||||
addClassesFromIndex(classKindFilter, includeTypeAliases, prefixMatcher)
|
||||
addClassesFromIndex(classKindFilter!!, includeTypeAliases, prefixMatcher)
|
||||
}
|
||||
} else if (callTypeAndReceiver is CallTypeAndReceiver.DOT) {
|
||||
val qualifier = bindingContext[BindingContext.QUALIFIER, callTypeAndReceiver.receiver]
|
||||
val qualifier = bindingContext[BindingContext.QUALIFIER, (callTypeAndReceiver as CallTypeAndReceiver.DOT).receiver]
|
||||
if (qualifier != null) return
|
||||
val receiver = callTypeAndReceiver.receiver as? KtSimpleNameExpression ?: return
|
||||
val receiver = (callTypeAndReceiver as CallTypeAndReceiver.DOT).receiver as? KtSimpleNameExpression ?: return
|
||||
|
||||
val helper = indicesHelper(false)
|
||||
|
||||
@@ -417,7 +417,7 @@ class BasicCompletionSession(
|
||||
val desc = classifier.getImportableDescriptor()
|
||||
val newScope = scope.addImportingScope(ExplicitImportsScope(listOf(desc)))
|
||||
|
||||
val newContext = (nameExpression.parent as KtExpression).analyzeInContext(newScope)
|
||||
val newContext = (nameExpression!!.parent as KtExpression).analyzeInContext(newScope)
|
||||
|
||||
val rvHelper = ReferenceVariantsHelper(
|
||||
newContext,
|
||||
@@ -428,11 +428,11 @@ class BasicCompletionSession(
|
||||
)
|
||||
val rvCollector = ReferenceVariantsCollector(
|
||||
rvHelper, indicesHelper(true), prefixMatcher,
|
||||
nameExpression, callTypeAndReceiver, resolutionFacade, newContext,
|
||||
nameExpression!!, callTypeAndReceiver, resolutionFacade, newContext,
|
||||
importableFqNameClassifier, configuration
|
||||
)
|
||||
|
||||
val receiverTypes = detectReceiverTypes(newContext, nameExpression, callTypeAndReceiver)
|
||||
val receiverTypes = detectReceiverTypes(newContext, nameExpression!!, callTypeAndReceiver)
|
||||
|
||||
val factory = lookupElementFactory.copy(receiverTypes = receiverTypes, standardLookupElementsPostProcessor = {
|
||||
|
||||
@@ -444,7 +444,7 @@ class BasicCompletionSession(
|
||||
|
||||
if (lookupDescriptor is CallableMemberDescriptor &&
|
||||
lookupDescriptor.isExtension &&
|
||||
lookupDescriptor.extensionReceiverParameter?.importableFqName != desc.fqNameSafe
|
||||
(lookupDescriptor as CallableMemberDescriptor).extensionReceiverParameter?.importableFqName != desc.fqNameSafe
|
||||
) {
|
||||
return@copy lookupElement
|
||||
}
|
||||
@@ -461,7 +461,7 @@ class BasicCompletionSession(
|
||||
val file = context.file as? KtFile
|
||||
if (file != null) {
|
||||
val receiverInFile =
|
||||
file.findElementAt(receiver.startOffset)?.getParentOfType<KtSimpleNameExpression>(false)
|
||||
file!!.findElementAt(receiver.startOffset)?.getParentOfType<KtSimpleNameExpression>(false)
|
||||
?: return
|
||||
receiverInFile.mainReference.bindToFqName(fqNameToImport, FORCED_SHORTENING)
|
||||
}
|
||||
@@ -507,8 +507,8 @@ class BasicCompletionSession(
|
||||
if (userType != typeRef.typeElement) return null
|
||||
val parent = typeRef.parent
|
||||
return when (parent) {
|
||||
is KtNamedFunction -> parent.takeIf { typeRef == it.receiverTypeReference }
|
||||
is KtProperty -> parent.takeIf { typeRef == it.receiverTypeReference }
|
||||
is KtNamedFunction -> (parent as KtNamedFunction).takeIf { typeRef == it.receiverTypeReference }
|
||||
is KtProperty -> (parent as KtProperty).takeIf { typeRef == it.receiverTypeReference }
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
@@ -567,7 +567,7 @@ class BasicCompletionSession(
|
||||
collector.addElements(
|
||||
thisExpressionItems(
|
||||
bindingContext,
|
||||
expression,
|
||||
expression!!,
|
||||
prefix,
|
||||
resolutionFacade
|
||||
).map { it.createLookupElement() })
|
||||
@@ -580,13 +580,13 @@ class BasicCompletionSession(
|
||||
// if "return" is parsed correctly in the current context - insert it and all return@xxx items
|
||||
"return" -> {
|
||||
if (expression != null) {
|
||||
collector.addElements(returnExpressionItems(bindingContext, expression))
|
||||
collector.addElements(returnExpressionItems(bindingContext, expression!!))
|
||||
}
|
||||
}
|
||||
|
||||
"break", "continue" -> {
|
||||
if (expression != null) {
|
||||
collector.addElements(breakOrContinueExpressionItems(expression, keyword))
|
||||
collector.addElements(breakOrContinueExpressionItems(expression!!, keyword))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -658,7 +658,7 @@ class BasicCompletionSession(
|
||||
val func = position.getParentOfType<KtNamedFunction>(strict = false) ?: return false
|
||||
val funcNameIdentifier = func.nameIdentifier ?: return false
|
||||
val identifierInNameExpression =
|
||||
nameExpression.nextLeaf { it is LeafPsiElement && it.elementType == KtTokens.IDENTIFIER } ?: return false
|
||||
nameExpression!!.nextLeaf { it is LeafPsiElement && (it as LeafPsiElement).elementType == KtTokens.IDENTIFIER } ?: return false
|
||||
if (!func.hasModifier(KtTokens.OPERATOR_KEYWORD) || identifierInNameExpression != funcNameIdentifier) return false
|
||||
val originalFunc = toFromOriginalFileMapper.toOriginalFile(func) ?: return false
|
||||
return !originalFunc.isTopLevel || (originalFunc.isExtensionDeclaration())
|
||||
@@ -690,7 +690,7 @@ class BasicCompletionSession(
|
||||
when (declaration) {
|
||||
is KtParameter -> completeParameterOrVarNameAndType(withType = true)
|
||||
is KtClassOrObject -> {
|
||||
if (declaration.isTopLevel()) {
|
||||
if ((declaration as KtClassOrObject).isTopLevel()) {
|
||||
completeTopLevelClassName()
|
||||
}
|
||||
}
|
||||
@@ -713,7 +713,7 @@ class BasicCompletionSession(
|
||||
private fun completeTopLevelClassName() {
|
||||
val name = parameters.originalFile.virtualFile.nameWithoutExtension
|
||||
if (!(Name.isValidIdentifier(name) && Name.identifier(name).render() == name && name[0].isUpperCase())) return
|
||||
if ((parameters.originalFile as KtFile).declarations.any { it is KtClassOrObject && it.name == name }) return
|
||||
if ((parameters.originalFile as KtFile).declarations.any { it is KtClassOrObject && (it as KtClassOrObject).name == name }) return
|
||||
|
||||
collector.addElement(LookupElementBuilder.create(name))
|
||||
}
|
||||
@@ -726,8 +726,8 @@ class BasicCompletionSession(
|
||||
val owner = list.parent
|
||||
return when (owner) {
|
||||
is KtCatchClause, is KtPropertyAccessor, is KtFunctionLiteral -> false
|
||||
is KtNamedFunction -> owner.nameIdentifier != null
|
||||
is KtPrimaryConstructor -> !owner.getContainingClassOrObject().isAnnotation()
|
||||
is KtNamedFunction -> (owner as KtNamedFunction).nameIdentifier != null
|
||||
is KtPrimaryConstructor -> !(owner as KtPrimaryConstructor).getContainingClassOrObject().isAnnotation()
|
||||
else -> true
|
||||
}
|
||||
}
|
||||
@@ -756,7 +756,7 @@ class BasicCompletionSession(
|
||||
|
||||
private fun completeDeclarationNameFromUnresolvedOrOverride(declaration: KtNamedDeclaration) {
|
||||
if (declaration is KtCallableDeclaration && declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) {
|
||||
OverridesCompletion(collector, basicLookupElementFactory).complete(position, declaration)
|
||||
OverridesCompletion(collector, basicLookupElementFactory).complete(position, declaration as KtCallableDeclaration)
|
||||
} else {
|
||||
val referenceScope = referenceScope(declaration) ?: return
|
||||
val originalScope = toFromOriginalFileMapper.toOriginalFile(referenceScope) ?: return
|
||||
@@ -769,20 +769,20 @@ class BasicCompletionSession(
|
||||
private fun referenceScope(declaration: KtNamedDeclaration): KtElement? {
|
||||
val parent = declaration.parent
|
||||
return when (parent) {
|
||||
is KtParameterList -> parent.parent as KtElement
|
||||
is KtParameterList -> (parent as KtParameterList).parent as KtElement
|
||||
|
||||
is KtClassBody -> {
|
||||
val classOrObject = parent.parent as KtClassOrObject
|
||||
if (classOrObject is KtObjectDeclaration && classOrObject.isCompanion()) {
|
||||
val classOrObject = (parent as KtClassBody).parent as KtClassOrObject
|
||||
if (classOrObject is KtObjectDeclaration && (classOrObject as KtObjectDeclaration).isCompanion()) {
|
||||
classOrObject.containingClassOrObject
|
||||
} else {
|
||||
classOrObject
|
||||
}
|
||||
}
|
||||
|
||||
is KtFile -> parent
|
||||
is KtFile -> parent as KtFile
|
||||
|
||||
is KtBlockExpression -> parent
|
||||
is KtBlockExpression -> parent as KtBlockExpression
|
||||
|
||||
else -> null
|
||||
}
|
||||
|
||||
@@ -64,7 +64,7 @@ class BasicLookupElementFactory(
|
||||
parametersAndTypeGrayed: Boolean = false
|
||||
): LookupElement {
|
||||
val _descriptor = if (descriptor is CallableMemberDescriptor)
|
||||
DescriptorUtils.unwrapFakeOverride(descriptor)
|
||||
DescriptorUtils.unwrapFakeOverride(descriptor as CallableMemberDescriptor)
|
||||
else
|
||||
descriptor
|
||||
return createLookupElementUnwrappedDescriptor(_descriptor, qualifyNestedClasses, includeClassTypeArguments, parametersAndTypeGrayed)
|
||||
@@ -134,22 +134,22 @@ class BasicLookupElementFactory(
|
||||
// for java classes we create special lookup elements
|
||||
// because they must be equal to ones created in TypesCompletion
|
||||
// otherwise we may have duplicates
|
||||
return createLookupElementForJavaClass(declaration, qualifyNestedClasses, includeClassTypeArguments)
|
||||
return createLookupElementForJavaClass(declaration as PsiClass, qualifyNestedClasses, includeClassTypeArguments)
|
||||
}
|
||||
}
|
||||
|
||||
if (descriptor is PackageViewDescriptor) {
|
||||
return createLookupElementForPackage(descriptor.fqName)
|
||||
return createLookupElementForPackage((descriptor as PackageViewDescriptor).fqName)
|
||||
}
|
||||
if (descriptor is PackageFragmentDescriptor) {
|
||||
return createLookupElementForPackage(descriptor.fqName)
|
||||
return createLookupElementForPackage((descriptor as PackageFragmentDescriptor).fqName)
|
||||
}
|
||||
|
||||
val lookupObject: DeclarationLookupObject
|
||||
val name: String = when (descriptor) {
|
||||
is ConstructorDescriptor -> {
|
||||
// for constructor use name and icon of containing class
|
||||
val classifierDescriptor = descriptor.containingDeclaration
|
||||
val classifierDescriptor = (descriptor as ConstructorDescriptor).containingDeclaration
|
||||
lookupObject = object : DeclarationLookupObjectImpl(descriptor) {
|
||||
override val psiElement by lazy { DescriptorToSourceUtilsIde.getAnyDeclaration(project, classifierDescriptor) }
|
||||
override fun getIcon(flags: Int) = KotlinDescriptorIconProvider.getIcon(classifierDescriptor, psiElement, flags)
|
||||
@@ -159,10 +159,10 @@ class BasicLookupElementFactory(
|
||||
|
||||
is SyntheticJavaPropertyDescriptor -> {
|
||||
lookupObject = object : DeclarationLookupObjectImpl(descriptor) {
|
||||
override val psiElement by lazy { DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor.getMethod) }
|
||||
override val psiElement by lazy { DescriptorToSourceUtilsIde.getAnyDeclaration(project, (descriptor as SyntheticJavaPropertyDescriptor).getMethod) }
|
||||
override fun getIcon(flags: Int) = KotlinDescriptorIconProvider.getIcon(descriptor, null, flags)
|
||||
}
|
||||
descriptor.name.asString()
|
||||
(descriptor as SyntheticJavaPropertyDescriptor).name.asString()
|
||||
}
|
||||
|
||||
else -> {
|
||||
@@ -185,41 +185,41 @@ class BasicLookupElementFactory(
|
||||
|
||||
when (descriptor) {
|
||||
is FunctionDescriptor -> {
|
||||
val returnType = descriptor.returnType
|
||||
element = element.withTypeText(if (returnType != null) SHORT_NAMES_RENDERER.renderType(returnType) else "", parametersAndTypeGrayed)
|
||||
val returnType = (descriptor as FunctionDescriptor).returnType
|
||||
element = element.withTypeText(if (returnType != null) SHORT_NAMES_RENDERER.renderType(returnType!!) else "", parametersAndTypeGrayed)
|
||||
|
||||
val insertsLambda = (insertHandler as? KotlinFunctionInsertHandler.Normal)?.lambdaInfo != null
|
||||
if (insertsLambda) {
|
||||
element = element.appendTailText(" {...} ", parametersAndTypeGrayed)
|
||||
}
|
||||
|
||||
element = element.appendTailText(SHORT_NAMES_RENDERER.renderFunctionParameters(descriptor), parametersAndTypeGrayed || insertsLambda)
|
||||
element = element.appendTailText(SHORT_NAMES_RENDERER.renderFunctionParameters(descriptor as FunctionDescriptor), parametersAndTypeGrayed || insertsLambda)
|
||||
}
|
||||
|
||||
is VariableDescriptor -> {
|
||||
element = element.withTypeText(SHORT_NAMES_RENDERER.renderType(descriptor.type), parametersAndTypeGrayed)
|
||||
element = element.withTypeText(SHORT_NAMES_RENDERER.renderType((descriptor as VariableDescriptor).type), parametersAndTypeGrayed)
|
||||
}
|
||||
|
||||
is ClassifierDescriptorWithTypeParameters -> {
|
||||
val typeParams = descriptor.declaredTypeParameters
|
||||
val typeParams = (descriptor as ClassifierDescriptorWithTypeParameters).declaredTypeParameters
|
||||
if (includeClassTypeArguments && typeParams.isNotEmpty()) {
|
||||
element = element.appendTailText(typeParams.joinToString(", ", "<", ">") { it.name.asString() }, true)
|
||||
}
|
||||
|
||||
var container = descriptor.containingDeclaration
|
||||
var container = (descriptor as ClassifierDescriptorWithTypeParameters).containingDeclaration
|
||||
|
||||
if (descriptor.isArtificialImportAliasedDescriptor) {
|
||||
container = descriptor.original // we show original descriptor instead of container for import aliased descriptors
|
||||
container = (descriptor as ClassifierDescriptorWithTypeParameters).original // we show original descriptor instead of container for import aliased descriptors
|
||||
}
|
||||
else if (qualifyNestedClasses) {
|
||||
element = element.withPresentableText(SHORT_NAMES_RENDERER.renderClassifierName(descriptor))
|
||||
element = element.withPresentableText(SHORT_NAMES_RENDERER.renderClassifierName(descriptor as ClassifierDescriptorWithTypeParameters))
|
||||
|
||||
while (container is ClassDescriptor) {
|
||||
val containerName = container.name
|
||||
val containerName = (container as ClassDescriptor).name
|
||||
if (!containerName.isSpecial) {
|
||||
element = element.withLookupString(containerName.asString())
|
||||
}
|
||||
container = container.containingDeclaration
|
||||
container = (container as ClassDescriptor).containingDeclaration
|
||||
}
|
||||
}
|
||||
|
||||
@@ -229,7 +229,7 @@ class BasicLookupElementFactory(
|
||||
|
||||
if (descriptor is TypeAliasDescriptor) {
|
||||
// here we render with DescriptorRenderer.SHORT_NAMES_IN_TYPES to include parameter names in functional types
|
||||
element = element.withTypeText(DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(descriptor.underlyingType), false)
|
||||
element = element.withTypeText(DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType((descriptor as TypeAliasDescriptor).underlyingType), false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -240,15 +240,15 @@ class BasicLookupElementFactory(
|
||||
|
||||
var isMarkedAsDsl = false
|
||||
if (descriptor is CallableDescriptor) {
|
||||
appendContainerAndReceiverInformation(descriptor) { element = element.appendTailText(it, true) }
|
||||
appendContainerAndReceiverInformation(descriptor as CallableDescriptor) { element = element.appendTailText(it, true) }
|
||||
|
||||
val dslTextAttributes = DslHighlighterExtension.dslCustomTextStyle(descriptor)?.let {
|
||||
val dslTextAttributes = DslHighlighterExtension.dslCustomTextStyle(descriptor as CallableDescriptor)?.let {
|
||||
EditorColorsManager.getInstance().globalScheme.getAttributes(it)
|
||||
}
|
||||
if (dslTextAttributes != null) {
|
||||
isMarkedAsDsl = true
|
||||
element = element.withBoldness(dslTextAttributes.fontType == Font.BOLD)
|
||||
dslTextAttributes.foregroundColor?.let { element = element.withItemTextForeground(it) }
|
||||
element = element.withBoldness(dslTextAttributes!!.fontType == Font.BOLD)
|
||||
dslTextAttributes!!.foregroundColor?.let { element = element.withItemTextForeground(it) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -257,7 +257,7 @@ class BasicLookupElementFactory(
|
||||
if (getterName != name) {
|
||||
element = element.withLookupString(getterName)
|
||||
}
|
||||
if (descriptor.isVar) {
|
||||
if ((descriptor as PropertyDescriptor).isVar) {
|
||||
element = element.withLookupString(JvmAbi.setterName(name))
|
||||
}
|
||||
}
|
||||
@@ -281,7 +281,7 @@ class BasicLookupElementFactory(
|
||||
}
|
||||
|
||||
if (information != null) {
|
||||
appendTailText(information)
|
||||
appendTailText(information!!)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -294,14 +294,14 @@ class BasicLookupElementFactory(
|
||||
}
|
||||
|
||||
descriptor is SyntheticJavaPropertyDescriptor -> {
|
||||
var from = descriptor.getMethod.name.asString() + "()"
|
||||
descriptor.setMethod?.let { from += "/" + it.name.asString() + "()" }
|
||||
var from = (descriptor as SyntheticJavaPropertyDescriptor).getMethod.name.asString() + "()"
|
||||
(descriptor as SyntheticJavaPropertyDescriptor).setMethod?.let { from += "/" + it.name.asString() + "()" }
|
||||
appendTailText(" (from $from)")
|
||||
return
|
||||
}
|
||||
|
||||
else -> {
|
||||
val receiverPresentation = SHORT_NAMES_RENDERER.renderType(extensionReceiver.type)
|
||||
val receiverPresentation = SHORT_NAMES_RENDERER.renderType(extensionReceiver!!.type)
|
||||
appendTailText(" for $receiverPresentation")
|
||||
}
|
||||
}
|
||||
@@ -310,7 +310,7 @@ class BasicLookupElementFactory(
|
||||
val containerPresentation = containerPresentation(descriptor)
|
||||
if (containerPresentation != null) {
|
||||
appendTailText(" ")
|
||||
appendTailText(containerPresentation)
|
||||
appendTailText(containerPresentation!!)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -323,8 +323,8 @@ class BasicLookupElementFactory(
|
||||
descriptor.isExtension -> {
|
||||
val container = descriptor.containingDeclaration
|
||||
val containerPresentation = when (container) {
|
||||
is ClassDescriptor -> DescriptorUtils.getFqNameFromTopLevelClass(container).toString()
|
||||
is PackageFragmentDescriptor -> container.fqName.toString()
|
||||
is ClassDescriptor -> DescriptorUtils.getFqNameFromTopLevelClass(container as ClassDescriptor).toString()
|
||||
is PackageFragmentDescriptor -> (container as PackageFragmentDescriptor).fqName.toString()
|
||||
else -> return null
|
||||
}
|
||||
return "in $containerPresentation"
|
||||
|
||||
@@ -106,42 +106,43 @@ class CompletionBindingContextProvider(project: Project) {
|
||||
val prevStatement = inStatement?.siblings(forward = false, withItself = false)?.firstIsInstanceOrNull<KtExpression>()
|
||||
val modificationScope = inStatement?.let { KotlinCodeBlockModificationListener.getInsideCodeBlockModificationScope(it) }
|
||||
|
||||
val psiElementsBeforeAndAfter = modificationScope?.let { collectPsiElementsBeforeAndAfter(modificationScope, inStatement) }
|
||||
val psiElementsBeforeAndAfter = modificationScope?.let { collectPsiElementsBeforeAndAfter(modificationScope!!, inStatement!!) }
|
||||
|
||||
val prevCompletionData = prevCompletionDataCache.value.data
|
||||
when {
|
||||
prevCompletionData == null ->
|
||||
log("No up-to-date data from previous completion\n")
|
||||
block != prevCompletionData.block ->
|
||||
block != prevCompletionData!!.block ->
|
||||
log("Not in the same block\n")
|
||||
prevStatement != prevCompletionData.prevStatement ->
|
||||
prevStatement != prevCompletionData!!.prevStatement ->
|
||||
log("Previous statement is not the same\n")
|
||||
psiElementsBeforeAndAfter != prevCompletionData.psiElementsBeforeAndAfter ->
|
||||
psiElementsBeforeAndAfter != prevCompletionData!!.psiElementsBeforeAndAfter ->
|
||||
log("PSI-tree has changed inside current scope\n")
|
||||
prevCompletionData.moduleDescriptor != resolutionFacade.moduleDescriptor ->
|
||||
prevCompletionData!!.moduleDescriptor != resolutionFacade.moduleDescriptor ->
|
||||
log("ModuleDescriptor has been reset")
|
||||
inStatement.isTooComplex() ->
|
||||
inStatement!!.isTooComplex() ->
|
||||
log("Current statement is too complex to use optimization\n")
|
||||
else -> {
|
||||
log("Statement position is the same - analyzing only one statement:\n${inStatement.text.prependIndent(" ")}\n")
|
||||
LOG.debug("Reusing data from completion of \"${prevCompletionData.debugText}\"")
|
||||
log("Statement position is the same - analyzing only one statement:\n${inStatement!!.text.prependIndent(" ")}\n")
|
||||
LOG.debug("Reusing data from completion of \"${prevCompletionData!!.debugText}\"")
|
||||
|
||||
//TODO: expected type?
|
||||
val statementContext = inStatement.analyzeInContext(scope = prevCompletionData.statementResolutionScope,
|
||||
contextExpression = block,
|
||||
dataFlowInfo = prevCompletionData.statementDataFlowInfo,
|
||||
isStatement = true)
|
||||
val statementContext = inStatement!!.analyzeInContext(scope = prevCompletionData!!.statementResolutionScope,
|
||||
contextExpression = block!!,
|
||||
dataFlowInfo = prevCompletionData!!.statementDataFlowInfo,
|
||||
isStatement = true)
|
||||
// we do not update prevCompletionDataCache because the same data should work
|
||||
return CompositeBindingContext.create(listOf(statementContext, prevCompletionData.bindingContext))
|
||||
return CompositeBindingContext.create(listOf(statementContext, prevCompletionData!!.bindingContext))
|
||||
}
|
||||
}
|
||||
|
||||
val bindingContext = resolutionFacade.analyze(position.parentsWithSelf.firstIsInstance<KtElement>(), BodyResolveMode.PARTIAL_FOR_COMPLETION)
|
||||
prevCompletionDataCache.value.data = if (block != null && modificationScope != null) {
|
||||
val resolutionScope = inStatement.getResolutionScope(bindingContext, resolutionFacade)
|
||||
val dataFlowInfo = bindingContext.getDataFlowInfoBefore(inStatement)
|
||||
CompletionData(block, prevStatement, psiElementsBeforeAndAfter!!, bindingContext, resolutionFacade.moduleDescriptor, resolutionScope, dataFlowInfo,
|
||||
debugText = position.text)
|
||||
val resolutionScope = inStatement!!.getResolutionScope(bindingContext, resolutionFacade)
|
||||
val dataFlowInfo = bindingContext.getDataFlowInfoBefore(inStatement!!)
|
||||
CompletionData(
|
||||
block!!, prevStatement, psiElementsBeforeAndAfter!!, bindingContext, resolutionFacade.moduleDescriptor, resolutionScope, dataFlowInfo,
|
||||
debugText = position.text)
|
||||
}
|
||||
else {
|
||||
null
|
||||
|
||||
@@ -97,12 +97,12 @@ abstract class CompletionSession(
|
||||
init {
|
||||
val reference = (position.parent as? KtSimpleNameExpression)?.mainReference
|
||||
if (reference != null) {
|
||||
if (reference.expression is KtLabelReferenceExpression) {
|
||||
if (reference!!.expression is KtLabelReferenceExpression) {
|
||||
this.nameExpression = null
|
||||
this.expression = reference.expression.parent.parent as? KtExpressionWithLabel
|
||||
this.expression = reference!!.expression.parent.parent as? KtExpressionWithLabel
|
||||
}
|
||||
else {
|
||||
this.nameExpression = reference.expression
|
||||
this.nameExpression = reference!!.expression
|
||||
this.expression = nameExpression
|
||||
}
|
||||
}
|
||||
@@ -137,8 +137,8 @@ abstract class CompletionSession(
|
||||
isVisibleFilter,
|
||||
NotPropertiesService.getNotProperties(position))
|
||||
|
||||
protected val callTypeAndReceiver = if (nameExpression == null) CallTypeAndReceiver.UNKNOWN else CallTypeAndReceiver.detect(nameExpression)
|
||||
protected val receiverTypes = nameExpression?.let { detectReceiverTypes(bindingContext, nameExpression, callTypeAndReceiver) }
|
||||
protected val callTypeAndReceiver = if (nameExpression == null) CallTypeAndReceiver.UNKNOWN else CallTypeAndReceiver.detect(nameExpression!!)
|
||||
protected val receiverTypes = nameExpression?.let { detectReceiverTypes(bindingContext, nameExpression!!, callTypeAndReceiver) }
|
||||
|
||||
|
||||
protected val basicLookupElementFactory = BasicLookupElementFactory(project, InsertHandlerProvider(callTypeAndReceiver.callType) { expectedInfos })
|
||||
@@ -171,10 +171,10 @@ abstract class CompletionSession(
|
||||
if (descriptor.importableFqName?.let(::isJavaClassNotToBeUsedInKotlin) == true) return false
|
||||
}
|
||||
|
||||
if (descriptor is TypeParameterDescriptor && !isTypeParameterVisible(descriptor)) return false
|
||||
if (descriptor is TypeParameterDescriptor && !isTypeParameterVisible(descriptor as TypeParameterDescriptor)) return false
|
||||
|
||||
if (descriptor is DeclarationDescriptorWithVisibility) {
|
||||
val visible = descriptor.isVisible(position, callTypeAndReceiver.receiver as? KtExpression, bindingContext, resolutionFacade)
|
||||
val visible = (descriptor as DeclarationDescriptorWithVisibility).isVisible(position, callTypeAndReceiver.receiver as? KtExpression, bindingContext, resolutionFacade)
|
||||
if (visible) return true
|
||||
return completeNonAccessible && (!descriptor.isFromLibrary() || isDebuggerContext)
|
||||
}
|
||||
@@ -199,8 +199,8 @@ abstract class CompletionSession(
|
||||
var parent: DeclarationDescriptor? = inDescriptor
|
||||
while (parent != null) {
|
||||
if (parent == owner) return true
|
||||
if (parent is ClassDescriptor && !parent.isInner) return false
|
||||
parent = parent.containingDeclaration
|
||||
if (parent is ClassDescriptor && !(parent as ClassDescriptor).isInner) return false
|
||||
parent = parent!!.containingDeclaration
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -309,7 +309,7 @@ abstract class CompletionSession(
|
||||
|
||||
protected val referenceVariantsCollector = if (nameExpression != null) {
|
||||
ReferenceVariantsCollector(referenceVariantsHelper, indicesHelper(true), prefixMatcher,
|
||||
nameExpression, callTypeAndReceiver, resolutionFacade, bindingContext,
|
||||
nameExpression!!, callTypeAndReceiver, resolutionFacade, bindingContext,
|
||||
importableFqNameClassifier, configuration)
|
||||
}
|
||||
else {
|
||||
@@ -322,7 +322,9 @@ abstract class CompletionSession(
|
||||
|
||||
protected fun referenceVariantsWithSingleFunctionTypeParameter(): ReferenceVariants? {
|
||||
val variants = referenceVariantsCollector?.allCollected ?: return null
|
||||
val filter = { descriptor: DeclarationDescriptor -> descriptor is FunctionDescriptor && LookupElementFactory.hasSingleFunctionTypeParameter(descriptor) }
|
||||
val filter = { descriptor: DeclarationDescriptor -> descriptor is FunctionDescriptor && LookupElementFactory.hasSingleFunctionTypeParameter(
|
||||
descriptor as FunctionDescriptor
|
||||
) }
|
||||
return ReferenceVariants(variants.imported.filter(filter), variants.notImportedExtensions.filter(filter))
|
||||
}
|
||||
|
||||
@@ -337,7 +339,7 @@ abstract class CompletionSession(
|
||||
val runtimeType = evaluator(explicitReceiver)
|
||||
if (runtimeType == null || runtimeType == type) return null
|
||||
|
||||
val expressionReceiver = ExpressionReceiver.create(explicitReceiver, runtimeType, bindingContext)
|
||||
val expressionReceiver = ExpressionReceiver.create(explicitReceiver, runtimeType!!, bindingContext)
|
||||
val (variants, notImportedExtensions) = ReferenceVariantsCollector(
|
||||
referenceVariantsHelper, indicesHelper(true), prefixMatcher,
|
||||
nameExpression!!, callTypeAndReceiver, resolutionFacade, bindingContext,
|
||||
@@ -347,7 +349,7 @@ abstract class CompletionSession(
|
||||
val filteredNotImportedExtensions = filterVariantsForRuntimeReceiverType(notImportedExtensions, referenceVariants.notImportedExtensions)
|
||||
|
||||
val runtimeVariants = ReferenceVariants(filteredVariants, filteredNotImportedExtensions)
|
||||
return Pair(runtimeVariants, lookupElementFactory.copy(receiverTypes = listOf(ReceiverType(runtimeType, 0))))
|
||||
return Pair(runtimeVariants, lookupElementFactory.copy(receiverTypes = listOf(ReceiverType(runtimeType!!, 0))))
|
||||
}
|
||||
|
||||
private fun <TDescriptor : DeclarationDescriptor> filterVariantsForRuntimeReceiverType(
|
||||
@@ -358,7 +360,7 @@ abstract class CompletionSession(
|
||||
val result = ArrayList<TDescriptor>()
|
||||
for (variant in runtimeVariants) {
|
||||
val candidates = baseVariantsByName[variant.name]
|
||||
if (candidates == null || candidates.none { compareDescriptors(project, variant, it) }) {
|
||||
if (candidates == null || candidates!!.none { compareDescriptors(project, variant, it) }) {
|
||||
result.add(variant)
|
||||
}
|
||||
}
|
||||
@@ -377,7 +379,7 @@ abstract class CompletionSession(
|
||||
?.createNonImportedDeclarationsFilter<CallableDescriptor>(referenceVariantsCollector!!.allCollected.imported)
|
||||
indicesHelper(true).processTopLevelCallables({ prefixMatcher.prefixMatches(it) }) {
|
||||
if (shadowedFilter != null) {
|
||||
shadowedFilter(listOf(it)).singleOrNull()?.let(processor)
|
||||
(shadowedFilter as (Collection<CallableDescriptor>) -> Collection<CallableDescriptor>)(listOf(it)).singleOrNull()?.let(processor)
|
||||
}
|
||||
else {
|
||||
processor(it)
|
||||
|
||||
@@ -183,7 +183,7 @@ fun thisExpressionItems(bindingContext: BindingContext, position: KtExpression,
|
||||
for ((receiver, expressionFactory) in scope.getImplicitReceiversWithInstanceToExpression()) {
|
||||
if (expressionFactory == null) continue
|
||||
// if prefix does not start with "this@" do not include immediate this in the form with label
|
||||
val expression = expressionFactory.createExpression(psiFactory, shortThis = !prefix.startsWith("this@")) as? KtThisExpression ?: continue
|
||||
val expression = expressionFactory!!.createExpression(psiFactory, shortThis = !prefix.startsWith("this@")) as? KtThisExpression ?: continue
|
||||
result.add(ThisItemLookupObject(receiver, expression.getLabelNameAsName()))
|
||||
}
|
||||
return result
|
||||
@@ -193,10 +193,10 @@ fun returnExpressionItems(bindingContext: BindingContext, position: KtElement):
|
||||
val result = ArrayList<LookupElement>()
|
||||
for (parent in position.parentsWithSelf) {
|
||||
if (parent is KtDeclarationWithBody) {
|
||||
val returnType = parent.returnType(bindingContext)
|
||||
val isUnit = returnType == null || KotlinBuiltIns.isUnit(returnType)
|
||||
val returnType = (parent as KtDeclarationWithBody).returnType(bindingContext)
|
||||
val isUnit = returnType == null || KotlinBuiltIns.isUnit(returnType!!)
|
||||
if (parent is KtFunctionLiteral) {
|
||||
val (label, call) = parent.findLabelAndCall()
|
||||
val (label, call) = (parent as KtFunctionLiteral).findLabelAndCall()
|
||||
if (label != null) {
|
||||
result.add(createKeywordElementWithSpace("return", tail = label.labelNameToTail(), addSpaceAfter = !isUnit))
|
||||
}
|
||||
@@ -206,22 +206,24 @@ fun returnExpressionItems(bindingContext: BindingContext, position: KtElement):
|
||||
if (!InlineUtil.isInline(bindingContext[BindingContext.REFERENCE_TARGET, callee])) break // not inlined
|
||||
}
|
||||
else {
|
||||
if (parent.hasBlockBody()) {
|
||||
if ((parent as KtDeclarationWithBody).hasBlockBody()) {
|
||||
result.add(createKeywordElementWithSpace("return", addSpaceAfter = !isUnit))
|
||||
|
||||
if (returnType != null) {
|
||||
if (returnType.nullability() == TypeNullability.NULLABLE) {
|
||||
if (returnType!!.nullability() == TypeNullability.NULLABLE) {
|
||||
result.add(createKeywordElement("return null"))
|
||||
}
|
||||
|
||||
if (KotlinBuiltIns.isBooleanOrNullableBoolean(returnType)) {
|
||||
if (KotlinBuiltIns.isBooleanOrNullableBoolean(returnType!!)) {
|
||||
result.add(createKeywordElement("return true"))
|
||||
result.add(createKeywordElement("return false"))
|
||||
}
|
||||
else if (KotlinBuiltIns.isCollectionOrNullableCollection(returnType) || KotlinBuiltIns.isListOrNullableList(returnType) || KotlinBuiltIns.isIterableOrNullableIterable(returnType)) {
|
||||
else if (KotlinBuiltIns.isCollectionOrNullableCollection(returnType!!) || KotlinBuiltIns.isListOrNullableList(
|
||||
returnType!!
|
||||
) || KotlinBuiltIns.isIterableOrNullableIterable(returnType!!)) {
|
||||
result.add(createKeywordElement("return", tail = " emptyList()"))
|
||||
}
|
||||
else if (KotlinBuiltIns.isSetOrNullableSet(returnType)) {
|
||||
else if (KotlinBuiltIns.isSetOrNullableSet(returnType!!)) {
|
||||
result.add(createKeywordElement("return", tail = " emptySet()"))
|
||||
}
|
||||
}
|
||||
@@ -284,7 +286,7 @@ fun breakOrContinueExpressionItems(position: KtElement, breakOrContinue: String)
|
||||
result.add(createKeywordElement(breakOrContinue))
|
||||
}
|
||||
|
||||
val label = (parent.parent as? KtLabeledExpression)?.getLabelNameAsName()
|
||||
val label = ((parent as KtLoopExpression).parent as? KtLabeledExpression)?.getLabelNameAsName()
|
||||
if (label != null) {
|
||||
result.add(createKeywordElement(breakOrContinue, tail = label.labelNameToTail()))
|
||||
}
|
||||
@@ -328,7 +330,7 @@ fun BasicLookupElementFactory.createLookupElementForType(type: KotlinType): Look
|
||||
private open class BaseTypeLookupElement(type: KotlinType, baseLookupElement: LookupElement) : LookupElementDecorator<LookupElement>(baseLookupElement) {
|
||||
val fullText = IdeDescriptorRenderers.SOURCE_CODE.renderType(type)
|
||||
|
||||
override fun equals(other: Any?) = other is BaseTypeLookupElement && fullText == other.fullText
|
||||
override fun equals(other: Any?) = other is BaseTypeLookupElement && fullText == (other as BaseTypeLookupElement).fullText
|
||||
override fun hashCode() = fullText.hashCode()
|
||||
|
||||
override fun renderElement(presentation: LookupElementPresentation) {
|
||||
|
||||
@@ -40,7 +40,7 @@ abstract class DeclarationLookupObjectImpl(
|
||||
override val importableFqName: FqName?
|
||||
get() {
|
||||
return if (descriptor != null)
|
||||
descriptor.importableFqName
|
||||
descriptor!!.importableFqName
|
||||
else
|
||||
(psiElement as? PsiClass)?.qualifiedName?.let(::FqName)
|
||||
}
|
||||
@@ -49,7 +49,7 @@ abstract class DeclarationLookupObjectImpl(
|
||||
|
||||
override fun hashCode(): Int {
|
||||
return if (descriptor != null)
|
||||
descriptor.original.hashCode()
|
||||
descriptor!!.original.hashCode()
|
||||
else
|
||||
psiElement!!.hashCode()
|
||||
}
|
||||
@@ -67,7 +67,7 @@ abstract class DeclarationLookupObjectImpl(
|
||||
override val isDeprecated: Boolean
|
||||
get() {
|
||||
return if (descriptor != null)
|
||||
KotlinBuiltIns.isDeprecated(descriptor)
|
||||
KotlinBuiltIns.isDeprecated(descriptor!!)
|
||||
else
|
||||
(psiElement as? PsiDocCommentOwner)?.isDeprecated == true
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ class DslMembersCompletion(
|
||||
?: false
|
||||
},
|
||||
callTypeAndReceiver = callTypeAndReceiver,
|
||||
receiverTypes = listOf(nearestReceiver.type)
|
||||
receiverTypes = listOf(nearestReceiver!!.type)
|
||||
)
|
||||
extensionDescriptors.forEach {
|
||||
collector.addDescriptorElements(it, elementFactory, notImported = true, withReceiverCast = false, prohibitDuplicates = true)
|
||||
|
||||
@@ -43,14 +43,14 @@ class FromUnresolvedNamesCompletion(
|
||||
val callTypeAndReceiver = CallTypeAndReceiver.detect(refExpr)
|
||||
if (callTypeAndReceiver.receiver != null) return@forEachDescendantOfType
|
||||
if (sampleDescriptor != null) {
|
||||
if (!callTypeAndReceiver.callType.descriptorKindFilter.accepts(sampleDescriptor)) return@forEachDescendantOfType
|
||||
if (!callTypeAndReceiver.callType.descriptorKindFilter.accepts(sampleDescriptor!!)) return@forEachDescendantOfType
|
||||
|
||||
if (callTypeAndReceiver is CallTypeAndReceiver.DEFAULT) {
|
||||
val isCall = refExpr.parent is KtCallExpression
|
||||
val canBeUsage = when (sampleDescriptor) {
|
||||
val canBeUsage = when (sampleDescriptor!!) {
|
||||
is FunctionDescriptor -> isCall // cannot use simply function name without arguments
|
||||
is VariableDescriptor -> true // variable can as well be used with arguments when it has invoke()
|
||||
is ClassDescriptor -> if (isCall) sampleDescriptor.kind == ClassKind.CLASS else sampleDescriptor.kind.isSingleton
|
||||
is ClassDescriptor -> if (isCall) (sampleDescriptor as ClassDescriptor).kind == ClassKind.CLASS else (sampleDescriptor as ClassDescriptor).kind.isSingleton
|
||||
else -> false // what else it can be?
|
||||
}
|
||||
if (!canBeUsage) return@forEachDescendantOfType
|
||||
@@ -60,7 +60,7 @@ class FromUnresolvedNamesCompletion(
|
||||
val name = refExpr.getReferencedName()
|
||||
if (!prefixMatcher.prefixMatches(name)) return@forEachDescendantOfType
|
||||
|
||||
if (afterOffset != null && refExpr.startOffset < afterOffset) return@forEachDescendantOfType
|
||||
if (afterOffset != null && refExpr.startOffset < afterOffset!!) return@forEachDescendantOfType
|
||||
|
||||
if (refExpr.resolveMainReferenceToDescriptors().isEmpty()) {
|
||||
names.add(name)
|
||||
|
||||
@@ -42,8 +42,8 @@ class InsertHandlerProvider(
|
||||
is FunctionDescriptor -> {
|
||||
when (callType) {
|
||||
CallType.DEFAULT, CallType.DOT, CallType.SAFE, CallType.SUPER_MEMBERS -> {
|
||||
val needTypeArguments = needTypeArguments(descriptor)
|
||||
val parameters = descriptor.valueParameters
|
||||
val needTypeArguments = needTypeArguments(descriptor as FunctionDescriptor)
|
||||
val parameters = (descriptor as FunctionDescriptor).valueParameters
|
||||
when (parameters.size) {
|
||||
0 -> KotlinFunctionInsertHandler.Normal(callType, needTypeArguments, inputValueArguments = false)
|
||||
|
||||
@@ -94,11 +94,11 @@ class InsertHandlerProvider(
|
||||
|
||||
fun addPotentiallyInferred(type: KotlinType) {
|
||||
val descriptor = type.constructor.declarationDescriptor as? TypeParameterDescriptor
|
||||
if (descriptor != null && descriptor in typeParameters && descriptor !in potentiallyInferred) {
|
||||
potentiallyInferred.add(descriptor)
|
||||
if (descriptor != null && descriptor in typeParameters && descriptor!! !in potentiallyInferred) {
|
||||
potentiallyInferred.add(descriptor!!)
|
||||
// Add possible inferred by type-arguments of upper-bound of parameter
|
||||
// e.g. <T, C: Iterable<T>>, so T inferred from C
|
||||
descriptor.upperBounds.filter { it.arguments.isNotEmpty() }.forEach(::addPotentiallyInferred)
|
||||
descriptor!!.upperBounds.filter { it.arguments.isNotEmpty() }.forEach(::addPotentiallyInferred)
|
||||
}
|
||||
|
||||
if (type.isFunctionType && getValueParametersCountFromFunctionType(type) <= 1) {
|
||||
@@ -124,7 +124,7 @@ class InsertHandlerProvider(
|
||||
val returnType = originalFunction.returnType
|
||||
// check that there is an expected type and return value from the function can potentially match it
|
||||
if (returnType != null) {
|
||||
addPotentiallyInferred(returnType)
|
||||
addPotentiallyInferred(returnType!!)
|
||||
|
||||
if (allTypeParametersPotentiallyInferred() && expectedInfos.any { it.fuzzyType?.checkIsSuperTypeOf(originalFunction.fuzzyReturnType()!!) != null }) {
|
||||
return false
|
||||
|
||||
@@ -146,7 +146,7 @@ object KDocTagCompletionProvider : CompletionProvider<CompletionParameters>() {
|
||||
val kdocOwner = parameters.position.getNonStrictParentOfType<KDoc>()?.getOwner()
|
||||
val resultWithPrefix = result.withPrefixMatcher(prefix)
|
||||
KDocKnownTag.values().forEach {
|
||||
if (kdocOwner == null || it.isApplicable(kdocOwner)) {
|
||||
if (kdocOwner == null || it.isApplicable(kdocOwner!!)) {
|
||||
resultWithPrefix.addElement(LookupElementBuilder.create("@" + it.name.toLowerCase()))
|
||||
}
|
||||
}
|
||||
@@ -155,7 +155,7 @@ object KDocTagCompletionProvider : CompletionProvider<CompletionParameters>() {
|
||||
private fun KDocKnownTag.isApplicable(declaration: KtDeclaration) = when (this) {
|
||||
KDocKnownTag.CONSTRUCTOR, KDocKnownTag.PROPERTY -> declaration is KtClassOrObject
|
||||
KDocKnownTag.RETURN -> declaration is KtNamedFunction
|
||||
KDocKnownTag.RECEIVER -> declaration is KtNamedFunction && declaration.receiverTypeReference != null
|
||||
KDocKnownTag.RECEIVER -> declaration is KtNamedFunction && (declaration as KtNamedFunction).receiverTypeReference != null
|
||||
else -> true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,11 +109,11 @@ object KeywordCompletion {
|
||||
fun PsiElement.isSpace() = this is PsiWhiteSpace && '\n' !in getText()
|
||||
|
||||
var next = position.nextLeaf { !(it.isSpace() || it.text == "$") }?.text
|
||||
if (next != null && next.startsWith("$")) {
|
||||
next = next.substring(1)
|
||||
if (next != null && next!!.startsWith("$")) {
|
||||
next = next!!.substring(1)
|
||||
}
|
||||
if (next != nextKeyword.value)
|
||||
keyword += " " + nextKeyword.value
|
||||
if (next != nextKeyword!!.value)
|
||||
keyword += " " + nextKeyword!!.value
|
||||
else
|
||||
applicableAsCompound = true
|
||||
}
|
||||
@@ -127,7 +127,7 @@ object KeywordCompletion {
|
||||
|
||||
val constructText = KEYWORD_CONSTRUCTS[keywordToken]
|
||||
if (constructText != null && !applicableAsCompound) {
|
||||
val element = createKeywordConstructLookupElement(position.project, keyword, constructText)
|
||||
val element = createKeywordConstructLookupElement(position.project, keyword, constructText!!)
|
||||
consumer(element)
|
||||
} else {
|
||||
if (listOf(CLASS_KEYWORD, OBJECT_KEYWORD, INTERFACE_KEYWORD).any { keyword.endsWith(it.value) }) {
|
||||
@@ -170,7 +170,7 @@ object KeywordCompletion {
|
||||
if (!Name.isValidIdentifier(name)
|
||||
|| Name.identifier(name).render() != name
|
||||
|| !name[0].isUpperCase()
|
||||
|| file.declarations.any { it is KtClassOrObject && it.name == name }
|
||||
|| file.declarations.any { it is KtClassOrObject && (it as KtClassOrObject).name == name }
|
||||
) return null
|
||||
return name
|
||||
}
|
||||
@@ -198,7 +198,7 @@ object KeywordCompletion {
|
||||
|
||||
private class CommentFilter() : ElementFilter {
|
||||
override fun isAcceptable(element : Any?, context : PsiElement?)
|
||||
= (element is PsiElement) && KtPsiUtil.isInComment(element)
|
||||
= (element is PsiElement) && KtPsiUtil.isInComment(element as PsiElement)
|
||||
|
||||
override fun isClassAcceptable(hintClass: Class<out Any?>)
|
||||
= true
|
||||
@@ -230,19 +230,19 @@ object KeywordCompletion {
|
||||
var parent = position.parent
|
||||
var prevParent = position
|
||||
while (parent != null) {
|
||||
when (parent) {
|
||||
when (parent as PsiElement?) {
|
||||
is KtBlockExpression -> {
|
||||
var prefixText = "fun foo() { "
|
||||
if (prevParent is KtExpression) {
|
||||
// check that we are right after a try-expression without finally-block or after if-expression without else
|
||||
val prevLeaf = prevParent.prevLeaf { it !is PsiWhiteSpace && it !is PsiComment && it !is PsiErrorElement }
|
||||
if (prevLeaf != null) {
|
||||
val isAfterThen = prevLeaf.goUpWhileIsLastChild().any { it.node.elementType == KtNodeTypes.THEN }
|
||||
val isAfterThen = prevLeaf!!.goUpWhileIsLastChild().any { it.node.elementType == KtNodeTypes.THEN }
|
||||
|
||||
var isAfterTry = false
|
||||
var isAfterCatch = false
|
||||
if (prevLeaf.node.elementType == KtTokens.RBRACE) {
|
||||
val blockParent = (prevLeaf.parent as? KtBlockExpression)?.parent
|
||||
if (prevLeaf!!.node.elementType == KtTokens.RBRACE) {
|
||||
val blockParent = (prevLeaf!!.parent as? KtBlockExpression)?.parent
|
||||
when (blockParent) {
|
||||
is KtTryExpression -> isAfterTry = true
|
||||
is KtCatchClause -> { isAfterTry = true; isAfterCatch = true }
|
||||
@@ -272,7 +272,7 @@ object KeywordCompletion {
|
||||
.siblings(forward = false, withItself = false)
|
||||
.firstIsInstanceOrNull<KtExpression>()
|
||||
if (lastExpression != null) {
|
||||
val contextAfterExpression = lastExpression
|
||||
val contextAfterExpression = lastExpression!!
|
||||
.siblings(forward = true, withItself = false)
|
||||
.takeWhile { it != prevParent }
|
||||
.joinToString { it.text }
|
||||
@@ -282,21 +282,21 @@ object KeywordCompletion {
|
||||
}
|
||||
|
||||
is KtDeclarationWithInitializer -> {
|
||||
val initializer = parent.initializer
|
||||
val initializer = (parent as KtDeclarationWithInitializer).initializer
|
||||
if (prevParent == initializer) {
|
||||
return buildFilterWithContext("val v = ", initializer, position)
|
||||
return buildFilterWithContext("val v = ", initializer!!, position)
|
||||
}
|
||||
}
|
||||
|
||||
is KtParameter -> {
|
||||
val default = parent.defaultValue
|
||||
val default = (parent as KtParameter).defaultValue
|
||||
if (prevParent == default) {
|
||||
return buildFilterWithContext("val v = ", default, position)
|
||||
return buildFilterWithContext("val v = ", default!!, position)
|
||||
}
|
||||
}
|
||||
|
||||
is KtDeclaration -> {
|
||||
val scope = parent.parent
|
||||
val scope = (parent as KtDeclaration).parent
|
||||
when (scope) {
|
||||
is KtClassOrObject -> {
|
||||
return if (parent is KtPrimaryConstructor) {
|
||||
@@ -377,7 +377,7 @@ object KeywordCompletion {
|
||||
val container = elementAt.parent.parent
|
||||
val possibleTargets = when (container) {
|
||||
is KtParameter -> {
|
||||
if (container.ownerFunction is KtPrimaryConstructor)
|
||||
if ((container as KtParameter).ownerFunction is KtPrimaryConstructor)
|
||||
listOf(VALUE_PARAMETER, MEMBER_PROPERTY)
|
||||
else
|
||||
listOf(VALUE_PARAMETER)
|
||||
@@ -393,9 +393,9 @@ object KeywordCompletion {
|
||||
|
||||
else -> listOf()
|
||||
}
|
||||
val modifierTargets = ModifierCheckerCore.possibleTargetMap[keywordTokenType]?.intersect(possibleTargets)
|
||||
val modifierTargets = ModifierCheckerCore.possibleTargetMap[keywordTokenType as KtModifierKeywordToken]?.intersect(possibleTargets)
|
||||
if (modifierTargets != null && possibleTargets.isNotEmpty() &&
|
||||
modifierTargets.none {
|
||||
modifierTargets!!.none {
|
||||
isModifierTargetSupportedAtLanguageLevel(keywordTokenType, it, languageVersionSettings)
|
||||
}) return false
|
||||
|
||||
@@ -405,19 +405,19 @@ object KeywordCompletion {
|
||||
|
||||
is KtClass -> {
|
||||
when {
|
||||
ownerDeclaration.isInterface() -> KotlinTarget.INTERFACE
|
||||
ownerDeclaration.isEnum() -> KotlinTarget.ENUM_CLASS
|
||||
ownerDeclaration.isAnnotation() -> KotlinTarget.ANNOTATION_CLASS
|
||||
(ownerDeclaration as KtClass).isInterface() -> KotlinTarget.INTERFACE
|
||||
(ownerDeclaration as KtClass).isEnum() -> KotlinTarget.ENUM_CLASS
|
||||
(ownerDeclaration as KtClass).isAnnotation() -> KotlinTarget.ANNOTATION_CLASS
|
||||
else -> KotlinTarget.CLASS_ONLY
|
||||
}
|
||||
}
|
||||
|
||||
is KtObjectDeclaration -> if (ownerDeclaration.isObjectLiteral()) KotlinTarget.OBJECT_LITERAL else KotlinTarget.OBJECT
|
||||
is KtObjectDeclaration -> if ((ownerDeclaration as KtObjectDeclaration).isObjectLiteral()) KotlinTarget.OBJECT_LITERAL else KotlinTarget.OBJECT
|
||||
|
||||
else -> return keywordTokenType != CONST_KEYWORD
|
||||
}
|
||||
|
||||
if (!ModifierCheckerCore.isPossibleParentTarget(keywordTokenType, parentTarget, languageVersionSettings)) return false
|
||||
if (!ModifierCheckerCore.isPossibleParentTarget(keywordTokenType as KtModifierKeywordToken, parentTarget, languageVersionSettings)) return false
|
||||
|
||||
if (keywordTokenType == CONST_KEYWORD) {
|
||||
return when (parentTarget) {
|
||||
@@ -500,7 +500,7 @@ object KeywordCompletion {
|
||||
if (position == scope) return
|
||||
|
||||
if (position is KtCodeFragment) {
|
||||
val ktContext = position.context as? KtElement ?: return
|
||||
val ktContext = (position as KtCodeFragment).context as? KtElement ?: return
|
||||
buildReducedContextBefore(builder, ktContext, scope)
|
||||
return
|
||||
} else if (position is PsiFile) {
|
||||
@@ -535,7 +535,7 @@ object KeywordCompletion {
|
||||
}
|
||||
else {
|
||||
while (child != null) {
|
||||
when (child) {
|
||||
when (child as PsiElement?) {
|
||||
is KtBlockExpression, is KtClassBody -> append("{}")
|
||||
else -> appendReducedText(child)
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ object KeywordValues {
|
||||
val additionalData = info.additionalData
|
||||
val skipTrueFalse = when (additionalData) {
|
||||
is IfConditionAdditionalData -> true
|
||||
is WhenEntryAdditionalData -> !additionalData.whenWithSubject
|
||||
is WhenEntryAdditionalData -> !(additionalData as WhenEntryAdditionalData).whenWithSubject
|
||||
else -> false
|
||||
}
|
||||
if (skipTrueFalse) {
|
||||
@@ -93,11 +93,13 @@ object KeywordValues {
|
||||
}
|
||||
}
|
||||
|
||||
if (callTypeAndReceiver is CallTypeAndReceiver.CALLABLE_REFERENCE && callTypeAndReceiver.receiver != null) {
|
||||
val qualifierType = bindingContext.get(BindingContext.DOUBLE_COLON_LHS, callTypeAndReceiver.receiver!!)?.type
|
||||
if (callTypeAndReceiver is CallTypeAndReceiver.CALLABLE_REFERENCE && (callTypeAndReceiver as CallTypeAndReceiver.CALLABLE_REFERENCE).receiver != null) {
|
||||
val qualifierType = bindingContext.get(BindingContext.DOUBLE_COLON_LHS, (callTypeAndReceiver as CallTypeAndReceiver.CALLABLE_REFERENCE).receiver!!)?.type
|
||||
if (qualifierType != null) {
|
||||
val kClassDescriptor = resolutionFacade.getFrontendService(ReflectionTypes::class.java).kClass
|
||||
val classLiteralType = KotlinTypeFactory.simpleNotNullType(Annotations.EMPTY, kClassDescriptor, listOf(TypeProjectionImpl(qualifierType)))
|
||||
val classLiteralType = KotlinTypeFactory.simpleNotNullType(Annotations.EMPTY, kClassDescriptor, listOf(TypeProjectionImpl(
|
||||
qualifierType!!
|
||||
)))
|
||||
val kClassTypes = listOf(classLiteralType.toFuzzyType(emptyList()))
|
||||
val kClassMatcher = { info: ExpectedInfo -> kClassTypes.matchExpectedInfo(info) }
|
||||
consumer.consume("class", kClassMatcher, SmartCompletionItemPriority.CLASS_LITERAL) {
|
||||
@@ -109,7 +111,10 @@ object KeywordValues {
|
||||
.singleOrNull() as? ClassDescriptor
|
||||
|
||||
if (javaLangClassDescriptor != null) {
|
||||
val javaLangClassType = KotlinTypeFactory.simpleNotNullType(Annotations.EMPTY, javaLangClassDescriptor, listOf(TypeProjectionImpl(qualifierType)))
|
||||
val javaLangClassType = KotlinTypeFactory.simpleNotNullType(Annotations.EMPTY,
|
||||
javaLangClassDescriptor!!, listOf(TypeProjectionImpl(
|
||||
qualifierType!!
|
||||
)))
|
||||
val javaClassTypes = listOf(javaLangClassType.toFuzzyType(emptyList()))
|
||||
val javaClassMatcher = { info: ExpectedInfo -> javaClassTypes.matchExpectedInfo(info) }
|
||||
consumer.consume("class", javaClassMatcher, SmartCompletionItemPriority.CLASS_LITERAL) {
|
||||
|
||||
@@ -56,7 +56,7 @@ class KotlinCompletionCharFilter() : CharFilter() {
|
||||
}
|
||||
|
||||
if (!lookup.isSelectionTouched) {
|
||||
currentItem?.putUserDataDeep(JUST_TYPING_PREFIX, lookup.itemPattern(currentItem))
|
||||
currentItem?.putUserDataDeep(JUST_TYPING_PREFIX, lookup.itemPattern(currentItem!!))
|
||||
}
|
||||
|
||||
return when (c) {
|
||||
|
||||
@@ -74,14 +74,14 @@ class KotlinCompletionContributor : CompletionContributor() {
|
||||
val offset = context.startOffset
|
||||
val tokenBefore = psiFile.findElementAt(max(0, offset - 1))
|
||||
|
||||
if (offset > 0 && tokenBefore!!.node.elementType == KtTokens.REGULAR_STRING_PART && tokenBefore.text.startsWith(".")) {
|
||||
val prev = tokenBefore.parent.prevSibling
|
||||
if (offset > 0 && tokenBefore!!.node.elementType == KtTokens.REGULAR_STRING_PART && tokenBefore!!.text.startsWith(".")) {
|
||||
val prev = tokenBefore!!.parent.prevSibling
|
||||
if (prev != null && prev is KtSimpleNameStringTemplateEntry) {
|
||||
val expression = prev.expression
|
||||
val expression = (prev as KtSimpleNameStringTemplateEntry).expression
|
||||
if (expression != null) {
|
||||
val prefix = tokenBefore.text.substring(0, offset - tokenBefore.startOffset)
|
||||
context.dummyIdentifier = "{" + expression.text + prefix + CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED + "}"
|
||||
context.offsetMap.addOffset(CompletionInitializationContext.START_OFFSET, expression.startOffset)
|
||||
val prefix = tokenBefore!!.text.substring(0, offset - tokenBefore!!.startOffset)
|
||||
context.dummyIdentifier = "{" + expression!!.text + prefix + CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED + "}"
|
||||
context.offsetMap.addOffset(CompletionInitializationContext.START_OFFSET, expression!!.startOffset)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -108,13 +108,13 @@ class KotlinCompletionContributor : CompletionContributor() {
|
||||
val tokenAt = psiFile.findElementAt(max(0, offset))
|
||||
if (tokenAt != null) {
|
||||
if (context.completionType == CompletionType.SMART && !isAtEndOfLine(offset, context.editor.document) /* do not use parent expression if we are at the end of line - it's probably parsed incorrectly */) {
|
||||
var parent = tokenAt.parent
|
||||
var parent = tokenAt!!.parent
|
||||
if (parent is KtExpression && parent !is KtBlockExpression) {
|
||||
// search expression to be replaced - go up while we are the first child of parent expression
|
||||
var expression: KtExpression = parent
|
||||
var expression: KtExpression = parent as KtExpression
|
||||
parent = expression.parent
|
||||
while (parent is KtExpression && parent.getFirstChild() == expression) {
|
||||
expression = parent
|
||||
expression = parent as KtExpression
|
||||
parent = expression.parent
|
||||
}
|
||||
|
||||
@@ -128,17 +128,17 @@ class KotlinCompletionContributor : CompletionContributor() {
|
||||
val argumentList = (expression.parent as? KtValueArgument)?.parent as? KtValueArgumentList
|
||||
if (argumentList != null) {
|
||||
context.offsetMap.addOffset(SmartCompletion.MULTIPLE_ARGUMENTS_REPLACEMENT_OFFSET,
|
||||
argumentList.rightParenthesis?.textRange?.startOffset ?: argumentList.endOffset)
|
||||
argumentList!!.rightParenthesis?.textRange?.startOffset ?: argumentList!!.endOffset)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// IDENTIFIER when 'f<caret>oo: Foo'
|
||||
// COLON when 'foo<caret>: Foo'
|
||||
if (tokenAt.node.elementType == KtTokens.IDENTIFIER || tokenAt.node.elementType == KtTokens.COLON) {
|
||||
val parameter = tokenAt.parent as? KtParameter
|
||||
if (tokenAt!!.node.elementType == KtTokens.IDENTIFIER || tokenAt!!.node.elementType == KtTokens.COLON) {
|
||||
val parameter = tokenAt!!.parent as? KtParameter
|
||||
if (parameter != null) {
|
||||
context.offsetMap.addOffset(VariableOrParameterNameWithTypeCompletion.REPLACEMENT_OFFSET, parameter.endOffset)
|
||||
context.offsetMap.addOffset(VariableOrParameterNameWithTypeCompletion.REPLACEMENT_OFFSET, parameter!!.endOffset)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -148,16 +148,16 @@ class KotlinCompletionContributor : CompletionContributor() {
|
||||
private fun replacementOffsetByExpression(expression: KtExpression): Int {
|
||||
when (expression) {
|
||||
is KtCallExpression -> {
|
||||
val calleeExpression = expression.calleeExpression
|
||||
val calleeExpression = (expression as KtCallExpression).calleeExpression
|
||||
if (calleeExpression != null) {
|
||||
return calleeExpression.textRange!!.endOffset
|
||||
return calleeExpression!!.textRange!!.endOffset
|
||||
}
|
||||
}
|
||||
|
||||
is KtQualifiedExpression -> {
|
||||
val selector = expression.selectorExpression
|
||||
val selector = (expression as KtQualifiedExpression).selectorExpression
|
||||
if (selector != null) {
|
||||
return replacementOffsetByExpression(selector)
|
||||
return replacementOffsetByExpression(selector!!)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -168,19 +168,19 @@ class KotlinCompletionContributor : CompletionContributor() {
|
||||
val classOrObject = tokenBefore?.parents?.firstIsInstanceOrNull<KtClassOrObject>() ?: return false
|
||||
val name = classOrObject.nameIdentifier ?: return false
|
||||
val body = classOrObject.getBody() ?: return false
|
||||
val offset = tokenBefore.startOffset
|
||||
val offset = tokenBefore!!.startOffset
|
||||
return name.endOffset <= offset && offset <= body.startOffset
|
||||
}
|
||||
|
||||
private fun specialLambdaSignatureDummyIdentifier(tokenBefore: PsiElement?): String? {
|
||||
var leaf = tokenBefore
|
||||
while (leaf is PsiWhiteSpace || leaf is PsiComment) {
|
||||
leaf = leaf.prevLeaf(true)
|
||||
leaf = leaf!!.prevLeaf(true)
|
||||
}
|
||||
|
||||
val lambda = leaf?.parents?.firstOrNull { it is KtFunctionLiteral } ?: return null
|
||||
|
||||
val lambdaChild = leaf.parents.takeWhile { it != lambda }.lastOrNull()
|
||||
val lambdaChild = leaf!!.parents.takeWhile { it != lambda }.lastOrNull()
|
||||
|
||||
return if (lambdaChild is KtParameterList)
|
||||
CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED
|
||||
@@ -217,7 +217,7 @@ class KotlinCompletionContributor : CompletionContributor() {
|
||||
builder.append(tail)
|
||||
|
||||
val text = builder.toString()
|
||||
val file = KtPsiFactory(tokenBefore.project).createFile(text)
|
||||
val file = KtPsiFactory(tokenBefore!!.project).createFile(text)
|
||||
val declaration = file.declarations.singleOrNull() ?: return null
|
||||
if (declaration.textLength != text.length) return null
|
||||
val containsErrorElement = !PsiTreeUtil.processElements(file, PsiElementProcessor<PsiElement>{ it !is PsiErrorElement })
|
||||
@@ -235,14 +235,14 @@ class KotlinCompletionContributor : CompletionContributor() {
|
||||
val position = parameters.position
|
||||
val parametersOriginFile = parameters.originalFile
|
||||
if (position.containingFile !is KtFile || parametersOriginFile !is KtFile) return
|
||||
if (parametersOriginFile.doNotComplete == true) return
|
||||
if ((parametersOriginFile as KtFile).doNotComplete == true) return
|
||||
|
||||
val toFromOriginalFileMapper = ToFromOriginalFileMapper.create(parameters)
|
||||
|
||||
if (position.node.elementType == KtTokens.LONG_TEMPLATE_ENTRY_START) {
|
||||
val expression = (position.parent as KtBlockStringTemplateEntry).expression
|
||||
if (expression is KtDotQualifiedExpression) {
|
||||
val correctedPosition = (expression.selectorExpression as KtNameReferenceExpression).firstChild
|
||||
val correctedPosition = ((expression as KtDotQualifiedExpression).selectorExpression as KtNameReferenceExpression).firstChild
|
||||
// Workaround for KT-16848
|
||||
// ex:
|
||||
// expression: some.IntellijIdeaRulezzz
|
||||
@@ -288,7 +288,7 @@ class KotlinCompletionContributor : CompletionContributor() {
|
||||
|
||||
fun addPostProcessor(session: CompletionSession) {
|
||||
if (lookupElementPostProcessor != null) {
|
||||
session.addLookupElementPostProcessor(lookupElementPostProcessor)
|
||||
session.addLookupElementPostProcessor(lookupElementPostProcessor!!)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -389,18 +389,18 @@ class KotlinCompletionContributor : CompletionContributor() {
|
||||
private fun specialInTypeArgsDummyIdentifier(tokenBefore: PsiElement?): String? {
|
||||
if (tokenBefore == null) return null
|
||||
|
||||
if (tokenBefore.getParentOfType<KtTypeArgumentList>(true) != null) { // already parsed inside type argument list
|
||||
if (tokenBefore!!.getParentOfType<KtTypeArgumentList>(true) != null) { // already parsed inside type argument list
|
||||
return CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED // do not insert '$' to not break type argument list parsing
|
||||
}
|
||||
|
||||
val pair = unclosedTypeArgListNameAndBalance(tokenBefore) ?: return null
|
||||
val pair = unclosedTypeArgListNameAndBalance(tokenBefore!!) ?: return null
|
||||
val (nameToken, balance) = pair
|
||||
assert(balance > 0)
|
||||
|
||||
val nameRef = nameToken.parent as? KtNameReferenceExpression ?: return null
|
||||
val bindingContext = nameRef.getResolutionFacade().analyze(nameRef, BodyResolveMode.PARTIAL)
|
||||
val targets = nameRef.getReferenceTargets(bindingContext)
|
||||
return if (targets.isNotEmpty() && targets.all { it is FunctionDescriptor || it is ClassDescriptor && it.kind == ClassKind.CLASS }) {
|
||||
return if (targets.isNotEmpty() && targets.all { it is FunctionDescriptor || it is ClassDescriptor && (it as ClassDescriptor).kind == ClassKind.CLASS }) {
|
||||
CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED + ">".repeat(balance) + "$"
|
||||
}
|
||||
else {
|
||||
@@ -415,7 +415,7 @@ class KotlinCompletionContributor : CompletionContributor() {
|
||||
Pair(nameToken, 1)
|
||||
}
|
||||
else {
|
||||
Pair(pair.first, pair.second + 1)
|
||||
Pair(pair!!.first, pair!!.second + 1)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -162,8 +162,8 @@ object LambdaSignatureTemplates {
|
||||
val parameterName = parameterType.extractParameterNameFromFunctionTypeArgument()?.render()
|
||||
val nameExpression = if (parameterName != null) {
|
||||
object : Expression() {
|
||||
override fun calculateResult(context: ExpressionContext?) = TextResult(parameterName)
|
||||
override fun calculateQuickResult(context: ExpressionContext?): Result? = TextResult(parameterName)
|
||||
override fun calculateResult(context: ExpressionContext?) = TextResult(parameterName!!)
|
||||
override fun calculateQuickResult(context: ExpressionContext?): Result? = TextResult(parameterName!!)
|
||||
override fun calculateLookupItems(context: ExpressionContext?) = emptyArray<LookupElement>()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ import com.intellij.psi.tree.IElementType
|
||||
class LeafElementFilter(private val elementType: IElementType) : ElementFilter {
|
||||
|
||||
override fun isAcceptable(element: Any?, context: PsiElement?)
|
||||
= element is LeafPsiElement && element.elementType == elementType
|
||||
= element is LeafPsiElement && (element as LeafPsiElement).elementType == elementType
|
||||
|
||||
override fun isClassAcceptable(hintClass: Class<*>)
|
||||
= LEAF_CLASS_FILTER.isClassAcceptable(hintClass)
|
||||
|
||||
@@ -85,8 +85,8 @@ class LookupCancelWatcher(val project: Project) : ProjectComponent {
|
||||
val offset = lookup.currentItem?.getUserData(AUTO_POPUP_AT)
|
||||
if (offset != null) {
|
||||
lastReminiscence?.dispose()
|
||||
if (offset <= lookup.editor.document.textLength) {
|
||||
lastReminiscence = Reminiscence(lookup.editor, offset)
|
||||
if (offset!! <= lookup.editor.document.textLength) {
|
||||
lastReminiscence = Reminiscence(lookup.editor, offset!!)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,15 +102,15 @@ class LookupElementFactory(
|
||||
// add special item for function with one argument of function type with more than one parameter
|
||||
if (descriptor is FunctionDescriptor && isNormalCall) {
|
||||
if (callType != CallType.SUPER_MEMBERS) {
|
||||
result.addSpecialFunctionCallElements(descriptor, useReceiverTypes)
|
||||
result.addSpecialFunctionCallElements(descriptor as FunctionDescriptor, useReceiverTypes)
|
||||
}
|
||||
else if (useReceiverTypes) {
|
||||
result.addIfNotNull(createSuperFunctionCallWithArguments(descriptor))
|
||||
result.addIfNotNull(createSuperFunctionCallWithArguments(descriptor as FunctionDescriptor))
|
||||
}
|
||||
}
|
||||
|
||||
// special "[]" item for get-operator
|
||||
if (callType == CallType.DOT && descriptor is FunctionDescriptor && descriptor.isOperator && descriptor.name == OperatorNameConventions.GET) {
|
||||
if (callType == CallType.DOT && descriptor is FunctionDescriptor && (descriptor as FunctionDescriptor).isOperator && (descriptor as FunctionDescriptor).name == OperatorNameConventions.GET) {
|
||||
val baseLookupElement = createLookupElement(descriptor, useReceiverTypes)
|
||||
val lookupElement = object : LookupElementDecorator<LookupElement>(baseLookupElement) {
|
||||
override fun getLookupString() = "[]"
|
||||
@@ -237,7 +237,7 @@ class LookupElementFactory(
|
||||
private val needTypeArguments: Boolean
|
||||
) : LookupElementDecorator<LookupElement>(originalLookupElement) {
|
||||
|
||||
override fun equals(other: Any?) = other is FunctionCallWithArgumentsLookupElement && delegate == other.delegate && argumentText == other.argumentText
|
||||
override fun equals(other: Any?) = other is FunctionCallWithArgumentsLookupElement && delegate == (other as FunctionCallWithArgumentsLookupElement).delegate && argumentText == (other as FunctionCallWithArgumentsLookupElement).argumentText
|
||||
override fun hashCode() = delegate.hashCode() * 17 + argumentText.hashCode()
|
||||
|
||||
override fun renderElement(presentation: LookupElementPresentation) {
|
||||
@@ -316,26 +316,26 @@ class LookupElementFactory(
|
||||
|
||||
// don't treat synthetic extensions as real extensions
|
||||
if (descriptor is SyntheticJavaPropertyDescriptor) {
|
||||
return callableWeight(descriptor.getMethod)
|
||||
return callableWeight((descriptor as SyntheticJavaPropertyDescriptor).getMethod)
|
||||
}
|
||||
if (descriptor is SamAdapterExtensionFunctionDescriptor) {
|
||||
return callableWeight(descriptor.baseDescriptorForSynthetic)
|
||||
return callableWeight((descriptor as SamAdapterExtensionFunctionDescriptor).baseDescriptorForSynthetic)
|
||||
}
|
||||
|
||||
if (descriptor.overriddenDescriptors.isNotEmpty()) {
|
||||
if ((descriptor as CallableDescriptor).overriddenDescriptors.isNotEmpty()) {
|
||||
// Optimization: when one of direct overridden fits, then nothing can fit better
|
||||
descriptor.overriddenDescriptors
|
||||
.mapNotNull { it.callableWeightBasedOnReceiver(receiverTypes, onReceiverTypeMismatch = null) }
|
||||
(descriptor as CallableDescriptor).overriddenDescriptors
|
||||
.mapNotNull { it.callableWeightBasedOnReceiver(receiverTypes!!, onReceiverTypeMismatch = null) }
|
||||
.minBy { it.enum }
|
||||
?.let { return it }
|
||||
|
||||
val overridden = descriptor.overriddenTreeUniqueAsSequence(useOriginal = false)
|
||||
val overridden = (descriptor as CallableDescriptor).overriddenTreeUniqueAsSequence(useOriginal = false)
|
||||
return overridden
|
||||
.map { callableWeightBasic(it, receiverTypes)!! }
|
||||
.map { callableWeightBasic(it, receiverTypes!!)!! }
|
||||
.minBy { it.enum }!!
|
||||
}
|
||||
|
||||
return callableWeightBasic(descriptor, receiverTypes)
|
||||
return callableWeightBasic(descriptor as CallableDescriptor, receiverTypes!!)
|
||||
}
|
||||
|
||||
private fun callableWeightBasic(descriptor: CallableDescriptor, receiverTypes: Collection<ReceiverType>): CallableWeight? {
|
||||
@@ -378,7 +378,7 @@ class LookupElementFactory(
|
||||
for (receiverType in receiverTypes) {
|
||||
val weight = callableWeightForReceiverType(receiverType.type, receiverParameter.type)
|
||||
if (weight != null) {
|
||||
if (bestWeight == null || weight < bestWeight) {
|
||||
if (bestWeight == null || weight!! < bestWeight!!) {
|
||||
bestWeight = weight
|
||||
bestReceiverType = receiverType
|
||||
}
|
||||
@@ -399,7 +399,7 @@ class LookupElementFactory(
|
||||
}
|
||||
}
|
||||
|
||||
return CallableWeight(bestWeight, receiverIndexToUse)
|
||||
return CallableWeight(bestWeight!!, receiverIndexToUse)
|
||||
}
|
||||
|
||||
private fun CallableDescriptor.callableWeightForReceiverType(
|
||||
|
||||
@@ -90,7 +90,7 @@ class LookupElementsCollector(
|
||||
withReceiverCast: Boolean = false,
|
||||
prohibitDuplicates: Boolean = false
|
||||
) {
|
||||
if (prohibitDuplicates && descriptor is CallableDescriptor && descriptor in processedCallables) return
|
||||
if (prohibitDuplicates && descriptor is CallableDescriptor && descriptor as CallableDescriptor in processedCallables) return
|
||||
|
||||
var lookupElements = lookupElementFactory.createStandardLookupElementsForDescriptor(descriptor, useReceiverTypes = true)
|
||||
|
||||
@@ -100,7 +100,7 @@ class LookupElementsCollector(
|
||||
|
||||
addElements(lookupElements, notImported)
|
||||
|
||||
if (prohibitDuplicates && descriptor is CallableDescriptor) processedCallables.add(descriptor)
|
||||
if (prohibitDuplicates && descriptor is CallableDescriptor) processedCallables.add(descriptor as CallableDescriptor)
|
||||
}
|
||||
|
||||
fun addElement(element: LookupElement, notImported: Boolean = false) {
|
||||
@@ -149,7 +149,7 @@ class LookupElementsCollector(
|
||||
val declarationLookupObject = result.`object` as? DeclarationLookupObject
|
||||
if (declarationLookupObject != null) {
|
||||
result = object : LookupElementDecorator<LookupElement>(result) {
|
||||
override fun getPsiElement() = declarationLookupObject.psiElement
|
||||
override fun getPsiElement() = declarationLookupObject!!.psiElement
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@ class OverridesCompletion(
|
||||
|
||||
for (memberObject in members) {
|
||||
val descriptor = memberObject.descriptor
|
||||
if (declaration != null && !canOverride(descriptor, declaration)) continue
|
||||
if (declaration != null && !canOverride(descriptor, declaration!!)) continue
|
||||
if (isConstructorParameter && descriptor !is PropertyDescriptor) continue
|
||||
|
||||
var lookupElement = lookupElementFactory.createLookupElement(descriptor)
|
||||
@@ -169,8 +169,8 @@ class OverridesCompletion(
|
||||
|
||||
is KtValVarKeywordOwner -> {
|
||||
if (descriptorToOverride !is PropertyDescriptor) return false
|
||||
return if (declaration.valOrVarKeyword?.node?.elementType == KtTokens.VAL_KEYWORD) {
|
||||
!descriptorToOverride.isVar
|
||||
return if ((declaration as KtValVarKeywordOwner).valOrVarKeyword?.node?.elementType == KtTokens.VAL_KEYWORD) {
|
||||
!(descriptorToOverride as PropertyDescriptor).isVar
|
||||
} else {
|
||||
true // var can override either var or val
|
||||
}
|
||||
|
||||
@@ -122,7 +122,7 @@ class ReferenceVariantsCollector(
|
||||
|
||||
val getOrSetPrefix = GET_SET_PREFIXES.firstOrNull { prefix.startsWith(it) }
|
||||
val additionalPropertyNameFilter: ((String) -> Boolean)? = getOrSetPrefix
|
||||
?.let { prefixMatcher.cloneWithPrefix(prefix.removePrefix(getOrSetPrefix).decapitalizeSmartForCompiler()).asStringNameFilter() }
|
||||
?.let { prefixMatcher.cloneWithPrefix(prefix.removePrefix(getOrSetPrefix!!).decapitalizeSmartForCompiler()).asStringNameFilter() }
|
||||
|
||||
val shadowedDeclarationsFilter = if (runtimeReceiver != null)
|
||||
ShadowedDeclarationsFilter(bindingContext, resolutionFacade, nameExpression, runtimeReceiver)
|
||||
@@ -151,15 +151,15 @@ class ReferenceVariantsCollector(
|
||||
|
||||
var basicVariants = getReferenceVariants(descriptorKindFilter, basicNameFilter)
|
||||
if (additionalPropertyNameFilter != null) {
|
||||
basicVariants += getReferenceVariants(descriptorKindFilter.intersect(DescriptorKindFilter.VARIABLES), additionalPropertyNameFilter.toNameFilter())
|
||||
basicVariants += getReferenceVariants(descriptorKindFilter.intersect(DescriptorKindFilter.VARIABLES), additionalPropertyNameFilter!!.toNameFilter())
|
||||
runDistinct = true
|
||||
}
|
||||
|
||||
val containingCodeFragment = nameExpression.containingKtFile as? KtCodeFragment
|
||||
if (containingCodeFragment != null) {
|
||||
val externalDescriptors = containingCodeFragment.externalDescriptors
|
||||
val externalDescriptors = containingCodeFragment!!.externalDescriptors
|
||||
if (externalDescriptors != null) {
|
||||
basicVariants += externalDescriptors
|
||||
basicVariants += externalDescriptors!!
|
||||
.filter { descriptorKindFilter.accepts(it) && basicNameFilter(it.name) }
|
||||
}
|
||||
}
|
||||
@@ -176,11 +176,11 @@ class ReferenceVariantsCollector(
|
||||
|
||||
if (completeExtensionsFromIndices) {
|
||||
val nameFilter = if (additionalPropertyNameFilter != null)
|
||||
descriptorNameFilter or additionalPropertyNameFilter
|
||||
descriptorNameFilter or additionalPropertyNameFilter!!
|
||||
else
|
||||
descriptorNameFilter
|
||||
val extensions = if (runtimeReceiver != null)
|
||||
indicesHelper.getCallableTopLevelExtensions(callTypeAndReceiver, listOf(runtimeReceiver.type), nameFilter)
|
||||
indicesHelper.getCallableTopLevelExtensions(callTypeAndReceiver, listOf(runtimeReceiver!!.type), nameFilter)
|
||||
else
|
||||
indicesHelper.getCallableTopLevelExtensions(callTypeAndReceiver, nameExpression, bindingContext, nameFilter)
|
||||
|
||||
@@ -206,7 +206,7 @@ class ReferenceVariantsCollector(
|
||||
var variants = _variants
|
||||
|
||||
if (shadowedDeclarationsFilter != null)
|
||||
variants = shadowedDeclarationsFilter.filter(variants)
|
||||
variants = shadowedDeclarationsFilter!!.filter(variants)
|
||||
|
||||
if (!configuration.javaGettersAndSetters)
|
||||
variants = referenceVariantsHelper.filterOutJavaGettersAndSetters(variants)
|
||||
@@ -223,10 +223,10 @@ class ReferenceVariantsCollector(
|
||||
private object TopLevelExtensionsExclude : DescriptorKindExclude() {
|
||||
override fun excludes(descriptor: DeclarationDescriptor): Boolean {
|
||||
if (descriptor !is CallableMemberDescriptor) return false
|
||||
if (descriptor.extensionReceiverParameter == null) return false
|
||||
if (descriptor.kind != CallableMemberDescriptor.Kind.DECLARATION) return false /* do not filter out synthetic extensions */
|
||||
if ((descriptor as CallableMemberDescriptor).extensionReceiverParameter == null) return false
|
||||
if ((descriptor as CallableMemberDescriptor).kind != CallableMemberDescriptor.Kind.DECLARATION) return false /* do not filter out synthetic extensions */
|
||||
if (descriptor.isArtificialImportAliasedDescriptor) return false // do not exclude aliased descriptors - they cannot be completed via indices
|
||||
val containingPackage = descriptor.containingDeclaration as? PackageFragmentDescriptor ?: return false
|
||||
val containingPackage = (descriptor as CallableMemberDescriptor).containingDeclaration as? PackageFragmentDescriptor ?: return false
|
||||
if (containingPackage.fqName.asString().startsWith("kotlinx.android.synthetic.")) return false // TODO: temporary solution for Android synthetic extensions
|
||||
return true
|
||||
}
|
||||
@@ -236,8 +236,8 @@ class ReferenceVariantsCollector(
|
||||
|
||||
private fun isDataClassComponentFunction(descriptor: DeclarationDescriptor): Boolean {
|
||||
return descriptor is FunctionDescriptor &&
|
||||
descriptor.isOperator &&
|
||||
DataClassDescriptorResolver.isComponentLike(descriptor.name) &&
|
||||
descriptor.kind == CallableMemberDescriptor.Kind.SYNTHESIZED
|
||||
(descriptor as FunctionDescriptor).isOperator &&
|
||||
DataClassDescriptorResolver.isComponentLike((descriptor as FunctionDescriptor).name) &&
|
||||
(descriptor as FunctionDescriptor).kind == CallableMemberDescriptor.Kind.SYNTHESIZED
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ class StaticMembersCompletion(
|
||||
private val isJvmModule: Boolean
|
||||
) {
|
||||
private val alreadyAdded = alreadyAdded.mapTo(HashSet()) {
|
||||
if (it is ImportedFromObjectCallableDescriptor<*>) it.callableFromObject else it
|
||||
if (it is ImportedFromObjectCallableDescriptor<*>) (it as ImportedFromObjectCallableDescriptor<*>).callableFromObject else it
|
||||
}
|
||||
|
||||
fun decoratedLookupElementFactory(itemPriority: ItemPriority): AbstractLookupElementFactory {
|
||||
|
||||
@@ -53,7 +53,7 @@ class KotlinCompletionStatistician : CompletionStatistician() {
|
||||
class KotlinProximityStatistician : ProximityStatistician() {
|
||||
override fun serialize(element: PsiElement, location: ProximityLocation): StatisticsInfo? {
|
||||
if (element !is KtDeclaration) return null
|
||||
val descriptor = element.resolveToDescriptorIfAny() ?: return null
|
||||
val descriptor = (element as KtDeclaration).resolveToDescriptorIfAny() ?: return null
|
||||
return KotlinStatisticsInfo.forDescriptor(descriptor)
|
||||
}
|
||||
}
|
||||
@@ -76,8 +76,8 @@ object KotlinStatisticsInfo {
|
||||
|
||||
val container = descriptor.containingDeclaration
|
||||
val containerFqName = when (container) {
|
||||
is ClassDescriptor -> container.importableFqName?.asString()
|
||||
is PackageFragmentDescriptor -> container.fqName.asString()
|
||||
is ClassDescriptor -> (container as ClassDescriptor).importableFqName?.asString()
|
||||
is PackageFragmentDescriptor -> (container as PackageFragmentDescriptor).fqName.asString()
|
||||
is ModuleDescriptor -> ""
|
||||
else -> null
|
||||
} ?: return StatisticsInfo.EMPTY
|
||||
|
||||
@@ -119,10 +119,10 @@ class VariableOrParameterNameWithTypeCompletion(
|
||||
if (name != null && prefixMatcher.isStartMatch(name)) {
|
||||
val descriptor = resolutionFacade.analyze(parameter)[BindingContext.VALUE_PARAMETER, parameter]
|
||||
if (descriptor != null) {
|
||||
val parameterType = descriptor.type
|
||||
val parameterType = descriptor!!.type
|
||||
if (parameterType.isVisible(visibilityFilter)) {
|
||||
val lookupElement = MyLookupElement.create(name, ArbitraryType(parameterType), withType, lookupElementFactory)!!
|
||||
val (count, name) = lookupElementToCount[lookupElement] ?: Pair(0, name)
|
||||
val lookupElement = MyLookupElement.create(name!!, ArbitraryType(parameterType), withType, lookupElementFactory)!!
|
||||
val (count, name) = lookupElementToCount[lookupElement] ?: Pair(0, name!!)
|
||||
lookupElementToCount[lookupElement] = Pair(count + 1, name)
|
||||
}
|
||||
}
|
||||
@@ -155,8 +155,8 @@ class VariableOrParameterNameWithTypeCompletion(
|
||||
if (prefixMatcher.isStartMatch(parameterName)) {
|
||||
val lookupElement = MyLookupElement.create(parameterName, type, withType, lookupElementFactory)
|
||||
if (lookupElement != null) {
|
||||
lookupElement.putUserData(PRIORITY_KEY, userPrefix.length) // suggestions with longer user prefix get lower priority
|
||||
if (withType || !lookupNamesAdded.contains(parameterName)) collector.addElement(lookupElement, notImported)
|
||||
lookupElement!!.putUserData(PRIORITY_KEY, userPrefix.length) // suggestions with longer user prefix get lower priority
|
||||
if (withType || !lookupNamesAdded.contains(parameterName)) collector.addElement(lookupElement!!, notImported)
|
||||
suggestionsByTypesAdded.add(type)
|
||||
lookupNamesAdded.add(parameterName)
|
||||
}
|
||||
@@ -173,7 +173,7 @@ class VariableOrParameterNameWithTypeCompletion(
|
||||
private abstract class Type(private val idString: String) {
|
||||
abstract fun createTypeLookupElement(lookupElementFactory: BasicLookupElementFactory): LookupElement?
|
||||
|
||||
override fun equals(other: Any?) = other is Type && other.idString == idString
|
||||
override fun equals(other: Any?) = other is Type && (other as Type).idString == idString
|
||||
override fun hashCode() = idString.hashCode()
|
||||
}
|
||||
|
||||
@@ -233,7 +233,7 @@ class VariableOrParameterNameWithTypeCompletion(
|
||||
val replacementOffset = context.offsetMap.tryGetOffset(REPLACEMENT_OFFSET)
|
||||
if (replacementOffset != null) {
|
||||
val tailOffset = context.tailOffset
|
||||
context.document.deleteString(tailOffset, replacementOffset)
|
||||
context.document.deleteString(tailOffset, replacementOffset!!)
|
||||
|
||||
val chars = context.document.charsSequence
|
||||
var offset = chars.skipSpaces(tailOffset)
|
||||
@@ -267,7 +267,7 @@ class VariableOrParameterNameWithTypeCompletion(
|
||||
}
|
||||
|
||||
override fun equals(other: Any?) =
|
||||
other is MyLookupElement && parameterName == other.parameterName && type == other.type && shouldInsertType == other.shouldInsertType
|
||||
other is MyLookupElement && parameterName == (other as MyLookupElement).parameterName && type == (other as MyLookupElement).type && shouldInsertType == (other as MyLookupElement).shouldInsertType
|
||||
|
||||
override fun hashCode() = parameterName.hashCode()
|
||||
}
|
||||
|
||||
@@ -129,10 +129,10 @@ object KindWeigher : LookupElementWeigher("kotlin.kind") {
|
||||
is PackageLookupObject -> Weight.packages
|
||||
|
||||
is DeclarationLookupObject -> {
|
||||
val descriptor = o.descriptor
|
||||
val descriptor = (o as DeclarationLookupObject).descriptor
|
||||
when (descriptor) {
|
||||
is VariableDescriptor, is FunctionDescriptor -> Weight.callable
|
||||
is ClassDescriptor -> if (descriptor.kind == ClassKind.ENUM_ENTRY) Weight.enumMember else Weight.default
|
||||
is ClassDescriptor -> if ((descriptor as ClassDescriptor).kind == ClassKind.ENUM_ENTRY) Weight.enumMember else Weight.default
|
||||
else -> Weight.default
|
||||
}
|
||||
}
|
||||
@@ -257,7 +257,7 @@ object PreferMatchingItemWeigher : LookupElementWeigher("kotlin.preferMatching",
|
||||
when {
|
||||
smartCompletionPriority != null && smartCompletionPriority != SmartCompletionItemPriority.DEFAULT -> Weight.specialExactMatch
|
||||
element.getUserData(NOT_IMPORTED_KEY) != null -> Weight.notImportedExactMatch
|
||||
o.descriptor is FunctionDescriptor -> Weight.functionExactMatch
|
||||
(o as DeclarationLookupObject).descriptor is FunctionDescriptor -> Weight.functionExactMatch
|
||||
else -> Weight.defaultExactMatch
|
||||
}
|
||||
}
|
||||
@@ -301,7 +301,7 @@ class SmartCompletionInBasicWeigher(
|
||||
|
||||
val priority = element.getUserData(SMART_COMPLETION_ITEM_PRIORITY_KEY)
|
||||
if (priority != null) { // it's an "additional item" came from smart completion, don't match it against expected type
|
||||
return itemWeight(priority, element.getUserData(NAME_SIMILARITY_KEY) ?: 0)
|
||||
return itemWeight(priority!!, element.getUserData(NAME_SIMILARITY_KEY) ?: 0)
|
||||
}
|
||||
|
||||
val o = element.`object`
|
||||
@@ -314,11 +314,11 @@ class SmartCompletionInBasicWeigher(
|
||||
|
||||
val (fuzzyTypes, name) = when (o) {
|
||||
is DeclarationLookupObject -> {
|
||||
val descriptor = o.descriptor ?: return NO_MATCH_WEIGHT
|
||||
val descriptor = (o as DeclarationLookupObject).descriptor ?: return NO_MATCH_WEIGHT
|
||||
descriptor.fuzzyTypesForSmartCompletion(smartCastCalculator, callTypeAndReceiver, resolutionFacade, bindingContext) to descriptor.name
|
||||
}
|
||||
|
||||
is ThisItemLookupObject -> smartCastCalculator.types(o.receiverParameter).map { it.toFuzzyType(emptyList()) } to null
|
||||
is ThisItemLookupObject -> smartCastCalculator.types((o as ThisItemLookupObject).receiverParameter).map { it.toFuzzyType(emptyList()) } to null
|
||||
|
||||
else -> return NO_MATCH_WEIGHT
|
||||
}
|
||||
@@ -330,7 +330,7 @@ class SmartCompletionInBasicWeigher(
|
||||
|
||||
val nameSimilarity = if (name != null) {
|
||||
val matchingInfos = matched.filter { it.second != ExpectedInfoMatch.noMatch }.map { it.first }
|
||||
calcNameSimilarity(name.asString(), matchingInfos)
|
||||
calcNameSimilarity(name!!.asString(), matchingInfos)
|
||||
}
|
||||
else {
|
||||
0
|
||||
@@ -347,7 +347,7 @@ class PreferContextElementsWeigher(context: DeclarationDescriptor) : LookupEleme
|
||||
private val contextElements = context.parentsWithSelf
|
||||
.takeWhile { it !is PackageFragmentDescriptor }
|
||||
.toList()
|
||||
.flatMap { if (it is CallableDescriptor) it.findOriginalTopMostOverriddenDescriptors() else listOf(it) }
|
||||
.flatMap { if (it is CallableDescriptor) (it as CallableDescriptor).findOriginalTopMostOverriddenDescriptors() else listOf(it) }
|
||||
.toSet()
|
||||
private val contextElementNames = contextElements.map { it.name }.toSet()
|
||||
|
||||
|
||||
@@ -25,12 +25,12 @@ import org.jetbrains.kotlin.renderer.render
|
||||
open class BaseDeclarationInsertHandler : InsertHandler<LookupElement> {
|
||||
override fun handleInsert(context: InsertionContext, item: LookupElement) {
|
||||
val name = (item.`object` as? DeclarationLookupObject)?.name
|
||||
if (name != null && !name.isSpecial) {
|
||||
if (name != null && !name!!.isSpecial) {
|
||||
val startOffset = context.startOffset
|
||||
if (startOffset > 0 && context.document.isTextAt(startOffset - 1, "`")) {
|
||||
context.document.deleteString(startOffset - 1, startOffset)
|
||||
}
|
||||
context.document.replaceString(startOffset, context.tailOffset, name.render())
|
||||
context.document.replaceString(startOffset, context.tailOffset, name!!.render())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ object CastReceiverInsertHandler {
|
||||
PsiTreeUtil.findElementOfClassAtOffset(context.file, context.startOffset, KtSimpleNameExpression::class.java, false)
|
||||
val qualifiedExpression = PsiTreeUtil.getParentOfType(expression, KtQualifiedExpression::class.java, true)
|
||||
if (qualifiedExpression != null) {
|
||||
val receiver = qualifiedExpression.receiverExpression
|
||||
val receiver = qualifiedExpression!!.receiverExpression
|
||||
|
||||
val descriptor = (item.`object` as? DeclarationLookupObject)?.descriptor as CallableDescriptor
|
||||
val project = context.project
|
||||
|
||||
@@ -48,10 +48,10 @@ abstract class KotlinCallableInsertHandler(val callType: CallType<*>) : BaseDecl
|
||||
val file = context.file
|
||||
val o = item.`object`
|
||||
if (file is KtFile && o is DeclarationLookupObject) {
|
||||
val descriptor = o.descriptor as? CallableDescriptor ?: return
|
||||
val descriptor = (o as DeclarationLookupObject).descriptor as? CallableDescriptor ?: return
|
||||
if (descriptor.extensionReceiverParameter != null || callType == CallType.CALLABLE_REFERENCE) {
|
||||
if (DescriptorUtils.isTopLevelDeclaration(descriptor) && !descriptor.isArtificialImportAliasedDescriptor) {
|
||||
ImportInsertHelper.getInstance(context.project).importDescriptor(file, descriptor)
|
||||
ImportInsertHelper.getInstance(context.project).importDescriptor(file as KtFile, descriptor)
|
||||
}
|
||||
} else if (callType == CallType.DEFAULT) {
|
||||
if (descriptor.isArtificialImportAliasedDescriptor) return
|
||||
@@ -64,7 +64,7 @@ abstract class KotlinCallableInsertHandler(val callType: CallType<*>) : BaseDecl
|
||||
|
||||
psiDocumentManager.commitAllDocuments()
|
||||
|
||||
shortenReferences.process(file, context.startOffset, context.tailOffset - 1)
|
||||
shortenReferences.process(file as KtFile, context.startOffset, context.tailOffset - 1)
|
||||
|
||||
psiDocumentManager.doPostponedOperationsAndUnblockDocument(context.document)
|
||||
|
||||
|
||||
@@ -60,14 +60,14 @@ object KotlinClassifierInsertHandler : BaseDeclarationInsertHandler() {
|
||||
val token = file.findElementAt(startOffset)!!
|
||||
val nameRef = token.parent as? KtNameReferenceExpression
|
||||
if (nameRef != null) {
|
||||
val bindingContext = nameRef.analyze(BodyResolveMode.PARTIAL)
|
||||
val bindingContext = nameRef!!.analyze(BodyResolveMode.PARTIAL)
|
||||
val target = bindingContext[BindingContext.SHORT_REFERENCE_TO_COMPANION_OBJECT, nameRef]
|
||||
?: bindingContext[BindingContext.REFERENCE_TARGET, nameRef] as? ClassDescriptor
|
||||
if (target != null && IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(target) == qualifiedName) return
|
||||
if (target != null && IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(target!!) == qualifiedName) return
|
||||
}
|
||||
|
||||
val tempPrefix = if (nameRef != null) {
|
||||
val isAnnotation = CallTypeAndReceiver.detect(nameRef) is CallTypeAndReceiver.ANNOTATION
|
||||
val isAnnotation = CallTypeAndReceiver.detect(nameRef!!) is CallTypeAndReceiver.ANNOTATION
|
||||
// we insert space so that any preceding spaces inserted by formatter on reference shortening are deleted
|
||||
// (but not for annotations where spaces are not allowed after @)
|
||||
if (isAnnotation) "" else " "
|
||||
@@ -84,7 +84,7 @@ object KotlinClassifierInsertHandler : BaseDeclarationInsertHandler() {
|
||||
val rangeMarker = document.createRangeMarker(classNameStart, classNameEnd)
|
||||
val wholeRangeMarker = document.createRangeMarker(startOffset, classNameEnd + tempSuffix.length)
|
||||
|
||||
ShortenReferences.DEFAULT.process(file, classNameStart, classNameEnd)
|
||||
ShortenReferences.DEFAULT.process(file as KtFile, classNameStart, classNameEnd)
|
||||
psiDocumentManager.doPostponedOperationsAndUnblockDocument(document)
|
||||
|
||||
if (rangeMarker.isValid && wholeRangeMarker.isValid) {
|
||||
|
||||
@@ -161,34 +161,34 @@ sealed class KotlinFunctionInsertHandler(callType: CallType<*>) : KotlinCallable
|
||||
PsiDocumentManager.getInstance(project).commitDocument(document)
|
||||
|
||||
openingBracketOffset = chars.indexOfSkippingSpace(openingBracket, offset)!!
|
||||
closeBracketOffset = chars.indexOfSkippingSpace(closingBracket, openingBracketOffset + 1)
|
||||
closeBracketOffset = chars.indexOfSkippingSpace(closingBracket, openingBracketOffset!! + 1)
|
||||
}
|
||||
|
||||
if (insertLambda && lambdaInfo!!.explicitParameters) {
|
||||
val placeholderRange = TextRange(openingBracketOffset, closeBracketOffset!! + 1)
|
||||
val placeholderRange = TextRange(openingBracketOffset!!, closeBracketOffset!! + 1)
|
||||
val explicitParameterTypes =
|
||||
LambdaSignatureTemplates.explicitParameterTypesRequired(context.file as KtFile, placeholderRange, lambdaInfo.lambdaType)
|
||||
LambdaSignatureTemplates.explicitParameterTypesRequired(context.file as KtFile, placeholderRange, lambdaInfo!!.lambdaType)
|
||||
LambdaSignatureTemplates.insertTemplate(
|
||||
context,
|
||||
placeholderRange,
|
||||
lambdaInfo.lambdaType,
|
||||
lambdaInfo!!.lambdaType,
|
||||
explicitParameterTypes,
|
||||
signatureOnly = false
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
document.insertString(openingBracketOffset + 1, argumentText)
|
||||
document.insertString(openingBracketOffset!! + 1, argumentText)
|
||||
if (closeBracketOffset != null) {
|
||||
closeBracketOffset += argumentText.length
|
||||
}
|
||||
|
||||
if (!insertTypeArguments) {
|
||||
if (shouldPlaceCaretInBrackets(completionChar) || closeBracketOffset == null) {
|
||||
editor.caretModel.moveToOffset(openingBracketOffset + 1 + inBracketsShift)
|
||||
editor.caretModel.moveToOffset(openingBracketOffset!! + 1 + inBracketsShift)
|
||||
AutoPopupController.getInstance(project)?.autoPopupParameterInfo(editor, offsetElement)
|
||||
} else {
|
||||
editor.caretModel.moveToOffset(closeBracketOffset + 1)
|
||||
editor.caretModel.moveToOffset(closeBracketOffset!! + 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,12 +43,12 @@ class WithExpressionPrefixInsertHandler(val prefix: String) : InsertHandler<Look
|
||||
var expression = token.getStrictParentOfType<KtExpression>() ?: return
|
||||
if (expression is KtSimpleNameExpression) {
|
||||
var parent = expression.getParent()
|
||||
if (parent is KtCallExpression && expression == parent.calleeExpression) {
|
||||
expression = parent
|
||||
parent = parent.parent
|
||||
if (parent is KtCallExpression && expression == (parent as KtCallExpression).calleeExpression) {
|
||||
expression = parent as KtCallExpression
|
||||
parent = (parent as KtCallExpression).parent
|
||||
}
|
||||
if (parent is KtDotQualifiedExpression && expression == parent.selectorExpression) {
|
||||
expression = parent
|
||||
if (parent is KtDotQualifiedExpression && expression == (parent as KtDotQualifiedExpression).selectorExpression) {
|
||||
expression = parent as KtDotQualifiedExpression
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -68,8 +68,8 @@ fun removeRedundantBracesInStringTemplate(context: InsertionContext) {
|
||||
psiDocumentManager.commitAllDocuments()
|
||||
|
||||
val token = context.file.findElementAt(tailOffset)
|
||||
if (token != null && token.node.elementType == KtTokens.LONG_TEMPLATE_ENTRY_END) {
|
||||
val entry = token.parent as KtBlockStringTemplateEntry
|
||||
if (token != null && token!!.node.elementType == KtTokens.LONG_TEMPLATE_ENTRY_END) {
|
||||
val entry = token!!.parent as KtBlockStringTemplateEntry
|
||||
val nameExpression = entry.expression as? KtNameReferenceExpression ?: return
|
||||
if (canPlaceAfterSimpleNameEntry(entry.nextSibling)) {
|
||||
context.tailOffset++ // place after '}' otherwise it gets invalidated
|
||||
@@ -155,20 +155,20 @@ fun createKeywordConstructLookupElement(
|
||||
|
||||
val sibling = when {
|
||||
element !is PsiWhiteSpace -> element
|
||||
element.textContains('\n') -> null
|
||||
else -> element.getNextSiblingIgnoringWhitespace(true)
|
||||
(element as PsiWhiteSpace).textContains('\n') -> null
|
||||
else -> (element as PsiWhiteSpace).getNextSiblingIgnoringWhitespace(true)
|
||||
}
|
||||
|
||||
if (sibling != null && beforeCaret.trimStart().startsWith(
|
||||
insertionContext.document.getText(
|
||||
TextRange.from(
|
||||
sibling.startOffset,
|
||||
sibling!!.startOffset,
|
||||
1
|
||||
)
|
||||
)
|
||||
)
|
||||
) {
|
||||
insertionContext.editor.moveCaret(sibling.startOffset + 1)
|
||||
insertionContext.editor.moveCaret(sibling!!.startOffset + 1)
|
||||
} else {
|
||||
insertionContext.document.insertString(offset, beforeCaret + afterCaret)
|
||||
insertionContext.editor.moveCaret(offset + beforeCaret.length)
|
||||
|
||||
@@ -59,9 +59,9 @@ class MultipleArgumentsItemProvider(
|
||||
for (expectedInfo in expectedInfos) {
|
||||
val additionalData = expectedInfo.additionalData
|
||||
if (additionalData is ArgumentPositionData.Positional) {
|
||||
val parameters = additionalData.function.valueParameters.drop(additionalData.argumentIndex)
|
||||
val parameters = (additionalData as ArgumentPositionData.Positional).function.valueParameters.drop((additionalData as ArgumentPositionData.Positional).argumentIndex)
|
||||
if (parameters.size > 1) {
|
||||
val tail = when (additionalData.callType) {
|
||||
val tail = when ((additionalData as ArgumentPositionData.Positional).callType) {
|
||||
Call.CallType.ARRAY_GET_METHOD, Call.CallType.ARRAY_SET_METHOD -> Tail.RBRACKET
|
||||
else -> Tail.RPARENTH
|
||||
}
|
||||
@@ -94,7 +94,7 @@ class MultipleArgumentsItemProvider(
|
||||
if (context.completionChar == Lookup.REPLACE_SELECT_CHAR) {
|
||||
val offset = context.offsetMap.tryGetOffset(SmartCompletion.MULTIPLE_ARGUMENTS_REPLACEMENT_OFFSET)
|
||||
if (offset != null) {
|
||||
context.document.deleteString(context.tailOffset, offset)
|
||||
context.document.deleteString(context.tailOffset, offset!!)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -102,7 +102,7 @@ class SmartCompletion(
|
||||
val postProcessedSearcher = if (inheritanceSearcher != null)
|
||||
object : InheritanceItemsSearcher {
|
||||
override fun search(nameFilter: (String) -> Boolean, consumer: (LookupElement) -> Unit) {
|
||||
inheritanceSearcher.search(nameFilter, { consumer(postProcess(it)) })
|
||||
inheritanceSearcher!!.search(nameFilter, { consumer(postProcess(it)) })
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -114,28 +114,28 @@ class SmartCompletion(
|
||||
val parent = expressionWithType.parent
|
||||
when (parent) {
|
||||
is KtBinaryExpression -> {
|
||||
if (parent.right == expressionWithType) {
|
||||
val operationToken = parent.operationToken
|
||||
if ((parent as KtBinaryExpression).right == expressionWithType) {
|
||||
val operationToken = (parent as KtBinaryExpression).operationToken
|
||||
if (operationToken == KtTokens.EQ || operationToken in COMPARISON_TOKENS) {
|
||||
val left = parent.left
|
||||
val left = (parent as KtBinaryExpression).left
|
||||
if (left is KtReferenceExpression) {
|
||||
return@lazy bindingContext[BindingContext.REFERENCE_TARGET, left]?.let(::setOf).orEmpty()
|
||||
return@lazy bindingContext[BindingContext.REFERENCE_TARGET, left as KtReferenceExpression]?.let(::setOf).orEmpty()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is KtWhenConditionWithExpression -> {
|
||||
val entry = parent.parent as KtWhenEntry
|
||||
val entry = (parent as KtWhenConditionWithExpression).parent as KtWhenEntry
|
||||
val whenExpression = entry.parent as KtWhenExpression
|
||||
val subject = whenExpression.subjectExpression ?: return@lazy emptySet()
|
||||
|
||||
val descriptorsToSkip = HashSet<DeclarationDescriptor>()
|
||||
|
||||
if (subject is KtSimpleNameExpression) {
|
||||
val variable = bindingContext[BindingContext.REFERENCE_TARGET, subject] as? VariableDescriptor
|
||||
val variable = bindingContext[BindingContext.REFERENCE_TARGET, subject as KtSimpleNameExpression] as? VariableDescriptor
|
||||
if (variable != null) {
|
||||
descriptorsToSkip.add(variable)
|
||||
descriptorsToSkip.add(variable!!)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,7 +184,7 @@ class SmartCompletion(
|
||||
val asTypePositionItems = buildForAsTypePosition(lookupElementFactory.basicFactory)
|
||||
if (asTypePositionItems != null) {
|
||||
assert(expectedInfos.isEmpty())
|
||||
return Pair(asTypePositionItems, null)
|
||||
return Pair(asTypePositionItems!!, null)
|
||||
}
|
||||
|
||||
val items = ArrayList<LookupElement>()
|
||||
@@ -216,7 +216,7 @@ class SmartCompletion(
|
||||
|
||||
if (expression is KtSimpleNameExpression) {
|
||||
StaticMembers(bindingContext, lookupElementFactory, resolutionFacade, moduleDescriptor)
|
||||
.addToCollection(items, expectedInfos, expression, descriptorsToSkip)
|
||||
.addToCollection(items, expectedInfos, expression as KtSimpleNameExpression, descriptorsToSkip)
|
||||
}
|
||||
|
||||
ClassLiteralItems.addToCollection(items, expectedInfos, lookupElementFactory.basicFactory, isJvmModule)
|
||||
@@ -230,7 +230,7 @@ class SmartCompletion(
|
||||
|
||||
val whenCondition = expressionWithType.parent as? KtWhenConditionWithExpression
|
||||
if (whenCondition != null) {
|
||||
val entry = whenCondition.parent as KtWhenEntry
|
||||
val entry = whenCondition!!.parent as KtWhenEntry
|
||||
val whenExpression = entry.parent as KtWhenExpression
|
||||
val entries = whenExpression.entries
|
||||
if (whenExpression.elseExpression == null && entry == entries.last() && entries.size != 1) {
|
||||
@@ -270,7 +270,7 @@ class SmartCompletion(
|
||||
if (context.completionChar == Lookup.REPLACE_SELECT_CHAR) {
|
||||
val offset = context.offsetMap.tryGetOffset(OLD_ARGUMENTS_REPLACEMENT_OFFSET)
|
||||
if (offset != null) {
|
||||
context.document.deleteString(context.tailOffset, offset)
|
||||
context.document.deleteString(context.tailOffset, offset!!)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -341,12 +341,12 @@ class SmartCompletion(
|
||||
// if our expression is initializer of implicitly typed variable - take type of variable from original file (+ the same for function)
|
||||
val declaration = implicitlyTypedDeclarationFromInitializer(expression)
|
||||
if (declaration != null) {
|
||||
val originalDeclaration = toFromOriginalFileMapper.toOriginalFile(declaration)
|
||||
val originalDeclaration = toFromOriginalFileMapper.toOriginalFile(declaration!!)
|
||||
if (originalDeclaration != null) {
|
||||
val originalDescriptor = originalDeclaration.resolveToDescriptorIfAny() as? CallableDescriptor
|
||||
val originalDescriptor = originalDeclaration!!.resolveToDescriptorIfAny() as? CallableDescriptor
|
||||
val returnType = originalDescriptor?.returnType
|
||||
if (returnType != null && !returnType.isError) {
|
||||
return listOf(ExpectedInfo(returnType, declaration.name, null))
|
||||
if (returnType != null && !returnType!!.isError) {
|
||||
return listOf(ExpectedInfo(returnType!!, declaration!!.name, null))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -370,8 +370,8 @@ class SmartCompletion(
|
||||
private fun implicitlyTypedDeclarationFromInitializer(expression: KtExpression): KtDeclaration? {
|
||||
val parent = expression.parent
|
||||
when (parent) {
|
||||
is KtVariableDeclaration -> if (expression == parent.initializer && parent.typeReference == null) return parent
|
||||
is KtNamedFunction -> if (expression == parent.initializer && parent.typeReference == null) return parent
|
||||
is KtVariableDeclaration -> if (expression == (parent as KtVariableDeclaration).initializer && (parent as KtVariableDeclaration).typeReference == null) return parent as KtVariableDeclaration
|
||||
is KtNamedFunction -> if (expression == (parent as KtNamedFunction).initializer && (parent as KtNamedFunction).typeReference == null) return parent as KtNamedFunction
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -408,14 +408,14 @@ class SmartCompletion(
|
||||
when (descriptor) {
|
||||
is CallableDescriptor -> {
|
||||
// members and extensions are not supported after "::" currently
|
||||
if (descriptor.dispatchReceiverParameter == null && descriptor.extensionReceiverParameter == null) {
|
||||
addIfNotNull(toLookupElement(descriptor))
|
||||
if ((descriptor as CallableDescriptor).dispatchReceiverParameter == null && (descriptor as CallableDescriptor).extensionReceiverParameter == null) {
|
||||
addIfNotNull(toLookupElement(descriptor as CallableDescriptor))
|
||||
}
|
||||
}
|
||||
|
||||
is ClassDescriptor -> {
|
||||
if (descriptor.modality != Modality.ABSTRACT && !descriptor.isInner) {
|
||||
descriptor.constructors
|
||||
if ((descriptor as ClassDescriptor).modality != Modality.ABSTRACT && !(descriptor as ClassDescriptor).isInner) {
|
||||
(descriptor as ClassDescriptor).constructors
|
||||
.filter(visibilityFilter)
|
||||
.mapNotNullTo(this, ::toLookupElement)
|
||||
}
|
||||
@@ -437,7 +437,7 @@ class SmartCompletion(
|
||||
val items = ArrayList<LookupElement>()
|
||||
for ((type, infos) in expectedInfosGrouped) {
|
||||
if (type == null) continue
|
||||
val lookupElement = lookupElementFactory.createLookupElementForType(type) ?: continue
|
||||
val lookupElement = lookupElementFactory.createLookupElementForType(type!!) ?: continue
|
||||
items.add(lookupElement.addTailAndNameSimilarity(infos))
|
||||
}
|
||||
return items
|
||||
|
||||
@@ -21,6 +21,7 @@ import com.intellij.codeInsight.completion.CompletionResultSet
|
||||
import com.intellij.codeInsight.completion.CompletionSorter
|
||||
import com.intellij.codeInsight.lookup.LookupElement
|
||||
import com.intellij.psi.impl.source.tree.LeafPsiElement
|
||||
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
|
||||
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
|
||||
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
|
||||
import org.jetbrains.kotlin.idea.completion.*
|
||||
@@ -67,7 +68,7 @@ class SmartCompletionSession(
|
||||
get() = smartCompletion?.expectedInfos ?: emptyList()
|
||||
|
||||
override fun doComplete() {
|
||||
if (nameExpression != null && NamedArgumentCompletion.isOnlyNamedArgumentExpected(nameExpression)) {
|
||||
if (nameExpression != null && NamedArgumentCompletion.isOnlyNamedArgumentExpected(nameExpression!!)) {
|
||||
NamedArgumentCompletion.complete(collector, expectedInfos, callTypeAndReceiver.callType)
|
||||
return
|
||||
}
|
||||
@@ -87,10 +88,10 @@ class SmartCompletionSession(
|
||||
val contextVariableTypesForReferenceVariants = filter?.let {
|
||||
withCollectRequiredContextVariableTypes { lookupElementFactory ->
|
||||
if (referenceVariantsCollector != null) {
|
||||
val (imported, notImported) = referenceVariantsCollector.collectReferenceVariants(descriptorKindFilter).excludeNonInitializedVariable()
|
||||
imported.forEach { collector.addElements(filter(it, lookupElementFactory)) }
|
||||
notImported.forEach { collector.addElements(filter(it, lookupElementFactory), notImported = true) }
|
||||
referenceVariantsCollector.collectingFinished()
|
||||
val (imported, notImported) = referenceVariantsCollector!!.collectReferenceVariants(descriptorKindFilter).excludeNonInitializedVariable()
|
||||
imported.forEach { collector.addElements((filter as (DeclarationDescriptor, AbstractLookupElementFactory) -> Collection<LookupElement>)(it, lookupElementFactory)) }
|
||||
notImported.forEach { collector.addElements((filter as (DeclarationDescriptor, AbstractLookupElementFactory) -> Collection<LookupElement>)(it, lookupElementFactory), notImported = true) }
|
||||
referenceVariantsCollector!!.collectingFinished()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -100,10 +101,10 @@ class SmartCompletionSession(
|
||||
val contextVariablesProvider = RealContextVariablesProvider(referenceVariantsHelper, position)
|
||||
withContextVariablesProvider(contextVariablesProvider) { lookupElementFactory ->
|
||||
if (filter != null && receiverTypes != null) {
|
||||
val results = ExtensionFunctionTypeValueCompletion(receiverTypes, callTypeAndReceiver.callType, lookupElementFactory)
|
||||
val results = ExtensionFunctionTypeValueCompletion(receiverTypes!!, callTypeAndReceiver.callType, lookupElementFactory)
|
||||
.processVariables(contextVariablesProvider)
|
||||
for ((invokeDescriptor, factory) in results) {
|
||||
collector.addElements(filter(invokeDescriptor, factory))
|
||||
collector.addElements((filter as (DeclarationDescriptor, AbstractLookupElementFactory) -> Collection<LookupElement>)(invokeDescriptor, factory))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,8 +115,8 @@ class SmartCompletionSession(
|
||||
|
||||
if (filter != null && contextVariableTypesForReferenceVariants!!.any { contextVariablesProvider.functionTypeVariables(it).isNotEmpty() }) {
|
||||
val (imported, notImported) = referenceVariantsWithSingleFunctionTypeParameter()!!
|
||||
imported.forEach { collector.addElements(filter(it, lookupElementFactory)) }
|
||||
notImported.forEach { collector.addElements(filter(it, lookupElementFactory), notImported = true) }
|
||||
imported.forEach { collector.addElements((filter as (DeclarationDescriptor, AbstractLookupElementFactory) -> Collection<LookupElement>)(it, lookupElementFactory)) }
|
||||
notImported.forEach { collector.addElements((filter as (DeclarationDescriptor, AbstractLookupElementFactory) -> Collection<LookupElement>)(it, lookupElementFactory), notImported = true) }
|
||||
}
|
||||
|
||||
flushToResultSet()
|
||||
@@ -125,9 +126,9 @@ class SmartCompletionSession(
|
||||
if (callTypeAndReceiver is CallTypeAndReceiver.DEFAULT) {
|
||||
val alreadyCollected = referenceVariantsCollector!!.allCollected.imported
|
||||
staticMembersCompletion = StaticMembersCompletion(prefixMatcher, resolutionFacade, lookupElementFactory, alreadyCollected, isJvmModule)
|
||||
val decoratedFactory = staticMembersCompletion.decoratedLookupElementFactory(ItemPriority.STATIC_MEMBER_FROM_IMPORTS)
|
||||
staticMembersCompletion.membersFromImports(file)
|
||||
.flatMap { filter(it, decoratedFactory) }
|
||||
val decoratedFactory = staticMembersCompletion!!.decoratedLookupElementFactory(ItemPriority.STATIC_MEMBER_FROM_IMPORTS)
|
||||
staticMembersCompletion!!.membersFromImports(file)
|
||||
.flatMap { (filter as (DeclarationDescriptor, AbstractLookupElementFactory) -> Collection<LookupElement>)(it, decoratedFactory) }
|
||||
.forEach { collector.addElement(it) }
|
||||
}
|
||||
else {
|
||||
@@ -136,7 +137,7 @@ class SmartCompletionSession(
|
||||
|
||||
if (shouldCompleteTopLevelCallablesFromIndex()) {
|
||||
processTopLevelCallables {
|
||||
collector.addElements(filter(it, lookupElementFactory), notImported = true)
|
||||
collector.addElements((filter as (DeclarationDescriptor, AbstractLookupElementFactory) -> Collection<LookupElement>)(it, lookupElementFactory), notImported = true)
|
||||
flushToResultSet()
|
||||
}
|
||||
}
|
||||
@@ -144,18 +145,18 @@ class SmartCompletionSession(
|
||||
if (isDebuggerContext) {
|
||||
val variantsAndFactory = getRuntimeReceiverTypeReferenceVariants(lookupElementFactory)
|
||||
if (variantsAndFactory != null) {
|
||||
val variants = variantsAndFactory.first
|
||||
@Suppress("NAME_SHADOWING") val lookupElementFactory = variantsAndFactory.second
|
||||
variants.imported.forEach { collector.addElements(filter(it, lookupElementFactory).map { it.withReceiverCast() }) }
|
||||
variants.notImportedExtensions.forEach { collector.addElements(filter(it, lookupElementFactory).map { it.withReceiverCast() }, notImported = true) }
|
||||
val variants = variantsAndFactory!!.first
|
||||
@Suppress("NAME_SHADOWING") val lookupElementFactory = variantsAndFactory!!.second
|
||||
variants.imported.forEach { collector.addElements((filter as (DeclarationDescriptor, AbstractLookupElementFactory) -> Collection<LookupElement>)(it, lookupElementFactory).map { it.withReceiverCast() }) }
|
||||
variants.notImportedExtensions.forEach { collector.addElements((filter as (DeclarationDescriptor, AbstractLookupElementFactory) -> Collection<LookupElement>)(it, lookupElementFactory).map { it.withReceiverCast() }, notImported = true) }
|
||||
flushToResultSet()
|
||||
}
|
||||
}
|
||||
|
||||
if (staticMembersCompletion != null && configuration.staticMembers) {
|
||||
val decoratedFactory = staticMembersCompletion.decoratedLookupElementFactory(ItemPriority.STATIC_MEMBER)
|
||||
staticMembersCompletion.processMembersFromIndices(indicesHelper(false)) {
|
||||
filter(it, decoratedFactory).forEach {
|
||||
val decoratedFactory = staticMembersCompletion!!.decoratedLookupElementFactory(ItemPriority.STATIC_MEMBER)
|
||||
staticMembersCompletion!!.processMembersFromIndices(indicesHelper(false)) {
|
||||
(filter as (DeclarationDescriptor, AbstractLookupElementFactory) -> Collection<LookupElement>)(it, decoratedFactory).forEach {
|
||||
collector.addElement(it)
|
||||
flushToResultSet()
|
||||
}
|
||||
@@ -175,9 +176,9 @@ class SmartCompletionSession(
|
||||
// special completion for outside parenthesis lambda argument
|
||||
private fun addFunctionLiteralArgumentCompletions() {
|
||||
if (nameExpression != null) {
|
||||
val callTypeAndReceiver = CallTypeAndReceiver.detect(nameExpression) as? CallTypeAndReceiver.INFIX ?: return
|
||||
val callTypeAndReceiver = CallTypeAndReceiver.detect(nameExpression!!) as? CallTypeAndReceiver.INFIX ?: return
|
||||
val call = callTypeAndReceiver.receiver.getCall(bindingContext)
|
||||
if (call != null && call.functionLiteralArguments.isEmpty()) {
|
||||
if (call != null && call!!.functionLiteralArguments.isEmpty()) {
|
||||
val dummyArgument = object : LambdaArgument {
|
||||
override fun getLambdaExpression() = throw UnsupportedOperationException()
|
||||
override fun getArgumentExpression() = throw UnsupportedOperationException()
|
||||
@@ -187,8 +188,8 @@ class SmartCompletionSession(
|
||||
override fun getSpreadElement(): LeafPsiElement? = null
|
||||
override fun isExternal() = false
|
||||
}
|
||||
val dummyArguments = call.valueArguments + listOf(dummyArgument)
|
||||
val dummyCall = object : DelegatingCall(call) {
|
||||
val dummyArguments = call!!.valueArguments + listOf(dummyArgument)
|
||||
val dummyCall = object : DelegatingCall(call!!) {
|
||||
override fun getValueArguments() = dummyArguments
|
||||
override fun getFunctionLiteralArguments() = listOf(dummyArgument)
|
||||
override fun getValueArgumentList() = throw UnsupportedOperationException()
|
||||
@@ -216,11 +217,11 @@ class SmartCompletionSession(
|
||||
val descriptor = (lookupElement.`object` as DeclarationLookupObject).descriptor
|
||||
var element = lookupElement
|
||||
|
||||
if (descriptor is FunctionDescriptor && descriptor.valueParameters.isNotEmpty()) {
|
||||
if (descriptor is FunctionDescriptor && (descriptor as FunctionDescriptor).valueParameters.isNotEmpty()) {
|
||||
element = element.keepOldArgumentListOnTab()
|
||||
}
|
||||
|
||||
if (descriptor is ValueParameterDescriptor && bindingContext[BindingContext.AUTO_CREATED_IT, descriptor]!!) {
|
||||
if (descriptor is ValueParameterDescriptor && bindingContext[BindingContext.AUTO_CREATED_IT, descriptor as ValueParameterDescriptor]!!) {
|
||||
element = element.assignSmartCompletionPriority(SmartCompletionItemPriority.IT)
|
||||
}
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@ class StaticMembers(
|
||||
if (delegatesClass is ClassDescriptor) {
|
||||
addToCollection(
|
||||
collection,
|
||||
delegatesClass,
|
||||
delegatesClass as ClassDescriptor,
|
||||
listOf(expectedInfo),
|
||||
context,
|
||||
enumEntriesToSkip,
|
||||
@@ -94,7 +94,7 @@ class StaticMembers(
|
||||
defaultPriority: SmartCompletionItemPriority
|
||||
) {
|
||||
fun processMember(descriptor: DeclarationDescriptor) {
|
||||
if (descriptor is DeclarationDescriptorWithVisibility && !descriptor.isVisible(
|
||||
if (descriptor is DeclarationDescriptorWithVisibility && !(descriptor as DeclarationDescriptorWithVisibility).isVisible(
|
||||
context,
|
||||
null,
|
||||
bindingContext,
|
||||
@@ -104,7 +104,7 @@ class StaticMembers(
|
||||
|
||||
val matcher: (ExpectedInfo) -> ExpectedInfoMatch = when {
|
||||
descriptor is CallableDescriptor -> {
|
||||
val returnType = descriptor.fuzzyReturnType() ?: return
|
||||
val returnType = (descriptor as CallableDescriptor).fuzzyReturnType() ?: return
|
||||
{ expectedInfo -> returnType.matchExpectedInfo(expectedInfo) }
|
||||
}
|
||||
DescriptorUtils.isEnumEntry(descriptor) && !enumEntriesToSkip.contains(descriptor) -> {
|
||||
@@ -126,7 +126,7 @@ class StaticMembers(
|
||||
|
||||
val companionObject = classDescriptor.companionObjectDescriptor
|
||||
if (companionObject != null) {
|
||||
companionObject.defaultType.memberScope.getContributedDescriptors()
|
||||
companionObject!!.defaultType.memberScope.getContributedDescriptors()
|
||||
.filter { !it.isExtension }
|
||||
.forEach(::processMember)
|
||||
}
|
||||
|
||||
@@ -95,8 +95,8 @@ class TypeInstantiationItems(
|
||||
|
||||
val classifier = fuzzyType.type.constructor.declarationDescriptor as? ClassifierDescriptorWithTypeParameters ?: return
|
||||
val classDescriptor = when (classifier) {
|
||||
is ClassDescriptor -> classifier
|
||||
is TypeAliasDescriptor -> classifier.classDescriptor
|
||||
is ClassDescriptor -> classifier as ClassDescriptor
|
||||
is TypeAliasDescriptor -> (classifier as TypeAliasDescriptor).classDescriptor
|
||||
else -> null
|
||||
}
|
||||
|
||||
@@ -109,15 +109,15 @@ class TypeInstantiationItems(
|
||||
items.addIfNotNull(createTypeInstantiationItem(typeAliasFuzzyType, classDescriptor, tail))
|
||||
}
|
||||
|
||||
if (classDescriptor != null && !forOrdinaryCompletion && !KotlinBuiltIns.isAny(classDescriptor)) { // do not search inheritors of Any
|
||||
if (classDescriptor != null && !forOrdinaryCompletion && !KotlinBuiltIns.isAny(classDescriptor!!)) { // do not search inheritors of Any
|
||||
val typeArgs = fuzzyType.type.arguments
|
||||
inheritanceSearchers.addInheritorSearcher(classDescriptor, classDescriptor, typeArgs, fuzzyType.freeParameters, tail)
|
||||
inheritanceSearchers.addInheritorSearcher(classDescriptor!!, classDescriptor!!, typeArgs, fuzzyType.freeParameters, tail)
|
||||
|
||||
val javaClassId = JavaToKotlinClassMap.mapKotlinToJava(DescriptorUtils.getFqName(classifier))
|
||||
if (javaClassId != null) {
|
||||
val javaAnalog = resolutionFacade.moduleDescriptor.resolveTopLevelClass(javaClassId.asSingleFqName(), NoLookupLocation.FROM_IDE)
|
||||
val javaAnalog = resolutionFacade.moduleDescriptor.resolveTopLevelClass(javaClassId!!.asSingleFqName(), NoLookupLocation.FROM_IDE)
|
||||
if (javaAnalog != null) {
|
||||
inheritanceSearchers.addInheritorSearcher(javaAnalog, classDescriptor, typeArgs, fuzzyType.freeParameters, tail)
|
||||
inheritanceSearchers.addInheritorSearcher(javaAnalog!!, classDescriptor!!, typeArgs, fuzzyType.freeParameters, tail)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -128,13 +128,13 @@ class TypeInstantiationItems(
|
||||
) {
|
||||
val _declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(resolutionFacade.project, descriptor) ?: return
|
||||
val declaration = if (_declaration is KtDeclaration)
|
||||
toFromOriginalFileMapper.toOriginalFile(_declaration) ?: return
|
||||
toFromOriginalFileMapper.toOriginalFile(_declaration as KtDeclaration) ?: return
|
||||
else
|
||||
_declaration
|
||||
|
||||
val psiClass: PsiClass = when (declaration) {
|
||||
is PsiClass -> declaration
|
||||
is KtClassOrObject -> declaration.toLightClass() ?: return
|
||||
is PsiClass -> declaration as PsiClass
|
||||
is KtClassOrObject -> (declaration as KtClassOrObject).toLightClass() ?: return
|
||||
else -> return
|
||||
}
|
||||
add(InheritanceSearcher(psiClass, kotlinClassDescriptor, typeArgs, freeParameters, tail))
|
||||
@@ -286,11 +286,11 @@ class TypeInstantiationItems(
|
||||
override fun equals(other: Any?): Boolean {
|
||||
if (other === this) return true
|
||||
if (other !is InstantiationLookupElement) return false
|
||||
if (getLookupString() != other.lookupString) return false
|
||||
if (getLookupString() != (other as InstantiationLookupElement).lookupString) return false
|
||||
val presentation1 = LookupElementPresentation()
|
||||
val presentation2 = LookupElementPresentation()
|
||||
renderElement(presentation1)
|
||||
other.renderElement(presentation2)
|
||||
(other as InstantiationLookupElement).renderElement(presentation2)
|
||||
return presentation1.itemText == presentation2.itemText && presentation1.tailText == presentation2.tailText
|
||||
}
|
||||
|
||||
@@ -312,8 +312,8 @@ class TypeInstantiationItems(
|
||||
val samConstructor = run {
|
||||
val container = classifier.containingDeclaration
|
||||
val scope = when (container) {
|
||||
is PackageFragmentDescriptor -> container.getMemberScope()
|
||||
is ClassDescriptor -> container.unsubstitutedMemberScope
|
||||
is PackageFragmentDescriptor -> (container as PackageFragmentDescriptor).getMemberScope()
|
||||
is ClassDescriptor -> (container as ClassDescriptor).unsubstitutedMemberScope
|
||||
else -> return
|
||||
}
|
||||
scope.collectSyntheticStaticMembersAndConstructors(resolutionFacade, DescriptorKindFilter.FUNCTIONS, { classifier.name == it })
|
||||
|
||||
@@ -149,13 +149,13 @@ fun Collection<FuzzyType>.matchExpectedInfo(expectedInfo: ExpectedInfo): Expecte
|
||||
val sequence = asSequence()
|
||||
val substitutor = sequence.map { expectedInfo.matchingSubstitutor(it) }.firstOrNull()
|
||||
if (substitutor != null) {
|
||||
return ExpectedInfoMatch.match(substitutor)
|
||||
return ExpectedInfoMatch.match(substitutor!!)
|
||||
}
|
||||
|
||||
if (sequence.any { it.nullability() == TypeNullability.NULLABLE }) {
|
||||
val substitutor2 = sequence.map { expectedInfo.matchingSubstitutor(it.makeNotNullable()) }.firstOrNull()
|
||||
if (substitutor2 != null) {
|
||||
return ExpectedInfoMatch.ifNotNullMatch(substitutor2)
|
||||
return ExpectedInfoMatch.ifNotNullMatch(substitutor2!!)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -305,7 +305,7 @@ fun DeclarationDescriptor.fuzzyTypesForSmartCompletion(
|
||||
bindingContext: BindingContext
|
||||
): Collection<FuzzyType> {
|
||||
if (callTypeAndReceiver is CallTypeAndReceiver.CALLABLE_REFERENCE) {
|
||||
val lhs = callTypeAndReceiver.receiver?.let { bindingContext[BindingContext.DOUBLE_COLON_LHS, it] }
|
||||
val lhs = (callTypeAndReceiver as CallTypeAndReceiver.CALLABLE_REFERENCE).receiver?.let { bindingContext[BindingContext.DOUBLE_COLON_LHS, it] }
|
||||
return listOfNotNull((this as? CallableDescriptor)?.callableReferenceType(resolutionFacade, lhs))
|
||||
}
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ class AnonymousSuperMacro : KotlinMacro() {
|
||||
override fun calculateResult(params: Array<Expression>, context: ExpressionContext): Result? {
|
||||
val editor = context.editor
|
||||
if (editor != null) {
|
||||
AnonymousTemplateEditingListener.registerListener(editor, context.project)
|
||||
AnonymousTemplateEditingListener.registerListener(editor!!, context.project)
|
||||
}
|
||||
|
||||
val vars = getSupertypes(params, context)
|
||||
@@ -75,8 +75,8 @@ class AnonymousSuperMacro : KotlinMacro() {
|
||||
return resolutionScope
|
||||
.collectDescriptorsFiltered(DescriptorKindFilter.NON_SINGLETON_CLASSIFIERS)
|
||||
.filter { it is ClassDescriptor &&
|
||||
(it.modality == Modality.OPEN || it.modality == Modality.ABSTRACT) &&
|
||||
(it.kind == ClassKind.CLASS || it.kind == ClassKind.INTERFACE) }
|
||||
((it as ClassDescriptor).modality == Modality.OPEN || (it as ClassDescriptor).modality == Modality.ABSTRACT) &&
|
||||
((it as ClassDescriptor).kind == ClassKind.CLASS || (it as ClassDescriptor).kind == ClassKind.INTERFACE) }
|
||||
.mapNotNull { DescriptorToSourceUtils.descriptorToDeclaration(it) as PsiNamedElement? }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,12 +42,12 @@ internal class AnonymousTemplateEditingListener(private val psiFile: PsiFile, pr
|
||||
if (templateState.template == null) return
|
||||
val variableRange = templateState.getVariableRange("SUPERTYPE") ?: return
|
||||
val name = psiFile.findElementAt(variableRange.startOffset)
|
||||
if (name != null && name.parent is KtReferenceExpression) {
|
||||
val ref = name.parent as KtReferenceExpression
|
||||
if (name != null && name!!.parent is KtReferenceExpression) {
|
||||
val ref = name!!.parent as KtReferenceExpression
|
||||
val descriptor = ref.analyze(BodyResolveMode.FULL).get(BindingContext.REFERENCE_TARGET, ref)
|
||||
if (descriptor is ClassDescriptor) {
|
||||
classRef = ref
|
||||
classDescriptor = descriptor
|
||||
classDescriptor = descriptor as ClassDescriptor
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -91,7 +91,7 @@ internal class AnonymousTemplateEditingListener(private val psiFile: PsiFile, pr
|
||||
if (templateState != null) {
|
||||
val listener = AnonymousTemplateEditingListener(psiFile, editor)
|
||||
editor.putUserData(LISTENER_KEY, listener)
|
||||
templateState.addTemplateStateListener(listener)
|
||||
templateState!!.addTemplateStateListener(listener)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ abstract class BaseKotlinVariableMacro<TState> : KotlinMacro() {
|
||||
val bindingContext = resolutionFacade.analyze(contextElement, BodyResolveMode.PARTIAL_FOR_COMPLETION)
|
||||
|
||||
fun isVisible(descriptor: DeclarationDescriptor): Boolean {
|
||||
return descriptor !is DeclarationDescriptorWithVisibility || descriptor.isVisible(contextElement, null, bindingContext, resolutionFacade)
|
||||
return descriptor !is DeclarationDescriptorWithVisibility || (descriptor as DeclarationDescriptorWithVisibility).isVisible(contextElement, null, bindingContext, resolutionFacade)
|
||||
}
|
||||
|
||||
val state = initState(contextElement, bindingContext)
|
||||
|
||||
@@ -37,12 +37,12 @@ class FunctionParametersMacro : KotlinMacro() {
|
||||
while (place != null) {
|
||||
if (place is KtFunction) {
|
||||
val result = ArrayList<Result>()
|
||||
for (param in place.valueParameters) {
|
||||
for (param in (place as KtFunction).valueParameters) {
|
||||
result.add(TextResult(param.name!!))
|
||||
}
|
||||
return ListResult(result)
|
||||
}
|
||||
place = place.parent
|
||||
place = place!!.parent
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ class KotlinClassNameMacro : KotlinMacro() {
|
||||
|
||||
override fun calculateResult(params: Array<Expression>, context: ExpressionContext): Result? {
|
||||
val element = context.psiElementAtStartOffset?.parentsWithSelf?.firstOrNull {
|
||||
it is KtClassOrObject && it.name != null && !it.hasModifier(KtTokens.COMPANION_KEYWORD)
|
||||
it is KtClassOrObject && (it as KtClassOrObject).name != null && !(it as KtClassOrObject).hasModifier(KtTokens.COMPANION_KEYWORD)
|
||||
} ?: return null
|
||||
return TextResult((element as KtClassOrObject).name!!)
|
||||
}
|
||||
|
||||
@@ -38,9 +38,9 @@ class SuitableVariableMacro : BaseKotlinVariableMacro<SuitableVariableMacro.Stat
|
||||
override fun initState(contextElement: KtElement, bindingContext: BindingContext): State? {
|
||||
val resolutionFacade = contextElement.getResolutionFacade()
|
||||
if (contextElement is KtNameReferenceExpression) {
|
||||
val callTypeAndReceiver = CallTypeAndReceiver.detect(contextElement)
|
||||
val callTypeAndReceiver = CallTypeAndReceiver.detect(contextElement as KtNameReferenceExpression)
|
||||
if (callTypeAndReceiver is CallTypeAndReceiver.DEFAULT) {
|
||||
val expectedInfos = ExpectedInfos(bindingContext, resolutionFacade, null).calculate(contextElement)
|
||||
val expectedInfos = ExpectedInfos(bindingContext, resolutionFacade, null).calculate(contextElement as KtNameReferenceExpression)
|
||||
if (expectedInfos.isNotEmpty()) {
|
||||
val scope = contextElement.getResolutionScope(bindingContext, resolutionFacade)
|
||||
val smartCastCalculator = SmartCastCalculator(bindingContext, scope.ownerDescriptor, contextElement, null, resolutionFacade)
|
||||
@@ -54,7 +54,7 @@ class SuitableVariableMacro : BaseKotlinVariableMacro<SuitableVariableMacro.Stat
|
||||
|
||||
override fun isSuitable(variableDescriptor: VariableDescriptor, project: Project, state: State?): Boolean {
|
||||
if (state == null) return true
|
||||
val types = state.smartCastCalculator.types(variableDescriptor)
|
||||
return state.expectedInfos.any { expectedInfo -> types.any { expectedInfo.filter.matchingSubstitutor(it.toFuzzyType(emptyList())) != null } }
|
||||
val types = state!!.smartCastCalculator.types(variableDescriptor)
|
||||
return state!!.expectedInfos.any { expectedInfo -> types.any { expectedInfo.filter.matchingSubstitutor(it.toFuzzyType(emptyList())) != null } }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,7 +63,7 @@ class KotlinConsoleKeeper(val project: Project) {
|
||||
}
|
||||
|
||||
if (module != null) {
|
||||
val classPath = JavaParametersBuilder.getModuleDependencies(module)
|
||||
val classPath = JavaParametersBuilder.getModuleDependencies(module!!)
|
||||
if (classPath.isNotEmpty()) {
|
||||
javaParameters.setUseDynamicParameters(javaParameters.isDynamicClasspath)
|
||||
javaParameters.programParametersList.add("-cp")
|
||||
|
||||
@@ -64,7 +64,7 @@ class ReplOutputProcessor(
|
||||
|
||||
historyMarkup.addRangeHighlighter(
|
||||
startOffset, endOffset, HighlighterLayer.LAST, null, HighlighterTargetArea.EXACT_RANGE
|
||||
).apply { gutterIconRenderer = ConsoleIndicatorRenderer(iconWithTooltip) }
|
||||
).apply { gutterIconRenderer = ConsoleIndicatorRenderer(iconWithTooltip!!) }
|
||||
}
|
||||
|
||||
private fun printWarningMessage(message: String, isAddHyperlink: Boolean) = WriteCommandAction.runWriteCommandAction(project) {
|
||||
|
||||
@@ -29,7 +29,7 @@ class ConsoleModuleDialog(private val project: Project) {
|
||||
|
||||
fun showIfNeeded(dataContext: DataContext) {
|
||||
val module = getModule(dataContext)
|
||||
if (module != null) return runConsole(module)
|
||||
if (module != null) return runConsole(module!!)
|
||||
|
||||
val modules = ModuleManager.getInstance(project).modules
|
||||
|
||||
|
||||
@@ -3386,7 +3386,16 @@
|
||||
level="WEAK WARNING"
|
||||
language="kotlin"
|
||||
/>
|
||||
|
||||
|
||||
<localInspection implementationClass="org.jetbrains.kotlin.idea.inspections.AntiSmartCastInspection"
|
||||
displayName="I just hate smart-casts"
|
||||
groupPath="Kotlin"
|
||||
groupName="Style issues"
|
||||
enabledByDefault="true"
|
||||
level="WEAK WARNING"
|
||||
language="kotlin"
|
||||
/>
|
||||
|
||||
<referenceImporter implementation="org.jetbrains.kotlin.idea.quickfix.KotlinReferenceImporter"/>
|
||||
|
||||
<fileType.fileViewProviderFactory filetype="KJSM" implementationClass="com.intellij.psi.ClassFileViewProviderFactory"/>
|
||||
|
||||
5
idea/resources/inspectionDescriptions/AntiSmartCast.html
Normal file
5
idea/resources/inspectionDescriptions/AntiSmartCast.html
Normal file
@@ -0,0 +1,5 @@
|
||||
<html>
|
||||
<body>
|
||||
This inspection is just a smart-cast killer. Not for production use.
|
||||
</body>
|
||||
</html>
|
||||
@@ -29,7 +29,7 @@ class CommonModuleResolveScopeEnlarger : ResolveScopeEnlarger() {
|
||||
var result = GlobalSearchScope.EMPTY_SCOPE
|
||||
for (entry in ModuleRootManager.getInstance(implementingModule).orderEntries) {
|
||||
if (entry is JdkOrderEntry) {
|
||||
val scopeForSdk = LibraryScopeCache.getInstance(project).getScopeForSdk(entry)
|
||||
val scopeForSdk = LibraryScopeCache.getInstance(project).getScopeForSdk(entry as JdkOrderEntry)
|
||||
result = result.uniteWith(scopeForSdk)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,22 +69,22 @@ class KotlinFoldingBuilder : CustomFoldingBuilder(), DumbAware {
|
||||
return
|
||||
}
|
||||
|
||||
val importList = root.importList
|
||||
val importList = (root as KtFile).importList
|
||||
if (importList != null) {
|
||||
val firstImport = importList.imports.firstOrNull()
|
||||
if (firstImport != null && importList.imports.size > 1) {
|
||||
val importKeyword = firstImport.firstChild
|
||||
val firstImport = importList!!.imports.firstOrNull()
|
||||
if (firstImport != null && importList!!.imports.size > 1) {
|
||||
val importKeyword = firstImport!!.firstChild
|
||||
|
||||
val startOffset = importKeyword.endOffset + 1
|
||||
val endOffset = importList.endOffset
|
||||
val endOffset = importList!!.endOffset
|
||||
|
||||
descriptors.add(FoldingDescriptor(importList, TextRange(startOffset, endOffset)).apply {
|
||||
descriptors.add(FoldingDescriptor(importList!!, TextRange(startOffset, endOffset)).apply {
|
||||
setCanBeRemovedWhenCollapsed(true)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
appendDescriptors(root.node, document, descriptors)
|
||||
appendDescriptors((root as KtFile).node, document, descriptors)
|
||||
}
|
||||
|
||||
private fun appendDescriptors(node: ASTNode, document: Document, descriptors: MutableList<FoldingDescriptor>) {
|
||||
@@ -140,7 +140,7 @@ class KotlinFoldingBuilder : CustomFoldingBuilder(), DumbAware {
|
||||
val lbrace = psi?.lBrace
|
||||
val rbrace = psi?.rBrace
|
||||
if (lbrace != null && rbrace != null) {
|
||||
return TextRange(lbrace.startOffset, rbrace.endOffset)
|
||||
return TextRange(lbrace!!.startOffset, rbrace!!.endOffset)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,7 +149,7 @@ class KotlinFoldingBuilder : CustomFoldingBuilder(), DumbAware {
|
||||
val leftParenthesis = valueArgumentList?.leftParenthesis
|
||||
val rightParenthesis = valueArgumentList?.rightParenthesis
|
||||
if (leftParenthesis != null && rightParenthesis != null) {
|
||||
return TextRange(leftParenthesis.startOffset, rightParenthesis.endOffset)
|
||||
return TextRange(leftParenthesis!!.startOffset, rightParenthesis!!.endOffset)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ class KotlinGotoTargetRenderProvider : GotoTargetRendererProvider {
|
||||
KtLightClassListCellRenderer()
|
||||
}
|
||||
is KtDeclaration -> {
|
||||
if (element.isEffectivelyActual()) {
|
||||
if ((element as KtDeclaration).isEffectivelyActual()) {
|
||||
DeclarationByModuleRenderer()
|
||||
} else {
|
||||
null
|
||||
|
||||
@@ -32,7 +32,7 @@ import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluat
|
||||
class KotlinLightConstantExpressionEvaluator : ConstantExpressionEvaluator {
|
||||
private fun evalConstantValue(constantValue: ConstantValue<*>): Any? {
|
||||
return if (constantValue is ArrayValue) {
|
||||
val items = constantValue.value.map { evalConstantValue(it) }
|
||||
val items = (constantValue as ArrayValue).value.map { evalConstantValue(it) }
|
||||
items.singleOrNull() ?: items
|
||||
} else constantValue.value
|
||||
}
|
||||
@@ -47,7 +47,7 @@ class KotlinLightConstantExpressionEvaluator : ConstantExpressionEvaluator {
|
||||
auxEvaluator: PsiConstantEvaluationHelper.AuxEvaluator?
|
||||
): Any? {
|
||||
val expressionToCompute = when (expression) {
|
||||
is KtLightElementBase -> expression.kotlinOrigin as? KtExpression ?: return null
|
||||
is KtLightElementBase -> (expression as KtLightElementBase).kotlinOrigin as? KtExpression ?: return null
|
||||
else -> return null
|
||||
}
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@ class KotlinPairMatcher : PairedBraceMatcher {
|
||||
override fun getCodeConstructStart(file: PsiFile, openingBraceOffset: Int): Int {
|
||||
val element = file.findElementAt(openingBraceOffset)
|
||||
if (element == null || element is PsiFile) return openingBraceOffset
|
||||
val parent = element.parent
|
||||
val parent = element!!.parent
|
||||
return when (parent) {
|
||||
is KtClassBody, is KtBlockExpression ->
|
||||
DeclarationRangeUtil.getPossibleDeclarationAtRange(parent.parent)?.startOffset ?: openingBraceOffset
|
||||
|
||||
@@ -64,7 +64,7 @@ sealed class PluginUpdateStatus {
|
||||
return other
|
||||
}
|
||||
is Update -> {
|
||||
if (VersionComparatorUtil.compare(other.pluginDescriptor.version, pluginDescriptor.version) > 0) {
|
||||
if (VersionComparatorUtil.compare((other as Update).pluginDescriptor.version, pluginDescriptor.version) > 0) {
|
||||
return other
|
||||
}
|
||||
}
|
||||
@@ -105,8 +105,8 @@ class KotlinPluginUpdater(private val propertiesComponent: PropertiesComponent)
|
||||
if (lastUpdateTime == 0L || System.currentTimeMillis() - lastUpdateTime > CACHED_REQUEST_DELAY) {
|
||||
queueUpdateCheck { updateStatus ->
|
||||
when (updateStatus) {
|
||||
is PluginUpdateStatus.Update -> notifyPluginUpdateAvailable(updateStatus)
|
||||
is PluginUpdateStatus.CheckFailed -> LOG.info("Plugin update check failed: ${updateStatus.message}, details: ${updateStatus.detail}")
|
||||
is PluginUpdateStatus.Update -> notifyPluginUpdateAvailable(updateStatus as PluginUpdateStatus.Update)
|
||||
is PluginUpdateStatus.CheckFailed -> LOG.info("Plugin update check failed: ${(updateStatus as PluginUpdateStatus.CheckFailed).message}, details: ${(updateStatus as PluginUpdateStatus.CheckFailed).detail}")
|
||||
}
|
||||
true
|
||||
}
|
||||
@@ -131,9 +131,9 @@ class KotlinPluginUpdater(private val propertiesComponent: PropertiesComponent)
|
||||
fun runCachedUpdate(callback: (PluginUpdateStatus) -> Boolean) {
|
||||
ApplicationManager.getApplication().assertIsDispatchThread()
|
||||
val cachedStatus = lastUpdateStatus
|
||||
if (cachedStatus != null && System.currentTimeMillis() - cachedStatus.timestamp < CACHED_REQUEST_DELAY) {
|
||||
if (cachedStatus != null && System.currentTimeMillis() - cachedStatus!!.timestamp < CACHED_REQUEST_DELAY) {
|
||||
if (cachedStatus !is PluginUpdateStatus.CheckFailed) {
|
||||
callback(cachedStatus)
|
||||
callback(cachedStatus!!)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -162,7 +162,7 @@ class KotlinPluginUpdater(private val propertiesComponent: PropertiesComponent)
|
||||
checkQueued = false
|
||||
|
||||
if (updateStatus is PluginUpdateStatus.Update) {
|
||||
updateStatus = verify(updateStatus)
|
||||
updateStatus = verify(updateStatus as PluginUpdateStatus.Update)
|
||||
}
|
||||
|
||||
if (updateStatus !is PluginUpdateStatus.CheckFailed) {
|
||||
|
||||
@@ -88,7 +88,7 @@ class HtmlClassifierNamePolicy(val base: ClassifierNamePolicy) : ClassifierNameP
|
||||
supertypes.joinTo(this) {
|
||||
val ref = it.constructor.declarationDescriptor
|
||||
if (ref != null)
|
||||
renderClassifier(ref, renderer)
|
||||
renderClassifier(ref!!, renderer)
|
||||
else
|
||||
"<ERROR CLASS>"
|
||||
}
|
||||
@@ -152,7 +152,7 @@ class KotlinQuickDocumentationProvider : AbstractDocumentationProvider() {
|
||||
}
|
||||
|
||||
override fun getQuickNavigateInfo(element: PsiElement?, originalElement: PsiElement?): String? {
|
||||
return if (element == null) null else getText(element, originalElement, true)
|
||||
return if (element == null) null else getText(element!!, originalElement, true)
|
||||
}
|
||||
|
||||
override fun generateDoc(element: PsiElement, originalElement: PsiElement?): String? {
|
||||
@@ -173,8 +173,8 @@ class KotlinQuickDocumentationProvider : AbstractDocumentationProvider() {
|
||||
|
||||
override fun getDocumentationElementForLookupItem(psiManager: PsiManager, `object`: Any?, element: PsiElement?): PsiElement? {
|
||||
if (`object` is DeclarationLookupObject) {
|
||||
`object`.psiElement?.let { return it }
|
||||
`object`.descriptor?.let { descriptor ->
|
||||
(`object` as DeclarationLookupObject).psiElement?.let { return it }
|
||||
(`object` as DeclarationLookupObject).descriptor?.let { descriptor ->
|
||||
return DescriptorToSourceUtilsIde.getAnyDeclaration(psiManager.project, descriptor)
|
||||
}
|
||||
}
|
||||
@@ -220,10 +220,10 @@ class KotlinQuickDocumentationProvider : AbstractDocumentationProvider() {
|
||||
description {
|
||||
insert(DescriptionBodyTemplate.Kotlin()) {
|
||||
content {
|
||||
appendKDocContent(section)
|
||||
appendKDocContent(section!!)
|
||||
}
|
||||
sections {
|
||||
appendKDocSection(section)
|
||||
appendKDocSection(section!!)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -239,11 +239,11 @@ class KotlinQuickDocumentationProvider : AbstractDocumentationProvider() {
|
||||
// When caret on special enum function (e.g SomeEnum.values<caret>())
|
||||
// element is not an KtReferenceExpression, but KtClass of enum
|
||||
// so reference extracted from originalElement
|
||||
val context = referenceExpression.analyze(BodyResolveMode.PARTIAL)
|
||||
val context = referenceExpression!!.analyze(BodyResolveMode.PARTIAL)
|
||||
(context[BindingContext.REFERENCE_TARGET, referenceExpression]
|
||||
?: context[BindingContext.REFERENCE_TARGET, referenceExpression.getChildOfType<KtReferenceExpression>()])?.let {
|
||||
?: context[BindingContext.REFERENCE_TARGET, referenceExpression!!.getChildOfType<KtReferenceExpression>()])?.let {
|
||||
if (it is FunctionDescriptor) // To protect from Some<caret>Enum.values()
|
||||
return renderEnumSpecialFunction(element, it, quickNavigation)
|
||||
return renderEnumSpecialFunction(element, it as FunctionDescriptor, quickNavigation)
|
||||
}
|
||||
}
|
||||
return renderKotlinDeclaration(element, quickNavigation)
|
||||
@@ -265,13 +265,13 @@ class KotlinQuickDocumentationProvider : AbstractDocumentationProvider() {
|
||||
val itElement = findElementWithText(originalElement, "it")
|
||||
val itReference = itElement?.getParentOfType<KtNameReferenceExpression>(false)
|
||||
if (itReference != null) {
|
||||
return getTextImpl(itReference, originalElement, quickNavigation)
|
||||
return getTextImpl(itReference!!, originalElement, quickNavigation)
|
||||
}
|
||||
}
|
||||
|
||||
if (element is KtTypeReference) {
|
||||
val declaration = element.parent
|
||||
if (declaration is KtCallableDeclaration && declaration.receiverTypeReference == element) {
|
||||
val declaration = (element as KtTypeReference).parent
|
||||
if (declaration is KtCallableDeclaration && (declaration as KtCallableDeclaration).receiverTypeReference == element) {
|
||||
val thisElement = findElementWithText(originalElement, "this")
|
||||
if (thisElement != null) {
|
||||
return getTextImpl(declaration, originalElement, quickNavigation)
|
||||
@@ -279,15 +279,17 @@ class KotlinQuickDocumentationProvider : AbstractDocumentationProvider() {
|
||||
}
|
||||
}
|
||||
|
||||
if (element is KtClass && element.isEnum()) {
|
||||
if (element is KtClass && (element as KtClass).isEnum()) {
|
||||
// When caret on special enum function (e.g SomeEnum.values<caret>())
|
||||
// element is not an KtReferenceExpression, but KtClass of enum
|
||||
return renderEnum(element, originalElement, quickNavigation)
|
||||
return renderEnum(element as KtClass, originalElement, quickNavigation)
|
||||
} else if (element is KtEnumEntry && !quickNavigation) {
|
||||
val ordinal = element.containingClassOrObject?.getBody()?.run { getChildrenOfType<KtEnumEntry>().indexOf(element) }
|
||||
val ordinal = (element as KtEnumEntry).containingClassOrObject?.getBody()?.run { getChildrenOfType<KtEnumEntry>().indexOf(
|
||||
element as KtEnumEntry
|
||||
) }
|
||||
|
||||
return buildString {
|
||||
insert(buildKotlinDeclaration(element, quickNavigation)) {
|
||||
insert(buildKotlinDeclaration(element as KtEnumEntry, quickNavigation)) {
|
||||
definition {
|
||||
it.inherit()
|
||||
ordinal?.let {
|
||||
@@ -297,11 +299,11 @@ class KotlinQuickDocumentationProvider : AbstractDocumentationProvider() {
|
||||
}
|
||||
}
|
||||
} else if (element is KtDeclaration) {
|
||||
return renderKotlinDeclaration(element, quickNavigation)
|
||||
} else if (element is KtNameReferenceExpression && element.getReferencedName() == "it") {
|
||||
return renderKotlinImplicitLambdaParameter(element, quickNavigation)
|
||||
return renderKotlinDeclaration(element as KtDeclaration, quickNavigation)
|
||||
} else if (element is KtNameReferenceExpression && (element as KtNameReferenceExpression).getReferencedName() == "it") {
|
||||
return renderKotlinImplicitLambdaParameter(element as KtNameReferenceExpression, quickNavigation)
|
||||
} else if (element is KtLightDeclaration<*, *>) {
|
||||
val origin = element.kotlinOrigin ?: return null
|
||||
val origin = (element as KtLightDeclaration<*, *>).kotlinOrigin ?: return null
|
||||
return renderKotlinDeclaration(origin, quickNavigation)
|
||||
} else if (element.isModifier()) {
|
||||
when(element.text) {
|
||||
@@ -322,10 +324,10 @@ class KotlinQuickDocumentationProvider : AbstractDocumentationProvider() {
|
||||
if (quickNavigation) {
|
||||
val referenceExpression = originalElement?.getNonStrictParentOfType<KtReferenceExpression>()
|
||||
if (referenceExpression != null) {
|
||||
val context = referenceExpression.analyze(BodyResolveMode.PARTIAL)
|
||||
val context = referenceExpression!!.analyze(BodyResolveMode.PARTIAL)
|
||||
val declarationDescriptor = context[BindingContext.REFERENCE_TARGET, referenceExpression]
|
||||
if (declarationDescriptor != null) {
|
||||
return mixKotlinToJava(declarationDescriptor, element, originalElement)
|
||||
return mixKotlinToJava(declarationDescriptor!!, element, originalElement)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -352,7 +354,7 @@ class KotlinQuickDocumentationProvider : AbstractDocumentationProvider() {
|
||||
}
|
||||
}
|
||||
|
||||
return buildKotlin(context, declarationDescriptor, quickNavigation, declaration)
|
||||
return buildKotlin(context, declarationDescriptor!!, quickNavigation, declaration)
|
||||
}
|
||||
|
||||
private fun renderKotlinImplicitLambdaParameter(element: KtReferenceExpression, quickNavigation: Boolean): String? {
|
||||
@@ -379,9 +381,9 @@ class KotlinQuickDocumentationProvider : AbstractDocumentationProvider() {
|
||||
@Suppress("NAME_SHADOWING")
|
||||
var declarationDescriptor = declarationDescriptor
|
||||
if (declarationDescriptor is ValueParameterDescriptor) {
|
||||
val property = context[BindingContext.VALUE_PARAMETER_AS_PROPERTY, declarationDescriptor]
|
||||
val property = context[BindingContext.VALUE_PARAMETER_AS_PROPERTY, declarationDescriptor as ValueParameterDescriptor]
|
||||
if (property != null) {
|
||||
declarationDescriptor = property
|
||||
declarationDescriptor = property!!
|
||||
}
|
||||
}
|
||||
|
||||
@@ -400,10 +402,10 @@ class KotlinQuickDocumentationProvider : AbstractDocumentationProvider() {
|
||||
if (comment != null) {
|
||||
insert(DescriptionBodyTemplate.Kotlin()) {
|
||||
content {
|
||||
appendKDocContent(comment)
|
||||
appendKDocContent(comment!!)
|
||||
}
|
||||
sections {
|
||||
if (comment is KDocSection) appendKDocSection(comment)
|
||||
if (comment is KDocSection) appendKDocSection(comment as KDocSection)
|
||||
}
|
||||
}
|
||||
} else if (declarationDescriptor is CallableDescriptor) { // If we couldn't find KDoc, try to find javadoc in one of super's
|
||||
@@ -420,7 +422,7 @@ class KotlinQuickDocumentationProvider : AbstractDocumentationProvider() {
|
||||
if (!DescriptorUtils.isLocal(descriptor)) {
|
||||
val containingDeclaration = descriptor.containingDeclaration
|
||||
if (containingDeclaration != null) {
|
||||
val fqName = containingDeclaration.fqNameSafe
|
||||
val fqName = containingDeclaration!!.fqNameSafe
|
||||
if (!fqName.isRoot) {
|
||||
DocumentationManagerUtil.createHyperlink(this, fqName.asString(), fqName.asString(), false)
|
||||
}
|
||||
@@ -524,8 +526,8 @@ class KotlinQuickDocumentationProvider : AbstractDocumentationProvider() {
|
||||
private fun findElementWithText(element: PsiElement?, text: String): PsiElement? {
|
||||
return when {
|
||||
element == null -> null
|
||||
element.text == text -> element
|
||||
element.prevLeaf()?.text == text -> element.prevLeaf()
|
||||
element!!.text == text -> element
|
||||
element!!.prevLeaf()?.text == text -> element!!.prevLeaf()
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,13 +57,13 @@ fun KtFile.canBeDecompiledToJava() = isCompiled && virtualFile?.fileType == Java
|
||||
// Add action to "Attach sources" notification panel
|
||||
class DecompileKotlinToJavaActionProvider : AttachSourcesProvider {
|
||||
override fun getActions(orderEntries: MutableList<LibraryOrderEntry>, psiFile: PsiFile): Collection<AttachSourcesProvider.AttachSourcesAction> {
|
||||
if (psiFile !is KtFile || !psiFile.canBeDecompiledToJava()) return emptyList()
|
||||
if (psiFile !is KtFile || !(psiFile as KtFile).canBeDecompiledToJava()) return emptyList()
|
||||
|
||||
return listOf(object : AttachSourcesProvider.AttachSourcesAction {
|
||||
override fun getName() = "Decompile to Java"
|
||||
|
||||
override fun perform(orderEntriesContainingFile: List<LibraryOrderEntry>?): ActionCallback {
|
||||
showDecompiledCode(psiFile)
|
||||
showDecompiledCode(psiFile as KtFile)
|
||||
return ActionCallback.DONE
|
||||
}
|
||||
|
||||
|
||||
@@ -84,8 +84,8 @@ class JavaToKotlinAction : AnAction() {
|
||||
MessagesEx.error(psiFile.project, "Failed to save conversion result: couldn't find document for " + psiFile.name).showLater()
|
||||
continue
|
||||
}
|
||||
document.replaceString(0, document.textLength, text)
|
||||
FileDocumentManager.getInstance().saveDocument(document)
|
||||
document!!.replaceString(0, document!!.textLength, text)
|
||||
FileDocumentManager.getInstance().saveDocument(document!!)
|
||||
|
||||
val virtualFile = psiFile.virtualFile
|
||||
if (ScratchRootType.getInstance().containsFile(virtualFile)) {
|
||||
@@ -186,7 +186,7 @@ class JavaToKotlinAction : AnAction() {
|
||||
|
||||
if (firstSyntaxError != null) {
|
||||
val count = javaFiles.filter { PsiTreeUtil.hasErrorElements(it) }.count()
|
||||
val question = firstSyntaxError.containingFile.name +
|
||||
val question = firstSyntaxError!!.containingFile.name +
|
||||
(if (count > 1) " and ${count - 1} more Java files" else " file") +
|
||||
" contain syntax errors, the conversion result may be incorrect"
|
||||
|
||||
@@ -200,7 +200,7 @@ class JavaToKotlinAction : AnAction() {
|
||||
cancelText,
|
||||
Messages.getWarningIcon()
|
||||
) == Messages.OK) {
|
||||
NavigationUtil.activateFileWithPsiElement(firstSyntaxError.navigationElement)
|
||||
NavigationUtil.activateFileWithPsiElement(firstSyntaxError!!.navigationElement)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,11 +169,11 @@ class KotlinAddImportAction internal constructor(
|
||||
if (selectedValue == null || project.isDisposed) return null
|
||||
|
||||
if (finalChoice) {
|
||||
addImport(selectedValue)
|
||||
addImport(selectedValue!!)
|
||||
return null
|
||||
}
|
||||
|
||||
val toExclude = AddImportAction.getAllExcludableStrings(selectedValue.excludeFqNameCheck.asString())
|
||||
val toExclude = AddImportAction.getAllExcludableStrings(selectedValue!!.excludeFqNameCheck.asString())
|
||||
|
||||
return object : BaseListPopupStep<String>(null, toExclude) {
|
||||
override fun getTextFor(value: String): String {
|
||||
@@ -217,7 +217,7 @@ class KotlinAddImportAction internal constructor(
|
||||
if (importAlias != null || descriptor is ClassDescriptor || descriptor is PackageViewDescriptor) {
|
||||
if (element is KtSimpleNameExpression) {
|
||||
if (importAlias != null) {
|
||||
importAlias.nameIdentifier?.copy()?.let { element.getIdentifier()?.replace(it) }
|
||||
importAlias!!.nameIdentifier?.copy()?.let { (element as KtSimpleNameExpression).getIdentifier()?.replace(it) }
|
||||
val resultDescriptor = element.resolveMainReferenceToDescriptors().firstOrNull()
|
||||
if (descriptor.importableFqName == resultDescriptor?.importableFqName) {
|
||||
return@forEach
|
||||
@@ -225,7 +225,7 @@ class KotlinAddImportAction internal constructor(
|
||||
}
|
||||
|
||||
descriptor.importableFqName?.let {
|
||||
element.mainReference.bindToFqName(
|
||||
(element as KtSimpleNameExpression).mainReference.bindToFqName(
|
||||
it,
|
||||
KtSimpleNameReference.ShorteningMode.FORCED_SHORTENING
|
||||
)
|
||||
|
||||
@@ -34,7 +34,7 @@ class KotlinCreateFromTemplateHandler : DefaultCreateFromTemplateHandler() {
|
||||
|
||||
val name = props[FileTemplate.ATTRIBUTE_NAME] as? String
|
||||
if (name != null) {
|
||||
props[FileTemplate.ATTRIBUTE_NAME] = name.quoteIfNeeded()
|
||||
props[FileTemplate.ATTRIBUTE_NAME] = name!!.quoteIfNeeded()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,11 +30,11 @@ class KotlinQualifiedNameProvider: QualifiedNameProvider {
|
||||
override fun adjustElementToCopy(element: PsiElement?) = null
|
||||
|
||||
override fun getQualifiedName(element: PsiElement?) = when(element) {
|
||||
is KtClassOrObject -> element.fqName?.asString()
|
||||
is KtNamedFunction -> getJavaQualifiedName(LightClassUtil.getLightClassMethod(element))
|
||||
is KtClassOrObject -> (element as KtClassOrObject).fqName?.asString()
|
||||
is KtNamedFunction -> getJavaQualifiedName(LightClassUtil.getLightClassMethod(element as KtNamedFunction))
|
||||
|
||||
is KtProperty -> {
|
||||
val lightClassPropertyMethods = LightClassUtil.getLightClassPropertyMethods(element)
|
||||
val lightClassPropertyMethods = LightClassUtil.getLightClassPropertyMethods(element as KtProperty)
|
||||
val lightElement: PsiElement? = lightClassPropertyMethods.getter ?: lightClassPropertyMethods.backingField
|
||||
getJavaQualifiedName(lightElement)
|
||||
}
|
||||
|
||||
@@ -64,16 +64,16 @@ class NewKotlinFileAction : CreateFileFromTemplateAction(
|
||||
if (createdElement is KtFile) {
|
||||
if (module != null) {
|
||||
for (hook in NewKotlinFileHook.EP_NAME.extensions) {
|
||||
hook.postProcess(createdElement, module)
|
||||
hook.postProcess(createdElement as KtFile, module!!)
|
||||
}
|
||||
}
|
||||
|
||||
val ktClass = createdElement.declarations.singleOrNull() as? KtNamedDeclaration
|
||||
val ktClass = (createdElement as KtFile).declarations.singleOrNull() as? KtNamedDeclaration
|
||||
if (ktClass != null) {
|
||||
CreateFromTemplateAction.moveCaretAfterNameIdentifier(ktClass)
|
||||
} else {
|
||||
val editor = FileEditorManager.getInstance(createdElement.project).selectedTextEditor ?: return
|
||||
if (editor.document == createdElement.viewProvider.document) {
|
||||
val editor = FileEditorManager.getInstance((createdElement as KtFile).project).selectedTextEditor ?: return
|
||||
if (editor.document == (createdElement as KtFile).viewProvider.document) {
|
||||
val lineCount = editor.document.lineCount
|
||||
if (lineCount > 0) {
|
||||
editor.caretModel.moveToLogicalPosition(LogicalPosition(lineCount - 1, 0))
|
||||
@@ -208,10 +208,10 @@ class NewKotlinFileAction : CreateFileFromTemplateAction(
|
||||
try {
|
||||
val psiFile = createFromTemplate(targetDir, className, template)
|
||||
if (psiFile is KtFile) {
|
||||
val singleClass = psiFile.declarations.singleOrNull() as? KtClass
|
||||
if (singleClass != null && !singleClass.isEnum() && !singleClass.isInterface() && name.contains("Abstract")) {
|
||||
val singleClass = (psiFile as KtFile).declarations.singleOrNull() as? KtClass
|
||||
if (singleClass != null && !singleClass!!.isEnum() && !singleClass!!.isInterface() && name.contains("Abstract")) {
|
||||
runWriteAction {
|
||||
singleClass.addModifier(KtTokens.ABSTRACT_KEYWORD)
|
||||
singleClass!!.addModifier(KtTokens.ABSTRACT_KEYWORD)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ class NewKotlinScriptAction : CreateFileFromTemplateAction(
|
||||
val module = ModuleUtilCore.findModuleForPsiElement(createdElement)
|
||||
|
||||
if (createdElement is KtFile && module != null) {
|
||||
NewKotlinFileHook.EP_NAME.extensions.forEach { it.postProcess(createdElement, module) }
|
||||
NewKotlinFileHook.EP_NAME.extensions.forEach { it.postProcess(createdElement as KtFile, module!!) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -41,12 +41,12 @@ abstract class KotlinGenerateActionBase : CodeInsightAction(), CodeInsightAction
|
||||
super.update(presentation, project, editor, file, dataContext, actionPlace)
|
||||
val actionHandler = handler
|
||||
if (actionHandler is ContextAwareActionHandler && presentation.isEnabled) {
|
||||
presentation.isEnabled = actionHandler.isAvailableForQuickList(editor, file, dataContext)
|
||||
presentation.isEnabled = (actionHandler as ContextAwareActionHandler).isAvailableForQuickList(editor, file, dataContext)
|
||||
}
|
||||
}
|
||||
|
||||
override fun isValidForFile(project: Project, editor: Editor, file: PsiFile): Boolean {
|
||||
if (file !is KtFile || file.isCompiled) return false
|
||||
if (file !is KtFile || (file as KtFile).isCompiled) return false
|
||||
|
||||
val targetClass = getTargetClass(editor, file) ?: return false
|
||||
return targetClass.canRefactor() && isValidForClass(targetClass)
|
||||
|
||||
@@ -79,9 +79,9 @@ class KotlinGenerateEqualsAndHashcodeAction : KotlinGenerateMemberActionBase<Kot
|
||||
override fun isValidForClass(targetClass: KtClassOrObject): Boolean {
|
||||
return targetClass is KtClass
|
||||
&& targetClass !is KtEnumEntry
|
||||
&& !targetClass.isEnum()
|
||||
&& !(targetClass as KtClass).isEnum()
|
||||
&& !targetClass.isAnnotation()
|
||||
&& !targetClass.isInterface()
|
||||
&& !(targetClass as KtClass).isInterface()
|
||||
}
|
||||
|
||||
override fun prepareMembersInfo(klass: KtClassOrObject, project: Project, editor: Editor?): Info? {
|
||||
@@ -96,12 +96,12 @@ class KotlinGenerateEqualsAndHashcodeAction : KotlinGenerateMemberActionBase<Kot
|
||||
var needEquals = equalsDescriptor == null
|
||||
var needHashCode = hashCodeDescriptor == null
|
||||
if (!needEquals && !needHashCode) {
|
||||
if (!confirmMemberRewrite(klass, equalsDescriptor!!, hashCodeDescriptor!!)) return null
|
||||
if (!confirmMemberRewrite(klass as KtClass, equalsDescriptor!!, hashCodeDescriptor!!)) return null
|
||||
|
||||
runWriteAction {
|
||||
try {
|
||||
equalsDescriptor.source.getPsi()?.delete()
|
||||
hashCodeDescriptor.source.getPsi()?.delete()
|
||||
equalsDescriptor!!.source.getPsi()?.delete()
|
||||
hashCodeDescriptor!!.source.getPsi()?.delete()
|
||||
needEquals = true
|
||||
needHashCode = true
|
||||
} catch (e: IncorrectOperationException) {
|
||||
@@ -117,7 +117,7 @@ class KotlinGenerateEqualsAndHashcodeAction : KotlinGenerateMemberActionBase<Kot
|
||||
return Info(needEquals, needHashCode, classDescriptor, descriptors, descriptors)
|
||||
}
|
||||
|
||||
return with(KotlinGenerateEqualsWizard(project, klass, properties, needEquals, needHashCode)) {
|
||||
return with(KotlinGenerateEqualsWizard(project, klass as KtClass, properties, needEquals, needHashCode)) {
|
||||
if (!klass.hasExpectModifier() && !showAndGet()) return null
|
||||
|
||||
Info(needEquals,
|
||||
|
||||
@@ -49,7 +49,7 @@ abstract class KotlinGenerateMemberActionBase<Info : Any> : KotlinGenerateAction
|
||||
val newMembers = generateMembers(project, editor, membersInfo)
|
||||
GlobalInspectionContextBase.cleanupElements(project, null, *newMembers.toTypedArray())
|
||||
if (editor != null) {
|
||||
newMembers.firstOrNull()?.let { GenerateMembersUtil.positionCaret(editor, it, false) }
|
||||
newMembers.firstOrNull()?.let { GenerateMembersUtil.positionCaret(editor!!, it, false) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,12 +61,12 @@ class KotlinGenerateSecondaryConstructorAction : KotlinGenerateMemberActionBase<
|
||||
override fun isValidForClass(targetClass: KtClassOrObject): Boolean {
|
||||
return targetClass is KtClass
|
||||
&& targetClass !is KtEnumEntry
|
||||
&& !targetClass.isInterface()
|
||||
&& !(targetClass as KtClass).isInterface()
|
||||
&& !targetClass.isAnnotation()
|
||||
&& !targetClass.hasExplicitPrimaryConstructor()
|
||||
}
|
||||
|
||||
private fun shouldPreselect(element: PsiElement) = element is KtProperty && !element.isVar
|
||||
private fun shouldPreselect(element: PsiElement) = element is KtProperty && !(element as KtProperty).isVar
|
||||
|
||||
private fun chooseSuperConstructors(klass: KtClassOrObject, classDescriptor: ClassDescriptor): List<DescriptorMemberChooserObject> {
|
||||
val project = klass.project
|
||||
@@ -164,10 +164,10 @@ class KotlinGenerateSecondaryConstructorAction : KotlinGenerateMemberActionBase<
|
||||
val parameterList = constructor.valueParameterList!!
|
||||
|
||||
if (superConstructor != null) {
|
||||
val substitutor = getTypeSubstitutor(superConstructor.containingDeclaration.defaultType, classDescriptor.defaultType)
|
||||
val substitutor = getTypeSubstitutor(superConstructor!!.containingDeclaration.defaultType, classDescriptor.defaultType)
|
||||
?: TypeSubstitutor.EMPTY
|
||||
val delegationCallArguments = ArrayList<String>()
|
||||
for (parameter in superConstructor.valueParameters) {
|
||||
for (parameter in superConstructor!!.valueParameters) {
|
||||
val isVararg = parameter.varargElementType != null
|
||||
|
||||
val paramName = KotlinNameSuggester.suggestNameByName(parameter.name.asString(), validator)
|
||||
|
||||
@@ -105,7 +105,7 @@ abstract class KotlinGenerateTestSupportActionBase(
|
||||
class Data : KotlinGenerateTestSupportActionBase(MethodKind.DATA) {
|
||||
override fun isApplicableTo(framework: TestFramework, targetClass: KtClassOrObject): Boolean {
|
||||
if (framework !is JavaTestFramework) return false
|
||||
return framework.findParametersMethod(targetClass.toLightClass()) == null
|
||||
return (framework as JavaTestFramework).findParametersMethod(targetClass.toLightClass()) == null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -128,7 +128,7 @@ class KotlinGenerateToStringAction : KotlinGenerateMemberActionBase<KotlinGenera
|
||||
}
|
||||
|
||||
override fun isValidForClass(targetClass: KtClassOrObject): Boolean =
|
||||
targetClass is KtClass && !targetClass.isAnnotation() && !targetClass.isInterface()
|
||||
targetClass is KtClass && !targetClass.isAnnotation() && !(targetClass as KtClass).isInterface()
|
||||
|
||||
override fun prepareMembersInfo(klass: KtClassOrObject, project: Project, editor: Editor?): Info? {
|
||||
if (klass !is KtClass) throw AssertionError("Not a class: ${klass.getElementTextWithContext()}")
|
||||
@@ -137,7 +137,7 @@ class KotlinGenerateToStringAction : KotlinGenerateMemberActionBase<KotlinGenera
|
||||
val classDescriptor = context.get(BindingContext.CLASS, klass) ?: return null
|
||||
|
||||
classDescriptor.findDeclaredToString(false)?.let {
|
||||
if (!confirmMemberRewrite(klass, it)) return null
|
||||
if (!confirmMemberRewrite(klass as KtClass, it)) return null
|
||||
|
||||
runWriteAction {
|
||||
try {
|
||||
@@ -157,7 +157,7 @@ class KotlinGenerateToStringAction : KotlinGenerateMemberActionBase<KotlinGenera
|
||||
Generator.SINGLE_TEMPLATE,
|
||||
project
|
||||
)
|
||||
return klass.adjuster?.let { it(info) } ?: info
|
||||
return (klass as KtClass).adjuster?.let { it(info) } ?: info
|
||||
}
|
||||
|
||||
val superToString = classDescriptor.getSuperClassOrAny().findDeclaredToString(true)!!
|
||||
|
||||
@@ -53,7 +53,7 @@ fun getPropertiesToUseInGeneratedMember(classOrObject: KtClassOrObject): List<Kt
|
||||
val descriptor = it.unsafeResolveToDescriptor()
|
||||
when (descriptor) {
|
||||
is ValueParameterDescriptor -> true
|
||||
is PropertyDescriptor -> descriptor.getter?.isDefault ?: true
|
||||
is PropertyDescriptor -> (descriptor as PropertyDescriptor).getter?.isDefault ?: true
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,11 +70,11 @@ class CheckComponentsUsageSearchAction : AnAction() {
|
||||
ProgressManager.getInstance().runProcess({
|
||||
ExpressionsOfTypeProcessor.mode = ExpressionsOfTypeProcessor.Mode.ALWAYS_SMART
|
||||
|
||||
smartRefsCount = ReferencesSearch.search(parameter).findAll().size
|
||||
smartRefsCount = ReferencesSearch.search(parameter!!).findAll().size
|
||||
|
||||
ExpressionsOfTypeProcessor.mode = ExpressionsOfTypeProcessor.Mode.ALWAYS_PLAIN
|
||||
|
||||
goldRefsCount = ReferencesSearch.search(parameter).findAll().size
|
||||
goldRefsCount = ReferencesSearch.search(parameter!!).findAll().size
|
||||
}, EmptyProgressIndicator())
|
||||
|
||||
if (smartRefsCount != goldRefsCount) {
|
||||
|
||||
@@ -38,7 +38,7 @@ class CopyAsDiagnosticTestAction : AnAction() {
|
||||
// Parameters `languageVersionSettings`, `dataFlowValueFactory` and `moduleDescriptor` are not-null only for compiler diagnostic tests
|
||||
val diagnostics = CheckerTestUtil.getDiagnosticsIncludingSyntaxErrors(
|
||||
bindingContext,
|
||||
psiFile,
|
||||
psiFile as KtFile,
|
||||
false,
|
||||
mutableListOf(),
|
||||
null,
|
||||
@@ -47,7 +47,7 @@ class CopyAsDiagnosticTestAction : AnAction() {
|
||||
null,
|
||||
null
|
||||
)
|
||||
val result = CheckerTestUtil.addDiagnosticMarkersToText(psiFile, diagnostics).toString()
|
||||
val result = CheckerTestUtil.addDiagnosticMarkersToText(psiFile as KtFile, diagnostics).toString()
|
||||
|
||||
val clipboard = Toolkit.getDefaultToolkit().systemClipboard
|
||||
clipboard.setContents(StringSelection(result)) { _, _ -> }
|
||||
|
||||
@@ -38,7 +38,7 @@ class DumbModeTrembleAction: DumbAwareAction() {
|
||||
return
|
||||
}
|
||||
|
||||
val isTrembleDumb = isTrembleDumb(project)
|
||||
val isTrembleDumb = isTrembleDumb(project!!)
|
||||
e.presentation.text = if (isTrembleDumb) "Disable Tremble Dumb Mode" else "Enable Tremble Dumb Mode"
|
||||
}
|
||||
|
||||
|
||||
@@ -114,10 +114,10 @@ class FindImplicitNothingAction : AnAction() {
|
||||
val callee = getCalleeExpressionIfAny() ?: return false
|
||||
when (callee) {
|
||||
is KtSimpleNameExpression -> {
|
||||
val target = bindingContext[BindingContext.REFERENCE_TARGET, callee] ?: return false
|
||||
val target = bindingContext[BindingContext.REFERENCE_TARGET, callee as KtSimpleNameExpression] ?: return false
|
||||
val callableDescriptor = (target as? CallableDescriptor ?: return false).original
|
||||
val declaration = DescriptorToSourceUtils.descriptorToDeclaration(callableDescriptor) as? KtCallableDeclaration
|
||||
if (declaration != null && declaration.typeReference == null) return false // implicit type
|
||||
if (declaration != null && declaration!!.typeReference == null) return false // implicit type
|
||||
val type = callableDescriptor.returnType ?: return false
|
||||
return type.isNothingOrNothingFunctionType()
|
||||
}
|
||||
|
||||
@@ -75,18 +75,18 @@ class SearchNotPropertyCandidatesAction : AnAction() {
|
||||
progress("Step 1: Collecting ${processed.size}:$pFunctions:${matchedDescriptors.size}", "$desc")
|
||||
when (desc) {
|
||||
|
||||
is ModuleDescriptor -> recursive(desc.getPackage(FqName("java")))
|
||||
is ClassDescriptor -> desc.unsubstitutedMemberScope.getContributedDescriptors { true }.forEach(::recursive)
|
||||
is PackageViewDescriptor -> desc.memberScope.getContributedDescriptors { true }.forEach(::recursive)
|
||||
is ModuleDescriptor -> recursive((desc as ModuleDescriptor).getPackage(FqName("java")))
|
||||
is ClassDescriptor -> (desc as ClassDescriptor).unsubstitutedMemberScope.getContributedDescriptors { true }.forEach(::recursive)
|
||||
is PackageViewDescriptor -> (desc as PackageViewDescriptor).memberScope.getContributedDescriptors { true }.forEach(::recursive)
|
||||
|
||||
is FunctionDescriptor -> {
|
||||
if (desc.isFromJava) {
|
||||
if ((desc as FunctionDescriptor).isFromJava) {
|
||||
val name = desc.fqNameUnsafe.shortName().asString()
|
||||
if (name.length > 3 &&
|
||||
((name.startsWith("get") && desc.valueParameters.isEmpty() && desc.returnType != null) ||
|
||||
(name.startsWith("set") && desc.valueParameters.size == 1))) {
|
||||
if (desc in matchedDescriptors) return
|
||||
matchedDescriptors += desc
|
||||
((name.startsWith("get") && (desc as FunctionDescriptor).valueParameters.isEmpty() && (desc as FunctionDescriptor).returnType != null) ||
|
||||
(name.startsWith("set") && (desc as FunctionDescriptor).valueParameters.size == 1))) {
|
||||
if (desc as FunctionDescriptor in matchedDescriptors) return
|
||||
matchedDescriptors += desc as FunctionDescriptor
|
||||
}
|
||||
}
|
||||
pFunctions++
|
||||
@@ -138,7 +138,7 @@ class SearchNotPropertyCandidatesAction : AnAction() {
|
||||
descriptors.forEach {
|
||||
val source = DescriptorToSourceUtilsIde.getAllDeclarations(project, it).filterIsInstance<PsiMethod>().firstOrNull()
|
||||
if (source != null) {
|
||||
if (source.body != null || source.hasModifierProperty(PsiModifier.ABSTRACT))
|
||||
if (source!!.body != null || source!!.hasModifierProperty(PsiModifier.ABSTRACT))
|
||||
nonTrivial += it
|
||||
impl = true
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ class CallableUsageReplacementStrategy(
|
||||
if (!resolvedCall.status.isSuccess) return null
|
||||
|
||||
val callElement = when (resolvedCall) {
|
||||
is VariableAsFunctionResolvedCall -> resolvedCall.variableCall.call.callElement
|
||||
is VariableAsFunctionResolvedCall -> (resolvedCall as VariableAsFunctionResolvedCall).variableCall.call.callElement
|
||||
else -> resolvedCall.call.callElement
|
||||
|
||||
}
|
||||
@@ -47,7 +47,7 @@ class CallableUsageReplacementStrategy(
|
||||
|
||||
return {
|
||||
if (usage is KtOperationReferenceExpression && usage.getReferencedNameElementType() != KtTokens.IDENTIFIER) {
|
||||
val nameExpression = OperatorToFunctionIntention.convert(usage.parent as KtExpression).second
|
||||
val nameExpression = OperatorToFunctionIntention.convert((usage as KtOperationReferenceExpression).parent as KtExpression).second
|
||||
createReplacer(nameExpression)?.invoke()
|
||||
} else {
|
||||
CodeInliner(usage, bindingContext, resolvedCall, callElement, inlineSetter, replacement).doInline()
|
||||
|
||||
@@ -50,15 +50,15 @@ class ClassUsageReplacementStrategy(
|
||||
|
||||
constructorReplacementStrategy?.createReplacer(usage)?.let { return it }
|
||||
|
||||
when (val parent = usage.parent) {
|
||||
when (val parent = (usage as KtNameReferenceExpression).parent) {
|
||||
is KtUserType -> {
|
||||
if (typeReplacement == null) return null
|
||||
return {
|
||||
val oldArgumentList = parent.typeArgumentList?.copy() as? KtTypeArgumentList
|
||||
val replaced = parent.replaced(typeReplacement)
|
||||
val oldArgumentList = (parent as KtUserType).typeArgumentList?.copy() as? KtTypeArgumentList
|
||||
val replaced = parent.replaced(typeReplacement!!)
|
||||
val newArgumentList = replaced.typeArgumentList
|
||||
if (oldArgumentList != null && oldArgumentList.arguments.size == newArgumentList?.arguments?.size) {
|
||||
newArgumentList.replace(oldArgumentList)
|
||||
if (oldArgumentList != null && oldArgumentList!!.arguments.size == newArgumentList?.arguments?.size) {
|
||||
newArgumentList!!.replace(oldArgumentList!!)
|
||||
}
|
||||
|
||||
ShortenReferences.DEFAULT.process(replaced)
|
||||
@@ -66,10 +66,10 @@ class ClassUsageReplacementStrategy(
|
||||
}
|
||||
|
||||
is KtCallExpression -> {
|
||||
if (usage != parent.calleeExpression) return null
|
||||
if (usage != (parent as KtCallExpression).calleeExpression) return null
|
||||
when {
|
||||
constructorReplacementStrategy == null && typeReplacement != null -> return {
|
||||
replaceConstructorCallWithOtherTypeConstruction(parent)
|
||||
replaceConstructorCallWithOtherTypeConstruction(parent as KtCallExpression)
|
||||
}
|
||||
else -> return null
|
||||
}
|
||||
@@ -77,7 +77,7 @@ class ClassUsageReplacementStrategy(
|
||||
|
||||
else -> {
|
||||
if (typeReplacement != null) {
|
||||
val fqNameStr = typeReplacement.text
|
||||
val fqNameStr = typeReplacement!!.text
|
||||
val fqName = FqName(fqNameStr)
|
||||
|
||||
return {
|
||||
@@ -96,20 +96,20 @@ class ClassUsageReplacementStrategy(
|
||||
.getInstance()[referenceExpression.text, callExpression.project, callExpression.resolveScope]
|
||||
.firstOrNull()
|
||||
|
||||
val replacementTypeArgumentList = typeReplacement.typeArgumentList
|
||||
val replacementTypeArgumentList = typeReplacement!!.typeArgumentList
|
||||
val replacementTypeArgumentCount = classFromReplacement?.typeParameters?.size
|
||||
?: replacementTypeArgumentList?.arguments?.size
|
||||
|
||||
val typeArgumentList = callExpression.typeArgumentList
|
||||
val callDescriptor = callExpression.resolveToCall()
|
||||
?.resultingDescriptor
|
||||
?.let { if (it is TypeAliasConstructorDescriptor) it.underlyingConstructorDescriptor else it }
|
||||
?.let { if (it is TypeAliasConstructorDescriptor) (it as TypeAliasConstructorDescriptor).underlyingConstructorDescriptor else it }
|
||||
val typeArgumentCount = callDescriptor?.typeParametersCount ?: typeArgumentList?.arguments?.size
|
||||
|
||||
if (typeArgumentCount != replacementTypeArgumentCount) {
|
||||
if (replacementTypeArgumentList == null) typeArgumentList?.delete()
|
||||
else callExpression.replaceOrCreateTypeArgumentList(
|
||||
replacementTypeArgumentList.copy() as KtTypeArgumentList
|
||||
replacementTypeArgumentList!!.copy() as KtTypeArgumentList
|
||||
)
|
||||
}
|
||||
|
||||
@@ -117,7 +117,7 @@ class ClassUsageReplacementStrategy(
|
||||
|
||||
val expressionToReplace = callExpression.getQualifiedExpressionForSelectorOrThis()
|
||||
val newExpression = if (typeReplacementQualifierAsExpression != null)
|
||||
factory.createExpressionByPattern("$0.$1", typeReplacementQualifierAsExpression, callExpression)
|
||||
factory.createExpressionByPattern("$0.$1", typeReplacementQualifierAsExpression!!, callExpression)
|
||||
else
|
||||
callExpression
|
||||
|
||||
|
||||
@@ -63,12 +63,12 @@ class CodeInliner<TCallElement : KtElement>(
|
||||
val descriptor = resolvedCall.resultingDescriptor
|
||||
val file = nameExpression.containingKtFile
|
||||
|
||||
val qualifiedElement = if (callElement is KtExpression) callElement.getQualifiedExpressionForSelectorOrThis() else callElement
|
||||
val qualifiedElement = if (callElement is KtExpression) (callElement as KtExpression).getQualifiedExpressionForSelectorOrThis() else callElement
|
||||
val assignment = (qualifiedElement as? KtExpression)
|
||||
?.getAssignmentByLHS()
|
||||
?.takeIf { it.operationToken == KtTokens.EQ }
|
||||
val callableForParameters = if (assignment != null && descriptor is PropertyDescriptor)
|
||||
descriptor.setter?.takeIf { inlineSetter && it.hasBody() } ?: descriptor
|
||||
(descriptor as PropertyDescriptor).setter?.takeIf { inlineSetter && it.hasBody() } ?: descriptor
|
||||
else
|
||||
descriptor
|
||||
val elementToBeReplaced = assignment.takeIf { callableForParameters is PropertySetterDescriptor } ?: qualifiedElement
|
||||
@@ -79,21 +79,21 @@ class CodeInliner<TCallElement : KtElement>(
|
||||
&& !codeToInline.alwaysKeepMainExpression
|
||||
&& assignment == null
|
||||
&& elementToBeReplaced is KtExpression
|
||||
&& !elementToBeReplaced.isUsedAsExpression(bindingContext)
|
||||
&& !(elementToBeReplaced as KtExpression).isUsedAsExpression(bindingContext)
|
||||
&& !codeToInline.mainExpression.shouldKeepValue(usageCount = 0)
|
||||
) {
|
||||
codeToInline.mainExpression = null
|
||||
}
|
||||
|
||||
var receiver = nameExpression.getReceiverExpression()?.marked(USER_CODE_KEY)
|
||||
var receiverType = if (receiver != null) bindingContext.getType(receiver) else null
|
||||
var receiverType = if (receiver != null) bindingContext.getType(receiver!!) else null
|
||||
|
||||
if (receiver == null) {
|
||||
val receiverValue = if (descriptor.isExtension) resolvedCall.extensionReceiver else resolvedCall.dispatchReceiver
|
||||
if (receiverValue is ImplicitReceiver) {
|
||||
val resolutionScope = elementToBeReplaced.getResolutionScope(bindingContext, elementToBeReplaced.getResolutionFacade())
|
||||
receiver = receiverValue.asExpression(resolutionScope, psiFactory)
|
||||
receiverType = receiverValue.type
|
||||
receiver = (receiverValue as ImplicitReceiver).asExpression(resolutionScope, psiFactory)
|
||||
receiverType = (receiverValue as ImplicitReceiver).type
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,7 +102,7 @@ class CodeInliner<TCallElement : KtElement>(
|
||||
for (thisExpression in codeToInline.collectDescendantsOfType<KtThisExpression>()) {
|
||||
// for this@ClassName we have only option to keep it as is (although it's sometimes incorrect but we have no other options)
|
||||
if (thisExpression.labelQualifier == null && receiver != null) {
|
||||
codeToInline.replaceExpression(thisExpression, receiver)
|
||||
codeToInline.replaceExpression(thisExpression, receiver!!)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,8 +113,8 @@ class CodeInliner<TCallElement : KtElement>(
|
||||
val lexicalScope = callElement.parent.getResolutionScope(bindingContext)
|
||||
|
||||
if (elementToBeReplaced is KtSafeQualifiedExpression) {
|
||||
wrapCodeForSafeCall(receiver!!, receiverType, elementToBeReplaced)
|
||||
} else if (callElement is KtBinaryExpression && callElement.operationToken == KtTokens.IDENTIFIER) {
|
||||
wrapCodeForSafeCall(receiver!!, receiverType, elementToBeReplaced as KtSafeQualifiedExpression)
|
||||
} else if (callElement is KtBinaryExpression && (callElement as KtBinaryExpression).operationToken == KtTokens.IDENTIFIER) {
|
||||
keepInfixFormIfPossible()
|
||||
}
|
||||
|
||||
@@ -122,7 +122,7 @@ class CodeInliner<TCallElement : KtElement>(
|
||||
if (receiver != null) {
|
||||
val thisReplaced = codeToInline.collectDescendantsOfType<KtExpression> { it[RECEIVER_VALUE_KEY] }
|
||||
if (receiver.shouldKeepValue(usageCount = thisReplaced.size)) {
|
||||
codeToInline.introduceValue(receiver, receiverType, thisReplaced, elementToBeReplaced)
|
||||
codeToInline.introduceValue(receiver!!, receiverType, thisReplaced, elementToBeReplaced as KtExpression)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -132,7 +132,7 @@ class CodeInliner<TCallElement : KtElement>(
|
||||
value,
|
||||
valueType,
|
||||
usagesReplaced,
|
||||
elementToBeReplaced,
|
||||
elementToBeReplaced as KtExpression,
|
||||
nameSuggestion = parameter.name.asString()
|
||||
)
|
||||
}
|
||||
@@ -143,8 +143,8 @@ class CodeInliner<TCallElement : KtElement>(
|
||||
.forEach { ImportInsertHelper.getInstance(project).importDescriptor(file, it) }
|
||||
|
||||
val replacementPerformer = when (elementToBeReplaced) {
|
||||
is KtExpression -> ExpressionReplacementPerformer(codeToInline, elementToBeReplaced)
|
||||
is KtAnnotationEntry -> AnnotationEntryReplacementPerformer(codeToInline, elementToBeReplaced)
|
||||
is KtExpression -> ExpressionReplacementPerformer(codeToInline, elementToBeReplaced as KtExpression)
|
||||
is KtAnnotationEntry -> AnnotationEntryReplacementPerformer(codeToInline, elementToBeReplaced as KtAnnotationEntry)
|
||||
else -> error("Unsupported element")
|
||||
}
|
||||
|
||||
@@ -165,8 +165,8 @@ class CodeInliner<TCallElement : KtElement>(
|
||||
val validator = CollectingNameValidator { !it.nameHasConflictsInScope(lexicalScope) }
|
||||
for (declaration in declarations) {
|
||||
val oldName = declaration.name
|
||||
if (oldName != null && oldName.nameHasConflictsInScope(lexicalScope)) {
|
||||
val newName = KotlinNameSuggester.suggestNameByName(oldName, validator)
|
||||
if (oldName != null && oldName!!.nameHasConflictsInScope(lexicalScope)) {
|
||||
val newName = KotlinNameSuggester.suggestNameByName(oldName!!, validator)
|
||||
val renameProcessor = RenameProcessor(project, declaration, newName, false, false)
|
||||
renameProcessor.run()
|
||||
}
|
||||
@@ -219,7 +219,7 @@ class CodeInliner<TCallElement : KtElement>(
|
||||
val callElement = resolvedCall.call.callElement
|
||||
val callExpression = callElement as? KtCallExpression
|
||||
val explicitTypeArgs = callExpression?.typeArgumentList?.arguments
|
||||
if (explicitTypeArgs != null && explicitTypeArgs.size != typeParameters.size) return
|
||||
if (explicitTypeArgs != null && explicitTypeArgs!!.size != typeParameters.size) return
|
||||
|
||||
for ((index, typeParameter) in typeParameters.withIndex()) {
|
||||
val parameterName = typeParameter.name
|
||||
@@ -229,7 +229,7 @@ class CodeInliner<TCallElement : KtElement>(
|
||||
|
||||
val type = resolvedCall.typeArguments[typeParameter]!!
|
||||
val typeElement = if (explicitTypeArgs != null) { // we use explicit type arguments if available to avoid shortening
|
||||
val explicitArgTypeElement = explicitTypeArgs[index].typeReference?.typeElement ?: continue
|
||||
val explicitArgTypeElement = explicitTypeArgs!![index].typeReference?.typeElement ?: continue
|
||||
explicitArgTypeElement.marked(USER_CODE_KEY)
|
||||
} else {
|
||||
psiFactory.createType(IdeDescriptorRenderers.SOURCE_CODE.renderType(type)).typeElement!!
|
||||
@@ -242,11 +242,11 @@ class CodeInliner<TCallElement : KtElement>(
|
||||
if (parent is KtClassLiteralExpression && typeClassifier != null) {
|
||||
// for class literal ("X::class") we need type arguments only for kotlin.Array
|
||||
val arguments =
|
||||
if (typeElement is KtUserType && KotlinBuiltIns.isArray(type)) typeElement.typeArgumentList?.text.orEmpty()
|
||||
if (typeElement is KtUserType && KotlinBuiltIns.isArray(type)) (typeElement as KtUserType).typeArgumentList?.text.orEmpty()
|
||||
else ""
|
||||
codeToInline.replaceExpression(
|
||||
usage, psiFactory.createExpression(
|
||||
IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(typeClassifier) + arguments
|
||||
IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(typeClassifier!!) + arguments
|
||||
)
|
||||
)
|
||||
} else if (parent is KtUserType) {
|
||||
@@ -263,11 +263,11 @@ class CodeInliner<TCallElement : KtElement>(
|
||||
if (codeToInline.statementsBefore.isEmpty()) {
|
||||
val qualified = codeToInline.mainExpression as? KtQualifiedExpression
|
||||
if (qualified != null) {
|
||||
if (qualified.receiverExpression[RECEIVER_VALUE_KEY]) {
|
||||
if (qualified!!.receiverExpression[RECEIVER_VALUE_KEY]) {
|
||||
if (qualified is KtSafeQualifiedExpression) return // already safe
|
||||
val selector = qualified.selectorExpression
|
||||
val selector = qualified!!.selectorExpression
|
||||
if (selector != null) {
|
||||
codeToInline.mainExpression = psiFactory.createExpressionByPattern("$0?.$1", receiver, selector)
|
||||
codeToInline.mainExpression = psiFactory.createExpressionByPattern("$0?.$1", receiver, selector!!)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -356,13 +356,13 @@ class CodeInliner<TCallElement : KtElement>(
|
||||
|
||||
when (val resolvedArgument = resolvedCall.valueArguments[parameter] ?: return null) {
|
||||
is ExpressionValueArgument -> {
|
||||
val valueArgument = resolvedArgument.valueArgument
|
||||
val valueArgument = (resolvedArgument as ExpressionValueArgument).valueArgument
|
||||
val expression = valueArgument?.getArgumentExpression()
|
||||
expression?.mark(USER_CODE_KEY) ?: return null
|
||||
if (valueArgument is LambdaArgument) {
|
||||
expression.mark(WAS_FUNCTION_LITERAL_ARGUMENT_KEY)
|
||||
expression!!.mark(WAS_FUNCTION_LITERAL_ARGUMENT_KEY)
|
||||
}
|
||||
return Argument(expression, bindingContext.getType(expression), isNamed = valueArgument.isNamed())
|
||||
return Argument(expression!!, bindingContext.getType(expression!!), isNamed = valueArgument!!.isNamed())
|
||||
}
|
||||
|
||||
is DefaultValueArgument -> {
|
||||
@@ -381,11 +381,11 @@ class CodeInliner<TCallElement : KtElement>(
|
||||
}
|
||||
|
||||
is VarargValueArgument -> {
|
||||
val arguments = resolvedArgument.arguments
|
||||
val arguments = (resolvedArgument as VarargValueArgument).arguments
|
||||
val single = arguments.singleOrNull()
|
||||
if (single?.getSpreadElement() != null) {
|
||||
val expression = single.getArgumentExpression()!!.marked(USER_CODE_KEY)
|
||||
return Argument(expression, bindingContext.getType(expression), isNamed = single.isNamed())
|
||||
val expression = single!!.getArgumentExpression()!!.marked(USER_CODE_KEY)
|
||||
return Argument(expression, bindingContext.getType(expression), isNamed = single!!.isNamed())
|
||||
}
|
||||
|
||||
val elementType = parameter.varargElementType!!
|
||||
@@ -435,7 +435,7 @@ class CodeInliner<TCallElement : KtElement>(
|
||||
ShortenReferences.FilterResult.SKIP
|
||||
} else {
|
||||
val thisReceiver = (element as? KtQualifiedExpression)?.receiverExpression as? KtThisExpression
|
||||
if (thisReceiver != null && thisReceiver[USER_CODE_KEY]) // don't remove explicit 'this' coming from user's code
|
||||
if (thisReceiver != null && thisReceiver!![USER_CODE_KEY]) // don't remove explicit 'this' coming from user's code
|
||||
ShortenReferences.FilterResult.GO_INSIDE
|
||||
else
|
||||
ShortenReferences.FilterResult.PROCESS
|
||||
@@ -512,8 +512,8 @@ class CodeInliner<TCallElement : KtElement>(
|
||||
|
||||
for (argument in argumentsToDrop) {
|
||||
argument as KtValueArgument
|
||||
val argumentList = argument.parent as KtValueArgumentList
|
||||
argumentList.removeArgument(argument)
|
||||
val argumentList = (argument as KtValueArgument).parent as KtValueArgumentList
|
||||
argumentList.removeArgument(argument as KtValueArgument)
|
||||
if (argumentList.arguments.isEmpty()) {
|
||||
val callExpression = argumentList.parent as KtCallExpression
|
||||
if (callExpression.lambdaArguments.isNotEmpty()) {
|
||||
|
||||
@@ -61,7 +61,7 @@ class CodeToInlineBuilder(
|
||||
|
||||
val descriptor = mainExpression.getResolvedCall(bindingContext)?.resultingDescriptor
|
||||
val alwaysKeepMainExpression = when (descriptor) {
|
||||
is PropertyDescriptor -> descriptor.getter?.isDefault == false
|
||||
is PropertyDescriptor -> (descriptor as PropertyDescriptor).getter?.isDefault == false
|
||||
else -> false
|
||||
}
|
||||
val codeToInline = MutableCodeToInline(
|
||||
@@ -76,12 +76,12 @@ class CodeToInlineBuilder(
|
||||
processReferences(codeToInline, bindingContext, reformat)
|
||||
|
||||
if (mainExpression != null) {
|
||||
val functionLiteralExpression = mainExpression.unpackFunctionLiteral(true)
|
||||
val functionLiteralExpression = mainExpression!!.unpackFunctionLiteral(true)
|
||||
if (functionLiteralExpression != null) {
|
||||
val functionLiteralParameterTypes = getParametersForFunctionLiteral(functionLiteralExpression, bindingContext)
|
||||
val functionLiteralParameterTypes = getParametersForFunctionLiteral(functionLiteralExpression!!, bindingContext)
|
||||
if (functionLiteralParameterTypes != null) {
|
||||
codeToInline.addPostInsertionAction(mainExpression) { inlinedExpression ->
|
||||
addFunctionLiteralParameterTypes(functionLiteralParameterTypes, inlinedExpression)
|
||||
codeToInline.addPostInsertionAction(mainExpression!!) { inlinedExpression ->
|
||||
addFunctionLiteralParameterTypes(functionLiteralParameterTypes!!, inlinedExpression)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -93,10 +93,10 @@ class CodeToInlineBuilder(
|
||||
private fun getParametersForFunctionLiteral(functionLiteralExpression: KtLambdaExpression, context: BindingContext): String? {
|
||||
val lambdaDescriptor = context.get(BindingContext.FUNCTION, functionLiteralExpression.functionLiteral)
|
||||
if (lambdaDescriptor == null ||
|
||||
ErrorUtils.containsErrorTypeInParameters(lambdaDescriptor) ||
|
||||
ErrorUtils.containsErrorType(lambdaDescriptor.returnType)
|
||||
ErrorUtils.containsErrorTypeInParameters(lambdaDescriptor!!) ||
|
||||
ErrorUtils.containsErrorType(lambdaDescriptor!!.returnType)
|
||||
) return null
|
||||
return lambdaDescriptor.valueParameters.joinToString {
|
||||
return lambdaDescriptor!!.valueParameters.joinToString {
|
||||
it.name.render() + ": " + IdeDescriptorRenderers.SOURCE_CODE.renderType(it.type)
|
||||
}
|
||||
}
|
||||
@@ -164,23 +164,23 @@ class CodeToInlineBuilder(
|
||||
}
|
||||
|
||||
if (expression.getReceiverExpression() == null) {
|
||||
if (target is ValueParameterDescriptor && target.containingDeclaration == targetCallable) {
|
||||
expression.putCopyableUserData(CodeToInline.PARAMETER_USAGE_KEY, target.name)
|
||||
} else if (target is TypeParameterDescriptor && target.containingDeclaration == targetCallable) {
|
||||
expression.putCopyableUserData(CodeToInline.TYPE_PARAMETER_USAGE_KEY, target.name)
|
||||
if (target is ValueParameterDescriptor && (target as ValueParameterDescriptor).containingDeclaration == targetCallable) {
|
||||
expression.putCopyableUserData(CodeToInline.PARAMETER_USAGE_KEY, (target as ValueParameterDescriptor).name)
|
||||
} else if (target is TypeParameterDescriptor && (target as TypeParameterDescriptor).containingDeclaration == targetCallable) {
|
||||
expression.putCopyableUserData(CodeToInline.TYPE_PARAMETER_USAGE_KEY, (target as TypeParameterDescriptor).name)
|
||||
}
|
||||
|
||||
val resolvedCall = expression.getResolvedCall(bindingContext)
|
||||
if (resolvedCall != null && resolvedCall.isReallySuccess()) {
|
||||
val receiver = if (resolvedCall.resultingDescriptor.isExtension)
|
||||
resolvedCall.extensionReceiver
|
||||
if (resolvedCall != null && resolvedCall!!.isReallySuccess()) {
|
||||
val receiver = if (resolvedCall!!.resultingDescriptor.isExtension)
|
||||
resolvedCall!!.extensionReceiver
|
||||
else
|
||||
resolvedCall.dispatchReceiver
|
||||
resolvedCall!!.dispatchReceiver
|
||||
if (receiver is ImplicitReceiver) {
|
||||
val resolutionScope = expression.getResolutionScope(bindingContext, resolutionFacade)
|
||||
val receiverExpression = receiver.asExpression(resolutionScope, psiFactory)
|
||||
val receiverExpression = (receiver as ImplicitReceiver).asExpression(resolutionScope, psiFactory)
|
||||
if (receiverExpression != null) {
|
||||
receiversToAdd.add(expression to receiverExpression)
|
||||
receiversToAdd.add(expression to receiverExpression!!)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ internal class MutableCodeToInline(
|
||||
val action = it.getCopyableUserData(POST_INSERTION_ACTION)
|
||||
if (action != null) {
|
||||
it.putCopyableUserData(POST_INSERTION_ACTION, null)
|
||||
action.invoke(it)
|
||||
action!!.invoke(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user