Support for import aliases in code completion

#KT-8848 Fixed
This commit is contained in:
Valentin Kipyatkov
2017-07-28 17:37:56 +03:00
parent 48246e5f34
commit 9361cd895c
44 changed files with 429 additions and 76 deletions
@@ -358,8 +358,15 @@ class JavaSyntheticPropertiesScope(storageManager: StorageManager, private val l
}
}
override fun createSubstitutedCopy(newOwner: DeclarationDescriptor, newModality: Modality, newVisibility: Visibility, original: PropertyDescriptor?, kind: CallableMemberDescriptor.Kind): PropertyDescriptorImpl {
return MyPropertyDescriptor(newOwner, this, annotations, newModality, newVisibility, isVar, name, kind, source).apply {
override fun createSubstitutedCopy(
newOwner: DeclarationDescriptor,
newModality: Modality,
newVisibility: Visibility,
original: PropertyDescriptor?,
kind: CallableMemberDescriptor.Kind,
newName: Name
): PropertyDescriptorImpl {
return MyPropertyDescriptor(newOwner, this, annotations, newModality, newVisibility, isVar, newName, kind, source).apply {
getMethod = this@MyPropertyDescriptor.getMethod
setMethod = this@MyPropertyDescriptor.setMethod
}
@@ -49,7 +49,11 @@ class AllUnderImportScope(
excludedImportNames.mapNotNull { if (it.parent() == fqName) it.shortName() else null }.toSet()
}
override fun getContributedDescriptors(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean): List<DeclarationDescriptor> {
override fun getContributedDescriptors(
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean,
changeNamesForAliased: Boolean
): Collection<DeclarationDescriptor> {
val nameFilterToUse = if (excludedNames.isEmpty()) { // optimization
nameFilter
}
@@ -57,12 +57,47 @@ class LazyExplicitImportScope(
return collectCallableMemberDescriptors(location, MemberScope::getContributedVariables)
}
override fun getContributedDescriptors(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean): Collection<DeclarationDescriptor> {
override fun getContributedDescriptors(
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean,
changeNamesForAliased: Boolean
): Collection<DeclarationDescriptor> {
val descriptors = SmartList<DeclarationDescriptor>()
descriptors.addIfNotNull(getContributedClassifier(aliasName, NoLookupLocation.WHEN_GET_ALL_DESCRIPTORS))
descriptors.addAll(getContributedFunctions(aliasName, NoLookupLocation.WHEN_GET_ALL_DESCRIPTORS))
descriptors.addAll(getContributedVariables(aliasName, NoLookupLocation.WHEN_GET_ALL_DESCRIPTORS))
if (changeNamesForAliased && aliasName != declaredName) {
for (i in descriptors.indices) {
val descriptor = descriptors[i]
val newDescriptor: DeclarationDescriptor = when (descriptor) {
is ClassDescriptor -> {
object : ClassDescriptor by descriptor {
override fun getName() = aliasName
}
}
is TypeAliasDescriptor -> {
object : TypeAliasDescriptor by descriptor {
override fun getName() = aliasName
}
}
is CallableMemberDescriptor -> {
descriptor
.newCopyBuilder()
.setName(aliasName)
.setOriginal(descriptor)
.build()!!
}
else -> error("Unknown kind of descriptor in import alias: $descriptor")
}
descriptors[i] = newDescriptor
}
}
return descriptors
}
@@ -208,7 +208,11 @@ class FileScopeFactory(
return scope.getContributedFunctions(name, location)
}
override fun getContributedDescriptors(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean): Collection<DeclarationDescriptor> {
override fun getContributedDescriptors(
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean,
changeNamesForAliased: Boolean
): Collection<DeclarationDescriptor> {
// we do not perform any filtering by visibility here because all descriptors from both visible/invisible filter scopes are to be added anyway
if (filteringKind == FilteringKind.INVISIBLE_CLASSES) return listOf()
return scope.getContributedDescriptors(
@@ -238,7 +238,11 @@ class LazyImportScope(
return importResolver.collectFromImports(name) { scope, name -> scope.getContributedFunctions(name, location) }
}
override fun getContributedDescriptors(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean): Collection<DeclarationDescriptor> {
override fun getContributedDescriptors(
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean,
changeNamesForAliased: Boolean
): Collection<DeclarationDescriptor> {
// we do not perform any filtering by visibility here because all descriptors from both visible/invisible filter scopes are to be added anyway
if (filteringKind == FilteringKind.INVISIBLE_CLASSES) return listOf()
@@ -248,7 +252,7 @@ class LazyImportScope(
val importPath = directive.importPath ?: continue
val importedName = importPath.importedName
if (importedName == null || nameFilter(importedName)) {
descriptors.addAll(importResolver.getImportScope(directive).getContributedDescriptors(kindFilter, nameFilter))
descriptors.addAll(importResolver.getImportScope(directive).getContributedDescriptors(kindFilter, nameFilter, changeNamesForAliased))
}
}
descriptors
@@ -51,10 +51,11 @@ class JvmPropertyDescriptorImpl private constructor(
newModality: Modality,
newVisibility: Visibility,
original: PropertyDescriptor?,
kind: CallableMemberDescriptor.Kind
kind: CallableMemberDescriptor.Kind,
newName: Name
): PropertyDescriptorImpl =
JvmPropertyDescriptorImpl(
newOwner, original, annotations, newModality, newVisibility, extraFlags, isVar, name, kind,
newOwner, original, annotations, newModality, newVisibility, extraFlags, isVar, newName, kind,
SourceElement.NO_SOURCE, isLateInit, isConst, isHeader, isImpl
)
@@ -109,6 +109,16 @@ interface ImportingScope : HierarchicalScope {
fun getContributedPackage(name: Name): PackageViewDescriptor?
fun getContributedDescriptors(
kindFilter: DescriptorKindFilter = DescriptorKindFilter.ALL,
nameFilter: (Name) -> Boolean = MemberScope.ALL_NAME_FILTER,
changeNamesForAliased: Boolean
): Collection<DeclarationDescriptor>
override fun getContributedDescriptors(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean): Collection<DeclarationDescriptor> {
return getContributedDescriptors(kindFilter, nameFilter, changeNamesForAliased = false)
}
object Empty : BaseImportingScope(null) {
override fun printStructure(p: Printer) {
p.println("ImportingScope.Empty")
@@ -131,4 +141,11 @@ abstract class BaseImportingScope(parent: ImportingScope?) : BaseHierarchicalSco
get() = super.parent as ImportingScope?
override fun getContributedPackage(name: Name): PackageViewDescriptor? = null
override fun getContributedDescriptors(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean): Collection<DeclarationDescriptor> {
return getContributedDescriptors(kindFilter, nameFilter, changeNamesForAliased = false)
}
override fun getContributedDescriptors(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean, changeNamesForAliased: Boolean): Collection<DeclarationDescriptor>
= emptyList()
}
@@ -40,12 +40,12 @@ class SubpackagesImportingScope(
override fun getContributedFunctions(name: Name, location: LookupLocation) = super.getContributedFunctions(name, location)
//TODO: kept old behavior, but it seems very strange (super call seems more applicable)
override fun getContributedClassifier(name: Name, location: LookupLocation): ClassifierDescriptor? {
return ImportingScope.Empty.getContributedClassifier(name, location)
}
override fun getContributedClassifier(name: Name, location: LookupLocation): ClassifierDescriptor? = null
override fun getContributedDescriptors(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean): Collection<DeclarationDescriptor> =
emptyList()
//TODO: kept old behavior, but it seems very strange (super call seems more applicable)
override fun getContributedDescriptors(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean): Collection<DeclarationDescriptor> {
return ImportingScope.Empty.getContributedDescriptors(kindFilter, nameFilter)
}
override fun getContributedDescriptors(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean, changeNamesForAliased: Boolean): Collection<DeclarationDescriptor>
= emptyList()
}
@@ -50,14 +50,18 @@ fun LexicalScope.getDeclarationsByLabel(labelName: Name): Collection<Declaration
// Result is guaranteed to be filtered by kind and name.
fun HierarchicalScope.collectDescriptorsFiltered(
kindFilter: DescriptorKindFilter = DescriptorKindFilter.ALL,
nameFilter: (Name) -> Boolean = { true }
nameFilter: (Name) -> Boolean = { true },
changeNamesForAliased: Boolean = false
): Collection<DeclarationDescriptor> {
if (kindFilter.kindMask == 0) return listOf()
return collectAllFromMeAndParent { it.getContributedDescriptors(kindFilter, nameFilter) }
.filter { kindFilter.accepts(it) && nameFilter(it.name) }
return collectAllFromMeAndParent {
if (it is ImportingScope)
it.getContributedDescriptors(kindFilter, nameFilter, changeNamesForAliased)
else
it.getContributedDescriptors(kindFilter, nameFilter)
}.filter { kindFilter.accepts(it) && nameFilter(it.name) }
}
@Deprecated("Use getContributedProperties instead") fun LexicalScope.findLocalVariable(name: Name): VariableDescriptor? {
return findFirstFromMeAndParent {
when {
@@ -103,7 +107,7 @@ fun HierarchicalScope.takeSnapshot(): HierarchicalScope = if (this is LexicalWri
private class MemberScopeToImportingScopeAdapter(override val parent: ImportingScope?, val memberScope: MemberScope) : ImportingScope {
override fun getContributedPackage(name: Name): PackageViewDescriptor? = null
override fun getContributedDescriptors(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean)
override fun getContributedDescriptors(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean, changeNamesForAliased: Boolean)
= memberScope.getContributedDescriptors(kindFilter, nameFilter)
override fun getContributedClassifier(name: Name, location: LookupLocation) = memberScope.getContributedClassifier(name, location)
@@ -74,10 +74,11 @@ public class JavaPropertyDescriptor extends PropertyDescriptorImpl implements Ja
@NotNull Modality newModality,
@NotNull Visibility newVisibility,
@Nullable PropertyDescriptor original,
@NotNull Kind kind
@NotNull Kind kind,
@NotNull Name newName
) {
return new JavaPropertyDescriptor(
newOwner, getAnnotations(), newModality, newVisibility, isVar(), getName(), SourceElement.NO_SOURCE, original,
newOwner, getAnnotations(), newModality, newVisibility, isVar(), newName, SourceElement.NO_SOURCE, original,
kind, isStaticFinal
);
}
@@ -18,6 +18,7 @@ package org.jetbrains.kotlin.descriptors;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.types.TypeSubstitution;
import java.util.Collection;
@@ -83,6 +84,12 @@ public interface CallableMemberDescriptor extends CallableDescriptor, MemberDesc
@NotNull
CopyBuilder<D> setCopyOverrides(boolean copyOverrides);
@NotNull
CopyBuilder<D> setName(@NotNull Name name);
@NotNull
CopyBuilder<D> setOriginal(@Nullable CallableMemberDescriptor original);
@Nullable
D build();
}
@@ -110,6 +110,7 @@ public interface FunctionDescriptor extends CallableMemberDescriptor {
@Override
CopyBuilder<D> setCopyOverrides(boolean copyOverrides);
@Override
@NotNull
CopyBuilder<D> setName(@NotNull Name name);
@@ -131,7 +132,8 @@ public interface FunctionDescriptor extends CallableMemberDescriptor {
CopyBuilder<D> setDispatchReceiverParameter(@Nullable ReceiverParameterDescriptor dispatchReceiverParameter);
@NotNull
CopyBuilder<D> setOriginal(@Nullable FunctionDescriptor original);
@Override
CopyBuilder<D> setOriginal(@Nullable CallableMemberDescriptor original);
@NotNull
CopyBuilder<D> setSignatureChange();
@@ -474,8 +474,8 @@ public abstract class FunctionDescriptorImpl extends DeclarationDescriptorNonRoo
@Override
@NotNull
public CopyConfiguration setOriginal(@Nullable FunctionDescriptor original) {
this.original = original;
public CopyConfiguration setOriginal(@Nullable CallableMemberDescriptor original) {
this.original = (FunctionDescriptor) original;
return this;
}
@@ -251,6 +251,7 @@ public class PropertyDescriptorImpl extends VariableDescriptorWithInitializerImp
private boolean copyOverrides = true;
private ReceiverParameterDescriptor dispatchReceiverParameter = PropertyDescriptorImpl.this.dispatchReceiverParameter;
private List<TypeParameterDescriptor> newTypeParameters = null;
private Name name = getName();
@NotNull
@Override
@@ -260,8 +261,9 @@ public class PropertyDescriptorImpl extends VariableDescriptorWithInitializerImp
}
@NotNull
public CopyConfiguration setOriginal(@Nullable PropertyDescriptor original) {
this.original = original;
@Override
public CopyConfiguration setOriginal(@Nullable CallableMemberDescriptor original) {
this.original = (PropertyDescriptor) original;
return this;
}
@@ -314,6 +316,13 @@ public class PropertyDescriptorImpl extends VariableDescriptorWithInitializerImp
return this;
}
@NotNull
@Override
public CopyBuilder<PropertyDescriptor> setName(@NotNull Name name) {
this.name = name;
return this;
}
@Nullable
@Override
public PropertyDescriptor build() {
@@ -331,7 +340,7 @@ public class PropertyDescriptorImpl extends VariableDescriptorWithInitializerImp
protected PropertyDescriptor doSubstitute(@NotNull CopyConfiguration copyConfiguration) {
PropertyDescriptorImpl substitutedDescriptor = createSubstitutedCopy(
copyConfiguration.owner, copyConfiguration.modality, copyConfiguration.visibility,
copyConfiguration.original, copyConfiguration.kind);
copyConfiguration.original, copyConfiguration.kind, copyConfiguration.name);
List<TypeParameterDescriptor> originalTypeParameters =
copyConfiguration.newTypeParameters == null ? getTypeParameters() : copyConfiguration.newTypeParameters;
@@ -444,10 +453,11 @@ public class PropertyDescriptorImpl extends VariableDescriptorWithInitializerImp
@NotNull Modality newModality,
@NotNull Visibility newVisibility,
@Nullable PropertyDescriptor original,
@NotNull Kind kind
@NotNull Kind kind,
@NotNull Name newName
) {
return new PropertyDescriptorImpl(
newOwner, original, getAnnotations(), newModality, newVisibility, isVar(), getName(), kind, SourceElement.NO_SOURCE,
newOwner, original, getAnnotations(), newModality, newVisibility, isVar(), newName, kind, SourceElement.NO_SOURCE,
isLateInit(), isConst(), isHeader(), isImpl(), isExternal(), isDelegated()
);
}
@@ -146,7 +146,7 @@ public class ErrorSimpleFunctionDescriptorImpl extends SimpleFunctionDescriptorI
@NotNull
@Override
public CopyBuilder<SimpleFunctionDescriptor> setOriginal(@Nullable FunctionDescriptor original) {
public CopyBuilder<SimpleFunctionDescriptor> setOriginal(@Nullable CallableMemberDescriptor original) {
return this;
}
@@ -16,6 +16,8 @@
package org.jetbrains.kotlin.serialization.deserialization.descriptors
import org.jetbrains.annotations.NotNull
import org.jetbrains.annotations.Nullable
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.descriptors.impl.*
@@ -119,10 +121,11 @@ class DeserializedPropertyDescriptor(
newModality: Modality,
newVisibility: Visibility,
original: PropertyDescriptor?,
kind: CallableMemberDescriptor.Kind
kind: CallableMemberDescriptor.Kind,
newName: Name
): PropertyDescriptorImpl {
return DeserializedPropertyDescriptor(
newOwner, original, annotations, newModality, newVisibility, isVar, name, kind, isLateInit, isConst, isExternal,
newOwner, original, annotations, newModality, newVisibility, isVar, newName, kind, isLateInit, isConst, isExternal,
@Suppress("DEPRECATION") isDelegated, isHeader, proto, nameResolver, typeTable, sinceKotlinInfoTable, containerSource
)
}
@@ -204,7 +204,7 @@ class ReferenceVariantsHelper(
descriptors.processAll(implicitReceiverTypes, implicitReceiverTypes, resolutionScope, callType, kindFilter, nameFilter)
// add non-instance members
descriptors.addAll(resolutionScope.collectDescriptorsFiltered(filterWithoutExtensions, nameFilter))
descriptors.addAll(resolutionScope.collectDescriptorsFiltered(filterWithoutExtensions, nameFilter, changeNamesForAliased = true))
descriptors.addAll(resolutionScope.collectAllFromMeAndParent { scope ->
scope.collectSyntheticStaticMembersAndConstructors(resolutionFacade, kindFilter, nameFilter)
})
@@ -231,7 +231,7 @@ class ReferenceVariantsHelper(
}
else {
val scope = contextElement.getResolutionScope(bindingContext, resolutionFacade)
return scope.collectDescriptorsFiltered(kindFilter, nameFilter)
return scope.collectDescriptorsFiltered(kindFilter, nameFilter, changeNamesForAliased = true)
}
}
@@ -346,7 +346,7 @@ class ReferenceVariantsHelper(
filterToUse = filterToUse.withKinds(DescriptorKindFilter.NON_SINGLETON_CLASSIFIERS_MASK)
}
for (descriptor in scope.collectDescriptorsFiltered(filterToUse, nameFilter)) {
for (descriptor in scope.collectDescriptorsFiltered(filterToUse, nameFilter, changeNamesForAliased = true)) {
if (descriptor is ClassDescriptor) {
if (descriptor.modality == Modality.ABSTRACT || descriptor.modality == Modality.SEALED) continue
if (!constructorFilter(descriptor)) continue
@@ -379,7 +379,7 @@ class ReferenceVariantsHelper(
}
}
for (descriptor in scope.collectDescriptorsFiltered(kindFilter exclude DescriptorKindExclude.NonExtensions, nameFilter)) {
for (descriptor in scope.collectDescriptorsFiltered(kindFilter exclude DescriptorKindExclude.NonExtensions, nameFilter, changeNamesForAliased = true)) {
// todo: sometimes resolution scope here is LazyJavaClassMemberScope. see ea.jetbrains.com/browser/ea_problems/72572
process(descriptor as CallableDescriptor)
}
@@ -35,7 +35,7 @@ class ExplicitImportsScope(private val descriptors: Collection<DeclarationDescri
override fun getContributedFunctions(name: Name, location: LookupLocation)
= descriptors.filter { it.name == name }.filterIsInstance<FunctionDescriptor>()
override fun getContributedDescriptors(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean)
override fun getContributedDescriptors(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean, changeNamesForAliased: Boolean)
= descriptors
override fun printStructure(p: Printer) {
@@ -36,6 +36,7 @@ import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import org.jetbrains.kotlin.synthetic.SamAdapterExtensionFunctionDescriptor
import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
@@ -149,6 +150,7 @@ class BasicLookupElementFactory(
}
classifierDescriptor.name.asString()
}
is SyntheticJavaPropertyDescriptor -> {
lookupObject = object : DeclarationLookupObjectImpl(descriptor) {
override val psiElement by lazy { DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor.getMethod) }
@@ -156,6 +158,7 @@ class BasicLookupElementFactory(
}
descriptor.name.asString()
}
else -> {
lookupObject = object : DeclarationLookupObjectImpl(descriptor) {
override val psiElement by lazy { DescriptorToSourceUtils.getSourceFromDescriptor(descriptor) }
@@ -196,7 +199,10 @@ class BasicLookupElementFactory(
var container = descriptor.containingDeclaration
if (qualifyNestedClasses) {
if (descriptor.isArtificialImportAliasedDescriptor) {
container = descriptor.original // we show original descriptor instead of container for import aliased descriptors
}
else if (qualifyNestedClasses) {
element = element.withPresentableText(SHORT_NAMES_RENDERER.renderClassifierName(descriptor))
while (container is ClassDescriptor) {
@@ -208,7 +214,7 @@ class BasicLookupElementFactory(
}
}
if (container is PackageFragmentDescriptor || container is ClassDescriptor) {
if (container is PackageFragmentDescriptor || container is ClassifierDescriptor) {
element = element.appendTailText(" (" + DescriptorUtils.getFqName(container) + ")", true)
}
@@ -249,7 +255,6 @@ class BasicLookupElementFactory(
}
fun appendContainerAndReceiverInformation(descriptor: CallableDescriptor, appendTailText: (String) -> Unit) {
val information = CompletionInformationProvider.EP_NAME.extensions.firstNotNullResult {
it.getContainerAndReceiverInformation(descriptor)
}
@@ -260,39 +265,56 @@ class BasicLookupElementFactory(
}
val extensionReceiver = descriptor.original.extensionReceiverParameter
if (extensionReceiver != null) {
when {
descriptor is SamAdapterExtensionFunctionDescriptor -> {
// no need to show them as extensions
return
}
descriptor is SyntheticJavaPropertyDescriptor -> {
var from = descriptor.getMethod.name.asString() + "()"
descriptor.setMethod?.let { from += "/" + it.name.asString() + "()" }
appendTailText(" (from $from)")
return
}
else -> {
val receiverPresentation = SHORT_NAMES_RENDERER.renderType(extensionReceiver.type)
appendTailText(" for $receiverPresentation")
}
}
}
val containerPresentation = containerPresentation(descriptor)
if (containerPresentation != null) {
appendTailText(" ")
appendTailText(containerPresentation)
}
}
private fun containerPresentation(descriptor: DeclarationDescriptor): String? {
when {
descriptor is SyntheticJavaPropertyDescriptor -> {
var from = descriptor.getMethod.name.asString() + "()"
descriptor.setMethod?.let { from += "/" + it.name.asString() + "()" }
appendTailText(" (from $from)")
descriptor.isArtificialImportAliasedDescriptor -> {
return "(${DescriptorUtils.getFqName(descriptor.original)})"
}
// no need to show them as extensions
descriptor is SamAdapterExtensionFunctionDescriptor -> {
}
extensionReceiver != null -> {
val receiverPresentation = SHORT_NAMES_RENDERER.renderType(extensionReceiver.type)
appendTailText(" for $receiverPresentation")
descriptor.isExtension -> {
val container = descriptor.containingDeclaration
val containerPresentation = when (container) {
is ClassDescriptor -> DescriptorUtils.getFqNameFromTopLevelClass(container).toString()
is PackageFragmentDescriptor -> container.fqName.toString()
else -> null
}
if (containerPresentation != null) {
appendTailText(" in $containerPresentation")
else -> return null
}
return "in $containerPresentation"
}
else -> {
val container = descriptor.containingDeclaration
if (container is PackageFragmentDescriptor) {
// we show container only for global functions and properties
//TODO: it would be probably better to show it also for static declarations which are not from the current class (imported)
appendTailText(" (${container.fqName})")
}
val container = descriptor.containingDeclaration as? PackageFragmentDescriptor
// we show container only for global functions and properties
?: return null
//TODO: it would be probably better to show it also for static declarations which are not from the current class (imported)
return "(${container.fqName})"
}
}
}
@@ -421,4 +421,7 @@ fun OffsetMap.tryGetOffset(key: OffsetKey): Int? {
}
}
var KtCodeFragment.extraCompletionFilter: ((LookupElement) -> Boolean)? by CopyableUserDataProperty(Key.create("EXTRA_COMPLETION_FILTER"))
var KtCodeFragment.extraCompletionFilter: ((LookupElement) -> Boolean)? by CopyableUserDataProperty(Key.create("EXTRA_COMPLETION_FILTER"))
val DeclarationDescriptor.isArtificialImportAliasedDescriptor: Boolean
get() = original.name != name
@@ -53,7 +53,7 @@ class ReferenceVariantsCollector(
private val runtimeReceiver: ExpressionReceiver? = null
) {
data class FilterConfiguration internal constructor(val descriptorKindFilter: DescriptorKindFilter,
private data class FilterConfiguration internal constructor(val descriptorKindFilter: DescriptorKindFilter,
val additionalPropertyNameFilter: ((String) -> Boolean)?,
val shadowedDeclarationsFilter: ShadowedDeclarationsFilter?,
val completeExtensionsFromIndices: Boolean)
@@ -78,7 +78,7 @@ class ReferenceVariantsCollector(
fun collectReferenceVariants(descriptorKindFilter: DescriptorKindFilter): ReferenceVariants {
assert(!isCollectingFinished)
val config = configure(descriptorKindFilter)
val config = configuration(descriptorKindFilter)
val basic = collectBasicVariants(config)
return basic + collectExtensionVariants(config, basic)
@@ -86,7 +86,7 @@ class ReferenceVariantsCollector(
fun collectReferenceVariants(descriptorKindFilter: DescriptorKindFilter, consumer: (ReferenceVariants) -> Unit) {
assert(!isCollectingFinished)
val config = configure(descriptorKindFilter)
val config = configuration(descriptorKindFilter)
val basic = collectBasicVariants(config)
consumer(basic)
@@ -107,8 +107,7 @@ class ReferenceVariantsCollector(
return variants
}
fun configure(descriptorKindFilter: DescriptorKindFilter): FilterConfiguration {
private fun configuration(descriptorKindFilter: DescriptorKindFilter): FilterConfiguration {
val completeExtensionsFromIndices = descriptorKindFilter.kindMask.and(DescriptorKindFilter.CALLABLES_MASK) != 0
&& DescriptorKindExclude.Extensions !in descriptorKindFilter.excludes
&& callTypeAndReceiver !is CallTypeAndReceiver.IMPORT_DIRECTIVE
@@ -130,7 +129,6 @@ class ReferenceVariantsCollector(
return ReferenceVariantsCollector.FilterConfiguration(descriptorKindFilter, additionalPropertyNameFilter, shadowedDeclarationsFilter, completeExtensionsFromIndices)
}
private fun doCollectBasicVariants(filterConfiguration: FilterConfiguration): ReferenceVariants {
fun getReferenceVariants(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean): Collection<DeclarationDescriptor> {
return referenceVariantsHelper.getReferenceVariants(
@@ -207,6 +205,7 @@ class ReferenceVariantsCollector(
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.isArtificialImportAliasedDescriptor) return false // do not exclude aliased descriptors - they cannot be completed via indices
val containingPackage = descriptor.containingDeclaration as? PackageFragmentDescriptor ?: return false
if (containingPackage.fqName.asString().startsWith("kotlinx.android.synthetic.")) return false // TODO: temporary solution for Android synthetic extensions
return true
@@ -20,6 +20,7 @@ import com.intellij.codeInsight.completion.InsertionContext
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.psi.PsiDocumentManager
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.idea.completion.isArtificialImportAliasedDescriptor
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.completion.DeclarationLookupObject
import org.jetbrains.kotlin.idea.imports.importableFqName
@@ -45,11 +46,12 @@ abstract class KotlinCallableInsertHandler(val callType: CallType<*>) : BaseDecl
if (file is KtFile && o is DeclarationLookupObject) {
val descriptor = o.descriptor as? CallableDescriptor ?: return
if (descriptor.extensionReceiverParameter != null || callType == CallType.CALLABLE_REFERENCE) {
if (DescriptorUtils.isTopLevelDeclaration(descriptor)) {
if (DescriptorUtils.isTopLevelDeclaration(descriptor) && !descriptor.isArtificialImportAliasedDescriptor) {
ImportInsertHelper.getInstance(context.project).importDescriptor(file, descriptor)
}
}
else if (callType == CallType.DEFAULT) {
if (descriptor.isArtificialImportAliasedDescriptor) return
val fqName = descriptor.importableFqName ?: return
context.document.replaceString(context.startOffset, context.tailOffset, fqName.render() + " ") // insert space after for correct parsing
@@ -24,6 +24,7 @@ import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassifierDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.completion.isAfterDot
import org.jetbrains.kotlin.idea.completion.isArtificialImportAliasedDescriptor
import org.jetbrains.kotlin.idea.core.completion.DeclarationLookupObject
import org.jetbrains.kotlin.idea.util.CallTypeAndReceiver
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
@@ -50,11 +51,14 @@ object KotlinClassifierInsertHandler : BaseDeclarationInsertHandler() {
val startOffset = context.startOffset
val document = context.document
val qualifiedName = qualifiedNameToInsert(item)
val lookupObject = item.`object` as DeclarationLookupObject
if (lookupObject.descriptor?.isArtificialImportAliasedDescriptor == true) return // never need to insert import or use qualified name for import-aliased class
val qualifiedName = qualifiedName(lookupObject)
// first try to resolve short name for faster handling
val token = file.findElementAt(startOffset)
val nameRef = token!!.parent as? KtNameReferenceExpression
val token = file.findElementAt(startOffset)!!
val nameRef = token.parent as? KtNameReferenceExpression
if (nameRef != null) {
val bindingContext = nameRef.analyze(BodyResolveMode.PARTIAL)
val target = bindingContext[BindingContext.SHORT_REFERENCE_TO_COMPANION_OBJECT, nameRef]
@@ -92,8 +96,7 @@ object KotlinClassifierInsertHandler : BaseDeclarationInsertHandler() {
}
}
private fun qualifiedNameToInsert(item: LookupElement): String {
val lookupObject = item.`object` as DeclarationLookupObject
private fun qualifiedName(lookupObject: DeclarationLookupObject): String {
return if (lookupObject.descriptor != null) {
IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(lookupObject.descriptor as ClassifierDescriptor)
}
@@ -0,0 +1,7 @@
import java.io.FileInputStream as FileInputStreamMy
fun foo(): FileInputS<caret>
// WITH_ORDER
// EXIST: { lookupString: "FileInputStreamMy", itemText: "FileInputStreamMy", tailText: " (java.io.FileInputStream)" }
// EXIST: { lookupString: "FileInputStream", itemText: "FileInputStream", tailText: " (java.io)" }
@@ -0,0 +1,7 @@
import kotlin.collections.firstOrNull as aaa
fun foo() {
listOf(1, 2).aa<caret>
}
// EXIST: { lookupString: "aaa", itemText: "aaa", tailText: "() for List<T> (kotlin.collections.firstOrNull)" }
@@ -0,0 +1,9 @@
import java.io.File
import kotlin.io.extension as ext
fun foo(file: File): String {
return file.ex<caret>
}
// COMPLETION_TYPE: SMART
// EXIST: { lookupString: "ext", itemText: "ext", tailText: " for File (kotlin.io.extension)" }
@@ -0,0 +1,5 @@
import java.util.ArrayList as JavaList
fun foo(): Ja<caret>
// EXIST: { lookupString: "JavaList", itemText: "JavaList" }
@@ -0,0 +1,7 @@
import kotlin.collections.listOf as list
fun foo() {
lis<caret>
}
// EXIST: { lookupString: "list", itemText: "list", tailText: "() (kotlin.collections.listOf)" }
@@ -0,0 +1,7 @@
import kotlin.io.DEFAULT_BUFFER_SIZE as BUFSIZE
fun foo() {
BUF<caret>
}
// EXIST: { lookupString: "BUFSIZE", itemText: "BUFSIZE", tailText: " (kotlin.io.DEFAULT_BUFFER_SIZE)" }
@@ -0,0 +1,5 @@
import kotlin.collections.ArrayList as KotlinArrayList
fun foo(): KotAr<caret>
// EXIST: { lookupString: "KotlinArrayList", itemText: "KotlinArrayList", tailText: "<E> (kotlin.collections.ArrayList)", typeText: "ArrayList<E>" }
@@ -0,0 +1,7 @@
import java.sql.Date as SqlDate
fun foo() {
val v: SqlDate = SqlDa<caret>
}
// ELEMENT: "SqlDate"
@@ -0,0 +1,7 @@
import java.sql.Date as SqlDate
fun foo() {
val v: SqlDate = SqlDate<caret>
}
// ELEMENT: "SqlDate"
@@ -0,0 +1,7 @@
import kotlin.collections.distinct as unique
fun foo() {
listOf(1, 2, 3).<caret>
}
// ELEMENT: "unique"
@@ -0,0 +1,7 @@
import kotlin.collections.distinct as unique
fun foo() {
listOf(1, 2, 3).unique()<caret>
}
// ELEMENT: "unique"
@@ -0,0 +1,8 @@
import java.io.File
import kotlin.io.extension as ext
fun foo(file: File): String {
return file.<caret>
}
// ELEMENT: "ext"
@@ -0,0 +1,8 @@
import java.io.File
import kotlin.io.extension as ext
fun foo(file: File): String {
return file.ext<caret>
}
// ELEMENT: "ext"
@@ -0,0 +1,7 @@
import kotlin.error as veryBad
fun foo() {
v<caret>
}
// ELEMENT: "veryBad"
@@ -0,0 +1,7 @@
import kotlin.error as veryBad
fun foo() {
veryBad(<caret>)
}
// ELEMENT: "veryBad"
@@ -0,0 +1,7 @@
import kotlin.io.DEFAULT_BUFFER_SIZE as BUFSIZE
fun foo() {
BUF<caret>
}
// ELEMENT: "BUFSIZE"
@@ -0,0 +1,7 @@
import kotlin.io.DEFAULT_BUFFER_SIZE as BUFSIZE
fun foo() {
BUFSIZE<caret>
}
// ELEMENT: "BUFSIZE"
@@ -0,0 +1,5 @@
import java.util.Date as JavaDate
fun foo(): JavaD<caret>
// ELEMENT: "JavaDate"
@@ -0,0 +1,5 @@
import java.util.Date as JavaDate
fun foo(): JavaDate<caret>
// ELEMENT: "JavaDate"
@@ -3014,6 +3014,57 @@ public class JvmBasicCompletionTestGenerated extends AbstractJvmBasicCompletionT
}
}
@TestMetadata("idea/idea-completion/testData/basic/java/importAliases")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public static class ImportAliases extends AbstractJvmBasicCompletionTest {
public void testAllFilesPresentInImportAliases() throws Exception {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/idea-completion/testData/basic/java/importAliases"), Pattern.compile("^(.+)\\.kt$"), TargetBackend.ANY, true);
}
@TestMetadata("Class.kt")
public void testClass() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/idea-completion/testData/basic/java/importAliases/Class.kt");
doTest(fileName);
}
@TestMetadata("ExtensionFun.kt")
public void testExtensionFun() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/idea-completion/testData/basic/java/importAliases/ExtensionFun.kt");
doTest(fileName);
}
@TestMetadata("ExtensionValSmart.kt")
public void testExtensionValSmart() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/idea-completion/testData/basic/java/importAliases/ExtensionValSmart.kt");
doTest(fileName);
}
@TestMetadata("PrefixUsed.kt")
public void testPrefixUsed() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/idea-completion/testData/basic/java/importAliases/PrefixUsed.kt");
doTest(fileName);
}
@TestMetadata("TopLevelFun.kt")
public void testTopLevelFun() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/idea-completion/testData/basic/java/importAliases/TopLevelFun.kt");
doTest(fileName);
}
@TestMetadata("TopLevelVal.kt")
public void testTopLevelVal() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/idea-completion/testData/basic/java/importAliases/TopLevelVal.kt");
doTest(fileName);
}
@TestMetadata("TypeAlias.kt")
public void testTypeAlias() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/idea-completion/testData/basic/java/importAliases/TypeAlias.kt");
doTest(fileName);
}
}
@TestMetadata("idea/idea-completion/testData/basic/java/syntheticExtensions")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
@@ -462,6 +462,51 @@ public class BasicCompletionHandlerTestGenerated extends AbstractBasicCompletion
}
}
@TestMetadata("idea/idea-completion/testData/handlers/basic/importAliases")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public static class ImportAliases extends AbstractBasicCompletionHandlerTest {
public void testAllFilesPresentInImportAliases() throws Exception {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/idea-completion/testData/handlers/basic/importAliases"), Pattern.compile("^([^.]+)\\.kt$"), TargetBackend.ANY, true);
}
@TestMetadata("CompanionObject.kt")
public void testCompanionObject() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/idea-completion/testData/handlers/basic/importAliases/CompanionObject.kt");
doTest(fileName);
}
@TestMetadata("ExtensionFun.kt")
public void testExtensionFun() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/idea-completion/testData/handlers/basic/importAliases/ExtensionFun.kt");
doTest(fileName);
}
@TestMetadata("ExtensionVal.kt")
public void testExtensionVal() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/idea-completion/testData/handlers/basic/importAliases/ExtensionVal.kt");
doTest(fileName);
}
@TestMetadata("TopLevelFun.kt")
public void testTopLevelFun() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/idea-completion/testData/handlers/basic/importAliases/TopLevelFun.kt");
doTest(fileName);
}
@TestMetadata("TopLevelVal.kt")
public void testTopLevelVal() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/idea-completion/testData/handlers/basic/importAliases/TopLevelVal.kt");
doTest(fileName);
}
@TestMetadata("Type.kt")
public void testType() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/idea-completion/testData/handlers/basic/importAliases/Type.kt");
doTest(fileName);
}
}
@TestMetadata("idea/idea-completion/testData/handlers/basic/override")
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)