idea: cleanup 'public', property access syntax
This commit is contained in:
+5
-5
@@ -74,9 +74,9 @@ class AllClassesCompletion(private val parameters: CompletionParameters,
|
||||
if (psiClass.isSyntheticKotlinClass()) return@processJavaClasses // filter out synthetic classes produced by Kotlin compiler
|
||||
|
||||
val kind = when {
|
||||
psiClass.isAnnotationType() -> ClassKind.ANNOTATION_CLASS
|
||||
psiClass.isInterface() -> ClassKind.INTERFACE
|
||||
psiClass.isEnum() -> ClassKind.ENUM_CLASS
|
||||
psiClass.isAnnotationType -> ClassKind.ANNOTATION_CLASS
|
||||
psiClass.isInterface -> ClassKind.INTERFACE
|
||||
psiClass.isEnum -> ClassKind.ENUM_CLASS
|
||||
else -> ClassKind.CLASS
|
||||
}
|
||||
if (kindFilter(kind)) {
|
||||
@@ -87,7 +87,7 @@ class AllClassesCompletion(private val parameters: CompletionParameters,
|
||||
}
|
||||
|
||||
private fun PsiClass.isSyntheticKotlinClass(): Boolean {
|
||||
if (!getName()!!.contains('$')) return false // optimization to not analyze annotations of all classes
|
||||
return getModifierList()?.findAnnotation(kotlin.jvm.internal.KotlinSyntheticClass::class.java.getName()) != null
|
||||
if (!name!!.contains('$')) return false // optimization to not analyze annotations of all classes
|
||||
return modifierList?.findAnnotation(kotlin.jvm.internal.KotlinSyntheticClass::class.java.name) != null
|
||||
}
|
||||
}
|
||||
|
||||
+22
-22
@@ -40,7 +40,7 @@ class BasicLookupElementFactory(
|
||||
private val project: Project,
|
||||
val insertHandlerProvider: InsertHandlerProvider
|
||||
) {
|
||||
public fun createLookupElement(
|
||||
fun createLookupElement(
|
||||
descriptor: DeclarationDescriptor,
|
||||
qualifyNestedClasses: Boolean = false,
|
||||
includeClassTypeArguments: Boolean = true,
|
||||
@@ -54,25 +54,25 @@ class BasicLookupElementFactory(
|
||||
return createLookupElement(_descriptor, declaration, qualifyNestedClasses, includeClassTypeArguments, parametersAndTypeGrayed)
|
||||
}
|
||||
|
||||
public fun createLookupElementForJavaClass(psiClass: PsiClass, qualifyNestedClasses: Boolean = false, includeClassTypeArguments: Boolean = true): LookupElement {
|
||||
fun createLookupElementForJavaClass(psiClass: PsiClass, qualifyNestedClasses: Boolean = false, includeClassTypeArguments: Boolean = true): LookupElement {
|
||||
val lookupObject = object : DeclarationLookupObjectImpl(null, psiClass) {
|
||||
override fun getIcon(flags: Int) = psiClass.getIcon(flags)
|
||||
}
|
||||
var element = LookupElementBuilder.create(lookupObject, psiClass.getName()!!)
|
||||
var element = LookupElementBuilder.create(lookupObject, psiClass.name!!)
|
||||
.withInsertHandler(KotlinClassifierInsertHandler)
|
||||
|
||||
val typeParams = psiClass.getTypeParameters()
|
||||
val typeParams = psiClass.typeParameters
|
||||
if (includeClassTypeArguments && typeParams.isNotEmpty()) {
|
||||
element = element.appendTailText(typeParams.map { it.getName() }.joinToString(", ", "<", ">"), true)
|
||||
element = element.appendTailText(typeParams.map { it.name }.joinToString(", ", "<", ">"), true)
|
||||
}
|
||||
|
||||
val qualifiedName = psiClass.getQualifiedName()!!
|
||||
val qualifiedName = psiClass.qualifiedName!!
|
||||
var containerName = qualifiedName.substringBeforeLast('.', FqName.ROOT.toString())
|
||||
|
||||
if (qualifyNestedClasses) {
|
||||
val nestLevel = psiClass.parents.takeWhile { it is PsiClass }.count()
|
||||
if (nestLevel > 0) {
|
||||
var itemText = psiClass.getName()
|
||||
var itemText = psiClass.name
|
||||
for (i in 1..nestLevel) {
|
||||
val outerClassName = containerName.substringAfterLast('.')
|
||||
element = element.withLookupString(outerClassName)
|
||||
@@ -92,12 +92,12 @@ class BasicLookupElementFactory(
|
||||
return element.withIconFromLookupObject()
|
||||
}
|
||||
|
||||
public fun createLookupElementForPackage(name: FqName): LookupElement {
|
||||
fun createLookupElementForPackage(name: FqName): LookupElement {
|
||||
var element = LookupElementBuilder.create(PackageLookupObject(name), name.shortName().asString())
|
||||
|
||||
element = element.withInsertHandler(BaseDeclarationInsertHandler())
|
||||
|
||||
if (!name.parent().isRoot()) {
|
||||
if (!name.parent().isRoot) {
|
||||
element = element.appendTailText(" (${name.asString()})", true)
|
||||
}
|
||||
|
||||
@@ -131,14 +131,14 @@ class BasicLookupElementFactory(
|
||||
val nameAndIconDescriptor: DeclarationDescriptor
|
||||
val iconDeclaration: PsiElement?
|
||||
if (descriptor is ConstructorDescriptor) {
|
||||
nameAndIconDescriptor = descriptor.getContainingDeclaration()
|
||||
nameAndIconDescriptor = descriptor.containingDeclaration
|
||||
iconDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, nameAndIconDescriptor)
|
||||
}
|
||||
else {
|
||||
nameAndIconDescriptor = descriptor
|
||||
iconDeclaration = declaration
|
||||
}
|
||||
val name = nameAndIconDescriptor.getName().asString()
|
||||
val name = nameAndIconDescriptor.name.asString()
|
||||
|
||||
val lookupObject = object : DeclarationLookupObjectImpl(descriptor, declaration) {
|
||||
override fun getIcon(flags: Int) = KotlinDescriptorIconProvider.getIcon(nameAndIconDescriptor, iconDeclaration, flags)
|
||||
@@ -150,7 +150,7 @@ class BasicLookupElementFactory(
|
||||
|
||||
when (descriptor) {
|
||||
is FunctionDescriptor -> {
|
||||
val returnType = descriptor.getReturnType()
|
||||
val returnType = descriptor.returnType
|
||||
element = element.withTypeText(if (returnType != null) DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(returnType) else "", parametersAndTypeGrayed)
|
||||
|
||||
val insertsLambda = (insertHandler as? KotlinFunctionInsertHandler.Normal)?.lambdaInfo != null
|
||||
@@ -162,16 +162,16 @@ class BasicLookupElementFactory(
|
||||
}
|
||||
|
||||
is VariableDescriptor -> {
|
||||
element = element.withTypeText(DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(descriptor.getType()), parametersAndTypeGrayed)
|
||||
element = element.withTypeText(DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(descriptor.type), parametersAndTypeGrayed)
|
||||
}
|
||||
|
||||
is ClassDescriptor -> {
|
||||
val typeParams = descriptor.declaredTypeParameters
|
||||
if (includeClassTypeArguments && typeParams.isNotEmpty()) {
|
||||
element = element.appendTailText(typeParams.map { it.getName().asString() }.joinToString(", ", "<", ">"), true)
|
||||
element = element.appendTailText(typeParams.map { it.name.asString() }.joinToString(", ", "<", ">"), true)
|
||||
}
|
||||
|
||||
var container = descriptor.getContainingDeclaration()
|
||||
var container = descriptor.containingDeclaration
|
||||
|
||||
if (qualifyNestedClasses) {
|
||||
element = element.withPresentableText(DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderClassifierName(descriptor))
|
||||
@@ -181,7 +181,7 @@ class BasicLookupElementFactory(
|
||||
if (!containerName.isSpecial) {
|
||||
element = element.withLookupString(containerName.asString())
|
||||
}
|
||||
container = container.getContainingDeclaration()
|
||||
container = container.containingDeclaration
|
||||
}
|
||||
}
|
||||
|
||||
@@ -220,12 +220,12 @@ class BasicLookupElementFactory(
|
||||
return element.withIconFromLookupObject()
|
||||
}
|
||||
|
||||
public fun appendContainerAndReceiverInformation(descriptor: CallableDescriptor, appendTailText: (String) -> Unit) {
|
||||
fun appendContainerAndReceiverInformation(descriptor: CallableDescriptor, appendTailText: (String) -> Unit) {
|
||||
val extensionReceiver = descriptor.original.extensionReceiverParameter
|
||||
when {
|
||||
descriptor is SyntheticJavaPropertyDescriptor -> {
|
||||
var from = descriptor.getMethod.getName().asString() + "()"
|
||||
descriptor.setMethod?.let { from += "/" + it.getName().asString() + "()" }
|
||||
var from = descriptor.getMethod.name.asString() + "()"
|
||||
descriptor.setMethod?.let { from += "/" + it.name.asString() + "()" }
|
||||
appendTailText(" (from $from)")
|
||||
}
|
||||
|
||||
@@ -237,7 +237,7 @@ class BasicLookupElementFactory(
|
||||
val receiverPresentation = DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(extensionReceiver.type)
|
||||
appendTailText(" for $receiverPresentation")
|
||||
|
||||
val container = descriptor.getContainingDeclaration()
|
||||
val container = descriptor.containingDeclaration
|
||||
val containerPresentation = if (container is ClassDescriptor)
|
||||
DescriptorUtils.getFqNameFromTopLevelClass(container).toString()
|
||||
else if (container is PackageFragmentDescriptor)
|
||||
@@ -250,7 +250,7 @@ class BasicLookupElementFactory(
|
||||
}
|
||||
|
||||
else -> {
|
||||
val container = descriptor.getContainingDeclaration()
|
||||
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)
|
||||
@@ -265,7 +265,7 @@ class BasicLookupElementFactory(
|
||||
return object : LookupElementDecorator<LookupElement>(this) {
|
||||
override fun renderElement(presentation: LookupElementPresentation) {
|
||||
super.renderElement(presentation)
|
||||
presentation.setIcon(DefaultLookupItemRenderer.getRawIcon(this@withIconFromLookupObject, presentation.isReal()))
|
||||
presentation.icon = DefaultLookupItemRenderer.getRawIcon(this@withIconFromLookupObject, presentation.isReal)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+13
-13
@@ -72,22 +72,22 @@ abstract class CompletionSession(
|
||||
protected val parameters: CompletionParameters,
|
||||
resultSet: CompletionResultSet
|
||||
) {
|
||||
protected val position = parameters.getPosition()
|
||||
protected val file = position.getContainingFile() as KtFile
|
||||
protected val position = parameters.position
|
||||
protected val file = position.containingFile as KtFile
|
||||
protected val resolutionFacade = file.getResolutionFacade()
|
||||
protected val moduleDescriptor = resolutionFacade.moduleDescriptor
|
||||
protected val project = position.getProject()
|
||||
protected val project = position.project
|
||||
protected val isJvmModule = !ProjectStructureUtil.isJsKotlinModule(parameters.originalFile as KtFile)
|
||||
|
||||
protected val nameExpression: KtSimpleNameExpression?
|
||||
protected val expression: KtExpression?
|
||||
|
||||
init {
|
||||
val reference = (position.getParent() as? KtSimpleNameExpression)?.mainReference
|
||||
val reference = (position.parent as? KtSimpleNameExpression)?.mainReference
|
||||
if (reference != null) {
|
||||
if (reference.expression is KtLabelReferenceExpression) {
|
||||
this.nameExpression = null
|
||||
this.expression = reference.expression.getParent().getParent() as? KtExpressionWithLabel
|
||||
this.expression = reference.expression.parent.parent as? KtExpressionWithLabel
|
||||
}
|
||||
else {
|
||||
this.nameExpression = reference.expression
|
||||
@@ -107,8 +107,8 @@ abstract class CompletionSession(
|
||||
private val kotlinIdentifierPartPattern = StandardPatterns.character().javaIdentifierPart().andNot(singleCharPattern('$'))
|
||||
|
||||
protected val prefix = CompletionUtil.findIdentifierPrefix(
|
||||
parameters.getPosition().getContainingFile(),
|
||||
parameters.getOffset(),
|
||||
parameters.position.containingFile,
|
||||
parameters.offset,
|
||||
kotlinIdentifierPartPattern or singleCharPattern('@'),
|
||||
kotlinIdentifierStartPattern)
|
||||
|
||||
@@ -151,7 +151,7 @@ abstract class CompletionSession(
|
||||
|
||||
// we need to exclude the original file from scope because our resolve session is built with this file replaced by synthetic one
|
||||
protected val searchScope: GlobalSearchScope = object : DelegatingGlobalSearchScope(originalSearchScope) {
|
||||
override fun contains(file: VirtualFile) = super.contains(file) && file != parameters.getOriginalFile().getVirtualFile()
|
||||
override fun contains(file: VirtualFile) = super.contains(file) && file != parameters.originalFile.virtualFile
|
||||
}
|
||||
|
||||
protected fun indicesHelper(mayIncludeInaccessible: Boolean): KotlinIndicesHelper {
|
||||
@@ -208,12 +208,12 @@ abstract class CompletionSession(
|
||||
}
|
||||
|
||||
private fun isTypeParameterVisible(typeParameter: TypeParameterDescriptor): Boolean {
|
||||
val owner = typeParameter.getContainingDeclaration()
|
||||
val owner = typeParameter.containingDeclaration
|
||||
var parent: DeclarationDescriptor? = inDescriptor
|
||||
while (parent != null) {
|
||||
if (parent == owner) return true
|
||||
if (parent is ClassDescriptor && !parent.isInner()) return false
|
||||
parent = parent.getContainingDeclaration()
|
||||
if (parent is ClassDescriptor && !parent.isInner) return false
|
||||
parent = parent.containingDeclaration
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -222,7 +222,7 @@ abstract class CompletionSession(
|
||||
collector.flushToResultSet()
|
||||
}
|
||||
|
||||
public fun complete(): Boolean {
|
||||
fun complete(): Boolean {
|
||||
val statisticsContext = calcContextForStatisticsInfo()
|
||||
if (statisticsContext != null) {
|
||||
collector.addLookupElementPostProcessor { lookupElement ->
|
||||
@@ -237,7 +237,7 @@ abstract class CompletionSession(
|
||||
return !collector.isResultEmpty
|
||||
}
|
||||
|
||||
public fun addLookupElementPostProcessor(processor: (LookupElement) -> LookupElement) {
|
||||
fun addLookupElementPostProcessor(processor: (LookupElement) -> LookupElement) {
|
||||
collector.addLookupElementPostProcessor(processor)
|
||||
}
|
||||
|
||||
|
||||
@@ -102,10 +102,10 @@ fun LookupElement.keepOldArgumentListOnTab(): LookupElement {
|
||||
}
|
||||
|
||||
fun rethrowWithCancelIndicator(exception: ProcessCanceledException): ProcessCanceledException {
|
||||
val indicator = CompletionService.getCompletionService().getCurrentCompletion() as CompletionProgressIndicator
|
||||
val indicator = CompletionService.getCompletionService().currentCompletion as CompletionProgressIndicator
|
||||
|
||||
// Force cancel to avoid deadlock in CompletionThreading.delegateWeighing()
|
||||
if (!indicator.isCanceled()) {
|
||||
if (!indicator.isCanceled) {
|
||||
indicator.cancel()
|
||||
}
|
||||
|
||||
@@ -113,12 +113,12 @@ fun rethrowWithCancelIndicator(exception: ProcessCanceledException): ProcessCanc
|
||||
}
|
||||
|
||||
fun PrefixMatcher.asNameFilter() = { name: Name ->
|
||||
if (name.isSpecial()) {
|
||||
if (name.isSpecial) {
|
||||
false
|
||||
}
|
||||
else {
|
||||
val identifier = name.getIdentifier()
|
||||
if (getPrefix().startsWith("$")) { // we need properties from scope for backing field completion
|
||||
val identifier = name.identifier
|
||||
if (prefix.startsWith("$")) { // we need properties from scope for backing field completion
|
||||
prefixMatches("$" + identifier)
|
||||
}
|
||||
else {
|
||||
@@ -128,10 +128,10 @@ fun PrefixMatcher.asNameFilter() = { name: Name ->
|
||||
}
|
||||
|
||||
fun LookupElementPresentation.prependTailText(text: String, grayed: Boolean) {
|
||||
val tails = getTailFragments()
|
||||
val tails = tailFragments
|
||||
clearTail()
|
||||
appendTailText(text, grayed)
|
||||
tails.forEach { appendTailText(it.text, it.isGrayed()) }
|
||||
tails.forEach { appendTailText(it.text, it.isGrayed) }
|
||||
}
|
||||
|
||||
enum class CallableWeight {
|
||||
@@ -148,8 +148,8 @@ enum class CallableWeight {
|
||||
val CALLABLE_WEIGHT_KEY = Key<CallableWeight>("CALLABLE_WEIGHT_KEY")
|
||||
|
||||
fun InsertionContext.isAfterDot(): Boolean {
|
||||
var offset = getStartOffset()
|
||||
val chars = getDocument().getCharsSequence()
|
||||
var offset = startOffset
|
||||
val chars = document.charsSequence
|
||||
while (offset > 0) {
|
||||
offset--
|
||||
val c = chars[offset]
|
||||
@@ -162,7 +162,7 @@ fun InsertionContext.isAfterDot(): Boolean {
|
||||
|
||||
// do not complete this items by prefix like "is"
|
||||
fun shouldCompleteThisItems(prefixMatcher: PrefixMatcher): Boolean {
|
||||
val prefix = prefixMatcher.getPrefix()
|
||||
val prefix = prefixMatcher.prefix
|
||||
val s = "this@"
|
||||
return prefix.startsWith(s) || s.startsWith(prefix)
|
||||
}
|
||||
@@ -200,7 +200,7 @@ fun returnExpressionItems(bindingContext: BindingContext, position: KtElement):
|
||||
}
|
||||
|
||||
// check if the current function literal is inlined and stop processing outer declarations if it's not
|
||||
val callee = call?.getCalleeExpression() as? KtReferenceExpression ?: break // not inlined
|
||||
val callee = call?.calleeExpression as? KtReferenceExpression ?: break // not inlined
|
||||
if (!InlineUtil.isInline(bindingContext[BindingContext.REFERENCE_TARGET, callee])) break // not inlined
|
||||
}
|
||||
else {
|
||||
@@ -233,7 +233,7 @@ fun returnExpressionItems(bindingContext: BindingContext, position: KtElement):
|
||||
|
||||
private fun KtDeclarationWithBody.returnType(bindingContext: BindingContext): KotlinType? {
|
||||
val callable = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, this] as? CallableDescriptor ?: return null
|
||||
return callable.getReturnType()
|
||||
return callable.returnType
|
||||
}
|
||||
|
||||
private fun Name?.labelNameToTail(): String = if (this != null) "@" + render() else ""
|
||||
@@ -248,7 +248,7 @@ private fun createKeywordElementWithSpace(
|
||||
return if (addSpaceAfter) {
|
||||
object: LookupElementDecorator<LookupElement>(element) {
|
||||
override fun handleInsert(context: InsertionContext) {
|
||||
WithTailInsertHandler.SPACE.handleInsert(context, getDelegate())
|
||||
WithTailInsertHandler.SPACE.handleInsert(context, delegate)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -295,7 +295,7 @@ fun breakOrContinueExpressionItems(position: KtElement, breakOrContinue: String)
|
||||
}
|
||||
|
||||
fun BasicLookupElementFactory.createLookupElementForType(type: KotlinType): LookupElement? {
|
||||
if (type.isError()) return null
|
||||
if (type.isError) return null
|
||||
|
||||
if (KotlinBuiltIns.isExactFunctionOrExtensionFunctionType(type)) {
|
||||
val text = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_IN_TYPES.renderType(type)
|
||||
@@ -303,7 +303,7 @@ fun BasicLookupElementFactory.createLookupElementForType(type: KotlinType): Look
|
||||
return BaseTypeLookupElement(type, baseLookupElement)
|
||||
}
|
||||
else {
|
||||
val classifier = type.getConstructor().getDeclarationDescriptor() ?: return null
|
||||
val classifier = type.constructor.declarationDescriptor ?: return null
|
||||
val baseLookupElement = createLookupElement(classifier, qualifyNestedClasses = true, includeClassTypeArguments = false)
|
||||
|
||||
val itemText = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_IN_TYPES.renderType(type)
|
||||
@@ -311,7 +311,7 @@ fun BasicLookupElementFactory.createLookupElementForType(type: KotlinType): Look
|
||||
val typeLookupElement = object : BaseTypeLookupElement(type, baseLookupElement) {
|
||||
override fun renderElement(presentation: LookupElementPresentation) {
|
||||
super.renderElement(presentation)
|
||||
presentation.setItemText(itemText)
|
||||
presentation.itemText = itemText
|
||||
}
|
||||
}
|
||||
|
||||
@@ -330,13 +330,13 @@ private open class BaseTypeLookupElement(type: KotlinType, baseLookupElement: Lo
|
||||
override fun hashCode() = fullText.hashCode()
|
||||
|
||||
override fun renderElement(presentation: LookupElementPresentation) {
|
||||
getDelegate().renderElement(presentation)
|
||||
delegate.renderElement(presentation)
|
||||
}
|
||||
|
||||
override fun handleInsert(context: InsertionContext) {
|
||||
context.getDocument().replaceString(context.getStartOffset(), context.getTailOffset(), fullText)
|
||||
context.setTailOffset(context.getStartOffset() + fullText.length)
|
||||
shortenReferences(context, context.getStartOffset(), context.getTailOffset())
|
||||
context.document.replaceString(context.startOffset, context.tailOffset, fullText)
|
||||
context.tailOffset = context.startOffset + fullText.length
|
||||
shortenReferences(context, context.startOffset, context.tailOffset)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -361,7 +361,7 @@ fun LookupElement.decorateAsStaticMember(
|
||||
else
|
||||
container
|
||||
|
||||
val qualifierPresentation = classDescriptor.getName().asString()
|
||||
val qualifierPresentation = classDescriptor.name.asString()
|
||||
val qualifierText = IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(classDescriptor)
|
||||
|
||||
return object: LookupElementDecorator<LookupElement>(this) {
|
||||
|
||||
+1
-1
@@ -61,7 +61,7 @@ class RealContextVariablesProvider(
|
||||
class CollectRequiredTypesContextVariablesProvider : ContextVariablesProvider {
|
||||
private val _requiredTypes = HashSet<FuzzyType>()
|
||||
|
||||
public val requiredTypes: Set<FuzzyType>
|
||||
val requiredTypes: Set<FuzzyType>
|
||||
get() = _requiredTypes
|
||||
|
||||
override fun functionTypeVariables(requiredType: FuzzyType): Collection<Pair<VariableDescriptor, TypeSubstitutor>> {
|
||||
|
||||
+3
-3
@@ -28,9 +28,9 @@ fun renderDataFlowValue(value: DataFlowValue): String? {
|
||||
|
||||
fun renderId(id: Any?): String? {
|
||||
return when (id) {
|
||||
is KtExpression -> id.getText()
|
||||
is ImplicitReceiver -> "this@${id.declarationDescriptor.getName()}"
|
||||
is VariableDescriptor -> id.getName().asString()
|
||||
is KtExpression -> id.text
|
||||
is ImplicitReceiver -> "this@${id.declarationDescriptor.name}"
|
||||
is VariableDescriptor -> id.name.asString()
|
||||
is PackageViewDescriptor -> id.fqName.asString()
|
||||
is com.intellij.openapi.util.Pair<*, *> -> renderId(id.first) + "." + renderId(id.second)
|
||||
else -> null
|
||||
|
||||
+7
-7
@@ -33,29 +33,29 @@ import org.jetbrains.kotlin.util.descriptorsEqualWithSubstitution
|
||||
* Stores information about resolved descriptor and position of that descriptor.
|
||||
* Position will be used for sorting
|
||||
*/
|
||||
public abstract class DeclarationLookupObjectImpl(
|
||||
public final override val descriptor: DeclarationDescriptor?,
|
||||
public final override val psiElement: PsiElement?
|
||||
abstract class DeclarationLookupObjectImpl(
|
||||
final override val descriptor: DeclarationDescriptor?,
|
||||
final override val psiElement: PsiElement?
|
||||
): DeclarationLookupObject {
|
||||
init {
|
||||
assert(descriptor != null || psiElement != null)
|
||||
}
|
||||
|
||||
override val name: Name?
|
||||
get() = descriptor?.getName() ?: (psiElement as? PsiNamedElement)?.getName()?.let { Name.identifier(it) }
|
||||
get() = descriptor?.name ?: (psiElement as? PsiNamedElement)?.name?.let { Name.identifier(it) }
|
||||
|
||||
override val importableFqName: FqName?
|
||||
get() {
|
||||
return if (descriptor != null)
|
||||
descriptor.importableFqName
|
||||
else
|
||||
(psiElement as? PsiClass)?.getQualifiedName()?.let { FqName(it) }
|
||||
(psiElement as? PsiClass)?.qualifiedName?.let { FqName(it) }
|
||||
}
|
||||
|
||||
override fun toString() = super<DeclarationLookupObject>.toString() + " " + (descriptor ?: psiElement)
|
||||
|
||||
override fun hashCode(): Int {
|
||||
return if (descriptor != null) descriptor.getOriginal().hashCode() else psiElement!!.hashCode()
|
||||
return if (descriptor != null) descriptor.original.hashCode() else psiElement!!.hashCode()
|
||||
}
|
||||
|
||||
override fun equals(other: Any?): Boolean {
|
||||
@@ -65,5 +65,5 @@ public abstract class DeclarationLookupObjectImpl(
|
||||
return descriptorsEqualWithSubstitution(descriptor, lookupObject.descriptor) && psiElement == lookupObject.psiElement
|
||||
}
|
||||
|
||||
override val isDeprecated = if (descriptor != null) KotlinBuiltIns.isDeprecated(descriptor) else (psiElement as? PsiDocCommentOwner)?.isDeprecated() ?: false
|
||||
override val isDeprecated = if (descriptor != null) KotlinBuiltIns.isDeprecated(descriptor) else (psiElement as? PsiDocCommentOwner)?.isDeprecated ?: false
|
||||
}
|
||||
|
||||
+2
-2
@@ -34,7 +34,7 @@ class InsertHandlerProvider(
|
||||
) {
|
||||
private val expectedInfos by lazy(LazyThreadSafetyMode.NONE) { expectedInfosCalculator() }
|
||||
|
||||
public fun insertHandler(descriptor: DeclarationDescriptor): InsertHandler<LookupElement> {
|
||||
fun insertHandler(descriptor: DeclarationDescriptor): InsertHandler<LookupElement> {
|
||||
if (callType == null) {
|
||||
error("Cannot create InsertHandler when no CallType known")
|
||||
}
|
||||
@@ -50,7 +50,7 @@ class InsertHandlerProvider(
|
||||
|
||||
1 -> {
|
||||
if (callType != CallType.SUPER_MEMBERS) { // for super call we don't suggest to generate "super.foo { ... }" (seems to be non-typical use)
|
||||
val parameterType = parameters.single().getType()
|
||||
val parameterType = parameters.single().type
|
||||
if (KotlinBuiltIns.isExactFunctionOrExtensionFunctionType(parameterType)) {
|
||||
val parameterCount = KotlinBuiltIns.getParameterTypeProjectionsFromFunctionType(parameterType).size
|
||||
if (parameterCount <= 1) {
|
||||
|
||||
+4
-4
@@ -69,7 +69,7 @@ class KDocNameCompletionSession(parameters: CompletionParameters,
|
||||
override val expectedInfos: Collection<ExpectedInfo> get() = emptyList()
|
||||
|
||||
override fun doComplete() {
|
||||
val position = parameters.getPosition().getParentOfType<KDocName>(false) ?: return
|
||||
val position = parameters.position.getParentOfType<KDocName>(false) ?: return
|
||||
val declaration = position.getContainingDoc().getOwner() ?: return
|
||||
val kdocLink = position.getStrictParentOfType<KDocLink>()!!
|
||||
val declarationDescriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, declaration]!!
|
||||
@@ -98,7 +98,7 @@ class KDocNameCompletionSession(parameters: CompletionParameters,
|
||||
|
||||
fun isApplicable(descriptor: DeclarationDescriptor): Boolean {
|
||||
if (descriptor is CallableDescriptor) {
|
||||
val extensionReceiver = descriptor.getExtensionReceiverParameter()
|
||||
val extensionReceiver = descriptor.extensionReceiverParameter
|
||||
if (extensionReceiver != null) {
|
||||
val substituted = descriptor.substituteExtensionIfCallable(implicitReceivers, bindingContext, DataFlowInfo.EMPTY,
|
||||
CallType.DEFAULT, moduleDescriptor)
|
||||
@@ -123,8 +123,8 @@ object KDocTagCompletionProvider: CompletionProvider<CompletionParameters>() {
|
||||
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) {
|
||||
// findIdentifierPrefix() requires identifier part characters to be a superset of identifier start characters
|
||||
val prefix = CompletionUtil.findIdentifierPrefix(
|
||||
parameters.getPosition().getContainingFile(),
|
||||
parameters.getOffset(),
|
||||
parameters.position.containingFile,
|
||||
parameters.offset,
|
||||
StandardPatterns.character().javaIdentifierPart() or singleCharPattern('@'),
|
||||
StandardPatterns.character().javaIdentifierStart() or singleCharPattern('@'))
|
||||
|
||||
|
||||
+22
-22
@@ -45,7 +45,7 @@ open class KeywordLookupObject
|
||||
|
||||
object KeywordCompletion {
|
||||
private val NON_ACTUAL_KEYWORDS = setOf(TYPE_ALIAS_KEYWORD)
|
||||
private val ALL_KEYWORDS = (KEYWORDS.getTypes() + SOFT_KEYWORDS.getTypes())
|
||||
private val ALL_KEYWORDS = (KEYWORDS.types + SOFT_KEYWORDS.types)
|
||||
.filter { it !in NON_ACTUAL_KEYWORDS }
|
||||
.map { it as KtKeywordToken }
|
||||
|
||||
@@ -57,18 +57,18 @@ object KeywordCompletion {
|
||||
ANNOTATION_KEYWORD to CLASS_KEYWORD
|
||||
)
|
||||
|
||||
public fun complete(position: PsiElement, prefix: String, isJvmModule: Boolean, consumer: (LookupElement) -> Unit) {
|
||||
fun complete(position: PsiElement, prefix: String, isJvmModule: Boolean, consumer: (LookupElement) -> Unit) {
|
||||
if (!GENERAL_FILTER.isAcceptable(position, position)) return
|
||||
|
||||
val parserFilter = buildFilter(position)
|
||||
for (keywordToken in ALL_KEYWORDS) {
|
||||
var keyword = keywordToken.getValue()
|
||||
var keyword = keywordToken.value
|
||||
|
||||
val nextKeyword = COMPOUND_KEYWORDS[keywordToken]
|
||||
if (nextKeyword != null) {
|
||||
fun PsiElement.isSpace() = this is PsiWhiteSpace && '\n' !in getText()
|
||||
|
||||
var next = position.nextLeaf { !(it.isSpace() || it.getText() == "$") }?.getText()
|
||||
var next = position.nextLeaf { !(it.isSpace() || it.text == "$") }?.text
|
||||
if (next != null && next.startsWith("$")) {
|
||||
next = next.substring(1)
|
||||
}
|
||||
@@ -128,13 +128,13 @@ object KeywordCompletion {
|
||||
}
|
||||
|
||||
override fun isAcceptable(element : Any?, context : PsiElement?) : Boolean {
|
||||
val parent = (element as? PsiElement)?.getParent()
|
||||
return parent != null && (getFilter()?.isAcceptable(parent, context) ?: true)
|
||||
val parent = (element as? PsiElement)?.parent
|
||||
return parent != null && (filter?.isAcceptable(parent, context) ?: true)
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildFilter(position: PsiElement): (KtKeywordToken) -> Boolean {
|
||||
var parent = position.getParent()
|
||||
var parent = position.parent
|
||||
var prevParent = position
|
||||
while (parent != null) {
|
||||
when (parent) {
|
||||
@@ -143,14 +143,14 @@ object KeywordCompletion {
|
||||
}
|
||||
|
||||
is KtWithExpressionInitializer -> {
|
||||
val initializer = parent.getInitializer()
|
||||
val initializer = parent.initializer
|
||||
if (prevParent == initializer) {
|
||||
return buildFilterWithContext("val v = ", initializer!!, position)
|
||||
}
|
||||
}
|
||||
|
||||
is KtParameter -> {
|
||||
val default = parent.getDefaultValue()
|
||||
val default = parent.defaultValue
|
||||
if (prevParent == default) {
|
||||
return buildFilterWithContext("val v = ", default!!, position)
|
||||
}
|
||||
@@ -184,8 +184,8 @@ object KeywordCompletion {
|
||||
contextElement: PsiElement,
|
||||
position: PsiElement): (KtKeywordToken) -> Boolean {
|
||||
val offset = position.getStartOffsetInAncestor(contextElement)
|
||||
val truncatedContext = contextElement.getText()!!.substring(0, offset)
|
||||
return buildFilterByText(prefixText + truncatedContext, contextElement.getProject())
|
||||
val truncatedContext = contextElement.text!!.substring(0, offset)
|
||||
return buildFilterByText(prefixText + truncatedContext, contextElement.project)
|
||||
}
|
||||
|
||||
private fun buildFilterWithReducedContext(prefixText: String,
|
||||
@@ -193,7 +193,7 @@ object KeywordCompletion {
|
||||
position: PsiElement): (KtKeywordToken) -> Boolean {
|
||||
val builder = StringBuilder()
|
||||
buildReducedContextBefore(builder, position, contextElement)
|
||||
return buildFilterByText(prefixText + builder.toString(), position.getProject())
|
||||
return buildFilterByText(prefixText + builder.toString(), position.project)
|
||||
}
|
||||
|
||||
|
||||
@@ -201,11 +201,11 @@ object KeywordCompletion {
|
||||
val psiFactory = KtPsiFactory(project)
|
||||
return fun (keywordTokenType): Boolean {
|
||||
val postfix = if (prefixText.endsWith("@")) ":X" else " X"
|
||||
val file = psiFactory.createFile(prefixText + keywordTokenType.getValue() + postfix)
|
||||
val file = psiFactory.createFile(prefixText + keywordTokenType.value + postfix)
|
||||
val elementAt = file.findElementAt(prefixText.length)!!
|
||||
|
||||
when {
|
||||
!elementAt.getNode()!!.getElementType().matchesKeyword(keywordTokenType) -> return false
|
||||
!elementAt.node!!.elementType.matchesKeyword(keywordTokenType) -> return false
|
||||
|
||||
elementAt.getNonStrictParentOfType<PsiErrorElement>() != null -> return false
|
||||
|
||||
@@ -289,13 +289,13 @@ object KeywordCompletion {
|
||||
// builds text within scope (or from the start of the file) before position element excluding almost all declarations
|
||||
private fun buildReducedContextBefore(builder: StringBuilder, position: PsiElement, scope: PsiElement?) {
|
||||
if (position == scope) return
|
||||
val parent = position.getParent() ?: return
|
||||
val parent = position.parent ?: return
|
||||
|
||||
buildReducedContextBefore(builder, parent, scope)
|
||||
|
||||
val prevDeclaration = position.siblings(forward = false, withItself = false).firstOrNull { it is KtDeclaration }
|
||||
|
||||
var child = parent.getFirstChild()
|
||||
var child = parent.firstChild
|
||||
while (child != position) {
|
||||
if (child is KtDeclaration) {
|
||||
if (child == prevDeclaration) {
|
||||
@@ -303,17 +303,17 @@ object KeywordCompletion {
|
||||
}
|
||||
}
|
||||
else {
|
||||
builder.append(child!!.getText())
|
||||
builder.append(child!!.text)
|
||||
}
|
||||
|
||||
child = child.getNextSibling()
|
||||
child = child.nextSibling
|
||||
}
|
||||
}
|
||||
|
||||
private fun StringBuilder.appendReducedText(element: PsiElement) {
|
||||
var child = element.getFirstChild()
|
||||
var child = element.firstChild
|
||||
if (child == null) {
|
||||
append(element.getText()!!)
|
||||
append(element.text!!)
|
||||
}
|
||||
else {
|
||||
while (child != null) {
|
||||
@@ -322,13 +322,13 @@ object KeywordCompletion {
|
||||
else -> appendReducedText(child)
|
||||
}
|
||||
|
||||
child = child.getNextSibling()
|
||||
child = child.nextSibling
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun PsiElement.getStartOffsetInAncestor(ancestor: PsiElement): Int {
|
||||
if (ancestor == this) return 0
|
||||
return getParent()!!.getStartOffsetInAncestor(ancestor) + getStartOffsetInParent()
|
||||
return parent!!.getStartOffsetInAncestor(ancestor) + startOffsetInParent
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,7 +83,7 @@ object KeywordValues {
|
||||
}
|
||||
|
||||
val nullMatcher = { info: ExpectedInfo ->
|
||||
if (info.fuzzyType != null && info.fuzzyType!!.type.isMarkedNullable())
|
||||
if (info.fuzzyType != null && info.fuzzyType!!.type.isMarkedNullable)
|
||||
ExpectedInfoMatch.match(TypeSubstitutor.EMPTY)
|
||||
else
|
||||
ExpectedInfoMatch.noMatch
|
||||
|
||||
+20
-20
@@ -30,33 +30,33 @@ import org.jetbrains.kotlin.psi.KtFile
|
||||
import org.jetbrains.kotlin.psi.KtFunctionLiteral
|
||||
import org.jetbrains.kotlin.psi.psiUtil.prevLeaf
|
||||
|
||||
public class KotlinCompletionCharFilter() : CharFilter() {
|
||||
class KotlinCompletionCharFilter() : CharFilter() {
|
||||
companion object {
|
||||
public val ACCEPT_OPENING_BRACE: Key<Unit> = Key("KotlinCompletionCharFilter.ACCEPT_OPENING_BRACE")
|
||||
val ACCEPT_OPENING_BRACE: Key<Unit> = Key("KotlinCompletionCharFilter.ACCEPT_OPENING_BRACE")
|
||||
|
||||
public val SUPPRESS_ITEM_SELECTION_BY_CHARS_ON_TYPING: Key<Unit> = Key("KotlinCompletionCharFilter.SUPPRESS_ITEM_SELECTION_BY_CHARS_ON_TYPING")
|
||||
public val HIDE_LOOKUP_ON_COLON: Key<Unit> = Key("KotlinCompletionCharFilter.HIDE_LOOKUP_ON_COLON")
|
||||
val SUPPRESS_ITEM_SELECTION_BY_CHARS_ON_TYPING: Key<Unit> = Key("KotlinCompletionCharFilter.SUPPRESS_ITEM_SELECTION_BY_CHARS_ON_TYPING")
|
||||
val HIDE_LOOKUP_ON_COLON: Key<Unit> = Key("KotlinCompletionCharFilter.HIDE_LOOKUP_ON_COLON")
|
||||
|
||||
public val JUST_TYPING_PREFIX: Key<String> = Key("KotlinCompletionCharFilter.JUST_TYPING_PREFIX")
|
||||
val JUST_TYPING_PREFIX: Key<String> = Key("KotlinCompletionCharFilter.JUST_TYPING_PREFIX")
|
||||
}
|
||||
|
||||
override fun acceptChar(c : Char, prefixLength : Int, lookup : Lookup) : Result? {
|
||||
if (lookup.getPsiFile() !is KtFile) return null
|
||||
if (!lookup.isCompletion()) return null
|
||||
if (lookup.psiFile !is KtFile) return null
|
||||
if (!lookup.isCompletion) return null
|
||||
// it does not work in tests, so we use other way
|
||||
// val isAutopopup = CompletionService.getCompletionService().getCurrentCompletion().isAutopopupCompletion()
|
||||
val completionParameters = (CompletionService.getCompletionService().getCurrentCompletion() as CompletionProgressIndicator).getParameters()
|
||||
val isAutopopup = completionParameters.getInvocationCount() == 0
|
||||
val completionParameters = (CompletionService.getCompletionService().currentCompletion as CompletionProgressIndicator).parameters
|
||||
val isAutopopup = completionParameters.invocationCount == 0
|
||||
|
||||
if (Character.isJavaIdentifierPart(c) || c == '@') {
|
||||
return CharFilter.Result.ADD_TO_PREFIX
|
||||
}
|
||||
|
||||
val currentItem = lookup.getCurrentItem()
|
||||
val currentItem = lookup.currentItem
|
||||
|
||||
// do not accept items by special chars in some special positions such as in the very beginning of function literal where name of the first parameter can be
|
||||
if (isAutopopup && !lookup.isSelectionTouched()
|
||||
&& (currentItem?.getUserData(SUPPRESS_ITEM_SELECTION_BY_CHARS_ON_TYPING) != null || isInFunctionLiteralStart(completionParameters.getPosition()))) {
|
||||
if (isAutopopup && !lookup.isSelectionTouched
|
||||
&& (currentItem?.getUserData(SUPPRESS_ITEM_SELECTION_BY_CHARS_ON_TYPING) != null || isInFunctionLiteralStart(completionParameters.position))) {
|
||||
return Result.HIDE_LOOKUP
|
||||
}
|
||||
|
||||
@@ -67,15 +67,15 @@ public class KotlinCompletionCharFilter() : CharFilter() {
|
||||
}
|
||||
}
|
||||
|
||||
if (!lookup.isSelectionTouched()) {
|
||||
if (!lookup.isSelectionTouched) {
|
||||
currentItem?.putUserDataDeep(JUST_TYPING_PREFIX, lookup.itemPattern(currentItem))
|
||||
}
|
||||
|
||||
return when (c) {
|
||||
'.' -> {
|
||||
if (prefixLength == 0 && isAutopopup && !lookup.isSelectionTouched()) {
|
||||
val caret = lookup.getEditor().getCaretModel().getOffset()
|
||||
if (caret > 0 && lookup.getEditor().getDocument().getCharsSequence()[caret - 1] == '.') {
|
||||
if (prefixLength == 0 && isAutopopup && !lookup.isSelectionTouched) {
|
||||
val caret = lookup.editor.caretModel.offset
|
||||
if (caret > 0 && lookup.editor.document.charsSequence[caret - 1] == '.') {
|
||||
return Result.HIDE_LOOKUP
|
||||
}
|
||||
}
|
||||
@@ -97,11 +97,11 @@ public class KotlinCompletionCharFilter() : CharFilter() {
|
||||
|
||||
private fun isInFunctionLiteralStart(position: PsiElement): Boolean {
|
||||
var prev = position.prevLeaf { it !is PsiWhiteSpace && it !is PsiComment }
|
||||
if (prev?.getNode()?.getElementType() == KtTokens.LPAR) {
|
||||
if (prev?.node?.elementType == KtTokens.LPAR) {
|
||||
prev = prev?.prevLeaf { it !is PsiWhiteSpace && it !is PsiComment }
|
||||
}
|
||||
if (prev?.getNode()?.getElementType() != KtTokens.LBRACE) return false
|
||||
val functionLiteral = prev!!.getParent() as? KtFunctionLiteral ?: return false
|
||||
return functionLiteral.getLBrace() == prev
|
||||
if (prev?.node?.elementType != KtTokens.LBRACE) return false
|
||||
val functionLiteral = prev!!.parent as? KtFunctionLiteral ?: return false
|
||||
return functionLiteral.lBrace == prev
|
||||
}
|
||||
}
|
||||
|
||||
+43
-43
@@ -45,14 +45,14 @@ import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
|
||||
import org.jetbrains.kotlin.utils.addToStdlib.check
|
||||
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
|
||||
|
||||
public var KtFile.doNotComplete: Boolean? by UserDataProperty(Key.create("DO_NOT_COMPLETE"))
|
||||
var KtFile.doNotComplete: Boolean? by UserDataProperty(Key.create("DO_NOT_COMPLETE"))
|
||||
|
||||
public class KotlinCompletionContributor : CompletionContributor() {
|
||||
class KotlinCompletionContributor : CompletionContributor() {
|
||||
private val AFTER_NUMBER_LITERAL = psiElement().afterLeafSkipping(psiElement().withText(""), psiElement().withElementType(elementType().oneOf(KtTokens.FLOAT_LITERAL, KtTokens.INTEGER_LITERAL)))
|
||||
private val AFTER_INTEGER_LITERAL_AND_DOT = psiElement().afterLeafSkipping(psiElement().withText("."), psiElement().withElementType(elementType().oneOf(KtTokens.INTEGER_LITERAL)))
|
||||
|
||||
companion object {
|
||||
public val DEFAULT_DUMMY_IDENTIFIER: String = CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED + "$" // add '$' to ignore context after the caret
|
||||
val DEFAULT_DUMMY_IDENTIFIER: String = CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED + "$" // add '$' to ignore context after the caret
|
||||
|
||||
private val STRING_TEMPLATE_AFTER_DOT_REAL_START_OFFSET = OffsetKey.create("STRING_TEMPLATE_AFTER_DOT_REAL_START_OFFSET")
|
||||
}
|
||||
@@ -68,13 +68,13 @@ public class KotlinCompletionContributor : CompletionContributor() {
|
||||
}
|
||||
|
||||
override fun beforeCompletion(context: CompletionInitializationContext) {
|
||||
val psiFile = context.getFile()
|
||||
val psiFile = context.file
|
||||
if (psiFile !is KtFile) return
|
||||
|
||||
// this code will make replacement offset "modified" and prevents altering it by the code in CompletionProgressIndicator
|
||||
context.replacementOffset = context.replacementOffset
|
||||
|
||||
val offset = context.getStartOffset()
|
||||
val offset = context.startOffset
|
||||
val tokenBefore = psiFile.findElementAt(Math.max(0, offset - 1))
|
||||
|
||||
if (offset > 0 && tokenBefore!!.node.elementType == KtTokens.REGULAR_STRING_PART && tokenBefore.text.startsWith(".")) {
|
||||
@@ -92,7 +92,7 @@ public class KotlinCompletionContributor : CompletionContributor() {
|
||||
}
|
||||
|
||||
context.dummyIdentifier = when {
|
||||
context.getCompletionType() == CompletionType.SMART -> DEFAULT_DUMMY_IDENTIFIER
|
||||
context.completionType == CompletionType.SMART -> DEFAULT_DUMMY_IDENTIFIER
|
||||
|
||||
PackageDirectiveCompletion.ACTIVATION_PATTERN.accepts(tokenBefore) -> PackageDirectiveCompletion.DUMMY_IDENTIFIER
|
||||
|
||||
@@ -109,30 +109,30 @@ public class KotlinCompletionContributor : CompletionContributor() {
|
||||
?: DEFAULT_DUMMY_IDENTIFIER
|
||||
}
|
||||
|
||||
if (context.getCompletionType() == CompletionType.SMART && !isAtEndOfLine(offset, context.getEditor().getDocument()) /* do not use parent expression if we are at the end of line - it's probably parsed incorrectly */) {
|
||||
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 */) {
|
||||
val tokenAt = psiFile.findElementAt(Math.max(0, offset))
|
||||
if (tokenAt != null) {
|
||||
var parent = tokenAt.getParent()
|
||||
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
|
||||
parent = expression.getParent()
|
||||
parent = expression.parent
|
||||
while (parent is KtExpression && parent.getFirstChild() == expression) {
|
||||
expression = parent
|
||||
parent = expression.getParent()
|
||||
parent = expression.parent
|
||||
}
|
||||
|
||||
val suggestedReplacementOffset = replacementOffsetByExpression(expression)
|
||||
if (suggestedReplacementOffset > context.getReplacementOffset()) {
|
||||
context.setReplacementOffset(suggestedReplacementOffset)
|
||||
if (suggestedReplacementOffset > context.replacementOffset) {
|
||||
context.replacementOffset = suggestedReplacementOffset
|
||||
}
|
||||
|
||||
context.getOffsetMap().addOffset(SmartCompletion.OLD_ARGUMENTS_REPLACEMENT_OFFSET, expression.endOffset)
|
||||
context.offsetMap.addOffset(SmartCompletion.OLD_ARGUMENTS_REPLACEMENT_OFFSET, expression.endOffset)
|
||||
|
||||
val argumentList = (expression.getParent() as? KtValueArgument)?.getParent() as? KtValueArgumentList
|
||||
val argumentList = (expression.parent as? KtValueArgument)?.parent as? KtValueArgumentList
|
||||
if (argumentList != null) {
|
||||
context.getOffsetMap().addOffset(SmartCompletion.MULTIPLE_ARGUMENTS_REPLACEMENT_OFFSET,
|
||||
argumentList.getRightParenthesis()?.getTextRange()?.getStartOffset() ?: argumentList.endOffset)
|
||||
context.offsetMap.addOffset(SmartCompletion.MULTIPLE_ARGUMENTS_REPLACEMENT_OFFSET,
|
||||
argumentList.rightParenthesis?.textRange?.startOffset ?: argumentList.endOffset)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -142,25 +142,25 @@ public class KotlinCompletionContributor : CompletionContributor() {
|
||||
private fun replacementOffsetByExpression(expression: KtExpression): Int {
|
||||
when (expression) {
|
||||
is KtCallExpression -> {
|
||||
val calleeExpression = expression.getCalleeExpression()
|
||||
val calleeExpression = expression.calleeExpression
|
||||
if (calleeExpression != null) {
|
||||
return calleeExpression.getTextRange()!!.getEndOffset()
|
||||
return calleeExpression.textRange!!.endOffset
|
||||
}
|
||||
}
|
||||
|
||||
is KtQualifiedExpression -> {
|
||||
val selector = expression.getSelectorExpression()
|
||||
val selector = expression.selectorExpression
|
||||
if (selector != null) {
|
||||
return replacementOffsetByExpression(selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
return expression.getTextRange()!!.getEndOffset()
|
||||
return expression.textRange!!.endOffset
|
||||
}
|
||||
|
||||
private fun isInClassHeader(tokenBefore: PsiElement?): Boolean {
|
||||
val classOrObject = tokenBefore?.parents?.firstIsInstanceOrNull<KtClassOrObject>() ?: return false
|
||||
val name = classOrObject.getNameIdentifier() ?: return false
|
||||
val name = classOrObject.nameIdentifier ?: return false
|
||||
val body = classOrObject.getBody() ?: return false
|
||||
val offset = tokenBefore!!.startOffset
|
||||
return name.endOffset <= offset && offset <= body.startOffset
|
||||
@@ -204,11 +204,11 @@ public class KotlinCompletionContributor : CompletionContributor() {
|
||||
var gtCount = 0
|
||||
val builder = StringBuilder()
|
||||
while (true) {
|
||||
val tokenType = token.getNode()!!.getElementType()
|
||||
val tokenType = token.node!!.elementType
|
||||
if (tokenType in declarationKeywords) {
|
||||
val balance = ltCount - gtCount
|
||||
if (balance < 0) return null
|
||||
builder.append(token.getText()!!.reversed())
|
||||
builder.append(token.text!!.reversed())
|
||||
builder.reverse()
|
||||
|
||||
var tail = "X" + ">".repeat(balance) + ".f"
|
||||
@@ -218,16 +218,16 @@ public class KotlinCompletionContributor : CompletionContributor() {
|
||||
builder.append(tail)
|
||||
|
||||
val text = builder.toString()
|
||||
val file = KtPsiFactory(tokenBefore.getProject()).createFile(text)
|
||||
val declaration = file.getDeclarations().singleOrNull() ?: return null
|
||||
if (declaration.getTextLength() != text.length) return null
|
||||
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 })
|
||||
return if (containsErrorElement) null else tail + "$"
|
||||
}
|
||||
if (tokenType !in declarationTokens) return null
|
||||
if (tokenType == KtTokens.LT) ltCount++
|
||||
if (tokenType == KtTokens.GT) gtCount++
|
||||
builder.append(token.getText()!!.reversed())
|
||||
builder.append(token.text!!.reversed())
|
||||
token = PsiTreeUtil.prevLeaf(token) ?: return null
|
||||
}
|
||||
}
|
||||
@@ -270,7 +270,7 @@ public class KotlinCompletionContributor : CompletionContributor() {
|
||||
return
|
||||
}
|
||||
|
||||
if (shouldSuppressCompletion(parameters, result.getPrefixMatcher())) {
|
||||
if (shouldSuppressCompletion(parameters, result.prefixMatcher)) {
|
||||
result.stopHere()
|
||||
return
|
||||
}
|
||||
@@ -292,12 +292,12 @@ public class KotlinCompletionContributor : CompletionContributor() {
|
||||
result.restartCompletionWhenNothingMatches()
|
||||
|
||||
val configuration = CompletionSessionConfiguration(parameters)
|
||||
if (parameters.getCompletionType() == CompletionType.BASIC) {
|
||||
if (parameters.completionType == CompletionType.BASIC) {
|
||||
val session = BasicCompletionSession(configuration, parameters, toFromOriginalFileMapper, result)
|
||||
|
||||
addPostProcessor(session)
|
||||
|
||||
if (parameters.isAutoPopup() && session.shouldDisableAutoPopup()) {
|
||||
if (parameters.isAutoPopup && session.shouldDisableAutoPopup()) {
|
||||
result.stopHere()
|
||||
return
|
||||
}
|
||||
@@ -356,14 +356,14 @@ public class KotlinCompletionContributor : CompletionContributor() {
|
||||
}
|
||||
|
||||
private fun shouldSuppressCompletion(parameters: CompletionParameters, prefixMatcher: PrefixMatcher): Boolean {
|
||||
val position = parameters.getPosition()
|
||||
val invocationCount = parameters.getInvocationCount()
|
||||
val position = parameters.position
|
||||
val invocationCount = parameters.invocationCount
|
||||
|
||||
// no completion inside number literals
|
||||
if (AFTER_NUMBER_LITERAL.accepts(position)) return true
|
||||
|
||||
// no completion auto-popup after integer and dot
|
||||
if (invocationCount == 0 && prefixMatcher.getPrefix().isEmpty() && AFTER_INTEGER_LITERAL_AND_DOT.accepts(position)) return true
|
||||
if (invocationCount == 0 && prefixMatcher.prefix.isEmpty() && AFTER_INTEGER_LITERAL_AND_DOT.accepts(position)) return 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 (invocationCount == 0) {
|
||||
@@ -380,11 +380,11 @@ public class KotlinCompletionContributor : CompletionContributor() {
|
||||
}
|
||||
|
||||
private fun isInExtensionReceiverOf(position: PsiElement): KtCallableDeclaration? {
|
||||
val nameRef = position.getParent() as? KtNameReferenceExpression ?: return null
|
||||
val userType = nameRef.getParent() as? KtUserType ?: return null
|
||||
val typeRef = userType.getParent() as? KtTypeReference ?: return null
|
||||
val nameRef = position.parent as? KtNameReferenceExpression ?: return null
|
||||
val userType = nameRef.parent as? KtUserType ?: return null
|
||||
val typeRef = userType.parent as? KtTypeReference ?: return null
|
||||
if (userType != typeRef.typeElement) return null
|
||||
val parent = typeRef.getParent()
|
||||
val parent = typeRef.parent
|
||||
return when (parent) {
|
||||
is KtNamedFunction -> parent.check { typeRef == it.receiverTypeReference }
|
||||
is KtProperty -> parent.check { typeRef == it.receiverTypeReference }
|
||||
@@ -394,7 +394,7 @@ public class KotlinCompletionContributor : CompletionContributor() {
|
||||
|
||||
private fun isAtEndOfLine(offset: Int, document: Document): Boolean {
|
||||
var i = offset
|
||||
val chars = document.getCharsSequence()
|
||||
val chars = document.charsSequence
|
||||
while (i < chars.length) {
|
||||
val c = chars[i]
|
||||
if (c == '\n') return true
|
||||
@@ -415,10 +415,10 @@ public class KotlinCompletionContributor : CompletionContributor() {
|
||||
val (nameToken, balance) = pair
|
||||
assert(balance > 0)
|
||||
|
||||
val nameRef = nameToken.getParent() as? KtNameReferenceExpression ?: return null
|
||||
val nameRef = nameToken.parent as? KtNameReferenceExpression ?: return null
|
||||
val bindingContext = nameRef.getResolutionFacade().analyze(nameRef, BodyResolveMode.PARTIAL)
|
||||
val targets = nameRef.getReferenceTargets(bindingContext)
|
||||
if (targets.isNotEmpty() && targets.all { it is FunctionDescriptor || it is ClassDescriptor && it.getKind() == ClassKind.CLASS }) {
|
||||
if (targets.isNotEmpty() && targets.all { it is FunctionDescriptor || it is ClassDescriptor && it.kind == ClassKind.CLASS }) {
|
||||
return CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED + ">".repeat(balance) + "$"
|
||||
}
|
||||
else {
|
||||
@@ -447,12 +447,12 @@ public class KotlinCompletionContributor : CompletionContributor() {
|
||||
private fun findCallNameTokenIfInTypeArgs(leaf: PsiElement): PsiElement? {
|
||||
var current = leaf
|
||||
while (true) {
|
||||
val tokenType = current.getNode()!!.getElementType()
|
||||
val tokenType = current.node!!.elementType
|
||||
if (tokenType !in callTypeArgsTokens) return null
|
||||
|
||||
if (tokenType == KtTokens.LT) {
|
||||
val nameToken = current.prevLeaf(skipEmptyElements = true) ?: return null
|
||||
if (nameToken.getNode()!!.getElementType() != KtTokens.IDENTIFIER) return null
|
||||
if (nameToken.node!!.elementType != KtTokens.IDENTIFIER) return null
|
||||
return nameToken
|
||||
}
|
||||
|
||||
@@ -472,7 +472,7 @@ public class KotlinCompletionContributor : CompletionContributor() {
|
||||
// and the following block will not be attached as a body to the constructor. Therefore
|
||||
// we need to use a regular identifier.
|
||||
val argumentList = tokenBefore?.getNonStrictParentOfType<KtValueArgumentList>() ?: return null
|
||||
if (argumentList.getParent() is KtConstructorDelegationCall) return CompletionUtil.DUMMY_IDENTIFIER_TRIMMED
|
||||
if (argumentList.parent is KtConstructorDelegationCall) return CompletionUtil.DUMMY_IDENTIFIER_TRIMMED
|
||||
return null
|
||||
}
|
||||
|
||||
|
||||
+3
-3
@@ -29,11 +29,11 @@ import org.jetbrains.kotlin.idea.core.completion.DeclarationLookupObject
|
||||
import org.jetbrains.kotlin.idea.imports.importableFqName
|
||||
import org.jetbrains.kotlin.name.FqName
|
||||
|
||||
public class KotlinExcludeFromCompletionLookupActionProvider : LookupActionProvider {
|
||||
class KotlinExcludeFromCompletionLookupActionProvider : LookupActionProvider {
|
||||
override fun fillActions(element: LookupElement, lookup: Lookup, consumer: Consumer<LookupElementAction>) {
|
||||
val lookupObject = element.getObject() as? DeclarationLookupObject ?: return
|
||||
val lookupObject = element.`object` as? DeclarationLookupObject ?: return
|
||||
|
||||
val project = lookup.getPsiFile().getProject()
|
||||
val project = lookup.psiFile.project
|
||||
|
||||
lookupObject.importableFqName?.let {
|
||||
addExcludes(consumer, project, it.asString())
|
||||
|
||||
@@ -22,10 +22,10 @@ import com.intellij.psi.filters.ElementFilter
|
||||
import com.intellij.psi.impl.source.tree.LeafPsiElement
|
||||
import com.intellij.psi.tree.IElementType
|
||||
|
||||
public class LeafElementFilter(private val elementType: IElementType) : ElementFilter {
|
||||
class LeafElementFilter(private val elementType: IElementType) : ElementFilter {
|
||||
|
||||
override fun isAcceptable(element: Any?, context: PsiElement?)
|
||||
= element is LeafPsiElement && element.getElementType() == elementType
|
||||
= element is LeafPsiElement && element.elementType == elementType
|
||||
|
||||
override fun isClassAcceptable(hintClass: Class<*>)
|
||||
= LEAF_CLASS_FILTER.isClassAcceptable(hintClass)
|
||||
|
||||
+3
-3
@@ -240,12 +240,12 @@ class LookupElementFactory(
|
||||
override fun renderElement(presentation: LookupElementPresentation) {
|
||||
super.renderElement(presentation)
|
||||
if (style == Style.BOLD) {
|
||||
presentation.setItemTextBold(true)
|
||||
presentation.isItemTextBold = true
|
||||
}
|
||||
else {
|
||||
presentation.setItemTextForeground(LookupCellRenderer.getGrayedForeground(false))
|
||||
presentation.itemTextForeground = LookupCellRenderer.getGrayedForeground(false)
|
||||
// gray all tail fragments too:
|
||||
val fragments = presentation.getTailFragments()
|
||||
val fragments = presentation.tailFragments
|
||||
presentation.clearTail()
|
||||
for (fragment in fragments) {
|
||||
presentation.appendTailText(fragment.text, true)
|
||||
|
||||
+16
-16
@@ -42,7 +42,7 @@ class LookupElementsCollector(
|
||||
|
||||
private val postProcessors = ArrayList<(LookupElement) -> LookupElement>()
|
||||
|
||||
public fun flushToResultSet() {
|
||||
fun flushToResultSet() {
|
||||
if (!elements.isEmpty()) {
|
||||
resultSet.addAllElements(elements)
|
||||
elements.clear()
|
||||
@@ -50,14 +50,14 @@ class LookupElementsCollector(
|
||||
}
|
||||
}
|
||||
|
||||
public var isResultEmpty: Boolean = true
|
||||
var isResultEmpty: Boolean = true
|
||||
private set
|
||||
|
||||
public fun addLookupElementPostProcessor(processor: (LookupElement) -> LookupElement) {
|
||||
fun addLookupElementPostProcessor(processor: (LookupElement) -> LookupElement) {
|
||||
postProcessors.add(processor)
|
||||
}
|
||||
|
||||
public fun addDescriptorElements(descriptors: Iterable<DeclarationDescriptor>,
|
||||
fun addDescriptorElements(descriptors: Iterable<DeclarationDescriptor>,
|
||||
lookupElementFactory: LookupElementFactory,
|
||||
notImported: Boolean = false,
|
||||
withReceiverCast: Boolean = false
|
||||
@@ -67,7 +67,7 @@ class LookupElementsCollector(
|
||||
}
|
||||
}
|
||||
|
||||
public fun addDescriptorElements(
|
||||
fun addDescriptorElements(
|
||||
descriptor: DeclarationDescriptor,
|
||||
lookupElementFactory: LookupElementFactory,
|
||||
notImported: Boolean = false,
|
||||
@@ -82,7 +82,7 @@ class LookupElementsCollector(
|
||||
addElements(lookupElements, notImported)
|
||||
}
|
||||
|
||||
public fun addElement(element: LookupElement, notImported: Boolean = false) {
|
||||
fun addElement(element: LookupElement, notImported: Boolean = false) {
|
||||
if (!prefixMatcher.prefixMatches(element)) return
|
||||
|
||||
if (notImported) {
|
||||
@@ -98,13 +98,13 @@ class LookupElementsCollector(
|
||||
|
||||
val decorated = object : LookupElementDecorator<LookupElement>(element) {
|
||||
override fun handleInsert(context: InsertionContext) {
|
||||
getDelegate().handleInsert(context)
|
||||
delegate.handleInsert(context)
|
||||
|
||||
if (context.shouldAddCompletionChar() && !isJustTyping(context, this)) {
|
||||
when (context.getCompletionChar()) {
|
||||
',' -> WithTailInsertHandler.COMMA.postHandleInsert(context, getDelegate())
|
||||
when (context.completionChar) {
|
||||
',' -> WithTailInsertHandler.COMMA.postHandleInsert(context, delegate)
|
||||
|
||||
'=' -> WithTailInsertHandler.EQ.postHandleInsert(context, getDelegate())
|
||||
'=' -> WithTailInsertHandler.EQ.postHandleInsert(context, delegate)
|
||||
|
||||
'!' -> {
|
||||
WithExpressionPrefixInsertHandler("!").postHandleInsert(context)
|
||||
@@ -133,20 +133,20 @@ class LookupElementsCollector(
|
||||
|
||||
// used to avoid insertion of spaces before/after ',', '=' on just typing
|
||||
private fun isJustTyping(context: InsertionContext, element: LookupElement): Boolean {
|
||||
if (!completionParameters.isAutoPopup()) return false
|
||||
val insertedText = context.getDocument().getText(TextRange(context.getStartOffset(), context.getTailOffset()))
|
||||
if (!completionParameters.isAutoPopup) return false
|
||||
val insertedText = context.document.getText(TextRange(context.startOffset, context.tailOffset))
|
||||
return insertedText == element.getUserDataDeep(KotlinCompletionCharFilter.JUST_TYPING_PREFIX)
|
||||
}
|
||||
|
||||
public fun addElements(elements: Iterable<LookupElement>, notImported: Boolean = false) {
|
||||
fun addElements(elements: Iterable<LookupElement>, notImported: Boolean = false) {
|
||||
elements.forEach { addElement(it, notImported) }
|
||||
}
|
||||
|
||||
public fun advertiseSecondCompletion() {
|
||||
JavaCompletionContributor.advertiseSecondCompletion(completionParameters.getOriginalFile().getProject(), resultSet)
|
||||
fun advertiseSecondCompletion() {
|
||||
JavaCompletionContributor.advertiseSecondCompletion(completionParameters.originalFile.project, resultSet)
|
||||
}
|
||||
|
||||
public fun restartCompletionOnPrefixChange(prefixCondition: ElementPattern<String>) {
|
||||
fun restartCompletionOnPrefixChange(prefixCondition: ElementPattern<String>) {
|
||||
resultSet.restartCompletionOnPrefixChange(prefixCondition)
|
||||
}
|
||||
}
|
||||
|
||||
+5
-5
@@ -35,7 +35,7 @@ import org.jetbrains.kotlin.types.KotlinType
|
||||
import java.util.*
|
||||
|
||||
object NamedArgumentCompletion {
|
||||
public fun isOnlyNamedArgumentExpected(nameExpression: KtSimpleNameExpression): Boolean {
|
||||
fun isOnlyNamedArgumentExpected(nameExpression: KtSimpleNameExpression): Boolean {
|
||||
val thisArgument = nameExpression.parent as? KtValueArgument ?: return false
|
||||
if (thisArgument.isNamed()) return false
|
||||
|
||||
@@ -46,7 +46,7 @@ object NamedArgumentCompletion {
|
||||
.any { it.isNamed() }
|
||||
}
|
||||
|
||||
public fun complete(collector: LookupElementsCollector, expectedInfos: Collection<ExpectedInfo>) {
|
||||
fun complete(collector: LookupElementsCollector, expectedInfos: Collection<ExpectedInfo>) {
|
||||
val nameToParameterType = HashMap<Name, MutableSet<KotlinType>>()
|
||||
for (expectedInfo in expectedInfos) {
|
||||
val argumentData = expectedInfo.additionalData as? ArgumentPositionData.Positional ?: continue
|
||||
@@ -70,10 +70,10 @@ object NamedArgumentCompletion {
|
||||
|
||||
private class NamedArgumentInsertHandler(private val parameterName: Name) : InsertHandler<LookupElement> {
|
||||
override fun handleInsert(context: InsertionContext, item: LookupElement) {
|
||||
val editor = context.getEditor()
|
||||
val editor = context.editor
|
||||
val text = parameterName.render()
|
||||
editor.getDocument().replaceString(context.getStartOffset(), context.getTailOffset(), text)
|
||||
editor.getCaretModel().moveToOffset(context.getStartOffset() + text.length)
|
||||
editor.document.replaceString(context.startOffset, context.tailOffset, text)
|
||||
editor.caretModel.moveToOffset(context.startOffset + text.length)
|
||||
|
||||
WithTailInsertHandler.EQ.postHandleInsert(context, item)
|
||||
}
|
||||
|
||||
+6
-6
@@ -37,16 +37,16 @@ object PackageDirectiveCompletion {
|
||||
val ACTIVATION_PATTERN = PlatformPatterns.psiElement().inside(KtPackageDirective::class.java)
|
||||
|
||||
fun perform(parameters: CompletionParameters, result: CompletionResultSet): Boolean {
|
||||
val position = parameters.getPosition()
|
||||
val position = parameters.position
|
||||
if (!ACTIVATION_PATTERN.accepts(position)) return false
|
||||
|
||||
val file = position.getContainingFile() as KtFile
|
||||
val file = position.containingFile as KtFile
|
||||
|
||||
val expression = file.findElementAt(parameters.getOffset())?.getParent() as? KtSimpleNameExpression ?: return false
|
||||
val expression = file.findElementAt(parameters.offset)?.parent as? KtSimpleNameExpression ?: return false
|
||||
|
||||
try {
|
||||
val prefixLength = parameters.getOffset() - expression.getTextOffset()
|
||||
val prefix = expression.getText()!!
|
||||
val prefixLength = parameters.offset - expression.textOffset
|
||||
val prefix = expression.text!!
|
||||
val prefixMatcher = PlainPrefixMatcher(prefix.substring(0, prefixLength))
|
||||
val result = result.withPrefixMatcher(prefixMatcher)
|
||||
|
||||
@@ -58,7 +58,7 @@ object PackageDirectiveCompletion {
|
||||
val lookupElementFactory = BasicLookupElementFactory(resolutionFacade.project, InsertHandlerProvider(callType = CallType.PACKAGE_DIRECTIVE, expectedInfosCalculator = { emptyList() }))
|
||||
for (variant in variants) {
|
||||
val lookupElement = lookupElementFactory.createLookupElement(variant)
|
||||
if (!lookupElement.getLookupString().contains(DUMMY_IDENTIFIER)) {
|
||||
if (!lookupElement.lookupString.contains(DUMMY_IDENTIFIER)) {
|
||||
result.addElement(lookupElement)
|
||||
}
|
||||
}
|
||||
|
||||
+18
-18
@@ -71,7 +71,7 @@ class ParameterNameAndTypeCompletion(
|
||||
|
||||
private val suggestionsByTypesAdded = HashSet<Type>()
|
||||
|
||||
public fun addFromImportedClasses(position: PsiElement, bindingContext: BindingContext, visibilityFilter: (DeclarationDescriptor) -> Boolean) {
|
||||
fun addFromImportedClasses(position: PsiElement, bindingContext: BindingContext, visibilityFilter: (DeclarationDescriptor) -> Boolean) {
|
||||
for ((classNameMatcher, userPrefix) in classNamePrefixMatchers.zip(userPrefixes)) {
|
||||
val resolutionScope = position.getResolutionScope(bindingContext, resolutionFacade)
|
||||
val classifiers = resolutionScope.collectDescriptorsFiltered(DescriptorKindFilter.NON_SINGLETON_CLASSIFIERS, classNameMatcher.asNameFilter())
|
||||
@@ -86,10 +86,10 @@ class ParameterNameAndTypeCompletion(
|
||||
}
|
||||
}
|
||||
|
||||
public fun addFromAllClasses(parameters: CompletionParameters, indicesHelper: KotlinIndicesHelper) {
|
||||
fun addFromAllClasses(parameters: CompletionParameters, indicesHelper: KotlinIndicesHelper) {
|
||||
for ((classNameMatcher, userPrefix) in classNamePrefixMatchers.zip(userPrefixes)) {
|
||||
AllClassesCompletion(
|
||||
parameters, indicesHelper, classNameMatcher, resolutionFacade, { !it.isSingleton() }
|
||||
parameters, indicesHelper, classNameMatcher, resolutionFacade, { !it.isSingleton }
|
||||
).collect(
|
||||
{ addSuggestionsForClassifier(it, userPrefix, notImported = true) },
|
||||
{ addSuggestionsForJavaClass(it, userPrefix, notImported = true) }
|
||||
@@ -99,18 +99,18 @@ class ParameterNameAndTypeCompletion(
|
||||
}
|
||||
}
|
||||
|
||||
public fun addFromParametersInFile(position: PsiElement, resolutionFacade: ResolutionFacade, visibilityFilter: (DeclarationDescriptor) -> Boolean) {
|
||||
fun addFromParametersInFile(position: PsiElement, resolutionFacade: ResolutionFacade, visibilityFilter: (DeclarationDescriptor) -> Boolean) {
|
||||
val lookupElementToCount = LinkedHashMap<LookupElement, Int>()
|
||||
position.getContainingFile().forEachDescendantOfType<KtParameter>(
|
||||
position.containingFile.forEachDescendantOfType<KtParameter>(
|
||||
canGoInside = { it !is KtExpression || it is KtDeclaration } // we analyze parameters inside bodies to not resolve too much
|
||||
) { parameter ->
|
||||
ProgressManager.checkCanceled()
|
||||
|
||||
val name = parameter.getName()
|
||||
val name = parameter.name
|
||||
if (name != null && prefixMatcher.isStartMatch(name)) {
|
||||
val descriptor = resolutionFacade.analyze(parameter)[BindingContext.VALUE_PARAMETER, parameter]
|
||||
if (descriptor != null) {
|
||||
val parameterType = descriptor.getType()
|
||||
val parameterType = descriptor.type
|
||||
if (parameterType.isVisible(visibilityFilter)) {
|
||||
val lookupElement = MyLookupElement.create(name, ArbitraryType(parameterType), lookupElementFactory)!!
|
||||
val count = lookupElementToCount[lookupElement] ?: 0
|
||||
@@ -127,11 +127,11 @@ class ParameterNameAndTypeCompletion(
|
||||
}
|
||||
|
||||
private fun addSuggestionsForClassifier(classifier: DeclarationDescriptor, userPrefix: String, notImported: Boolean) {
|
||||
addSuggestions(classifier.getName().asString(), userPrefix, DescriptorType(classifier as ClassifierDescriptor), notImported)
|
||||
addSuggestions(classifier.name.asString(), userPrefix, DescriptorType(classifier as ClassifierDescriptor), notImported)
|
||||
}
|
||||
|
||||
private fun addSuggestionsForJavaClass(psiClass: PsiClass, userPrefix: String, notImported: Boolean) {
|
||||
addSuggestions(psiClass.getName()!!, userPrefix, JavaClassType(psiClass), notImported)
|
||||
addSuggestions(psiClass.name!!, userPrefix, JavaClassType(psiClass), notImported)
|
||||
}
|
||||
|
||||
private fun addSuggestions(className: String, userPrefix: String, type: Type, notImported: Boolean) {
|
||||
@@ -153,9 +153,9 @@ class ParameterNameAndTypeCompletion(
|
||||
}
|
||||
|
||||
private fun KotlinType.isVisible(visibilityFilter: (DeclarationDescriptor) -> Boolean): Boolean {
|
||||
if (isError()) return false
|
||||
val classifier = getConstructor().getDeclarationDescriptor() ?: return false
|
||||
return visibilityFilter(classifier) && getArguments().all { it.isStarProjection || it.getType().isVisible(visibilityFilter) }
|
||||
if (isError) return false
|
||||
val classifier = constructor.declarationDescriptor ?: return false
|
||||
return visibilityFilter(classifier) && arguments.all { it.isStarProjection || it.type.isVisible(visibilityFilter) }
|
||||
}
|
||||
|
||||
private abstract class Type(private val idString: String) {
|
||||
@@ -170,7 +170,7 @@ class ParameterNameAndTypeCompletion(
|
||||
= lookupElementFactory.createLookupElement(classifier, qualifyNestedClasses = true)
|
||||
}
|
||||
|
||||
private class JavaClassType(private val psiClass: PsiClass) : Type(psiClass.getQualifiedName()!!) {
|
||||
private class JavaClassType(private val psiClass: PsiClass) : Type(psiClass.qualifiedName!!) {
|
||||
override fun createTypeLookupElement(lookupElementFactory: BasicLookupElementFactory)
|
||||
= lookupElementFactory.createLookupElementForJavaClass(psiClass, qualifyNestedClasses = true)
|
||||
}
|
||||
@@ -202,19 +202,19 @@ class ParameterNameAndTypeCompletion(
|
||||
|
||||
override fun renderElement(presentation: LookupElementPresentation) {
|
||||
super.renderElement(presentation)
|
||||
presentation.setItemText(parameterName + ": " + presentation.getItemText())
|
||||
presentation.itemText = parameterName + ": " + presentation.itemText
|
||||
}
|
||||
|
||||
override fun handleInsert(context: InsertionContext) {
|
||||
val settings = CodeStyleSettingsManager.getInstance(context.getProject()).getCurrentSettings().getCustomSettings(KotlinCodeStyleSettings::class.java)
|
||||
val settings = CodeStyleSettingsManager.getInstance(context.project).currentSettings.getCustomSettings(KotlinCodeStyleSettings::class.java)
|
||||
val spaceBefore = if (settings.SPACE_BEFORE_TYPE_COLON) " " else ""
|
||||
val spaceAfter = if (settings.SPACE_AFTER_TYPE_COLON) " " else ""
|
||||
val text = parameterName + spaceBefore + ":" + spaceAfter
|
||||
val startOffset = context.getStartOffset()
|
||||
context.getDocument().insertString(startOffset, text)
|
||||
val startOffset = context.startOffset
|
||||
context.document.insertString(startOffset, text)
|
||||
|
||||
// update start offset so that it does not include the text we inserted
|
||||
context.getOffsetMap().addOffset(CompletionInitializationContext.START_OFFSET, startOffset + text.length)
|
||||
context.offsetMap.addOffset(CompletionInitializationContext.START_OFFSET, startOffset + text.length)
|
||||
|
||||
super.handleInsert(context)
|
||||
}
|
||||
|
||||
+8
-8
@@ -34,8 +34,8 @@ class ToFromOriginalFileMapper(
|
||||
//TODO: lazy initialization?
|
||||
|
||||
init {
|
||||
val originalText = originalFile.getText()
|
||||
val syntheticText = syntheticFile.getText()
|
||||
val originalText = originalFile.text
|
||||
val syntheticText = syntheticFile.text
|
||||
assert(originalText.subSequence(0, completionOffset) == syntheticText.subSequence(0, completionOffset))
|
||||
|
||||
syntheticLength = syntheticText.length
|
||||
@@ -47,7 +47,7 @@ class ToFromOriginalFileMapper(
|
||||
shift = syntheticLength - originalLength
|
||||
}
|
||||
|
||||
public fun toOriginalFile(offset: Int): Int? {
|
||||
fun toOriginalFile(offset: Int): Int? {
|
||||
return when {
|
||||
offset <= completionOffset -> offset
|
||||
offset >= syntheticLength - tailLength -> offset - shift
|
||||
@@ -55,7 +55,7 @@ class ToFromOriginalFileMapper(
|
||||
}
|
||||
}
|
||||
|
||||
public fun toSyntheticFile(offset: Int): Int? {
|
||||
fun toSyntheticFile(offset: Int): Int? {
|
||||
return when {
|
||||
offset <= completionOffset -> offset
|
||||
offset >= originalLength - tailLength -> offset + shift
|
||||
@@ -63,14 +63,14 @@ class ToFromOriginalFileMapper(
|
||||
}
|
||||
}
|
||||
|
||||
public fun toOriginalFile(declaration: KtDeclaration): KtDeclaration? {
|
||||
if (declaration.getContainingFile() != syntheticFile) return declaration
|
||||
fun toOriginalFile(declaration: KtDeclaration): KtDeclaration? {
|
||||
if (declaration.containingFile != syntheticFile) return declaration
|
||||
val offset = toOriginalFile(declaration.startOffset) ?: return null
|
||||
return PsiTreeUtil.findElementOfClassAtOffset(originalFile, offset, KtDeclaration::class.java, true)
|
||||
}
|
||||
|
||||
public fun toSyntheticFile(declaration: KtDeclaration): KtDeclaration? {
|
||||
if (declaration.getContainingFile() != originalFile) return declaration
|
||||
fun toSyntheticFile(declaration: KtDeclaration): KtDeclaration? {
|
||||
if (declaration.containingFile != originalFile) return declaration
|
||||
val offset = toSyntheticFile(declaration.startOffset) ?: return null
|
||||
return PsiTreeUtil.findElementOfClassAtOffset(syntheticFile, offset, KtDeclaration::class.java, true)
|
||||
}
|
||||
|
||||
@@ -113,7 +113,7 @@ object KindWeigher : LookupElementWeigher("kotlin.kind") {
|
||||
}
|
||||
|
||||
override fun weigh(element: LookupElement): Weight {
|
||||
val o = element.getObject()
|
||||
val o = element.`object`
|
||||
|
||||
return when (o) {
|
||||
is PackageLookupObject -> Weight.packages
|
||||
@@ -156,7 +156,7 @@ object VariableOrFunctionWeigher : LookupElementWeigher("kotlin.variableOrFuncti
|
||||
|
||||
object DeprecatedWeigher : LookupElementWeigher("kotlin.deprecated") {
|
||||
override fun weigh(element: LookupElement): Int {
|
||||
val o = element.getObject() as? DeclarationLookupObject ?: return 0
|
||||
val o = element.`object` as? DeclarationLookupObject ?: return 0
|
||||
return if (o.isDeprecated) 1 else 0
|
||||
}
|
||||
}
|
||||
|
||||
+10
-10
@@ -28,28 +28,28 @@ import org.jetbrains.kotlin.psi.*
|
||||
|
||||
object CastReceiverInsertHandler {
|
||||
fun postHandleInsert(context: InsertionContext, item: LookupElement) {
|
||||
val expression = PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getStartOffset(), KtSimpleNameExpression::class.java, false)
|
||||
val expression = 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.getReceiverExpression()
|
||||
val receiver = qualifiedExpression.receiverExpression
|
||||
|
||||
val descriptor = (item.getObject() as? DeclarationLookupObject)?.descriptor as CallableDescriptor
|
||||
val project = context.getProject()
|
||||
val descriptor = (item.`object` as? DeclarationLookupObject)?.descriptor as CallableDescriptor
|
||||
val project = context.project
|
||||
|
||||
val thisObj = if (descriptor.getExtensionReceiverParameter() != null) descriptor.getExtensionReceiverParameter() else descriptor.getDispatchReceiverParameter()
|
||||
val fqName = IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(thisObj!!.getType().getConstructor().getDeclarationDescriptor()!!)
|
||||
val thisObj = if (descriptor.extensionReceiverParameter != null) descriptor.extensionReceiverParameter else descriptor.dispatchReceiverParameter
|
||||
val fqName = IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(thisObj!!.type.constructor.declarationDescriptor!!)
|
||||
|
||||
val parentCast = KtPsiFactory(project).createExpression("(expr as $fqName)") as KtParenthesizedExpression
|
||||
val cast = parentCast.getExpression() as KtBinaryExpressionWithTypeRHS
|
||||
cast.getLeft().replace(receiver)
|
||||
val cast = parentCast.expression as KtBinaryExpressionWithTypeRHS
|
||||
cast.left.replace(receiver)
|
||||
|
||||
val psiDocumentManager = PsiDocumentManager.getInstance(project)
|
||||
psiDocumentManager.commitAllDocuments()
|
||||
psiDocumentManager.doPostponedOperationsAndUnblockDocument(context.getDocument())
|
||||
psiDocumentManager.doPostponedOperationsAndUnblockDocument(context.document)
|
||||
|
||||
val expr = receiver.replace(parentCast) as KtParenthesizedExpression
|
||||
|
||||
ShortenReferences.DEFAULT.process((expr.getExpression() as KtBinaryExpressionWithTypeRHS).getRight()!!)
|
||||
ShortenReferences.DEFAULT.process((expr.expression as KtBinaryExpressionWithTypeRHS).right!!)
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
-9
@@ -42,13 +42,13 @@ fun insertLambdaTemplate(context: InsertionContext, placeholderRange: TextRange,
|
||||
|
||||
// we start template later to not interfere with insertion of tail type
|
||||
val commandProcessor = CommandProcessor.getInstance()
|
||||
val commandName = commandProcessor.getCurrentCommandName()!!
|
||||
val commandGroupId = commandProcessor.getCurrentCommandGroupId()
|
||||
val commandName = commandProcessor.currentCommandName!!
|
||||
val commandGroupId = commandProcessor.currentCommandGroupId
|
||||
|
||||
val rangeMarker = context.getDocument().createRangeMarker(placeholderRange)
|
||||
val rangeMarker = context.document.createRangeMarker(placeholderRange)
|
||||
|
||||
context.setLaterRunnable {
|
||||
context.getProject().executeWriteCommand(commandName, groupId = commandGroupId) {
|
||||
context.project.executeWriteCommand(commandName, groupId = commandGroupId) {
|
||||
try {
|
||||
if (rangeMarker.isValid()) {
|
||||
context.getDocument().deleteString(rangeMarker.getStartOffset(), rangeMarker.getEndOffset())
|
||||
@@ -72,9 +72,9 @@ fun lambdaPresentation(lambdaType: KotlinType?): String {
|
||||
}
|
||||
|
||||
private fun needExplicitParameterTypes(context: InsertionContext, placeholderRange: TextRange, lambdaType: KotlinType): Boolean {
|
||||
PsiDocumentManager.getInstance(context.getProject()).commitAllDocuments()
|
||||
val file = context.getFile() as KtFile
|
||||
val expression = PsiTreeUtil.findElementOfClassAtRange(file, placeholderRange.getStartOffset(), placeholderRange.getEndOffset(), KtExpression::class.java)
|
||||
PsiDocumentManager.getInstance(context.project).commitAllDocuments()
|
||||
val file = context.file as KtFile
|
||||
val expression = PsiTreeUtil.findElementOfClassAtRange(file, placeholderRange.startOffset, placeholderRange.endOffset, KtExpression::class.java)
|
||||
?: return false
|
||||
|
||||
val resolutionFacade = file.getResolutionFacade()
|
||||
@@ -97,7 +97,7 @@ private fun buildTemplate(lambdaType: KotlinType, explicitParameterTypes: Boolea
|
||||
val manager = TemplateManager.getInstance(project)
|
||||
|
||||
val template = manager.createTemplate("", "")
|
||||
template.setToShortenLongNames(true)
|
||||
template.isToShortenLongNames = true
|
||||
//template.setToReformat(true) //TODO
|
||||
template.addTextSegment("{ ")
|
||||
|
||||
@@ -128,4 +128,4 @@ private class ParameterNameExpression(val nameSuggestions: Array<String>) : Expr
|
||||
}
|
||||
|
||||
fun functionParameterTypes(functionType: KotlinType): List<KotlinType>
|
||||
= KotlinBuiltIns.getParameterTypeProjectionsFromFunctionType(functionType).map { it.getType() }
|
||||
= KotlinBuiltIns.getParameterTypeProjectionsFromFunctionType(functionType).map { it.type }
|
||||
|
||||
+5
-5
@@ -28,22 +28,22 @@ import org.jetbrains.kotlin.psi.KtFile
|
||||
import org.jetbrains.kotlin.resolve.DescriptorUtils
|
||||
|
||||
abstract class KotlinCallableInsertHandler : BaseDeclarationInsertHandler() {
|
||||
public override fun handleInsert(context: InsertionContext, item: LookupElement) {
|
||||
override fun handleInsert(context: InsertionContext, item: LookupElement) {
|
||||
super.handleInsert(context, item)
|
||||
|
||||
addImport(context, item)
|
||||
}
|
||||
|
||||
private fun addImport(context : InsertionContext, item : LookupElement) {
|
||||
PsiDocumentManager.getInstance(context.getProject()).commitAllDocuments()
|
||||
PsiDocumentManager.getInstance(context.project).commitAllDocuments()
|
||||
|
||||
val file = context.getFile()
|
||||
val o = item.getObject()
|
||||
val file = context.file
|
||||
val o = item.`object`
|
||||
if (file is KtFile && o is DeclarationLookupObject) {
|
||||
val descriptor = o.descriptor as? CallableDescriptor
|
||||
if (descriptor != null) {
|
||||
// for completion after dot, import insertion may be required only for extensions
|
||||
if (context.isAfterDot() && descriptor.getExtensionReceiverParameter() == null) {
|
||||
if (context.isAfterDot() && descriptor.extensionReceiverParameter == null) {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
+11
-11
@@ -41,20 +41,20 @@ object KotlinClassifierInsertHandler : BaseDeclarationInsertHandler() {
|
||||
|
||||
super.handleInsert(context, item)
|
||||
|
||||
val file = context.getFile()
|
||||
val file = context.file
|
||||
if (file is KtFile) {
|
||||
if (!context.isAfterDot()) {
|
||||
val psiDocumentManager = PsiDocumentManager.getInstance(context.getProject())
|
||||
val psiDocumentManager = PsiDocumentManager.getInstance(context.project)
|
||||
psiDocumentManager.commitAllDocuments()
|
||||
|
||||
val startOffset = context.getStartOffset()
|
||||
val document = context.getDocument()
|
||||
val startOffset = context.startOffset
|
||||
val document = context.document
|
||||
|
||||
val qualifiedName = qualifiedNameToInsert(item)
|
||||
|
||||
// first try to resolve short name for faster handling
|
||||
val token = file.findElementAt(startOffset)
|
||||
val nameRef = token!!.getParent() as? KtNameReferenceExpression
|
||||
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]
|
||||
@@ -72,7 +72,7 @@ object KotlinClassifierInsertHandler : BaseDeclarationInsertHandler() {
|
||||
"$;val v:" // if we have no reference in the current context we have a more complicated prefix to get one
|
||||
}
|
||||
val tempSuffix = ".xxx" // we add "xxx" after dot because of KT-9606
|
||||
document.replaceString(startOffset, context.getTailOffset(), tempPrefix + qualifiedName + tempSuffix)
|
||||
document.replaceString(startOffset, context.tailOffset, tempPrefix + qualifiedName + tempSuffix)
|
||||
|
||||
psiDocumentManager.commitAllDocuments()
|
||||
|
||||
@@ -84,21 +84,21 @@ object KotlinClassifierInsertHandler : BaseDeclarationInsertHandler() {
|
||||
ShortenReferences.DEFAULT.process(file, classNameStart, classNameEnd)
|
||||
psiDocumentManager.doPostponedOperationsAndUnblockDocument(document)
|
||||
|
||||
if (rangeMarker.isValid() && wholeRangeMarker.isValid()) {
|
||||
document.deleteString(wholeRangeMarker.getStartOffset(), rangeMarker.getStartOffset())
|
||||
document.deleteString(rangeMarker.getEndOffset(), wholeRangeMarker.getEndOffset())
|
||||
if (rangeMarker.isValid && wholeRangeMarker.isValid) {
|
||||
document.deleteString(wholeRangeMarker.startOffset, rangeMarker.startOffset)
|
||||
document.deleteString(rangeMarker.endOffset, wholeRangeMarker.endOffset)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun qualifiedNameToInsert(item: LookupElement): String {
|
||||
val lookupObject = item.getObject() as DeclarationLookupObject
|
||||
val lookupObject = item.`object` as DeclarationLookupObject
|
||||
if (lookupObject.descriptor != null) {
|
||||
return IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(lookupObject.descriptor as ClassifierDescriptor)
|
||||
}
|
||||
else {
|
||||
val qualifiedName = (lookupObject.psiElement as PsiClass).getQualifiedName()!!
|
||||
val qualifiedName = (lookupObject.psiElement as PsiClass).qualifiedName!!
|
||||
return if (FqNameUnsafe.isValid(qualifiedName)) FqNameUnsafe(qualifiedName).render() else qualifiedName
|
||||
}
|
||||
}
|
||||
|
||||
+6
-6
@@ -78,7 +78,7 @@ sealed class KotlinFunctionInsertHandler : KotlinCallableInsertHandler() {
|
||||
}
|
||||
|
||||
private fun addArguments(context: InsertionContext, offsetElement: PsiElement, item: LookupElement) {
|
||||
val completionChar = context.getCompletionChar()
|
||||
val completionChar = context.completionChar
|
||||
if (completionChar == '(') { //TODO: more correct behavior related to braces type
|
||||
context.setAddCompletionChar(false)
|
||||
}
|
||||
@@ -101,9 +101,9 @@ sealed class KotlinFunctionInsertHandler : KotlinCallableInsertHandler() {
|
||||
if (offset1 < chars.length) {
|
||||
if (chars[offset1] == '<') {
|
||||
PsiDocumentManager.getInstance(project).commitDocument(document)
|
||||
val token = context.getFile().findElementAt(offset1)!!
|
||||
if (token.getNode().getElementType() == KtTokens.LT) {
|
||||
val parent = token.getParent()
|
||||
val token = context.file.findElementAt(offset1)!!
|
||||
if (token.node.elementType == KtTokens.LT) {
|
||||
val parent = token.parent
|
||||
if (parent is KtTypeArgumentList && parent.getText().indexOf('\n') < 0/* if type argument list is on multiple lines this is more likely wrong parsing*/) {
|
||||
offset = parent.endOffset
|
||||
insertTypeArguments = false
|
||||
@@ -194,7 +194,7 @@ sealed class KotlinFunctionInsertHandler : KotlinCallableInsertHandler() {
|
||||
}
|
||||
|
||||
object Infix : KotlinFunctionInsertHandler() {
|
||||
public override fun handleInsert(context: InsertionContext, item: LookupElement) {
|
||||
override fun handleInsert(context: InsertionContext, item: LookupElement) {
|
||||
super.handleInsert(context, item)
|
||||
|
||||
if (context.completionChar == ' ') {
|
||||
@@ -209,7 +209,7 @@ sealed class KotlinFunctionInsertHandler : KotlinCallableInsertHandler() {
|
||||
|
||||
object OnlyName : KotlinFunctionInsertHandler()
|
||||
|
||||
public override fun handleInsert(context: InsertionContext, item: LookupElement) {
|
||||
override fun handleInsert(context: InsertionContext, item: LookupElement) {
|
||||
super.handleInsert(context, item)
|
||||
|
||||
val psiDocumentManager = PsiDocumentManager.getInstance(context.project)
|
||||
|
||||
+7
-7
@@ -22,22 +22,22 @@ import com.intellij.codeInsight.lookup.LookupElement
|
||||
import com.intellij.psi.PsiDocumentManager
|
||||
|
||||
object KotlinPropertyInsertHandler : KotlinCallableInsertHandler() {
|
||||
public override fun handleInsert(context: InsertionContext, item: LookupElement) {
|
||||
override fun handleInsert(context: InsertionContext, item: LookupElement) {
|
||||
super.handleInsert(context, item)
|
||||
|
||||
if (context.getCompletionChar() == Lookup.REPLACE_SELECT_CHAR) {
|
||||
if (context.completionChar == Lookup.REPLACE_SELECT_CHAR) {
|
||||
deleteEmptyParenthesis(context)
|
||||
}
|
||||
}
|
||||
|
||||
private fun deleteEmptyParenthesis(context: InsertionContext) {
|
||||
val psiDocumentManager = PsiDocumentManager.getInstance(context.getProject())
|
||||
val psiDocumentManager = PsiDocumentManager.getInstance(context.project)
|
||||
psiDocumentManager.commitAllDocuments()
|
||||
psiDocumentManager.doPostponedOperationsAndUnblockDocument(context.getDocument())
|
||||
psiDocumentManager.doPostponedOperationsAndUnblockDocument(context.document)
|
||||
|
||||
val offset = context.getTailOffset()
|
||||
val document = context.getDocument()
|
||||
val chars = document.getCharsSequence()
|
||||
val offset = context.tailOffset
|
||||
val document = context.document
|
||||
val chars = document.charsSequence
|
||||
|
||||
val lParenOffset = chars.indexOfSkippingSpace('(', offset) ?: return
|
||||
val rParenOffset = chars.indexOfSkippingSpace(')', lParenOffset + 1) ?: return
|
||||
|
||||
+5
-5
@@ -38,20 +38,20 @@ class WithExpressionPrefixInsertHandler(val prefix: String) : InsertHandler<Look
|
||||
psiDocumentManager.doPostponedOperationsAndUnblockDocument(context.document)
|
||||
psiDocumentManager.commitAllDocuments()
|
||||
|
||||
val offset = context.getStartOffset()
|
||||
val token = context.getFile().findElementAt(offset)!!
|
||||
val offset = context.startOffset
|
||||
val token = context.file.findElementAt(offset)!!
|
||||
var expression = token.getStrictParentOfType<KtExpression>() ?: return
|
||||
if (expression is KtSimpleNameExpression) {
|
||||
var parent = expression.getParent()
|
||||
if (parent is KtCallExpression && expression == parent.getCalleeExpression()) {
|
||||
if (parent is KtCallExpression && expression == parent.calleeExpression) {
|
||||
expression = parent
|
||||
parent = parent.getParent()
|
||||
}
|
||||
if (parent is KtDotQualifiedExpression && expression == parent.getSelectorExpression()) {
|
||||
if (parent is KtDotQualifiedExpression && expression == parent.selectorExpression) {
|
||||
expression = parent
|
||||
}
|
||||
}
|
||||
|
||||
context.getDocument().insertString(expression.getTextRange().getStartOffset(), prefix)
|
||||
context.document.insertString(expression.textRange.startOffset, prefix)
|
||||
}
|
||||
}
|
||||
+8
-8
@@ -35,22 +35,22 @@ class WithTailInsertHandler(val tailText: String,
|
||||
}
|
||||
|
||||
fun postHandleInsert(context: InsertionContext, item: LookupElement) {
|
||||
val completionChar = context.getCompletionChar()
|
||||
val completionChar = context.completionChar
|
||||
if (completionChar == tailText.singleOrNull() || (spaceAfter && completionChar == ' ')) {
|
||||
context.setAddCompletionChar(false)
|
||||
}
|
||||
//TODO: what if completion char is different?
|
||||
|
||||
val document = context.getDocument()
|
||||
PsiDocumentManager.getInstance(context.getProject()).doPostponedOperationsAndUnblockDocument(document)
|
||||
val document = context.document
|
||||
PsiDocumentManager.getInstance(context.project).doPostponedOperationsAndUnblockDocument(document)
|
||||
|
||||
var tailOffset = context.getTailOffset()
|
||||
var tailOffset = context.tailOffset
|
||||
if (completionChar == Lookup.REPLACE_SELECT_CHAR && item.getUserData(KEEP_OLD_ARGUMENT_LIST_ON_TAB_KEY) != null) {
|
||||
val offset = context.getOffsetMap().getOffset(SmartCompletion.OLD_ARGUMENTS_REPLACEMENT_OFFSET)
|
||||
val offset = context.offsetMap.getOffset(SmartCompletion.OLD_ARGUMENTS_REPLACEMENT_OFFSET)
|
||||
if (offset != -1) tailOffset = offset
|
||||
}
|
||||
|
||||
val moveCaret = context.getEditor().getCaretModel().getOffset() == tailOffset
|
||||
val moveCaret = context.editor.caretModel.offset == tailOffset
|
||||
|
||||
//TODO: analyze parenthesis balance to decide whether to replace or not
|
||||
var insert = true
|
||||
@@ -77,10 +77,10 @@ class WithTailInsertHandler(val tailText: String,
|
||||
document.insertString(tailOffset, textToInsert)
|
||||
|
||||
if (moveCaret) {
|
||||
context.getEditor().getCaretModel().moveToOffset(tailOffset + textToInsert.length)
|
||||
context.editor.caretModel.moveToOffset(tailOffset + textToInsert.length)
|
||||
|
||||
if (tailText == ",") {
|
||||
AutoPopupController.getInstance(context.getProject())?.autoPopupParameterInfo(context.getEditor(), null)
|
||||
AutoPopupController.getInstance(context.project)?.autoPopupParameterInfo(context.editor, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -60,4 +60,4 @@ fun CharSequence.skipSpacesAndLineBreaks(index: Int): Int
|
||||
|
||||
fun CharSequence.isCharAt(offset: Int, c: Char) = offset < length && this[offset] == c
|
||||
|
||||
fun Document.isTextAt(offset: Int, text: String) = offset + text.length <= getTextLength() && getText(TextRange(offset, offset + text.length)) == text
|
||||
fun Document.isTextAt(offset: Int, text: String) = offset + text.length <= textLength && getText(TextRange(offset, offset + text.length)) == text
|
||||
|
||||
+1
-1
@@ -33,7 +33,7 @@ import org.jetbrains.kotlin.types.Variance
|
||||
import java.util.*
|
||||
|
||||
object ClassLiteralItems {
|
||||
public fun addToCollection(
|
||||
fun addToCollection(
|
||||
collection: MutableCollection<LookupElement>,
|
||||
expectedInfos: Collection<ExpectedInfo>,
|
||||
lookupElementFactory: BasicLookupElementFactory,
|
||||
|
||||
@@ -28,13 +28,13 @@ import org.jetbrains.kotlin.idea.core.fuzzyType
|
||||
import java.util.*
|
||||
|
||||
object LambdaItems {
|
||||
public fun collect(functionExpectedInfos: Collection<ExpectedInfo>): Collection<LookupElement> {
|
||||
fun collect(functionExpectedInfos: Collection<ExpectedInfo>): Collection<LookupElement> {
|
||||
val list = ArrayList<LookupElement>()
|
||||
addToCollection(list, functionExpectedInfos)
|
||||
return list
|
||||
}
|
||||
|
||||
public fun addToCollection(collection: MutableCollection<LookupElement>, expectedInfos: Collection<ExpectedInfo>) {
|
||||
fun addToCollection(collection: MutableCollection<LookupElement>, expectedInfos: Collection<ExpectedInfo>) {
|
||||
val functionExpectedInfos = expectedInfos.filterFunctionExpected()
|
||||
if (functionExpectedInfos.isEmpty()) return
|
||||
|
||||
@@ -59,9 +59,9 @@ object LambdaItems {
|
||||
val lookupString = lambdaPresentation(functionType)
|
||||
val lookupElement = LookupElementBuilder.create(lookupString)
|
||||
.withInsertHandler({ context, lookupElement ->
|
||||
val offset = context.getStartOffset()
|
||||
val offset = context.startOffset
|
||||
val placeholder = "{}"
|
||||
context.getDocument().replaceString(offset, context.getTailOffset(), placeholder)
|
||||
context.document.replaceString(offset, context.tailOffset, placeholder)
|
||||
insertLambdaTemplate(context, TextRange(offset, offset + placeholder.length), functionType)
|
||||
})
|
||||
.suppressAutoInsertion()
|
||||
|
||||
+9
-9
@@ -48,7 +48,7 @@ class MultipleArgumentsItemProvider(
|
||||
private val resolutionFacade: ResolutionFacade
|
||||
) {
|
||||
|
||||
public fun addToCollection(collection: MutableCollection<LookupElement>,
|
||||
fun addToCollection(collection: MutableCollection<LookupElement>,
|
||||
expectedInfos: Collection<ExpectedInfo>,
|
||||
context: KtExpression) {
|
||||
val resolutionScope = context.getResolutionScope(bindingContext, resolutionFacade)
|
||||
@@ -69,7 +69,7 @@ class MultipleArgumentsItemProvider(
|
||||
|
||||
if (i > 0 && parameters.asSequence().drop(i + 1).all { it.hasDefaultValue() }) { // this is the last parameter or all others have default values
|
||||
val lookupElement = createParametersLookupElement(variables, tail)
|
||||
if (added.add(lookupElement.getLookupString())) { // check that we don't already have item with the same text
|
||||
if (added.add(lookupElement.lookupString)) { // check that we don't already have item with the same text
|
||||
collection.add(lookupElement)
|
||||
}
|
||||
}
|
||||
@@ -83,16 +83,16 @@ class MultipleArgumentsItemProvider(
|
||||
val compoundIcon = LayeredIcon(2)
|
||||
val firstIcon = KotlinDescriptorIconProvider.getIcon(variables.first(), null, 0)
|
||||
val lastIcon = KotlinDescriptorIconProvider.getIcon(variables.last(), null, 0)
|
||||
compoundIcon.setIcon(lastIcon, 0, 2 * firstIcon.getIconWidth() / 5, 0)
|
||||
compoundIcon.setIcon(lastIcon, 0, 2 * firstIcon.iconWidth / 5, 0)
|
||||
compoundIcon.setIcon(firstIcon, 1, 0, 0)
|
||||
|
||||
return LookupElementBuilder
|
||||
.create(variables.map { it.getName().render() }.joinToString(", ")) //TODO: use code formatting settings
|
||||
.create(variables.map { it.name.render() }.joinToString(", ")) //TODO: use code formatting settings
|
||||
.withInsertHandler { context, lookupElement ->
|
||||
if (context.getCompletionChar() == Lookup.REPLACE_SELECT_CHAR) {
|
||||
val offset = context.getOffsetMap().getOffset(SmartCompletion.MULTIPLE_ARGUMENTS_REPLACEMENT_OFFSET)
|
||||
if (context.completionChar == Lookup.REPLACE_SELECT_CHAR) {
|
||||
val offset = context.offsetMap.getOffset(SmartCompletion.MULTIPLE_ARGUMENTS_REPLACEMENT_OFFSET)
|
||||
if (offset != -1) {
|
||||
context.getDocument().deleteString(context.getTailOffset(), offset)
|
||||
context.document.deleteString(context.tailOffset, offset)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,11 +103,11 @@ class MultipleArgumentsItemProvider(
|
||||
}
|
||||
|
||||
private fun variableInScope(parameter: ValueParameterDescriptor, scope: LexicalScope): VariableDescriptor? {
|
||||
val name = parameter.getName()
|
||||
val name = parameter.name
|
||||
//TODO: there can be more than one property with such name in scope and we should be able to select one (but we need API for this)
|
||||
val variable = scope.findVariable(name, NoLookupLocation.FROM_IDE) { !it.isExtension }
|
||||
?: scope.getVariableFromImplicitReceivers(name) ?: return null
|
||||
return if (smartCastCalculator.types(variable).any { KotlinTypeChecker.DEFAULT.isSubtypeOf(it, parameter.getType()) })
|
||||
return if (smartCastCalculator.types(variable).any { KotlinTypeChecker.DEFAULT.isSubtypeOf(it, parameter.type) })
|
||||
variable
|
||||
else
|
||||
null
|
||||
|
||||
+30
-30
@@ -77,20 +77,20 @@ class SmartCompletion(
|
||||
expression
|
||||
}
|
||||
|
||||
public val expectedInfos: Collection<ExpectedInfo> = calcExpectedInfos(expressionWithType)
|
||||
val expectedInfos: Collection<ExpectedInfo> = calcExpectedInfos(expressionWithType)
|
||||
|
||||
private val callableTypeExpectedInfo = expectedInfos.filterCallableExpected()
|
||||
|
||||
public val smartCastCalculator: SmartCastCalculator by lazy(LazyThreadSafetyMode.NONE) {
|
||||
val smartCastCalculator: SmartCastCalculator by lazy(LazyThreadSafetyMode.NONE) {
|
||||
SmartCastCalculator(bindingContext, resolutionFacade.moduleDescriptor, expression, callTypeAndReceiver.receiver as? KtExpression, resolutionFacade)
|
||||
}
|
||||
|
||||
public val descriptorFilter: ((DeclarationDescriptor, AbstractLookupElementFactory) -> Collection<LookupElement>)? =
|
||||
val descriptorFilter: ((DeclarationDescriptor, AbstractLookupElementFactory) -> Collection<LookupElement>)? =
|
||||
{ descriptor: DeclarationDescriptor, factory: AbstractLookupElementFactory ->
|
||||
filterDescriptor(descriptor, factory).map { postProcess(it) }
|
||||
}.check { expectedInfos.isNotEmpty() }
|
||||
|
||||
public fun additionalItems(lookupElementFactory: LookupElementFactory): Pair<Collection<LookupElement>, InheritanceItemsSearcher?> {
|
||||
fun additionalItems(lookupElementFactory: LookupElementFactory): Pair<Collection<LookupElement>, InheritanceItemsSearcher?> {
|
||||
val (items, inheritanceSearcher) = additionalItemsNoPostProcess(lookupElementFactory)
|
||||
val postProcessedItems = items.map { postProcess(it) }
|
||||
//TODO: could not use "let" because of KT-8754
|
||||
@@ -105,14 +105,14 @@ class SmartCompletion(
|
||||
return postProcessedItems to postProcessedSearcher
|
||||
}
|
||||
|
||||
public val descriptorsToSkip: Set<DeclarationDescriptor> by lazy<Set<DeclarationDescriptor>>(LazyThreadSafetyMode.NONE) {
|
||||
val parent = expressionWithType.getParent()
|
||||
val descriptorsToSkip: Set<DeclarationDescriptor> by lazy<Set<DeclarationDescriptor>>(LazyThreadSafetyMode.NONE) {
|
||||
val parent = expressionWithType.parent
|
||||
when (parent) {
|
||||
is KtBinaryExpression -> {
|
||||
if (parent.getRight() == expressionWithType) {
|
||||
val operationToken = parent.getOperationToken()
|
||||
if (parent.right == expressionWithType) {
|
||||
val operationToken = parent.operationToken
|
||||
if (operationToken == KtTokens.EQ || operationToken in COMPARISON_TOKENS) {
|
||||
val left = parent.getLeft()
|
||||
val left = parent.left
|
||||
if (left is KtReferenceExpression) {
|
||||
return@lazy bindingContext[BindingContext.REFERENCE_TARGET, left].singletonOrEmptySet()
|
||||
}
|
||||
@@ -122,8 +122,8 @@ class SmartCompletion(
|
||||
|
||||
is KtWhenConditionWithExpression -> {
|
||||
val entry = parent.getParent() as KtWhenEntry
|
||||
val whenExpression = entry.getParent() as KtWhenExpression
|
||||
val subject = whenExpression.getSubjectExpression() ?: return@lazy emptySet()
|
||||
val whenExpression = entry.parent as KtWhenExpression
|
||||
val subject = whenExpression.subjectExpression ?: return@lazy emptySet()
|
||||
|
||||
val descriptorsToSkip = HashSet<DeclarationDescriptor>()
|
||||
|
||||
@@ -137,12 +137,12 @@ class SmartCompletion(
|
||||
val subjectType = bindingContext.getType(subject) ?: return@lazy emptySet()
|
||||
val classDescriptor = TypeUtils.getClassDescriptor(subjectType)
|
||||
if (classDescriptor != null && DescriptorUtils.isEnumClass(classDescriptor)) {
|
||||
val conditions = whenExpression.getEntries()
|
||||
.flatMap { it.getConditions().toList() }
|
||||
val conditions = whenExpression.entries
|
||||
.flatMap { it.conditions.toList() }
|
||||
.filterIsInstance<KtWhenConditionWithExpression>()
|
||||
for (condition in conditions) {
|
||||
val selectorExpr = (condition.getExpression() as? KtDotQualifiedExpression)
|
||||
?.getSelectorExpression() as? KtReferenceExpression ?: continue
|
||||
val selectorExpr = (condition.expression as? KtDotQualifiedExpression)
|
||||
?.selectorExpression as? KtReferenceExpression ?: continue
|
||||
val target = bindingContext[BindingContext.REFERENCE_TARGET, selectorExpr] as? ClassDescriptor ?: continue
|
||||
if (DescriptorUtils.isEnumEntry(target)) {
|
||||
descriptorsToSkip.add(target)
|
||||
@@ -256,10 +256,10 @@ class SmartCompletion(
|
||||
return if (item.getUserData(KEEP_OLD_ARGUMENT_LIST_ON_TAB_KEY) == null) {
|
||||
object : LookupElementDecorator<LookupElement>(item) {
|
||||
override fun handleInsert(context: InsertionContext) {
|
||||
if (context.getCompletionChar() == Lookup.REPLACE_SELECT_CHAR) {
|
||||
val offset = context.getOffsetMap().getOffset(OLD_ARGUMENTS_REPLACEMENT_OFFSET)
|
||||
if (context.completionChar == Lookup.REPLACE_SELECT_CHAR) {
|
||||
val offset = context.offsetMap.getOffset(OLD_ARGUMENTS_REPLACEMENT_OFFSET)
|
||||
if (offset != -1) {
|
||||
context.getDocument().deleteString(context.getTailOffset(), offset)
|
||||
context.document.deleteString(context.tailOffset, offset)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -274,7 +274,7 @@ class SmartCompletion(
|
||||
|
||||
private fun MutableCollection<LookupElement>.addThisItems(place: KtExpression, expectedInfos: Collection<ExpectedInfo>, smartCastCalculator: SmartCastCalculator) {
|
||||
if (shouldCompleteThisItems(prefixMatcher)) {
|
||||
val items = thisExpressionItems(bindingContext, place, prefixMatcher.getPrefix(), resolutionFacade)
|
||||
val items = thisExpressionItems(bindingContext, place, prefixMatcher.prefix, resolutionFacade)
|
||||
for (item in items) {
|
||||
val types = smartCastCalculator.types(item.receiverParameter).map { FuzzyType(it, emptyList()) }
|
||||
val matcher = { expectedInfo: ExpectedInfo -> types.matchExpectedInfo(expectedInfo) }
|
||||
@@ -292,9 +292,9 @@ class SmartCompletion(
|
||||
val originalDeclaration = toFromOriginalFileMapper.toOriginalFile(declaration)
|
||||
if (originalDeclaration != null) {
|
||||
val originalDescriptor = originalDeclaration.resolveToDescriptor() as? CallableDescriptor
|
||||
val returnType = originalDescriptor?.getReturnType()
|
||||
val returnType = originalDescriptor?.returnType
|
||||
if (returnType != null && !returnType.isError) {
|
||||
return listOf(ExpectedInfo(returnType, declaration.getName(), null))
|
||||
return listOf(ExpectedInfo(returnType, declaration.name, null))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -316,10 +316,10 @@ class SmartCompletion(
|
||||
}
|
||||
|
||||
private fun implicitlyTypedDeclarationFromInitializer(expression: KtExpression): KtDeclaration? {
|
||||
val parent = expression.getParent()
|
||||
val parent = expression.parent
|
||||
when (parent) {
|
||||
is KtVariableDeclaration -> if (expression == parent.getInitializer() && parent.getTypeReference() == null) return parent
|
||||
is KtNamedFunction -> if (expression == parent.getInitializer() && parent.getTypeReference() == null) return parent
|
||||
is KtVariableDeclaration -> if (expression == parent.initializer && parent.typeReference == null) return parent
|
||||
is KtNamedFunction -> if (expression == parent.initializer && parent.typeReference == null) return parent
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -371,11 +371,11 @@ class SmartCompletion(
|
||||
}
|
||||
|
||||
private fun buildForAsTypePosition(lookupElementFactory: BasicLookupElementFactory): Collection<LookupElement>? {
|
||||
val binaryExpression = ((expression.getParent() as? KtUserType)
|
||||
?.getParent() as? KtTypeReference)
|
||||
?.getParent() as? KtBinaryExpressionWithTypeRHS
|
||||
val binaryExpression = ((expression.parent as? KtUserType)
|
||||
?.parent as? KtTypeReference)
|
||||
?.parent as? KtBinaryExpressionWithTypeRHS
|
||||
?: return null
|
||||
val elementType = binaryExpression.getOperationReference().getReferencedNameElementType()
|
||||
val elementType = binaryExpression.operationReference.getReferencedNameElementType()
|
||||
if (elementType != KtTokens.AS_KEYWORD && elementType != KtTokens.AS_SAFE) return null
|
||||
val expectedInfos = calcExpectedInfos(binaryExpression)
|
||||
|
||||
@@ -391,7 +391,7 @@ class SmartCompletion(
|
||||
}
|
||||
|
||||
companion object {
|
||||
public val OLD_ARGUMENTS_REPLACEMENT_OFFSET: OffsetKey = OffsetKey.create("nonFunctionReplacementOffset")
|
||||
public val MULTIPLE_ARGUMENTS_REPLACEMENT_OFFSET: OffsetKey = OffsetKey.create("multipleArgumentsReplacementOffset")
|
||||
val OLD_ARGUMENTS_REPLACEMENT_OFFSET: OffsetKey = OffsetKey.create("nonFunctionReplacementOffset")
|
||||
val MULTIPLE_ARGUMENTS_REPLACEMENT_OFFSET: OffsetKey = OffsetKey.create("multipleArgumentsReplacementOffset")
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -140,7 +140,7 @@ class SmartCompletionSession(
|
||||
}
|
||||
}
|
||||
|
||||
if (position.getContainingFile() is KtCodeFragment) {
|
||||
if (position.containingFile is KtCodeFragment) {
|
||||
val variantsAndFactory = getRuntimeReceiverTypeReferenceVariants(lookupElementFactory)
|
||||
if (variantsAndFactory != null) {
|
||||
val variants = variantsAndFactory.first
|
||||
@@ -176,7 +176,7 @@ class SmartCompletionSession(
|
||||
if (nameExpression != null) {
|
||||
val callTypeAndReceiver = CallTypeAndReceiver.detect(nameExpression) as? CallTypeAndReceiver.INFIX ?: return
|
||||
val call = callTypeAndReceiver.receiver.getCall(bindingContext)
|
||||
if (call != null && call.getFunctionLiteralArguments().isEmpty()) {
|
||||
if (call != null && call.functionLiteralArguments.isEmpty()) {
|
||||
val dummyArgument = object : LambdaArgument {
|
||||
override fun getLambdaExpression() = throw UnsupportedOperationException()
|
||||
override fun getArgumentExpression() = throw UnsupportedOperationException()
|
||||
@@ -186,7 +186,7 @@ class SmartCompletionSession(
|
||||
override fun getSpreadElement(): LeafPsiElement? = null
|
||||
override fun isExternal() = false
|
||||
}
|
||||
val dummyArguments = call.getValueArguments() + listOf(dummyArgument)
|
||||
val dummyArguments = call.valueArguments + listOf(dummyArgument)
|
||||
val dummyCall = object : DelegatingCall(call) {
|
||||
override fun getValueArguments() = dummyArguments
|
||||
override fun getFunctionLiteralArguments() = listOf(dummyArgument)
|
||||
|
||||
+7
-7
@@ -38,7 +38,7 @@ class StaticMembers(
|
||||
private val lookupElementFactory: LookupElementFactory,
|
||||
private val resolutionFacade: ResolutionFacade
|
||||
) {
|
||||
public fun addToCollection(collection: MutableCollection<LookupElement>,
|
||||
fun addToCollection(collection: MutableCollection<LookupElement>,
|
||||
expectedInfos: Collection<ExpectedInfo>,
|
||||
context: KtSimpleNameExpression,
|
||||
enumEntriesToSkip: Set<DeclarationDescriptor>) {
|
||||
@@ -47,7 +47,7 @@ class StaticMembers(
|
||||
expectedInfo -> expectedInfo.fuzzyType?.type?.let { TypeUtils.getClassDescriptor(it) }
|
||||
}
|
||||
for ((classDescriptor, expectedInfosForClass) in expectedInfosByClass) {
|
||||
if (classDescriptor != null && !classDescriptor.getName().isSpecial()) {
|
||||
if (classDescriptor != null && !classDescriptor.name.isSpecial) {
|
||||
addToCollection(collection, classDescriptor, expectedInfosForClass, context, enumEntriesToSkip)
|
||||
}
|
||||
}
|
||||
@@ -78,17 +78,17 @@ class StaticMembers(
|
||||
collection.addLookupElements(descriptor, expectedInfos, matcher) { createLookupElements(it) }
|
||||
}
|
||||
|
||||
classDescriptor.getStaticScope().getContributedDescriptors().forEach(::processMember)
|
||||
classDescriptor.staticScope.getContributedDescriptors().forEach(::processMember)
|
||||
|
||||
val companionObject = classDescriptor.getCompanionObjectDescriptor()
|
||||
val companionObject = classDescriptor.companionObjectDescriptor
|
||||
if (companionObject != null) {
|
||||
companionObject.getDefaultType().getMemberScope().getContributedDescriptors()
|
||||
companionObject.defaultType.memberScope.getContributedDescriptors()
|
||||
.filter { !it.isExtension }
|
||||
.forEach(::processMember)
|
||||
}
|
||||
|
||||
var members = classDescriptor.getDefaultType().getMemberScope().getContributedDescriptors()
|
||||
if (classDescriptor.getKind() != ClassKind.ENUM_CLASS) {
|
||||
var members = classDescriptor.defaultType.memberScope.getContributedDescriptors()
|
||||
if (classDescriptor.kind != ClassKind.ENUM_CLASS) {
|
||||
members = members.filter { DescriptorUtils.isNonCompanionObject(it) }
|
||||
}
|
||||
members.forEach(::processMember)
|
||||
|
||||
+20
-20
@@ -61,7 +61,7 @@ class TypeInstantiationItems(
|
||||
val lookupElementFactory: LookupElementFactory,
|
||||
val forOrdinaryCompletion: Boolean
|
||||
) {
|
||||
public fun addTo(
|
||||
fun addTo(
|
||||
items: MutableCollection<LookupElement>,
|
||||
inheritanceSearchers: MutableCollection<InheritanceItemsSearcher>,
|
||||
expectedInfos: Collection<ExpectedInfo>
|
||||
@@ -130,21 +130,21 @@ class TypeInstantiationItems(
|
||||
}
|
||||
|
||||
// not all inner classes can be instantiated and we handle them via constructors returned by ReferenceVariantsHelper
|
||||
if (classifier.isInner()) return null
|
||||
if (classifier.isInner) return null
|
||||
|
||||
val isAbstract = classifier.getModality() == Modality.ABSTRACT
|
||||
val isAbstract = classifier.modality == Modality.ABSTRACT
|
||||
if (forOrdinaryCompletion && isAbstract) return null
|
||||
|
||||
val allConstructors = classifier.getConstructors()
|
||||
val allConstructors = classifier.constructors
|
||||
val visibleConstructors = allConstructors.filter {
|
||||
if (isAbstract)
|
||||
visibilityFilter(it) || it.getVisibility() == Visibilities.PROTECTED
|
||||
visibilityFilter(it) || it.visibility == Visibilities.PROTECTED
|
||||
else
|
||||
visibilityFilter(it)
|
||||
}
|
||||
if (allConstructors.isNotEmpty() && visibleConstructors.isEmpty()) return null
|
||||
|
||||
var lookupString = lookupElement.getLookupString()
|
||||
var lookupString = lookupElement.lookupString
|
||||
var allLookupStrings = setOf(lookupString)
|
||||
var itemText = lookupString
|
||||
var signatureText: String? = null
|
||||
@@ -164,11 +164,11 @@ class TypeInstantiationItems(
|
||||
itemText += "<...>"
|
||||
}
|
||||
|
||||
val constructorParenthesis = if (classifier.getKind() != ClassKind.INTERFACE) "()" else ""
|
||||
val constructorParenthesis = if (classifier.kind != ClassKind.INTERFACE) "()" else ""
|
||||
itemText += constructorParenthesis
|
||||
itemText = "object: $itemText{...}"
|
||||
lookupString = "object"
|
||||
allLookupStrings = setOf(lookupString, lookupElement.getLookupString())
|
||||
allLookupStrings = setOf(lookupString, lookupElement.lookupString)
|
||||
insertHandler = InsertHandler<LookupElement> { context, item ->
|
||||
val startOffset = context.startOffset
|
||||
|
||||
@@ -216,12 +216,12 @@ class TypeInstantiationItems(
|
||||
|
||||
insertHandler = object : InsertHandler<LookupElement> {
|
||||
override fun handleInsert(context: InsertionContext, item: LookupElement) {
|
||||
context.getDocument().replaceString(context.getStartOffset(), context.getTailOffset(), typeText)
|
||||
context.setTailOffset(context.getStartOffset() + typeText.length)
|
||||
context.document.replaceString(context.startOffset, context.tailOffset, typeText)
|
||||
context.tailOffset = context.startOffset + typeText.length
|
||||
|
||||
baseInsertHandler.handleInsert(context, item)
|
||||
|
||||
shortenReferences(context, context.getStartOffset(), context.getTailOffset())
|
||||
shortenReferences(context, context.startOffset, context.tailOffset)
|
||||
}
|
||||
}
|
||||
if (baseInsertHandler.inputValueArguments) {
|
||||
@@ -240,29 +240,29 @@ class TypeInstantiationItems(
|
||||
override fun getAllLookupStrings() = allLookupStrings
|
||||
|
||||
override fun renderElement(presentation: LookupElementPresentation) {
|
||||
getDelegate().renderElement(presentation)
|
||||
presentation.setItemText(itemText)
|
||||
delegate.renderElement(presentation)
|
||||
presentation.itemText = itemText
|
||||
|
||||
presentation.clearTail()
|
||||
if (signatureText != null) {
|
||||
presentation.appendTailText(signatureText!!, false)
|
||||
}
|
||||
presentation.appendTailText(" (" + DescriptorUtils.getFqName(classifier.getContainingDeclaration()) + ")", true)
|
||||
presentation.appendTailText(" (" + DescriptorUtils.getFqName(classifier.containingDeclaration) + ")", true)
|
||||
}
|
||||
|
||||
override fun handleInsert(context: InsertionContext) {
|
||||
insertHandler.handleInsert(context, getDelegate())
|
||||
insertHandler.handleInsert(context, delegate)
|
||||
}
|
||||
|
||||
override fun equals(other: Any?): Boolean {
|
||||
if (other === this) return true
|
||||
if (other !is InstantiationLookupElement) return false
|
||||
if (getLookupString() != other.getLookupString()) return false
|
||||
if (getLookupString() != other.lookupString) return false
|
||||
val presentation1 = LookupElementPresentation()
|
||||
val presentation2 = LookupElementPresentation()
|
||||
renderElement(presentation1)
|
||||
other.renderElement(presentation2)
|
||||
return presentation1.getItemText() == presentation2.getItemText() && presentation1.getTailText() == presentation2.getTailText()
|
||||
return presentation1.itemText == presentation2.itemText && presentation1.tailText == presentation2.tailText
|
||||
}
|
||||
}
|
||||
|
||||
@@ -274,11 +274,11 @@ class TypeInstantiationItems(
|
||||
}
|
||||
|
||||
private fun addSamConstructorItem(collection: MutableCollection<LookupElement>, `class`: ClassDescriptor, tail: Tail?) {
|
||||
if (`class`.getKind() == ClassKind.INTERFACE) {
|
||||
val container = `class`.getContainingDeclaration()
|
||||
if (`class`.kind == ClassKind.INTERFACE) {
|
||||
val container = `class`.containingDeclaration
|
||||
val scope = when (container) {
|
||||
is PackageFragmentDescriptor -> container.getMemberScope()
|
||||
is ClassDescriptor -> container.getStaticScope()
|
||||
is ClassDescriptor -> container.staticScope
|
||||
else -> return
|
||||
}
|
||||
val samConstructor = scope.getContributedFunctions(`class`.name, NoLookupLocation.FROM_IDE)
|
||||
|
||||
@@ -44,11 +44,11 @@ import java.util.*
|
||||
class ArtificialElementInsertHandler(
|
||||
val textBeforeCaret: String, val textAfterCaret: String, val shortenRefs: Boolean) : InsertHandler<LookupElement>{
|
||||
override fun handleInsert(context: InsertionContext, item: LookupElement) {
|
||||
val offset = context.getEditor().getCaretModel().getOffset()
|
||||
val startOffset = offset - item.getLookupString().length
|
||||
context.getDocument().deleteString(startOffset, offset) // delete inserted lookup string
|
||||
context.getDocument().insertString(startOffset, textBeforeCaret + textAfterCaret)
|
||||
context.getEditor().getCaretModel().moveToOffset(startOffset + textBeforeCaret.length)
|
||||
val offset = context.editor.caretModel.offset
|
||||
val startOffset = offset - item.lookupString.length
|
||||
context.document.deleteString(startOffset, offset) // delete inserted lookup string
|
||||
context.document.insertString(startOffset, textBeforeCaret + textAfterCaret)
|
||||
context.editor.caretModel.moveToOffset(startOffset + textBeforeCaret.length)
|
||||
|
||||
if (shortenRefs) {
|
||||
shortenReferences(context, startOffset, startOffset + textBeforeCaret.length + textAfterCaret.length)
|
||||
@@ -66,31 +66,31 @@ fun LookupElement.addTail(tail: Tail?): LookupElement {
|
||||
|
||||
Tail.COMMA -> object: LookupElementDecorator<LookupElement>(this) {
|
||||
override fun handleInsert(context: InsertionContext) {
|
||||
WithTailInsertHandler.COMMA.handleInsert(context, getDelegate())
|
||||
WithTailInsertHandler.COMMA.handleInsert(context, delegate)
|
||||
}
|
||||
}
|
||||
|
||||
Tail.RPARENTH -> object: LookupElementDecorator<LookupElement>(this) {
|
||||
override fun handleInsert(context: InsertionContext) {
|
||||
WithTailInsertHandler.RPARENTH.handleInsert(context, getDelegate())
|
||||
WithTailInsertHandler.RPARENTH.handleInsert(context, delegate)
|
||||
}
|
||||
}
|
||||
|
||||
Tail.RBRACKET -> object: LookupElementDecorator<LookupElement>(this) {
|
||||
override fun handleInsert(context: InsertionContext) {
|
||||
WithTailInsertHandler.RBRACKET.handleInsert(context, getDelegate())
|
||||
WithTailInsertHandler.RBRACKET.handleInsert(context, delegate)
|
||||
}
|
||||
}
|
||||
|
||||
Tail.ELSE -> object: LookupElementDecorator<LookupElement>(this) {
|
||||
override fun handleInsert(context: InsertionContext) {
|
||||
WithTailInsertHandler.ELSE.handleInsert(context, getDelegate())
|
||||
WithTailInsertHandler.ELSE.handleInsert(context, delegate)
|
||||
}
|
||||
}
|
||||
|
||||
Tail.RBRACE -> object: LookupElementDecorator<LookupElement>(this) {
|
||||
override fun handleInsert(context: InsertionContext) {
|
||||
WithTailInsertHandler.RBRACE.handleInsert(context, getDelegate())
|
||||
WithTailInsertHandler.RBRACE.handleInsert(context, delegate)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -102,11 +102,11 @@ fun LookupElement.withOptions(options: ItemOptions): LookupElement {
|
||||
lookupElement = object : LookupElementDecorator<LookupElement>(this) {
|
||||
override fun renderElement(presentation: LookupElementPresentation) {
|
||||
super.renderElement(presentation)
|
||||
presentation.setItemText("*" + presentation.getItemText())
|
||||
presentation.itemText = "*" + presentation.itemText
|
||||
}
|
||||
|
||||
override fun handleInsert(context: InsertionContext) {
|
||||
WithExpressionPrefixInsertHandler("*").handleInsert(context, getDelegate())
|
||||
WithExpressionPrefixInsertHandler("*").handleInsert(context, delegate)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -118,7 +118,7 @@ fun LookupElement.addTailAndNameSimilarity(
|
||||
nameSimilarityExpectedInfos: Collection<ExpectedInfo> = matchedExpectedInfos
|
||||
): LookupElement {
|
||||
val lookupElement = addTail(mergeTails(matchedExpectedInfos.map { it.tail }))
|
||||
val similarity = calcNameSimilarity(lookupElement.getLookupString(), nameSimilarityExpectedInfos)
|
||||
val similarity = calcNameSimilarity(lookupElement.lookupString, nameSimilarityExpectedInfos)
|
||||
if (similarity != 0) {
|
||||
lookupElement.putUserData(NAME_SIMILARITY_KEY, similarity)
|
||||
}
|
||||
@@ -170,7 +170,7 @@ fun<TDescriptor: DeclarationDescriptor?> MutableCollection<LookupElement>.addLoo
|
||||
override fun equals(other: Any?)
|
||||
= descriptorsEqualWithSubstitution(this.descriptor, (other as? ItemData)?.descriptor) && itemOptions ==
|
||||
(other as? ItemData)?.itemOptions
|
||||
override fun hashCode() = if (this.descriptor != null) this.descriptor.getOriginal().hashCode() else 0
|
||||
override fun hashCode() = if (this.descriptor != null) this.descriptor.original.hashCode() else 0
|
||||
}
|
||||
|
||||
fun ItemData.createLookupElements() = lookupElementFactory(this.descriptor).map { it.withOptions(this.itemOptions) }
|
||||
@@ -225,10 +225,10 @@ private fun MutableCollection<LookupElement>.addLookupElementsForNullable(factor
|
||||
object: LookupElementDecorator<LookupElement>(it) {
|
||||
override fun renderElement(presentation: LookupElementPresentation) {
|
||||
super.renderElement(presentation)
|
||||
presentation.setItemText("!! " + presentation.getItemText())
|
||||
presentation.itemText = "!! " + presentation.itemText
|
||||
}
|
||||
override fun handleInsert(context: InsertionContext) {
|
||||
WithTailInsertHandler("!!", spaceBefore = false, spaceAfter = false).handleInsert(context, getDelegate())
|
||||
WithTailInsertHandler("!!", spaceBefore = false, spaceAfter = false).handleInsert(context, delegate)
|
||||
}
|
||||
}.postProcess()
|
||||
}
|
||||
@@ -237,10 +237,10 @@ private fun MutableCollection<LookupElement>.addLookupElementsForNullable(factor
|
||||
object: LookupElementDecorator<LookupElement>(it) {
|
||||
override fun renderElement(presentation: LookupElementPresentation) {
|
||||
super.renderElement(presentation)
|
||||
presentation.setItemText("?: " + presentation.getItemText())
|
||||
presentation.itemText = "?: " + presentation.itemText
|
||||
}
|
||||
override fun handleInsert(context: InsertionContext) {
|
||||
WithTailInsertHandler("?:", spaceBefore = true, spaceAfter = true).handleInsert(context, getDelegate()) //TODO: code style
|
||||
WithTailInsertHandler("?:", spaceBefore = true, spaceAfter = true).handleInsert(context, delegate) //TODO: code style
|
||||
}
|
||||
}.postProcess()
|
||||
}
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ import com.intellij.codeInsight.completion.CompletionType
|
||||
import org.jetbrains.kotlin.idea.test.JdkAndMockLibraryProjectDescriptor
|
||||
import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatform
|
||||
|
||||
public abstract class AbstractCompiledKotlinInJavaCompletionTest : KotlinFixtureCompletionBaseTestCase() {
|
||||
abstract class AbstractCompiledKotlinInJavaCompletionTest : KotlinFixtureCompletionBaseTestCase() {
|
||||
override fun getPlatform() = JvmPlatform
|
||||
|
||||
override fun getProjectDescriptor() = JdkAndMockLibraryProjectDescriptor(COMPLETION_TEST_DATA_BASE_PATH + "/injava/mockLib", false)
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ import org.jetbrains.kotlin.idea.test.JdkAndMockLibraryProjectDescriptor
|
||||
import org.jetbrains.kotlin.idea.test.PluginTestCaseBase
|
||||
import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatform
|
||||
|
||||
public abstract class AbstractJvmWithLibBasicCompletionTest : KotlinFixtureCompletionBaseTestCase() {
|
||||
abstract class AbstractJvmWithLibBasicCompletionTest : KotlinFixtureCompletionBaseTestCase() {
|
||||
private val TEST_PATH = COMPLETION_TEST_DATA_BASE_PATH + "/basic/withLib"
|
||||
|
||||
override fun getProjectDescriptor(): LightProjectDescriptor {
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ import org.jetbrains.kotlin.idea.completion.KeywordLookupObject
|
||||
import org.jetbrains.kotlin.idea.test.KotlinLightProjectDescriptor
|
||||
import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatform
|
||||
|
||||
public abstract class AbstractKeywordCompletionTest : KotlinFixtureCompletionBaseTestCase() {
|
||||
abstract class AbstractKeywordCompletionTest : KotlinFixtureCompletionBaseTestCase() {
|
||||
override fun getPlatform() = JvmPlatform
|
||||
|
||||
override fun defaultCompletionType() = CompletionType.BASIC
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
|
||||
import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatform
|
||||
import java.io.File
|
||||
|
||||
public abstract class AbstractKotlinSourceInJavaCompletionTest : KotlinFixtureCompletionBaseTestCase() {
|
||||
abstract class AbstractKotlinSourceInJavaCompletionTest : KotlinFixtureCompletionBaseTestCase() {
|
||||
override fun getPlatform() = JvmPlatform
|
||||
|
||||
override fun doTest(testPath: String) {
|
||||
|
||||
+2
-2
@@ -20,13 +20,13 @@ import com.intellij.codeInsight.completion.CompletionType
|
||||
import org.jetbrains.kotlin.idea.test.AstAccessControl
|
||||
import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatform
|
||||
|
||||
public abstract class AbstractMultiFileJvmBasicCompletionTest : KotlinCompletionTestCase() {
|
||||
abstract class AbstractMultiFileJvmBasicCompletionTest : KotlinCompletionTestCase() {
|
||||
protected fun doTest(testPath: String) {
|
||||
configureByFile(getTestName(false) + ".kt", "")
|
||||
// several tests require disabling this check after adding InclusiveRange, need to investigate why
|
||||
// val shouldFail = testPath.contains("NoSpecifiedType")
|
||||
// AstAccessControl.testWithControlledAccessToAst(shouldFail, getFile().getVirtualFile(), getProject(), getTestRootDisposable(), {
|
||||
testCompletion(getFile().getText(), JvmPlatform, { completionType, invocationCount ->
|
||||
testCompletion(file.text, JvmPlatform, { completionType, invocationCount ->
|
||||
setType(completionType)
|
||||
complete(invocationCount)
|
||||
myItems
|
||||
|
||||
+2
-2
@@ -20,7 +20,7 @@ import com.intellij.codeInsight.completion.CompletionType
|
||||
import org.jetbrains.kotlin.idea.test.AstAccessControl
|
||||
import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatform
|
||||
|
||||
public abstract class AbstractMultiFileSmartCompletionTest : KotlinCompletionTestCase() {
|
||||
abstract class AbstractMultiFileSmartCompletionTest : KotlinCompletionTestCase() {
|
||||
override fun setUp() {
|
||||
super.setUp()
|
||||
setType(CompletionType.SMART)
|
||||
@@ -30,7 +30,7 @@ public abstract class AbstractMultiFileSmartCompletionTest : KotlinCompletionTes
|
||||
configureByFile(getTestName(false) + ".kt", "")
|
||||
// several tests require disabling this check after adding InclusiveRange, need to investigate why
|
||||
// AstAccessControl.testWithControlledAccessToAst(false, getFile().getVirtualFile(), getProject(), getTestRootDisposable(), {
|
||||
testCompletion(getFile().getText(), JvmPlatform, { completionType, invocationCount ->
|
||||
testCompletion(file.text, JvmPlatform, { completionType, invocationCount ->
|
||||
setType(completionType)
|
||||
complete(invocationCount)
|
||||
myItems
|
||||
|
||||
+29
-29
@@ -39,17 +39,17 @@ import java.util.*
|
||||
* Extract a number of statements about completion from the given text. Those statements
|
||||
* should be asserted during test execution.
|
||||
*/
|
||||
public object ExpectedCompletionUtils {
|
||||
object ExpectedCompletionUtils {
|
||||
|
||||
public class CompletionProposal {
|
||||
class CompletionProposal {
|
||||
private val map: Map<String, String?>
|
||||
|
||||
public constructor(lookupString: String) {
|
||||
constructor(lookupString: String) {
|
||||
map = HashMap<String, String?>()
|
||||
map.put(LOOKUP_STRING, lookupString)
|
||||
}
|
||||
|
||||
public constructor(map: MutableMap<String, String?>) {
|
||||
constructor(map: MutableMap<String, String?>) {
|
||||
this.map = map
|
||||
for (key in map.keys) {
|
||||
if (key !in validKeys) {
|
||||
@@ -58,7 +58,7 @@ public object ExpectedCompletionUtils {
|
||||
}
|
||||
}
|
||||
|
||||
public constructor(json: JsonObject) {
|
||||
constructor(json: JsonObject) {
|
||||
map = HashMap<String, String?>()
|
||||
for (entry in json.entrySet()) {
|
||||
val key = entry.key
|
||||
@@ -70,7 +70,7 @@ public object ExpectedCompletionUtils {
|
||||
}
|
||||
}
|
||||
|
||||
public fun matches(expectedProposal: CompletionProposal): Boolean
|
||||
fun matches(expectedProposal: CompletionProposal): Boolean
|
||||
= expectedProposal.map.entries.none { it.value != map[it.key] }
|
||||
|
||||
override fun toString(): String {
|
||||
@@ -82,13 +82,13 @@ public object ExpectedCompletionUtils {
|
||||
}
|
||||
|
||||
companion object {
|
||||
public val LOOKUP_STRING: String = "lookupString"
|
||||
public val ALL_LOOKUP_STRINGS: String = "allLookupStrings"
|
||||
public val PRESENTATION_ITEM_TEXT: String = "itemText"
|
||||
public val PRESENTATION_TYPE_TEXT: String = "typeText"
|
||||
public val PRESENTATION_TAIL_TEXT: String = "tailText"
|
||||
public val PRESENTATION_TEXT_ATTRIBUTES: String = "attributes"
|
||||
public val validKeys: Set<String> = setOf(LOOKUP_STRING, ALL_LOOKUP_STRINGS, PRESENTATION_ITEM_TEXT, PRESENTATION_TYPE_TEXT, PRESENTATION_TAIL_TEXT, PRESENTATION_TEXT_ATTRIBUTES)
|
||||
val LOOKUP_STRING: String = "lookupString"
|
||||
val ALL_LOOKUP_STRINGS: String = "allLookupStrings"
|
||||
val PRESENTATION_ITEM_TEXT: String = "itemText"
|
||||
val PRESENTATION_TYPE_TEXT: String = "typeText"
|
||||
val PRESENTATION_TAIL_TEXT: String = "tailText"
|
||||
val PRESENTATION_TEXT_ATTRIBUTES: String = "attributes"
|
||||
val validKeys: Set<String> = setOf(LOOKUP_STRING, ALL_LOOKUP_STRINGS, PRESENTATION_ITEM_TEXT, PRESENTATION_TYPE_TEXT, PRESENTATION_TAIL_TEXT, PRESENTATION_TEXT_ATTRIBUTES)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,11 +113,11 @@ public object ExpectedCompletionUtils {
|
||||
private val WITH_ORDER_PREFIX = "WITH_ORDER"
|
||||
private val AUTOCOMPLETE_SETTING_PREFIX = "AUTOCOMPLETE_SETTING:"
|
||||
|
||||
public val RUNTIME_TYPE: String = "RUNTIME_TYPE:"
|
||||
val RUNTIME_TYPE: String = "RUNTIME_TYPE:"
|
||||
|
||||
private val COMPLETION_TYPE_PREFIX = "COMPLETION_TYPE:"
|
||||
|
||||
public val KNOWN_PREFIXES: List<String> = ImmutableList.of(
|
||||
val KNOWN_PREFIXES: List<String> = ImmutableList.of(
|
||||
EXIST_LINE_PREFIX,
|
||||
ABSENT_LINE_PREFIX,
|
||||
ABSENT_JS_LINE_PREFIX,
|
||||
@@ -136,7 +136,7 @@ public object ExpectedCompletionUtils {
|
||||
LightClassComputationControl.LIGHT_CLASS_DIRECTIVE,
|
||||
AstAccessControl.ALLOW_AST_ACCESS_DIRECTIVE)
|
||||
|
||||
public fun itemsShouldExist(fileText: String, platform: TargetPlatform?): Array<CompletionProposal> {
|
||||
fun itemsShouldExist(fileText: String, platform: TargetPlatform?): Array<CompletionProposal> {
|
||||
return when (platform) {
|
||||
JvmPlatform -> processProposalAssertions(fileText, EXIST_LINE_PREFIX, EXIST_JAVA_ONLY_LINE_PREFIX)
|
||||
JsPlatform -> processProposalAssertions(fileText, EXIST_LINE_PREFIX, EXIST_JS_ONLY_LINE_PREFIX)
|
||||
@@ -145,7 +145,7 @@ public object ExpectedCompletionUtils {
|
||||
}
|
||||
}
|
||||
|
||||
public fun itemsShouldAbsent(fileText: String, platform: TargetPlatform?): Array<CompletionProposal> {
|
||||
fun itemsShouldAbsent(fileText: String, platform: TargetPlatform?): Array<CompletionProposal> {
|
||||
return when (platform) {
|
||||
JvmPlatform -> processProposalAssertions(fileText, ABSENT_LINE_PREFIX, ABSENT_JAVA_LINE_PREFIX, EXIST_JS_ONLY_LINE_PREFIX)
|
||||
JsPlatform -> processProposalAssertions(fileText, ABSENT_LINE_PREFIX, ABSENT_JS_LINE_PREFIX, EXIST_JAVA_ONLY_LINE_PREFIX)
|
||||
@@ -154,7 +154,7 @@ public object ExpectedCompletionUtils {
|
||||
}
|
||||
}
|
||||
|
||||
public fun processProposalAssertions(fileText: String, vararg prefixes: String): Array<CompletionProposal> {
|
||||
fun processProposalAssertions(fileText: String, vararg prefixes: String): Array<CompletionProposal> {
|
||||
val proposals = ArrayList<CompletionProposal>()
|
||||
for (proposalStr in InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, *prefixes)) {
|
||||
if (proposalStr.startsWith("{")) {
|
||||
@@ -180,7 +180,7 @@ public object ExpectedCompletionUtils {
|
||||
return ArrayUtil.toObjectArray(proposals, CompletionProposal::class.java)
|
||||
}
|
||||
|
||||
public fun getExpectedNumber(fileText: String, platform: TargetPlatform?): Int? {
|
||||
fun getExpectedNumber(fileText: String, platform: TargetPlatform?): Int? {
|
||||
return when (platform) {
|
||||
null -> InTextDirectivesUtils.getPrefixedInt(fileText, NUMBER_LINE_PREFIX)
|
||||
JvmPlatform -> getPlatformExpectedNumber(fileText, NUMBER_JAVA_LINE_PREFIX)
|
||||
@@ -189,15 +189,15 @@ public object ExpectedCompletionUtils {
|
||||
}
|
||||
}
|
||||
|
||||
public fun isNothingElseExpected(fileText: String): Boolean {
|
||||
fun isNothingElseExpected(fileText: String): Boolean {
|
||||
return !InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, NOTHING_ELSE_PREFIX).isEmpty()
|
||||
}
|
||||
|
||||
public fun getInvocationCount(fileText: String): Int? {
|
||||
fun getInvocationCount(fileText: String): Int? {
|
||||
return InTextDirectivesUtils.getPrefixedInt(fileText, INVOCATION_COUNT_PREFIX)
|
||||
}
|
||||
|
||||
public fun getCompletionType(fileText: String): CompletionType? {
|
||||
fun getCompletionType(fileText: String): CompletionType? {
|
||||
val completionTypeString = InTextDirectivesUtils.findStringWithPrefixes(fileText, COMPLETION_TYPE_PREFIX)
|
||||
return when (completionTypeString) {
|
||||
"BASIC" -> CompletionType.BASIC
|
||||
@@ -207,19 +207,19 @@ public object ExpectedCompletionUtils {
|
||||
}
|
||||
}
|
||||
|
||||
public fun getAutocompleteSetting(fileText: String): Boolean? {
|
||||
fun getAutocompleteSetting(fileText: String): Boolean? {
|
||||
return InTextDirectivesUtils.getPrefixedBoolean(fileText, AUTOCOMPLETE_SETTING_PREFIX)
|
||||
}
|
||||
|
||||
public fun isWithOrder(fileText: String): Boolean {
|
||||
fun isWithOrder(fileText: String): Boolean {
|
||||
return !InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, WITH_ORDER_PREFIX).isEmpty()
|
||||
}
|
||||
|
||||
public fun assertDirectivesValid(fileText: String) {
|
||||
fun assertDirectivesValid(fileText: String) {
|
||||
InTextDirectivesUtils.assertHasUnknownPrefixes(fileText, KNOWN_PREFIXES)
|
||||
}
|
||||
|
||||
public fun assertContainsRenderedItems(expected: Array<CompletionProposal>, items: Array<LookupElement>, checkOrder: Boolean, nothingElse: Boolean) {
|
||||
fun assertContainsRenderedItems(expected: Array<CompletionProposal>, items: Array<LookupElement>, checkOrder: Boolean, nothingElse: Boolean) {
|
||||
val itemsInformation = getItemsInformation(items)
|
||||
val allItemsString = listToString(itemsInformation)
|
||||
|
||||
@@ -272,7 +272,7 @@ public object ExpectedCompletionUtils {
|
||||
return InTextDirectivesUtils.getPrefixedInt(fileText, NUMBER_LINE_PREFIX)
|
||||
}
|
||||
|
||||
public fun assertNotContainsRenderedItems(unexpected: Array<CompletionProposal>, items: Array<LookupElement>) {
|
||||
fun assertNotContainsRenderedItems(unexpected: Array<CompletionProposal>, items: Array<LookupElement>) {
|
||||
val itemsInformation = getItemsInformation(items)
|
||||
val allItemsString = listToString(itemsInformation)
|
||||
|
||||
@@ -284,7 +284,7 @@ public object ExpectedCompletionUtils {
|
||||
}
|
||||
}
|
||||
|
||||
public fun getItemsInformation(items: Array<LookupElement>): List<CompletionProposal> {
|
||||
fun getItemsInformation(items: Array<LookupElement>): List<CompletionProposal> {
|
||||
val presentation = LookupElementPresentation()
|
||||
|
||||
val result = ArrayList<CompletionProposal>(items.size)
|
||||
@@ -336,5 +336,5 @@ public object ExpectedCompletionUtils {
|
||||
}
|
||||
}
|
||||
|
||||
public fun listToString(items: Collection<CompletionProposal>): String = items.joinToString("\n")
|
||||
fun listToString(items: Collection<CompletionProposal>): String = items.joinToString("\n")
|
||||
}
|
||||
|
||||
+4
-4
@@ -24,8 +24,8 @@ import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
|
||||
import org.jetbrains.kotlin.resolve.TargetPlatform
|
||||
import java.io.File
|
||||
|
||||
public abstract class KotlinFixtureCompletionBaseTestCase : KotlinLightCodeInsightFixtureTestCase() {
|
||||
public abstract fun getPlatform(): TargetPlatform
|
||||
abstract class KotlinFixtureCompletionBaseTestCase : KotlinLightCodeInsightFixtureTestCase() {
|
||||
abstract fun getPlatform(): TargetPlatform
|
||||
|
||||
protected open fun complete(completionType: CompletionType, invocationCount: Int): Array<LookupElement>?
|
||||
= myFixture.complete(completionType, invocationCount)
|
||||
@@ -33,7 +33,7 @@ public abstract class KotlinFixtureCompletionBaseTestCase : KotlinLightCodeInsig
|
||||
protected abstract fun defaultCompletionType(): CompletionType
|
||||
protected open fun defaultInvocationCount(): Int = 0
|
||||
|
||||
public open fun doTest(testPath: String) {
|
||||
open fun doTest(testPath: String) {
|
||||
setUpFixture(testPath)
|
||||
|
||||
val fileText = FileUtil.loadFile(File(testPath), true)
|
||||
@@ -42,7 +42,7 @@ public abstract class KotlinFixtureCompletionBaseTestCase : KotlinLightCodeInsig
|
||||
|
||||
protected open fun setUpFixture(testPath: String) {
|
||||
//TODO: this is a hacky workaround for js second completion tests failing with PsiInvalidElementAccessException
|
||||
LibraryModificationTracker.getInstance(getProject()).incModificationCount()
|
||||
LibraryModificationTracker.getInstance(project).incModificationCount()
|
||||
|
||||
myFixture.configureByFile(testPath)
|
||||
}
|
||||
|
||||
+10
-10
@@ -26,7 +26,7 @@ import org.jetbrains.kotlin.test.InTextDirectivesUtils
|
||||
import org.jetbrains.kotlin.utils.addToStdlib.indexOfOrNull
|
||||
import java.io.File
|
||||
|
||||
public abstract class AbstractCompletionHandlerTest(private val defaultCompletionType: CompletionType) : CompletionHandlerTestBase() {
|
||||
abstract class AbstractCompletionHandlerTest(private val defaultCompletionType: CompletionType) : CompletionHandlerTestBase() {
|
||||
private val INVOCATION_COUNT_PREFIX = "INVOCATION_COUNT:"
|
||||
private val LOOKUP_STRING_PREFIX = "ELEMENT:"
|
||||
private val ELEMENT_TEXT_PREFIX = "ELEMENT_TEXT:"
|
||||
@@ -38,8 +38,8 @@ public abstract class AbstractCompletionHandlerTest(private val defaultCompletio
|
||||
setUpFixture(testPath)
|
||||
|
||||
val settingManager = CodeStyleSettingsManager.getInstance()
|
||||
val tempSettings = settingManager.getCurrentSettings().clone()
|
||||
settingManager.setTemporarySettings(tempSettings)
|
||||
val tempSettings = settingManager.currentSettings.clone()
|
||||
settingManager.temporarySettings = tempSettings
|
||||
try {
|
||||
val fileText = FileUtil.loadFile(File(testPath))
|
||||
val invocationCount = InTextDirectivesUtils.getPrefixedInt(fileText, INVOCATION_COUNT_PREFIX) ?: 1
|
||||
@@ -56,16 +56,16 @@ public abstract class AbstractCompletionHandlerTest(private val defaultCompletio
|
||||
|
||||
val completionType = ExpectedCompletionUtils.getCompletionType(fileText) ?: defaultCompletionType
|
||||
|
||||
val codeStyleSettings = KotlinCodeStyleSettings.getInstance(getProject())
|
||||
val codeStyleSettings = KotlinCodeStyleSettings.getInstance(project)
|
||||
for (line in InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, CODE_STYLE_SETTING_PREFIX)) {
|
||||
val index = line.indexOfOrNull('=') ?: error("Invalid code style setting '$line': '=' expected")
|
||||
val settingName = line.substring(0, index).trim()
|
||||
val settingValue = line.substring(index + 1).trim()
|
||||
val field = codeStyleSettings.javaClass.getDeclaredField(settingName)
|
||||
when (field.getType().getName()) {
|
||||
when (field.type.name) {
|
||||
"boolean" -> field.setBoolean(codeStyleSettings, settingValue.toBoolean())
|
||||
"int" -> field.setInt(codeStyleSettings, settingValue.toInt())
|
||||
else -> error("Unsupported setting type: ${field.getType()}")
|
||||
else -> error("Unsupported setting type: ${field.type}")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,10 +83,10 @@ public abstract class AbstractCompletionHandlerTest(private val defaultCompletio
|
||||
override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
|
||||
}
|
||||
|
||||
public abstract class AbstractBasicCompletionHandlerTest() : AbstractCompletionHandlerTest(CompletionType.BASIC)
|
||||
abstract class AbstractBasicCompletionHandlerTest() : AbstractCompletionHandlerTest(CompletionType.BASIC)
|
||||
|
||||
public abstract class AbstractSmartCompletionHandlerTest() : AbstractCompletionHandlerTest(CompletionType.SMART)
|
||||
abstract class AbstractSmartCompletionHandlerTest() : AbstractCompletionHandlerTest(CompletionType.SMART)
|
||||
|
||||
public abstract class AbstractCompletionCharFilterTest() : AbstractCompletionHandlerTest(CompletionType.BASIC)
|
||||
abstract class AbstractCompletionCharFilterTest() : AbstractCompletionHandlerTest(CompletionType.BASIC)
|
||||
|
||||
public abstract class AbstractKeywordCompletionHandlerTest() : AbstractCompletionHandlerTest(CompletionType.BASIC)
|
||||
abstract class AbstractKeywordCompletionHandlerTest() : AbstractCompletionHandlerTest(CompletionType.BASIC)
|
||||
|
||||
+2
-3
@@ -21,13 +21,12 @@ import org.jetbrains.kotlin.idea.completion.test.COMPLETION_TEST_DATA_BASE_PATH
|
||||
import org.jetbrains.kotlin.idea.completion.test.handlers.CompletionHandlerTestBase
|
||||
import java.io.File
|
||||
|
||||
@Deprecated("All tests from here to be moved to the generated test")
|
||||
public class BasicCompletionHandlerTest : CompletionHandlerTestBase(){
|
||||
@Deprecated("All tests from here to be moved to the generated test") class BasicCompletionHandlerTest : CompletionHandlerTestBase(){
|
||||
private fun checkResult(){
|
||||
fixture.checkResultByFile(getTestName(false) + ".kt.after")
|
||||
}
|
||||
|
||||
override fun getTestDataPath() = File(COMPLETION_TEST_DATA_BASE_PATH, "/handlers").getPath() + File.separator
|
||||
override fun getTestDataPath() = File(COMPLETION_TEST_DATA_BASE_PATH, "/handlers").path + File.separator
|
||||
|
||||
private fun doTest() {
|
||||
doTest(2, "*", null, null, '\n')
|
||||
|
||||
+13
-13
@@ -29,7 +29,7 @@ import org.jetbrains.kotlin.idea.completion.test.ExpectedCompletionUtils
|
||||
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
|
||||
import org.jetbrains.kotlin.test.KotlinTestUtils
|
||||
|
||||
public abstract class CompletionHandlerTestBase() : KotlinLightCodeInsightFixtureTestCase() {
|
||||
abstract class CompletionHandlerTestBase() : KotlinLightCodeInsightFixtureTestCase() {
|
||||
protected val fixture: JavaCodeInsightTestFixture
|
||||
get() = myFixture
|
||||
|
||||
@@ -55,8 +55,8 @@ public abstract class CompletionHandlerTestBase() : KotlinLightCodeInsightFixtur
|
||||
}
|
||||
|
||||
private fun getExistentLookupElement(lookupString: String?, itemText: String?, tailText: String?): LookupElement? {
|
||||
val lookup = LookupManager.getInstance(getProject())?.getActiveLookup() as LookupImpl? ?: return null
|
||||
val items = lookup.getItems()
|
||||
val lookup = LookupManager.getInstance(project)?.activeLookup as LookupImpl? ?: return null
|
||||
val items = lookup.items
|
||||
|
||||
if (lookupString == "*") {
|
||||
assert(itemText == null)
|
||||
@@ -67,13 +67,13 @@ public abstract class CompletionHandlerTestBase() : KotlinLightCodeInsightFixtur
|
||||
var foundElement : LookupElement? = null
|
||||
val presentation = LookupElementPresentation()
|
||||
for (lookupElement in items) {
|
||||
val lookupOk = if (lookupString != null) lookupElement.getLookupString() == lookupString else true
|
||||
val lookupOk = if (lookupString != null) lookupElement.lookupString == lookupString else true
|
||||
|
||||
if (lookupOk) {
|
||||
lookupElement.renderElement(presentation)
|
||||
|
||||
val textOk = if (itemText != null) {
|
||||
val itemItemText = presentation.getItemText()
|
||||
val itemItemText = presentation.itemText
|
||||
itemItemText != null && itemItemText == itemText
|
||||
}
|
||||
else {
|
||||
@@ -82,7 +82,7 @@ public abstract class CompletionHandlerTestBase() : KotlinLightCodeInsightFixtur
|
||||
|
||||
if (textOk) {
|
||||
val tailOk = if (tailText != null) {
|
||||
val itemTailText = presentation.getTailText()
|
||||
val itemTailText = presentation.tailText
|
||||
itemTailText != null && itemTailText == tailText
|
||||
}
|
||||
else {
|
||||
@@ -111,17 +111,17 @@ public abstract class CompletionHandlerTestBase() : KotlinLightCodeInsightFixtur
|
||||
override fun getTestDataPath() = KotlinTestUtils.getHomeDirectory()
|
||||
|
||||
protected fun selectItem(item: LookupElement?, completionChar: Char) {
|
||||
val lookup = (fixture.getLookup() as LookupImpl)
|
||||
if (lookup.getCurrentItem() != item) { // do not touch selection if not changed - important for char filter tests
|
||||
lookup.setCurrentItem(item)
|
||||
val lookup = (fixture.lookup as LookupImpl)
|
||||
if (lookup.currentItem != item) { // do not touch selection if not changed - important for char filter tests
|
||||
lookup.currentItem = item
|
||||
}
|
||||
lookup.setFocusDegree(LookupImpl.FocusDegree.FOCUSED);
|
||||
lookup.focusDegree = LookupImpl.FocusDegree.FOCUSED;
|
||||
if (LookupEvent.isSpecialCompletionChar(completionChar)) {
|
||||
(object : WriteCommandAction.Simple<Any>(getProject()) {
|
||||
protected override fun run(result: Result<Any>) {
|
||||
(object : WriteCommandAction.Simple<Any>(project) {
|
||||
override fun run(result: Result<Any>) {
|
||||
run()
|
||||
}
|
||||
protected override fun run() {
|
||||
override fun run() {
|
||||
lookup.finishLookup(completionChar)
|
||||
}
|
||||
}).execute().throwException()
|
||||
|
||||
+7
-7
@@ -23,24 +23,24 @@ import org.jetbrains.kotlin.idea.completion.test.KotlinCompletionTestCase
|
||||
import java.io.File
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
public class SmartCompletionMultifileHandlerTest : KotlinCompletionTestCase() {
|
||||
public fun testImportExtensionFunction() { doTest() }
|
||||
class SmartCompletionMultifileHandlerTest : KotlinCompletionTestCase() {
|
||||
fun testImportExtensionFunction() { doTest() }
|
||||
|
||||
public fun testImportExtensionProperty() { doTest() }
|
||||
fun testImportExtensionProperty() { doTest() }
|
||||
|
||||
public fun testAnonymousObjectGenericJava() { doTest() }
|
||||
fun testAnonymousObjectGenericJava() { doTest() }
|
||||
|
||||
override fun setUp() {
|
||||
setType(CompletionType.SMART)
|
||||
super.setUp()
|
||||
}
|
||||
|
||||
public fun doTest() {
|
||||
fun doTest() {
|
||||
val fileName = getTestName(false)
|
||||
|
||||
val fileNames = listOf(fileName + "-1.kt", fileName + "-2.kt", fileName + ".java")
|
||||
|
||||
configureByFiles(null, *fileNames.filter { File(getTestDataPath() + it).exists() }.toTypedArray())
|
||||
configureByFiles(null, *fileNames.filter { File(testDataPath + it).exists() }.toTypedArray())
|
||||
|
||||
complete(1)
|
||||
if (myItems != null) {
|
||||
@@ -51,5 +51,5 @@ public class SmartCompletionMultifileHandlerTest : KotlinCompletionTestCase() {
|
||||
checkResultByFile(fileName + ".kt.after")
|
||||
}
|
||||
|
||||
override fun getTestDataPath() = File(COMPLETION_TEST_DATA_BASE_PATH, "/handlers/multifile/smart/").getPath() + File.separator
|
||||
override fun getTestDataPath() = File(COMPLETION_TEST_DATA_BASE_PATH, "/handlers/multifile/smart/").path + File.separator
|
||||
}
|
||||
|
||||
+5
-5
@@ -27,7 +27,7 @@ import org.jetbrains.kotlin.test.util.configureWithExtraFile
|
||||
import org.junit.Assert
|
||||
import java.io.File
|
||||
|
||||
public abstract class AbstractCompletionWeigherTest(val completionType: CompletionType, val relativeTestDataPath: String) : KotlinLightCodeInsightFixtureTestCase() {
|
||||
abstract class AbstractCompletionWeigherTest(val completionType: CompletionType, val relativeTestDataPath: String) : KotlinLightCodeInsightFixtureTestCase() {
|
||||
fun doTest(path: String) {
|
||||
val pathPrefix = RELATIVE_COMPLETION_TEST_DATA_BASE_PATH + "/" + relativeTestDataPath
|
||||
assert(path.startsWith(pathPrefix))
|
||||
@@ -35,7 +35,7 @@ public abstract class AbstractCompletionWeigherTest(val completionType: Completi
|
||||
|
||||
myFixture.configureWithExtraFile(relativePath, ".Data", ".Data1", ".Data2", ".Data3", ".Data4", ".Data5", ".Data6", relativePaths = true)
|
||||
|
||||
val text = myFixture.getEditor().getDocument().getText()
|
||||
val text = myFixture.editor.document.text
|
||||
|
||||
val items = InTextDirectivesUtils.findArrayWithPrefixes(text, "// ORDER:")
|
||||
Assert.assertTrue("""Some items should be defined with "// ORDER:" directive""", !items.isEmpty())
|
||||
@@ -44,13 +44,13 @@ public abstract class AbstractCompletionWeigherTest(val completionType: Completi
|
||||
myFixture.assertPreferredCompletionItems(InTextDirectivesUtils.getPrefixedInt(text, "// SELECTED:") ?: 0, *items)
|
||||
}
|
||||
|
||||
override fun getTestDataPath() = File(COMPLETION_TEST_DATA_BASE_PATH, relativeTestDataPath).getPath() + File.separator
|
||||
override fun getTestDataPath() = File(COMPLETION_TEST_DATA_BASE_PATH, relativeTestDataPath).path + File.separator
|
||||
}
|
||||
|
||||
public abstract class AbstractBasicCompletionWeigherTest() : AbstractCompletionWeigherTest(CompletionType.BASIC, "weighers/basic") {
|
||||
abstract class AbstractBasicCompletionWeigherTest() : AbstractCompletionWeigherTest(CompletionType.BASIC, "weighers/basic") {
|
||||
override fun getProjectDescriptor() = KotlinLightProjectDescriptor.INSTANCE
|
||||
}
|
||||
|
||||
public abstract class AbstractSmartCompletionWeigherTest() : AbstractCompletionWeigherTest(CompletionType.SMART, "weighers/smart") {
|
||||
abstract class AbstractSmartCompletionWeigherTest() : AbstractCompletionWeigherTest(CompletionType.SMART, "weighers/smart") {
|
||||
override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user