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
@@ -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)