Misc: Cleanup "org.jetbrains.kotlin.idea.quickfix" package
This commit is contained in:
@@ -12,13 +12,13 @@ add.init.keyword.in.whole.project.modal.title=Adding 'init' keyword in whole pro
|
||||
add.init.keyword.in.whole.project.family=Add 'init' keyword in whole project
|
||||
insert.delegation.call=Insert ''{0}()'' call
|
||||
make.class.annotation.class=Make ''{0}'' an annotation class
|
||||
make.class.annotation.class.family=Make Class an Annotation Class
|
||||
make.class.annotation.class.family=Make class an annotation class
|
||||
add.star.projections=Add ''{0}''
|
||||
change.to.star.projection=Change type arguments to {0}
|
||||
change.to.star.projection.family=Change to Star Projection
|
||||
change.to.star.projection.family=Change to star projection
|
||||
remove.parts.from.property=Remove {0} from property
|
||||
remove.parts.from.property.family=Remove Parts from Property
|
||||
remove.psi.element.family=Remove Element
|
||||
remove.parts.from.property.family=Remove parts from property
|
||||
remove.psi.element.family=Remove element
|
||||
remove.right.part.of.binary.expression=Remove right part of a binary expression
|
||||
remove.elvis.operator=Remove elvis operator
|
||||
remove.redundant.nullable=Remove redundant '?'
|
||||
@@ -54,10 +54,10 @@ change.element.type=Change ''{0}'' type to ''{1}''
|
||||
change.function.parameter.type=Change parameter ''{0}'' type of function ''{1}'' to ''{2}''
|
||||
change.primary.constructor.parameter.type=Change parameter ''{0}'' type of primary constructor of class ''{1}'' to ''{2}''
|
||||
change.type=Change type from ''{0}'' to ''{1}''
|
||||
change.type.family=Change Type
|
||||
change.type.family=Change type
|
||||
change.function.signature=Change the signature of function ''{0}''
|
||||
cast.expression.to.type=Cast expression ''{0}'' to ''{1}''
|
||||
cast.expression.family=Cast Expression
|
||||
cast.expression.family=Cast expression
|
||||
|
||||
replace.call.error.skipped.defaults=Cannot skip default arguments.
|
||||
replace.call.error.undefined.returntype=Unable to determine the return type.
|
||||
@@ -147,10 +147,10 @@ migrate.lambda.syntax=Migrate lambda syntax
|
||||
migrate.lambda.syntax.family=Migrate lambda syntax
|
||||
remove.val.var.from.parameter=Remove ''{0}'' from parameter
|
||||
add.override.to.equals.hashCode.toString=Add 'override' to equals, hashCode, toString in project
|
||||
add.when.else.branch.action.family.name=Add Else Branch
|
||||
add.when.else.branch.action.family.name=Add else branch
|
||||
add.when.else.branch.action=Add else branch
|
||||
move.when.else.branch.to.the.end.action=Move else branch to the end
|
||||
move.when.else.branch.to.the.end.family.name=Move Else Branch to the End
|
||||
move.when.else.branch.to.the.end.family.name=Move else branch to the end
|
||||
change.to.property.name.family.name=Change to property name
|
||||
change.to.property.name.action=Change ''{0}'' to ''{1}''
|
||||
create.from.usage.family=Create from usage
|
||||
|
||||
@@ -54,7 +54,7 @@ public class AddConstModifierFix(val property: KtProperty) : AddModifierFix(prop
|
||||
}
|
||||
}
|
||||
|
||||
public class AddConstModifierIntention : SelfTargetingIntention<KtProperty>(javaClass(), "Add 'const' modifier") {
|
||||
public class AddConstModifierIntention : SelfTargetingIntention<KtProperty>(KtProperty::class.java, "Add 'const' modifier") {
|
||||
override fun applyTo(element: KtProperty, editor: Editor) {
|
||||
AddConstModifierFix.addConstModifier(element)
|
||||
}
|
||||
|
||||
@@ -50,12 +50,12 @@ public class AddFunctionBodyFix extends KotlinQuickFixAction<KtFunction> {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiFile file) {
|
||||
return super.isAvailable(project, editor, file) && !getElement().hasBody();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, Editor editor, KtFile file) throws IncorrectOperationException {
|
||||
public void invoke(@NotNull Project project, Editor editor, @NotNull KtFile file) throws IncorrectOperationException {
|
||||
KtFunction newElement = (KtFunction) getElement().copy();
|
||||
KtPsiFactory psiFactory = KtPsiFactoryKt.KtPsiFactory(file);
|
||||
if (!(newElement.getLastChild() instanceof PsiWhiteSpace)) {
|
||||
@@ -71,7 +71,7 @@ public class AddFunctionBodyFix extends KotlinQuickFixAction<KtFunction> {
|
||||
return new KotlinSingleIntentionActionFactory() {
|
||||
@Nullable
|
||||
@Override
|
||||
public KotlinQuickFixAction createAction(Diagnostic diagnostic) {
|
||||
public KotlinQuickFixAction createAction(@NotNull Diagnostic diagnostic) {
|
||||
PsiElement element = diagnostic.getPsiElement();
|
||||
KtFunction function = PsiTreeUtil.getParentOfType(element, KtFunction.class, false);
|
||||
if (function == null) return null;
|
||||
|
||||
@@ -86,19 +86,19 @@ public class AddFunctionParametersFix(
|
||||
val validator = CollectingNameValidator()
|
||||
|
||||
for (i in arguments.indices) {
|
||||
val argument = arguments.get(i)
|
||||
val argument = arguments[i]
|
||||
val expression = argument.getArgumentExpression()
|
||||
|
||||
if (i < parameters.size) {
|
||||
validator.addName(parameters.get(i).name.asString())
|
||||
validator.addName(parameters[i].name.asString())
|
||||
val argumentType = expression?.let {
|
||||
val bindingContext = it.analyze()
|
||||
bindingContext[BindingContext.SMARTCAST, it] ?: bindingContext.getType(it)
|
||||
}
|
||||
val parameterType = parameters.get(i).type
|
||||
val parameterType = parameters[i].type
|
||||
|
||||
if (argumentType != null && !KotlinTypeChecker.DEFAULT.isSubtypeOf(argumentType, parameterType)) {
|
||||
it.parameters.get(i).currentTypeInfo = KotlinTypeInfo(false, argumentType)
|
||||
it.parameters[i].currentTypeInfo = KotlinTypeInfo(false, argumentType)
|
||||
typesToShorten.add(argumentType)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,16 +69,14 @@ class AddFunctionToSupertypeFix private constructor(
|
||||
override fun getFamilyName() = "Add function to supertype"
|
||||
|
||||
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
|
||||
CommandProcessor.getInstance().runUndoTransparentAction(object : Runnable {
|
||||
override fun run() {
|
||||
if (functions.size == 1 || editor == null || !editor.component.isShowing) {
|
||||
addFunction(functions.first(), project)
|
||||
}
|
||||
else {
|
||||
JBPopupFactory.getInstance().createListPopup(createFunctionPopup(project)).showInBestPositionFor(editor)
|
||||
}
|
||||
CommandProcessor.getInstance().runUndoTransparentAction {
|
||||
if (functions.size == 1 || editor == null || !editor.component.isShowing) {
|
||||
addFunction(functions.first(), project)
|
||||
}
|
||||
})
|
||||
else {
|
||||
JBPopupFactory.getInstance().createListPopup(createFunctionPopup(project)).showInBestPositionFor(editor)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun addFunction(functionData: FunctionData, project: Project) {
|
||||
@@ -158,16 +156,16 @@ class AddFunctionToSupertypeFix private constructor(
|
||||
}
|
||||
|
||||
private fun getSuperClasses(classDescriptor: ClassDescriptor): List<ClassDescriptor> {
|
||||
val supertypes = classDescriptor.defaultType.supertypes().sortedWith(object : Comparator<KotlinType> {
|
||||
override fun compare(o1: KotlinType, o2: KotlinType): Int {
|
||||
return when {
|
||||
o1 == o2 -> 0
|
||||
KotlinTypeChecker.DEFAULT.isSubtypeOf(o1, o2) -> -1
|
||||
KotlinTypeChecker.DEFAULT.isSubtypeOf(o2, o1) -> 1
|
||||
else -> o1.toString().compareTo(o2.toString())
|
||||
val supertypes = classDescriptor.defaultType.supertypes().sortedWith(
|
||||
Comparator<KotlinType> { o1, o2 ->
|
||||
when {
|
||||
o1 == o2 -> 0
|
||||
KotlinTypeChecker.DEFAULT.isSubtypeOf(o1, o2) -> -1
|
||||
KotlinTypeChecker.DEFAULT.isSubtypeOf(o2, o1) -> 1
|
||||
else -> o1.toString().compareTo(o2.toString())
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
return supertypes.mapNotNull { it.constructor.declarationDescriptor as? ClassDescriptor }
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ import org.jetbrains.kotlin.psi.psiUtil.parents
|
||||
|
||||
public class AddLoopLabelFix(loop: KtLoopExpression, val jumpExpression: KtElement): KotlinQuickFixAction<KtLoopExpression>(loop) {
|
||||
override fun getText() = "Add label to loop"
|
||||
override fun getFamilyName() = getText()
|
||||
override fun getFamilyName() = text
|
||||
|
||||
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile): Boolean {
|
||||
return super.isAvailable(project, editor, file)
|
||||
@@ -37,12 +37,12 @@ public class AddLoopLabelFix(loop: KtLoopExpression, val jumpExpression: KtEleme
|
||||
val usedLabels = collectUsedLabels(element)
|
||||
val labelName = getUniqueLabelName(usedLabels)
|
||||
|
||||
val jumpWithLabel = KtPsiFactory(project).createExpression(jumpExpression.getText() + "@" + labelName)
|
||||
val jumpWithLabel = KtPsiFactory(project).createExpression(jumpExpression.text + "@" + labelName)
|
||||
jumpExpression.replace(jumpWithLabel)
|
||||
|
||||
// TODO(yole) use createExpressionByPattern() once it's available
|
||||
val labeledLoopExpression = KtPsiFactory(project).createLabeledExpression(labelName)
|
||||
labeledLoopExpression.getBaseExpression()!!.replace(element)
|
||||
labeledLoopExpression.baseExpression!!.replace(element)
|
||||
element.replace(labeledLoopExpression)
|
||||
|
||||
// TODO(yole) We should initiate in-place rename for the label here, but in-place rename for labels is not yet implemented
|
||||
@@ -75,7 +75,7 @@ public class AddLoopLabelFix(loop: KtLoopExpression, val jumpExpression: KtEleme
|
||||
|
||||
companion object: KotlinSingleIntentionActionFactory() {
|
||||
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
|
||||
val element = diagnostic.getPsiElement() as? KtElement
|
||||
val element = diagnostic.psiElement as? KtElement
|
||||
assert(element is KtBreakExpression || element is KtContinueExpression)
|
||||
assert((element as? KtLabeledExpression)?.getLabelName() == null)
|
||||
val loop = element?.getStrictParentOfType<KtLoopExpression>() ?: return null
|
||||
|
||||
@@ -49,7 +49,7 @@ public class AddNameToArgumentFix(argument: KtValueArgument) : KotlinQuickFixAct
|
||||
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
|
||||
val possibleNames = calculatePossibleArgumentNames()
|
||||
assert(possibleNames.isNotEmpty()) { "isAvailable() should be checked before invoke()" }
|
||||
if (possibleNames.size() == 1 || editor == null || !editor.component.isShowing) {
|
||||
if (possibleNames.size == 1 || editor == null || !editor.component.isShowing) {
|
||||
addName(project, element, possibleNames.first())
|
||||
}
|
||||
else {
|
||||
|
||||
+2
-2
@@ -54,7 +54,7 @@ public class AddOverrideToEqualsHashCodeToStringFix extends KotlinQuickFixAction
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiFile file) {
|
||||
return super.isAvailable(project, editor, file) && isEqualsHashCodeOrToString(getElement());
|
||||
}
|
||||
|
||||
@@ -78,7 +78,7 @@ public class AddOverrideToEqualsHashCodeToStringFix extends KotlinQuickFixAction
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void invoke(@NotNull Project project, Editor editor, KtFile file) throws IncorrectOperationException {
|
||||
protected void invoke(@NotNull Project project, Editor editor, @NotNull KtFile file) throws IncorrectOperationException {
|
||||
Collection<KtFile> files = PluginJetFilesProvider.allFilesInProject(file.getProject());
|
||||
|
||||
for (KtFile jetFile : files) {
|
||||
|
||||
@@ -54,7 +54,7 @@ public abstract class AddStarProjectionsFix extends KotlinQuickFixAction<KtUserT
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, Editor editor, KtFile file) throws IncorrectOperationException {
|
||||
public void invoke(@NotNull Project project, Editor editor, @NotNull KtFile file) throws IncorrectOperationException {
|
||||
assert getElement().getTypeArguments().isEmpty();
|
||||
|
||||
String typeString = TypeReconstructionUtil.getTypeNameAndStarProjectionsString(getElement().getText(), argumentCount);
|
||||
@@ -72,7 +72,7 @@ public abstract class AddStarProjectionsFix extends KotlinQuickFixAction<KtUserT
|
||||
public static KotlinSingleIntentionActionFactory createFactoryForIsExpression() {
|
||||
return new KotlinSingleIntentionActionFactory() {
|
||||
@Override
|
||||
public IntentionAction createAction(Diagnostic diagnostic) {
|
||||
public IntentionAction createAction(@NotNull Diagnostic diagnostic) {
|
||||
DiagnosticWithParameters2<KtTypeReference, Integer, String> diagnosticWithParameters =
|
||||
Errors.NO_TYPE_ARGUMENTS_ON_RHS.cast(diagnostic);
|
||||
KtTypeElement typeElement = diagnosticWithParameters.getPsiElement().getTypeElement();
|
||||
@@ -89,7 +89,7 @@ public abstract class AddStarProjectionsFix extends KotlinQuickFixAction<KtUserT
|
||||
public static KotlinSingleIntentionActionFactory createFactoryForJavaClass() {
|
||||
return new KotlinSingleIntentionActionFactory() {
|
||||
@Override
|
||||
public IntentionAction createAction(Diagnostic diagnostic) {
|
||||
public IntentionAction createAction(@NotNull Diagnostic diagnostic) {
|
||||
DiagnosticWithParameters1<KtElement, Integer> diagnosticWithParameters = Errors.WRONG_NUMBER_OF_TYPE_ARGUMENTS.cast(diagnostic);
|
||||
|
||||
Integer size = diagnosticWithParameters.getA();
|
||||
@@ -99,9 +99,7 @@ public abstract class AddStarProjectionsFix extends KotlinQuickFixAction<KtUserT
|
||||
|
||||
return new AddStarProjectionsFix(userType, size) {
|
||||
@Override
|
||||
public boolean isAvailable(
|
||||
@NotNull Project project, Editor editor, PsiFile file
|
||||
) {
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiFile file) {
|
||||
// We are looking for the occurrence of Type in javaClass<Type>()
|
||||
return super.isAvailable(project, editor, file) && isZeroTypeArguments() && isInsideJavaClassCall();
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
|
||||
package org.jetbrains.kotlin.idea.quickfix;
|
||||
|
||||
import com.intellij.codeInsight.CodeInsightUtilBase;
|
||||
import com.intellij.codeInsight.CodeInsightUtilCore;
|
||||
import com.intellij.openapi.editor.Editor;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.openapi.util.TextRange;
|
||||
@@ -51,12 +51,12 @@ public class AddWhenElseBranchFix extends KotlinQuickFixAction<KtWhenExpression>
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiFile file) {
|
||||
return super.isAvailable(project, editor, file) && getElement().getCloseBrace() != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, Editor editor, KtFile file) throws IncorrectOperationException {
|
||||
public void invoke(@NotNull Project project, Editor editor, @NotNull KtFile file) throws IncorrectOperationException {
|
||||
PsiElement whenCloseBrace = getElement().getCloseBrace();
|
||||
assert (whenCloseBrace != null) : "isAvailable should check if close brace exist";
|
||||
|
||||
@@ -66,7 +66,7 @@ public class AddWhenElseBranchFix extends KotlinQuickFixAction<KtWhenExpression>
|
||||
PsiElement insertedBranch = getElement().addBefore(entry, whenCloseBrace);
|
||||
getElement().addAfter(psiFactory.createNewLine(), insertedBranch);
|
||||
|
||||
KtWhenEntry insertedWhenEntry = (KtWhenEntry) CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(insertedBranch);
|
||||
KtWhenEntry insertedWhenEntry = (KtWhenEntry) CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(insertedBranch);
|
||||
TextRange textRange = insertedWhenEntry.getTextRange();
|
||||
|
||||
int indexOfOpenBrace = insertedWhenEntry.getText().indexOf('{');
|
||||
|
||||
@@ -61,7 +61,7 @@ import java.util.*
|
||||
internal abstract class AutoImportFixBase<T: KtExpression>(expression: T) :
|
||||
KotlinQuickFixAction<T>(expression), HighPriorityAction, HintAction {
|
||||
|
||||
private val modificationCountOnCreate = PsiModificationTracker.SERVICE.getInstance(element.getProject()).getModificationCount()
|
||||
private val modificationCountOnCreate = PsiModificationTracker.SERVICE.getInstance(element.project).modificationCount
|
||||
|
||||
private val suggestionCount: Int by CachedValueProperty(
|
||||
calculator = { computeSuggestions().size },
|
||||
@@ -73,9 +73,9 @@ internal abstract class AutoImportFixBase<T: KtExpression>(expression: T) :
|
||||
protected abstract fun getCallTypeAndReceiver(): CallTypeAndReceiver<*, *>
|
||||
|
||||
override fun showHint(editor: Editor): Boolean {
|
||||
if (!element.isValid() || isOutdated()) return false
|
||||
if (!element.isValid || isOutdated()) return false
|
||||
|
||||
if (ApplicationManager.getApplication().isUnitTestMode() && HintManager.getInstance().hasShownHintsThatWillHideByOtherHint(true)) return false
|
||||
if (ApplicationManager.getApplication().isUnitTestMode && HintManager.getInstance().hasShownHintsThatWillHideByOtherHint(true)) return false
|
||||
|
||||
if (suggestionCount == 0) return false
|
||||
|
||||
@@ -97,15 +97,15 @@ internal abstract class AutoImportFixBase<T: KtExpression>(expression: T) :
|
||||
|
||||
override fun startInWriteAction() = true
|
||||
|
||||
private fun isOutdated() = modificationCountOnCreate != PsiModificationTracker.SERVICE.getInstance(element.getProject()).getModificationCount()
|
||||
private fun isOutdated() = modificationCountOnCreate != PsiModificationTracker.SERVICE.getInstance(element.project).modificationCount
|
||||
|
||||
protected open fun createAction(project: Project, editor: Editor): KotlinAddImportAction {
|
||||
return createSingleImportAction(project, editor, element, computeSuggestions())
|
||||
}
|
||||
|
||||
fun computeSuggestions(): Collection<DeclarationDescriptor> {
|
||||
if (!element.isValid()) return listOf()
|
||||
if (element.getContainingFile() !is KtFile) return emptyList()
|
||||
if (!element.isValid) return listOf()
|
||||
if (element.containingFile !is KtFile) return emptyList()
|
||||
|
||||
val callTypeAndReceiver = getCallTypeAndReceiver()
|
||||
|
||||
@@ -123,7 +123,7 @@ internal abstract class AutoImportFixBase<T: KtExpression>(expression: T) :
|
||||
val nameStr = name.asString()
|
||||
if (nameStr.isEmpty()) return emptyList()
|
||||
|
||||
val file = element.getContainingFile() as KtFile
|
||||
val file = element.containingFile as KtFile
|
||||
|
||||
fun filterByCallType(descriptor: DeclarationDescriptor) = callTypeAndReceiver.callType.descriptorKindFilter.accepts(descriptor)
|
||||
|
||||
@@ -131,9 +131,9 @@ internal abstract class AutoImportFixBase<T: KtExpression>(expression: T) :
|
||||
|
||||
val bindingContext = element.analyze(BodyResolveMode.PARTIAL)
|
||||
|
||||
val diagnostics = bindingContext.getDiagnostics().forElement(element)
|
||||
val diagnostics = bindingContext.diagnostics.forElement(element)
|
||||
|
||||
if (!diagnostics.any { it.getFactory() in getSupportedErrors() }) return emptyList()
|
||||
if (!diagnostics.any { it.factory in getSupportedErrors() }) return emptyList()
|
||||
|
||||
val resolutionFacade = element.getResolutionFacade()
|
||||
|
||||
@@ -193,7 +193,7 @@ internal class AutoImportFix(expression: KtSimpleNameExpression) : AutoImportFix
|
||||
val elementType = element.firstChild.node.elementType
|
||||
if (elementType in OperatorConventions.ASSIGNMENT_OPERATIONS) {
|
||||
val counterpart = OperatorConventions.ASSIGNMENT_OPERATION_COUNTERPARTS[elementType]
|
||||
val counterpartName = OperatorConventions.BINARY_OPERATION_NAMES.get(counterpart)
|
||||
val counterpartName = OperatorConventions.BINARY_OPERATION_NAMES[counterpart]
|
||||
if (counterpartName != null) {
|
||||
return@run listOf(conventionName, counterpartName)
|
||||
}
|
||||
@@ -214,7 +214,7 @@ internal class AutoImportFix(expression: KtSimpleNameExpression) : AutoImportFix
|
||||
|
||||
companion object : KotlinSingleIntentionActionFactory() {
|
||||
override fun createAction(diagnostic: Diagnostic) =
|
||||
(diagnostic.getPsiElement() as? KtSimpleNameExpression)?.let { AutoImportFix(it) }
|
||||
(diagnostic.psiElement as? KtSimpleNameExpression)?.let { AutoImportFix(it) }
|
||||
|
||||
override fun isApplicableForCodeFragment() = true
|
||||
|
||||
|
||||
@@ -62,7 +62,7 @@ public class CastExpressionFix extends KotlinQuickFixAction<KtExpression> {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiFile file) {
|
||||
if (!super.isAvailable(project, editor, file)) return false;
|
||||
KotlinType expressionType = ResolutionUtils.analyze(getElement()).getType(getElement());
|
||||
return expressionType != null
|
||||
@@ -73,7 +73,7 @@ public class CastExpressionFix extends KotlinQuickFixAction<KtExpression> {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, Editor editor, KtFile file) throws IncorrectOperationException {
|
||||
public void invoke(@NotNull Project project, Editor editor, @NotNull KtFile file) throws IncorrectOperationException {
|
||||
String renderedType = IdeDescriptorRenderers.SOURCE_CODE.renderType(type);
|
||||
|
||||
KtPsiFactory psiFactory = KtPsiFactoryKt.KtPsiFactory(file);
|
||||
|
||||
@@ -38,7 +38,7 @@ public class ChangeAccessorTypeFix extends KotlinQuickFixAction<KtPropertyAccess
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiFile file) {
|
||||
KtProperty property = PsiTreeUtil.getParentOfType(getElement(), KtProperty.class);
|
||||
if (property == null) return false;
|
||||
KotlinType type = QuickFixUtil.getDeclarationReturnType(property);
|
||||
@@ -65,7 +65,7 @@ public class ChangeAccessorTypeFix extends KotlinQuickFixAction<KtPropertyAccess
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, Editor editor, KtFile file) throws IncorrectOperationException {
|
||||
public void invoke(@NotNull Project project, Editor editor, @NotNull KtFile file) throws IncorrectOperationException {
|
||||
KtTypeReference newTypeReference = KtPsiFactoryKt
|
||||
.KtPsiFactory(file).createType(IdeDescriptorRenderers.SOURCE_CODE.renderType(type));
|
||||
|
||||
|
||||
@@ -127,13 +127,13 @@ public class ChangeFunctionLiteralReturnTypeFix extends KotlinQuickFixAction<KtL
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiFile file) {
|
||||
return super.isAvailable(project, editor, file) &&
|
||||
(functionLiteralReturnTypeRef != null || (appropriateQuickFix != null && appropriateQuickFix.isAvailable(project, editor, file)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, Editor editor, KtFile file) throws IncorrectOperationException {
|
||||
public void invoke(@NotNull Project project, Editor editor, @NotNull KtFile file) throws IncorrectOperationException {
|
||||
if (functionLiteralReturnTypeRef != null) {
|
||||
KtTypeReference newTypeRef = KtPsiFactoryKt.KtPsiFactory(file).createType(IdeDescriptorRenderers.SOURCE_CODE.renderType(type));
|
||||
newTypeRef = (KtTypeReference) functionLiteralReturnTypeRef.replace(newTypeRef);
|
||||
|
||||
@@ -48,7 +48,7 @@ class ChangeFunctionLiteralSignatureFix private constructor(
|
||||
val validator = CollectingNameValidator()
|
||||
descriptor.clearNonReceiverParameters()
|
||||
for (type in parameterTypes) {
|
||||
val name = KotlinNameSuggester.suggestNamesByType(type, validator, "param").get(0)
|
||||
val name = KotlinNameSuggester.suggestNamesByType(type, validator, "param")[0]
|
||||
descriptor.addParameter(KotlinParameterInfo(functionDescriptor, -1, name, KotlinTypeInfo(false, type)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,12 +101,12 @@ public class ChangeFunctionReturnTypeFix extends KotlinQuickFixAction<KtFunction
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAvailable(@NotNull Project project, @Nullable Editor editor, @Nullable PsiFile file) {
|
||||
public boolean isAvailable(@NotNull Project project, @Nullable Editor editor, @NotNull PsiFile file) {
|
||||
return super.isAvailable(project, editor, file) && !ErrorUtils.containsErrorType(type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, @Nullable Editor editor, KtFile file) throws IncorrectOperationException {
|
||||
public void invoke(@NotNull Project project, @Nullable Editor editor, @NotNull KtFile file) throws IncorrectOperationException {
|
||||
if (changeFunctionLiteralReturnTypeFix != null) {
|
||||
changeFunctionLiteralReturnTypeFix.invoke(project, editor, file);
|
||||
}
|
||||
|
||||
@@ -40,11 +40,13 @@ public class ChangeParameterTypeFix extends KotlinQuickFixAction<KtParameter> {
|
||||
KtNamedDeclaration declaration = PsiTreeUtil.getParentOfType(element, KtNamedDeclaration.class);
|
||||
isPrimaryConstructorParameter = declaration instanceof KtPrimaryConstructor;
|
||||
FqName declarationFQName = declaration == null ? null : declaration.getFqName();
|
||||
containingDeclarationName = declarationFQName == null ? declaration.getName() : declarationFQName.asString();
|
||||
containingDeclarationName = declarationFQName != null ? declarationFQName.asString()
|
||||
: declaration != null ? declaration.getName()
|
||||
: null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiFile file) {
|
||||
return super.isAvailable(project, editor, file) && containingDeclarationName != null;
|
||||
}
|
||||
|
||||
@@ -65,7 +67,7 @@ public class ChangeParameterTypeFix extends KotlinQuickFixAction<KtParameter> {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, Editor editor, KtFile file) throws IncorrectOperationException {
|
||||
public void invoke(@NotNull Project project, Editor editor, @NotNull KtFile file) throws IncorrectOperationException {
|
||||
KtTypeReference newTypeRef = KtPsiFactoryKt.KtPsiFactory(file).createType(IdeDescriptorRenderers.SOURCE_CODE.renderType(type));
|
||||
newTypeRef = getElement().setTypeReference(newTypeRef);
|
||||
assert newTypeRef != null;
|
||||
|
||||
@@ -45,7 +45,7 @@ public class ChangeToFunctionInvocationFix extends KotlinQuickFixAction<KtExpres
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, Editor editor, KtFile file) throws IncorrectOperationException {
|
||||
public void invoke(@NotNull Project project, Editor editor, @NotNull KtFile file) throws IncorrectOperationException {
|
||||
KtExpression reference = (KtExpression) getElement().copy();
|
||||
getElement().replace(KtPsiFactoryKt.KtPsiFactory(file).createExpression(reference.getText() + "()"));
|
||||
}
|
||||
@@ -53,7 +53,7 @@ public class ChangeToFunctionInvocationFix extends KotlinQuickFixAction<KtExpres
|
||||
public static KotlinSingleIntentionActionFactory createFactory() {
|
||||
return new KotlinSingleIntentionActionFactory() {
|
||||
@Override
|
||||
public KotlinQuickFixAction<KtExpression> createAction(Diagnostic diagnostic) {
|
||||
public KotlinQuickFixAction<KtExpression> createAction(@NotNull Diagnostic diagnostic) {
|
||||
if (diagnostic.getPsiElement() instanceof KtExpression) {
|
||||
return new ChangeToFunctionInvocationFix((KtExpression) diagnostic.getPsiElement());
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ public class ChangeToStarProjectionFix extends KotlinQuickFixAction<KtTypeElemen
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, Editor editor, KtFile file) throws IncorrectOperationException {
|
||||
public void invoke(@NotNull Project project, Editor editor, @NotNull KtFile file) throws IncorrectOperationException {
|
||||
for (KtTypeReference typeReference : getElement().getTypeArgumentsAsTypes()) {
|
||||
if (typeReference != null) {
|
||||
typeReference.replace(KtPsiFactoryKt.KtPsiFactory(file).createStar());
|
||||
@@ -57,7 +57,7 @@ public class ChangeToStarProjectionFix extends KotlinQuickFixAction<KtTypeElemen
|
||||
public static KotlinSingleIntentionActionFactory createFactory() {
|
||||
return new KotlinSingleIntentionActionFactory() {
|
||||
@Override
|
||||
public IntentionAction createAction(Diagnostic diagnostic) {
|
||||
public IntentionAction createAction(@NotNull Diagnostic diagnostic) {
|
||||
KtBinaryExpressionWithTypeRHS expression = QuickFixUtil
|
||||
.getParentElementOfType(diagnostic, KtBinaryExpressionWithTypeRHS.class);
|
||||
KtTypeReference typeReference;
|
||||
|
||||
@@ -59,7 +59,7 @@ public class ChangeTypeFix extends KotlinQuickFixAction<KtTypeReference> {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, Editor editor, KtFile file) throws IncorrectOperationException {
|
||||
public void invoke(@NotNull Project project, Editor editor, @NotNull KtFile file) throws IncorrectOperationException {
|
||||
KtTypeReference newTypeRef = (KtTypeReference) getElement().replace(KtPsiFactoryKt.KtPsiFactory(file).createType(renderedType));
|
||||
ShortenReferences.DEFAULT.process(newTypeRef);
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ public class ChangeVariableMutabilityFix(element: KtNamedDeclaration, private va
|
||||
|
||||
override fun getText() = if (makeVar) "Make variable mutable" else "Make variable immutable"
|
||||
|
||||
override fun getFamilyName(): String = getText()
|
||||
override fun getFamilyName(): String = text
|
||||
|
||||
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile): Boolean {
|
||||
return when (element) {
|
||||
@@ -52,15 +52,15 @@ public class ChangeVariableMutabilityFix(element: KtNamedDeclaration, private va
|
||||
companion object {
|
||||
public val VAL_WITH_SETTER_FACTORY: KotlinSingleIntentionActionFactory = object: KotlinSingleIntentionActionFactory() {
|
||||
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
|
||||
val accessor = diagnostic.getPsiElement() as KtPropertyAccessor
|
||||
val property = accessor.getParent() as KtProperty
|
||||
val accessor = diagnostic.psiElement as KtPropertyAccessor
|
||||
val property = accessor.parent as KtProperty
|
||||
return ChangeVariableMutabilityFix(property, true)
|
||||
}
|
||||
}
|
||||
|
||||
public val VAL_REASSIGNMENT_FACTORY: KotlinSingleIntentionActionFactory = object: KotlinSingleIntentionActionFactory() {
|
||||
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
|
||||
val propertyDescriptor = Errors.VAL_REASSIGNMENT.cast(diagnostic).getA()
|
||||
val propertyDescriptor = Errors.VAL_REASSIGNMENT.cast(diagnostic).a
|
||||
val declaration = DescriptorToSourceUtils.descriptorToDeclaration(propertyDescriptor) as? KtNamedDeclaration ?: return null
|
||||
return ChangeVariableMutabilityFix(declaration, true)
|
||||
}
|
||||
|
||||
@@ -17,7 +17,6 @@
|
||||
package org.jetbrains.kotlin.idea.quickfix;
|
||||
|
||||
import com.intellij.codeInsight.intention.IntentionAction;
|
||||
import com.intellij.openapi.diagnostic.Logger;
|
||||
import com.intellij.openapi.editor.Editor;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.psi.PsiElement;
|
||||
@@ -48,8 +47,6 @@ import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
public class ChangeVariableTypeFix extends KotlinQuickFixAction<KtVariableDeclaration> {
|
||||
private final static Logger LOG = Logger.getInstance(ChangeVariableTypeFix.class);
|
||||
|
||||
private final KotlinType type;
|
||||
|
||||
public ChangeVariableTypeFix(@NotNull KtVariableDeclaration element, @NotNull KotlinType type) {
|
||||
@@ -75,19 +72,19 @@ public class ChangeVariableTypeFix extends KotlinQuickFixAction<KtVariableDeclar
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiFile file) {
|
||||
return super.isAvailable(project, editor, file) && !ErrorUtils.containsErrorType(type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, Editor editor, KtFile file) throws IncorrectOperationException {
|
||||
public void invoke(@NotNull Project project, Editor editor, @NotNull KtFile file) throws IncorrectOperationException {
|
||||
KtPsiFactory psiFactory = KtPsiFactoryKt.KtPsiFactory(file);
|
||||
|
||||
PsiElement nameIdentifier = getElement().getNameIdentifier();
|
||||
assert nameIdentifier != null : "ChangeVariableTypeFix applied to variable without name";
|
||||
|
||||
KtTypeReference replacingTypeReference = psiFactory.createType(IdeDescriptorRenderers.SOURCE_CODE.renderType(type));
|
||||
ArrayList<KtTypeReference> toShorten = new ArrayList<KtTypeReference>();
|
||||
List<KtTypeReference> toShorten = new ArrayList<KtTypeReference>();
|
||||
toShorten.add(getElement().setTypeReference(replacingTypeReference));
|
||||
|
||||
if (getElement() instanceof KtProperty) {
|
||||
|
||||
@@ -56,20 +56,20 @@ public class ChangeVisibilityModifierFix extends KotlinQuickFixAction<KtDeclarat
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiFile file) {
|
||||
if (!(file instanceof KtFile)) return false;
|
||||
return super.isAvailable(project, editor, file) && (findVisibilityChangeTo((KtFile)file) != null);
|
||||
return super.isAvailable(project, editor, file) && (findVisibilityChangeTo() != null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, Editor editor, KtFile file) throws IncorrectOperationException {
|
||||
KtModifierKeywordToken modifier = findVisibilityChangeTo(file);
|
||||
public void invoke(@NotNull Project project, Editor editor, @NotNull KtFile file) throws IncorrectOperationException {
|
||||
KtModifierKeywordToken modifier = findVisibilityChangeTo();
|
||||
assert modifier != null;
|
||||
PsiModificationUtilsKt.setVisibility(getElement(), modifier);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private KtModifierKeywordToken findVisibilityChangeTo(KtFile file) {
|
||||
private KtModifierKeywordToken findVisibilityChangeTo() {
|
||||
BindingContext bindingContext = ResolutionUtils.analyze(getElement());
|
||||
DeclarationDescriptor descriptor;
|
||||
if (getElement() instanceof KtParameter) {
|
||||
@@ -110,7 +110,7 @@ public class ChangeVisibilityModifierFix extends KotlinQuickFixAction<KtDeclarat
|
||||
public static KotlinSingleIntentionActionFactory createFactory() {
|
||||
return new KotlinSingleIntentionActionFactory() {
|
||||
@Override
|
||||
public KotlinQuickFixAction<KtDeclaration> createAction(Diagnostic diagnostic) {
|
||||
public KotlinQuickFixAction<KtDeclaration> createAction(@NotNull Diagnostic diagnostic) {
|
||||
PsiElement element = diagnostic.getPsiElement();
|
||||
if (!(element instanceof KtDeclaration)) return null;
|
||||
return new ChangeVisibilityModifierFix((KtDeclaration)element);
|
||||
|
||||
@@ -22,7 +22,6 @@ import com.intellij.openapi.project.Project
|
||||
import com.intellij.psi.PsiElement
|
||||
import org.jetbrains.kotlin.diagnostics.Diagnostic
|
||||
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.combineWhenConditions
|
||||
import org.jetbrains.kotlin.idea.quickfix.quickfixUtil.createIntentionFactory
|
||||
import org.jetbrains.kotlin.lexer.KtTokens
|
||||
import org.jetbrains.kotlin.psi.*
|
||||
import java.util.*
|
||||
|
||||
+1
-3
@@ -21,17 +21,15 @@ import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.project.Project
|
||||
import org.jetbrains.kotlin.diagnostics.Diagnostic
|
||||
import org.jetbrains.kotlin.idea.intentions.ConvertPropertyInitializerToGetterIntention
|
||||
import org.jetbrains.kotlin.idea.intentions.SpecifyTypeExplicitlyIntention
|
||||
import org.jetbrains.kotlin.psi.KtExpression
|
||||
import org.jetbrains.kotlin.psi.KtFile
|
||||
import org.jetbrains.kotlin.psi.KtProperty
|
||||
import org.jetbrains.kotlin.psi.KtPsiFactory
|
||||
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
|
||||
|
||||
class ConvertExtensionPropertyInitializerToGetterFix(element: KtExpression) : KotlinQuickFixAction<KtExpression>(element) {
|
||||
override fun getText(): String = "Convert extension property initializer to getter"
|
||||
|
||||
override fun getFamilyName(): String = getText()
|
||||
override fun getFamilyName(): String = text
|
||||
|
||||
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
|
||||
val property = element.getParentOfType<KtProperty>(true) ?: return
|
||||
|
||||
@@ -25,7 +25,6 @@ import com.intellij.psi.PsiFile
|
||||
import com.intellij.psi.impl.source.tree.LeafPsiElement
|
||||
import org.jetbrains.kotlin.descriptors.ClassDescriptor
|
||||
import org.jetbrains.kotlin.descriptors.ClassifierDescriptor
|
||||
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
|
||||
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
|
||||
import org.jetbrains.kotlin.diagnostics.Diagnostic
|
||||
import org.jetbrains.kotlin.idea.KotlinBundle
|
||||
@@ -38,12 +37,11 @@ import org.jetbrains.kotlin.psi.KtPostfixExpression
|
||||
import org.jetbrains.kotlin.psi.KtPsiFactory
|
||||
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
|
||||
import org.jetbrains.kotlin.types.TypeUtils
|
||||
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
|
||||
import org.jetbrains.kotlin.util.OperatorChecks
|
||||
import org.jetbrains.kotlin.util.OperatorNameConventions
|
||||
|
||||
public abstract class ExclExclCallFix : IntentionAction {
|
||||
override fun getFamilyName(): String = getText()
|
||||
override fun getFamilyName(): String = text
|
||||
|
||||
override fun startInWriteAction(): Boolean = true
|
||||
|
||||
@@ -60,13 +58,13 @@ public class RemoveExclExclCallFix(val psiElement: PsiElement) : ExclExclCallFix
|
||||
if (!FileModificationService.getInstance().prepareFileForWrite(file)) return
|
||||
|
||||
val postfixExpression = getExclExclPostfixExpression() ?: return
|
||||
val expression = KtPsiFactory(project).createExpression(postfixExpression.getBaseExpression()!!.getText())
|
||||
val expression = KtPsiFactory(project).createExpression(postfixExpression.baseExpression!!.text)
|
||||
postfixExpression.replace(expression)
|
||||
}
|
||||
|
||||
private fun getExclExclPostfixExpression(): KtPostfixExpression? {
|
||||
val operationParent = psiElement.getParent()
|
||||
if (operationParent is KtPostfixExpression && operationParent.getBaseExpression() != null) {
|
||||
val operationParent = psiElement.parent
|
||||
if (operationParent is KtPostfixExpression && operationParent.baseExpression != null) {
|
||||
return operationParent
|
||||
}
|
||||
return null
|
||||
@@ -74,7 +72,7 @@ public class RemoveExclExclCallFix(val psiElement: PsiElement) : ExclExclCallFix
|
||||
|
||||
companion object : KotlinSingleIntentionActionFactory() {
|
||||
override fun createAction(diagnostic: Diagnostic): IntentionAction
|
||||
= RemoveExclExclCallFix(diagnostic.getPsiElement())
|
||||
= RemoveExclExclCallFix(diagnostic.psiElement)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,13 +85,13 @@ public class AddExclExclCallFix(val psiElement: PsiElement) : ExclExclCallFix()
|
||||
|
||||
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
|
||||
val modifiedExpression = getExpressionForIntroduceCall() ?: return
|
||||
val exclExclExpression = KtPsiFactory(project).createExpression(modifiedExpression.getText() + "!!")
|
||||
val exclExclExpression = KtPsiFactory(project).createExpression(modifiedExpression.text + "!!")
|
||||
modifiedExpression.replace(exclExclExpression)
|
||||
}
|
||||
|
||||
protected fun getExpressionForIntroduceCall(): KtExpression? {
|
||||
if (psiElement is LeafPsiElement && psiElement.getElementType() == KtTokens.DOT) {
|
||||
val sibling = psiElement.getPrevSibling()
|
||||
if (psiElement is LeafPsiElement && psiElement.elementType == KtTokens.DOT) {
|
||||
val sibling = psiElement.prevSibling
|
||||
if (sibling is KtExpression) {
|
||||
return sibling
|
||||
}
|
||||
@@ -107,7 +105,7 @@ public class AddExclExclCallFix(val psiElement: PsiElement) : ExclExclCallFix()
|
||||
|
||||
companion object : KotlinSingleIntentionActionFactory() {
|
||||
override fun createAction(diagnostic: Diagnostic): IntentionAction
|
||||
= AddExclExclCallFix(diagnostic.getPsiElement())
|
||||
= AddExclExclCallFix(diagnostic.psiElement)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,7 +126,7 @@ object MissingIteratorExclExclFixFactory : KotlinSingleIntentionActionFactory()
|
||||
val memberScope = descriptor.unsubstitutedMemberScope
|
||||
val functions = memberScope.getContributedFunctions(OperatorNameConventions.ITERATOR, NoLookupLocation.FROM_IDE)
|
||||
|
||||
return functions.any { it.isOperator() && OperatorChecks.canBeOperator(it) }
|
||||
return functions.any { it.isOperator && OperatorChecks.canBeOperator(it) }
|
||||
}
|
||||
|
||||
when (descriptor) {
|
||||
|
||||
@@ -49,9 +49,9 @@ public class InsertDelegationCallQuickfix(val isThis: Boolean, element: KtSecond
|
||||
val descriptor = element.resolveToDescriptor()
|
||||
|
||||
// if empty call is ok and it's resolved to another constructor, do not move caret
|
||||
if (resolvedCall?.isReallySuccess() ?: false && resolvedCall!!.getCandidateDescriptor().getOriginal() != descriptor) return
|
||||
if (resolvedCall?.isReallySuccess() ?: false && resolvedCall!!.candidateDescriptor.original != descriptor) return
|
||||
|
||||
val leftParOffset = newDelegationCall.getValueArgumentList()!!.getLeftParenthesis()!!.getTextOffset()
|
||||
val leftParOffset = newDelegationCall.valueArgumentList!!.leftParenthesis!!.textOffset
|
||||
|
||||
editor?.moveCaret(leftParOffset + 1)
|
||||
}
|
||||
@@ -69,12 +69,12 @@ public class InsertDelegationCallQuickfix(val isThis: Boolean, element: KtSecond
|
||||
return InsertDelegationCallQuickfix(isThis = true, element = secondaryConstructor)
|
||||
}
|
||||
|
||||
private fun KtClassOrObject.getConstructorsCount() = (descriptor as ClassDescriptor).getConstructors().size()
|
||||
private fun KtClassOrObject.getConstructorsCount() = (descriptor as ClassDescriptor).constructors.size
|
||||
}
|
||||
|
||||
object InsertSuperDelegationCallFactory : KotlinSingleIntentionActionFactory() {
|
||||
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
|
||||
val secondaryConstructor = diagnostic.getPsiElement().getNonStrictParentOfType<KtSecondaryConstructor>() ?: return null
|
||||
val secondaryConstructor = diagnostic.psiElement.getNonStrictParentOfType<KtSecondaryConstructor>() ?: return null
|
||||
if (!secondaryConstructor.hasImplicitDelegationCall()) return null
|
||||
val klass = secondaryConstructor.getContainingClassOrObject() as? KtClass ?: return null
|
||||
if (klass.hasPrimaryConstructor()) return null
|
||||
|
||||
@@ -89,7 +89,7 @@ public class KotlinReferenceImporter : ReferenceImporter {
|
||||
|
||||
var suggestions = AutoImportFix(this).computeSuggestions()
|
||||
|
||||
if (suggestions.distinctBy { it.importableFqName!! }.size() != 1) return false
|
||||
if (suggestions.distinctBy { it.importableFqName!! }.size != 1) return false
|
||||
|
||||
// we do not auto-import nested classes because this will probably add qualification into the text and this will confuse the user
|
||||
if (suggestions.any { it is ClassDescriptor && it.containingDeclaration is ClassDescriptor }) return false
|
||||
|
||||
@@ -44,7 +44,7 @@ public class MakeClassAnAnnotationClassFix extends KotlinQuickFixAction<KtAnnota
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiFile file) {
|
||||
if (!super.isAvailable(project, editor, file)) {
|
||||
return false;
|
||||
}
|
||||
@@ -102,7 +102,7 @@ public class MakeClassAnAnnotationClassFix extends KotlinQuickFixAction<KtAnnota
|
||||
return new KotlinSingleIntentionActionFactory() {
|
||||
@Nullable
|
||||
@Override
|
||||
public IntentionAction createAction(Diagnostic diagnostic) {
|
||||
public IntentionAction createAction(@NotNull Diagnostic diagnostic) {
|
||||
KtAnnotationEntry annotation = QuickFixUtil.getParentElementOfType(diagnostic, KtAnnotationEntry.class);
|
||||
return annotation == null ? null : new MakeClassAnAnnotationClassFix(annotation);
|
||||
}
|
||||
|
||||
@@ -61,17 +61,17 @@ public class MakeOverriddenMemberOpenFix(declaration: KtDeclaration) : KotlinQui
|
||||
overriddenNonOverridableMembers.add(overriddenMember)
|
||||
containingDeclarationsNames.add(containingDeclarationName)
|
||||
}
|
||||
return overriddenNonOverridableMembers.size() > 0
|
||||
return overriddenNonOverridableMembers.size > 0
|
||||
}
|
||||
|
||||
override fun getText(): String {
|
||||
if (overriddenNonOverridableMembers.size() == 1) {
|
||||
val name = containingDeclarationsNames.get(0) + "." + element.name
|
||||
if (overriddenNonOverridableMembers.size == 1) {
|
||||
val name = containingDeclarationsNames[0] + "." + element.name
|
||||
return "Make $name $OPEN_KEYWORD"
|
||||
}
|
||||
|
||||
Collections.sort(containingDeclarationsNames)
|
||||
val declarations = containingDeclarationsNames.subList(0, containingDeclarationsNames.size()-1).joinToString(", ") + " and " +
|
||||
val declarations = containingDeclarationsNames.subList(0, containingDeclarationsNames.size - 1).joinToString(", ") + " and " +
|
||||
containingDeclarationsNames.last()
|
||||
return "Make '${element.name}' in $declarations open"
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ import org.jetbrains.kotlin.psi.KtPrimaryConstructor
|
||||
import org.jetbrains.kotlin.idea.quickfix.quickfixUtil.addConstructorKeyword
|
||||
|
||||
public class MissingConstructorKeywordFix(element: KtPrimaryConstructor) : KotlinQuickFixAction<KtPrimaryConstructor>(element), CleanupFix {
|
||||
override fun getFamilyName(): String = getText()
|
||||
override fun getFamilyName(): String = text
|
||||
override fun getText(): String = "Add 'constructor' keyword"
|
||||
|
||||
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
|
||||
@@ -40,7 +40,7 @@ public class MissingConstructorKeywordFix(element: KtPrimaryConstructor) : Kotli
|
||||
|
||||
public fun createWholeProjectFixFactory(): KotlinSingleIntentionActionFactory = createIntentionFactory {
|
||||
WholeProjectForEachElementOfTypeFix.createByPredicate<KtPrimaryConstructor>(
|
||||
predicate = { it.getModifierList() != null && !it.hasConstructorKeyword() },
|
||||
predicate = { it.modifierList != null && !it.hasConstructorKeyword() },
|
||||
taskProcessor = { it.addConstructorKeyword() },
|
||||
name = "Add missing 'constructor' keyword in whole project"
|
||||
)
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
|
||||
package org.jetbrains.kotlin.idea.quickfix;
|
||||
|
||||
import com.intellij.codeInsight.CodeInsightUtilBase;
|
||||
import com.intellij.codeInsight.CodeInsightUtilCore;
|
||||
import com.intellij.openapi.editor.Editor;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.psi.PsiElement;
|
||||
@@ -47,7 +47,7 @@ public class MoveWhenElseBranchFix extends KotlinQuickFixAction<KtWhenExpression
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiFile file) {
|
||||
if (!super.isAvailable(project, editor, file)) {
|
||||
return false;
|
||||
}
|
||||
@@ -55,7 +55,7 @@ public class MoveWhenElseBranchFix extends KotlinQuickFixAction<KtWhenExpression
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, Editor editor, KtFile file) throws IncorrectOperationException {
|
||||
public void invoke(@NotNull Project project, Editor editor, @NotNull KtFile file) throws IncorrectOperationException {
|
||||
KtWhenEntry elseEntry = null;
|
||||
KtWhenEntry lastEntry = null;
|
||||
for (KtWhenEntry entry : getElement().getEntries()) {
|
||||
@@ -70,7 +70,7 @@ public class MoveWhenElseBranchFix extends KotlinQuickFixAction<KtWhenExpression
|
||||
PsiElement insertedBranch = getElement().addAfter(elseEntry, lastEntry);
|
||||
getElement().addAfter(KtPsiFactoryKt.KtPsiFactory(file).createNewLine(), lastEntry);
|
||||
getElement().deleteChildRange(elseEntry, elseEntry);
|
||||
KtWhenEntry insertedWhenEntry = (KtWhenEntry) CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(insertedBranch);
|
||||
KtWhenEntry insertedWhenEntry = (KtWhenEntry) CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(insertedBranch);
|
||||
|
||||
editor.getCaretModel().moveToOffset(insertedWhenEntry.getTextOffset() + cursorOffset);
|
||||
}
|
||||
@@ -79,7 +79,7 @@ public class MoveWhenElseBranchFix extends KotlinQuickFixAction<KtWhenExpression
|
||||
return new KotlinSingleIntentionActionFactory() {
|
||||
@Nullable
|
||||
@Override
|
||||
public KotlinQuickFixAction createAction(Diagnostic diagnostic) {
|
||||
public KotlinQuickFixAction createAction(@NotNull Diagnostic diagnostic) {
|
||||
PsiElement element = diagnostic.getPsiElement();
|
||||
KtWhenExpression whenExpression = PsiTreeUtil.getParentOfType(element, KtWhenExpression.class, false);
|
||||
if (whenExpression == null) return null;
|
||||
|
||||
+6
-4
@@ -110,7 +110,7 @@ public class QuickFixFactoryForTypeMismatchError extends KotlinIntentionActionsF
|
||||
KtPropertyAccessor getter = property.getGetter();
|
||||
KtExpression initializer = property.getInitializer();
|
||||
if (QuickFixUtil.canEvaluateTo(initializer, expression) ||
|
||||
(getter != null && QuickFixUtil.canFunctionOrGetterReturnExpression(property.getGetter(), expression))) {
|
||||
(getter != null && QuickFixUtil.canFunctionOrGetterReturnExpression(getter, expression))) {
|
||||
LexicalScope scope = ScopeUtils.getResolutionScope(property, context, ResolutionUtils.getResolutionFacade(property));
|
||||
KotlinType typeToInsert = TypeUtils.approximateWithResolvableType(expressionType, scope, false);
|
||||
actions.add(new ChangeVariableTypeFix(property, typeToInsert));
|
||||
@@ -161,9 +161,11 @@ public class QuickFixFactoryForTypeMismatchError extends KotlinIntentionActionsF
|
||||
ValueArgument valueArgument = CallUtilKt.getValueArgumentForExpression(resolvedCall.getCall(), argumentExpression);
|
||||
if (valueArgument != null) {
|
||||
KtParameter correspondingParameter = QuickFixUtil.getParameterDeclarationForValueArgument(resolvedCall, valueArgument);
|
||||
KotlinType valueArgumentType = diagnostic.getFactory() == Errors.NULL_FOR_NONNULL_TYPE
|
||||
? expressionType
|
||||
: context.getType(valueArgument.getArgumentExpression());
|
||||
KtExpression expressionFromArgument = valueArgument.getArgumentExpression();
|
||||
KotlinType valueArgumentType =
|
||||
diagnostic.getFactory() == Errors.NULL_FOR_NONNULL_TYPE
|
||||
? expressionType
|
||||
: expressionFromArgument != null ? context.getType(expressionFromArgument) : null;
|
||||
if (correspondingParameter != null && valueArgumentType != null) {
|
||||
KtCallableDeclaration callable = PsiTreeUtil.getParentOfType(correspondingParameter, KtCallableDeclaration.class, true);
|
||||
LexicalScope scope = callable != null ? ScopeUtils.getResolutionScope(callable, context, ResolutionUtils
|
||||
|
||||
@@ -70,7 +70,7 @@ public class QuickFixRegistrar : QuickFixContributor {
|
||||
MUST_BE_INITIALIZED_OR_BE_ABSTRACT.registerFactory(InitializePropertyQuickFixFactory)
|
||||
MUST_BE_INITIALIZED.registerFactory(InitializePropertyQuickFixFactory)
|
||||
|
||||
val addAbstractToClassFactory = AddModifierFix.createFactory(ABSTRACT_KEYWORD, javaClass<KtClass>())
|
||||
val addAbstractToClassFactory = AddModifierFix.createFactory(ABSTRACT_KEYWORD, KtClass::class.java)
|
||||
ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS.registerFactory(removeAbstractModifierFactory, addAbstractToClassFactory)
|
||||
|
||||
ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS.registerFactory(removeAbstractModifierFactory, addAbstractToClassFactory)
|
||||
@@ -109,8 +109,8 @@ public class QuickFixRegistrar : QuickFixContributor {
|
||||
VARIANCE_ON_TYPE_PARAMETER_OF_FUNCTION_OR_PROPERTY.registerFactory(RemoveModifierFix.createRemoveVarianceFactory())
|
||||
|
||||
val removeOpenModifierFactory = RemoveModifierFix.createRemoveModifierFromListOwnerFactory(OPEN_KEYWORD)
|
||||
NON_FINAL_MEMBER_IN_FINAL_CLASS.registerFactory(AddModifierFix.createFactory(OPEN_KEYWORD, javaClass<KtClass>()),
|
||||
removeOpenModifierFactory)
|
||||
NON_FINAL_MEMBER_IN_FINAL_CLASS.registerFactory(AddModifierFix.createFactory(OPEN_KEYWORD, KtClass::class.java),
|
||||
removeOpenModifierFactory)
|
||||
|
||||
val removeModifierFactory = RemoveModifierFix.createRemoveModifierFactory()
|
||||
GETTER_VISIBILITY_DIFFERS_FROM_PROPERTY_VISIBILITY.registerFactory(removeModifierFactory)
|
||||
@@ -195,7 +195,7 @@ public class QuickFixRegistrar : QuickFixContributor {
|
||||
UNCHECKED_CAST.registerFactory(changeToStarProjectionFactory)
|
||||
CANNOT_CHECK_FOR_ERASED.registerFactory(changeToStarProjectionFactory)
|
||||
|
||||
INACCESSIBLE_OUTER_CLASS_EXPRESSION.registerFactory(AddModifierFix.createFactory(INNER_KEYWORD, javaClass<KtClass>()))
|
||||
INACCESSIBLE_OUTER_CLASS_EXPRESSION.registerFactory(AddModifierFix.createFactory(INNER_KEYWORD, KtClass::class.java))
|
||||
|
||||
FINAL_SUPERTYPE.registerFactory(AddModifierFix.MakeClassOpenFactory)
|
||||
FINAL_UPPER_BOUND.registerFactory(AddModifierFix.MakeClassOpenFactory)
|
||||
|
||||
@@ -52,12 +52,12 @@ public class RemoveFunctionBodyFix extends KotlinQuickFixAction<KtFunction> {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiFile file) {
|
||||
return super.isAvailable(project, editor, file) && getElement().hasBody();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, Editor editor, KtFile file) throws IncorrectOperationException {
|
||||
public void invoke(@NotNull Project project, Editor editor, @NotNull KtFile file) throws IncorrectOperationException {
|
||||
KtFunction function = (KtFunction) getElement().copy();
|
||||
assert function instanceof ASTDelegatePsiElement;
|
||||
ASTDelegatePsiElement functionElementWithAst = (ASTDelegatePsiElement) function;
|
||||
@@ -91,7 +91,7 @@ public class RemoveFunctionBodyFix extends KotlinQuickFixAction<KtFunction> {
|
||||
public static KotlinSingleIntentionActionFactory createFactory() {
|
||||
return new KotlinSingleIntentionActionFactory() {
|
||||
@Override
|
||||
public KotlinQuickFixAction<KtFunction> createAction(Diagnostic diagnostic) {
|
||||
public KotlinQuickFixAction<KtFunction> createAction(@NotNull Diagnostic diagnostic) {
|
||||
KtFunction function = QuickFixUtil.getParentElementOfType(diagnostic, KtFunction.class);
|
||||
if (function == null) return null;
|
||||
return new RemoveFunctionBodyFix(function);
|
||||
|
||||
@@ -70,7 +70,7 @@ public class RemoveModifierFix(
|
||||
public fun createRemoveModifierFromListOwnerFactory(modifier: KtModifierKeywordToken, isRedundant: Boolean = false): KotlinSingleIntentionActionFactory {
|
||||
return object : KotlinSingleIntentionActionFactory() {
|
||||
override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtModifierListOwner>? {
|
||||
val modifierListOwner = QuickFixUtil.getParentElementOfType(diagnostic, javaClass<KtModifierListOwner>()) ?: return null
|
||||
val modifierListOwner = QuickFixUtil.getParentElementOfType(diagnostic, KtModifierListOwner::class.java) ?: return null
|
||||
return RemoveModifierFix(modifierListOwner, modifier, isRedundant)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ import org.jetbrains.kotlin.resolve.BindingContext
|
||||
|
||||
public class RemoveNameFromFunctionExpressionFix(element: KtNamedFunction) : KotlinQuickFixAction<KtNamedFunction>(element), CleanupFix {
|
||||
override fun getText(): String = "Remove identifier from anonymous function"
|
||||
override fun getFamilyName(): String = getText()
|
||||
override fun getFamilyName(): String = text
|
||||
|
||||
override fun invoke(project: Project, editor: Editor?, file: KtFile) = removeNameFromFunction(element)
|
||||
|
||||
@@ -38,7 +38,7 @@ public class RemoveNameFromFunctionExpressionFix(element: KtNamedFunction) : Kot
|
||||
|
||||
private fun removeNameFromFunction(function: KtNamedFunction) {
|
||||
var wereAutoLabelUsages = false
|
||||
val name = function.getNameAsName() ?: return
|
||||
val name = function.nameAsName ?: return
|
||||
|
||||
function.forEachDescendantOfType<KtReturnExpression> {
|
||||
if (!wereAutoLabelUsages && it.getLabelNameAsName() == name) {
|
||||
@@ -46,7 +46,7 @@ public class RemoveNameFromFunctionExpressionFix(element: KtNamedFunction) : Kot
|
||||
}
|
||||
}
|
||||
|
||||
function.getNameIdentifier()?.delete()
|
||||
function.nameIdentifier?.delete()
|
||||
|
||||
if (wereAutoLabelUsages) {
|
||||
val psiFactory = KtPsiFactory(function)
|
||||
|
||||
@@ -58,7 +58,7 @@ public class RemoveNullableFix extends KotlinQuickFixAction<KtNullableType> {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, Editor editor, KtFile file) throws IncorrectOperationException {
|
||||
public void invoke(@NotNull Project project, Editor editor, @NotNull KtFile file) throws IncorrectOperationException {
|
||||
KtTypeElement type = super.getElement().getInnerType();
|
||||
assert type != null : "No inner type " + getElement().getText() + ", should have been rejected in createFactory()";
|
||||
super.getElement().replace(type);
|
||||
@@ -67,7 +67,7 @@ public class RemoveNullableFix extends KotlinQuickFixAction<KtNullableType> {
|
||||
public static KotlinSingleIntentionActionFactory createFactory(final NullableKind typeOfError) {
|
||||
return new KotlinSingleIntentionActionFactory() {
|
||||
@Override
|
||||
public KotlinQuickFixAction<KtNullableType> createAction(Diagnostic diagnostic) {
|
||||
public KotlinQuickFixAction<KtNullableType> createAction(@NotNull Diagnostic diagnostic) {
|
||||
KtNullableType nullType = QuickFixUtil.getParentElementOfType(diagnostic, KtNullableType.class);
|
||||
if (nullType == null || nullType.getInnerType() == null) return null;
|
||||
return new RemoveNullableFix(nullType, typeOfError);
|
||||
|
||||
@@ -84,13 +84,13 @@ public class RemovePartsFromPropertyFix extends KotlinQuickFixAction<KtProperty>
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiFile file) {
|
||||
KotlinType type = QuickFixUtil.getDeclarationReturnType(getElement());
|
||||
return super.isAvailable(project, editor, file) && type != null && !type.isError();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, Editor editor, KtFile file) throws IncorrectOperationException {
|
||||
public void invoke(@NotNull Project project, Editor editor, @NotNull KtFile file) throws IncorrectOperationException {
|
||||
KotlinType type = QuickFixUtil.getDeclarationReturnType(getElement());
|
||||
KtProperty newElement = (KtProperty) getElement().copy();
|
||||
KtPropertyAccessor getter = newElement.getGetter();
|
||||
@@ -123,7 +123,7 @@ public class RemovePartsFromPropertyFix extends KotlinQuickFixAction<KtProperty>
|
||||
public static KotlinSingleIntentionActionFactory createFactory() {
|
||||
return new KotlinSingleIntentionActionFactory() {
|
||||
@Override
|
||||
public KotlinQuickFixAction<KtProperty> createAction(Diagnostic diagnostic) {
|
||||
public KotlinQuickFixAction<KtProperty> createAction(@NotNull Diagnostic diagnostic) {
|
||||
PsiElement element = diagnostic.getPsiElement();
|
||||
assert element instanceof KtElement;
|
||||
KtProperty property = PsiTreeUtil.getParentOfType(element, KtProperty.class);
|
||||
|
||||
@@ -53,14 +53,14 @@ public class RemovePsiElementSimpleFix extends KotlinQuickFixAction<PsiElement>
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, Editor editor, KtFile file) throws IncorrectOperationException {
|
||||
public void invoke(@NotNull Project project, Editor editor, @NotNull KtFile file) throws IncorrectOperationException {
|
||||
element.delete();
|
||||
}
|
||||
|
||||
public static KotlinSingleIntentionActionFactory createRemoveImportFactory() {
|
||||
return new KotlinSingleIntentionActionFactory() {
|
||||
@Override
|
||||
public KotlinQuickFixAction<PsiElement> createAction(Diagnostic diagnostic) {
|
||||
public KotlinQuickFixAction<PsiElement> createAction(@NotNull Diagnostic diagnostic) {
|
||||
KtImportDirective directive = QuickFixUtil.getParentElementOfType(diagnostic, KtImportDirective.class);
|
||||
if (directive == null) return null;
|
||||
else {
|
||||
@@ -79,7 +79,7 @@ public class RemovePsiElementSimpleFix extends KotlinQuickFixAction<PsiElement>
|
||||
public static KotlinSingleIntentionActionFactory createRemoveSpreadFactory() {
|
||||
return new KotlinSingleIntentionActionFactory() {
|
||||
@Override
|
||||
public KotlinQuickFixAction<PsiElement> createAction(Diagnostic diagnostic) {
|
||||
public KotlinQuickFixAction<PsiElement> createAction(@NotNull Diagnostic diagnostic) {
|
||||
PsiElement element = diagnostic.getPsiElement();
|
||||
if ((element instanceof LeafPsiElement) && ((LeafPsiElement) element).getElementType() == KtTokens.MUL) {
|
||||
return new RemovePsiElementSimpleFix(element, KotlinBundle.message("remove.spread.sign"));
|
||||
@@ -92,7 +92,7 @@ public class RemovePsiElementSimpleFix extends KotlinQuickFixAction<PsiElement>
|
||||
public static KotlinSingleIntentionActionFactory createRemoveTypeArgumentsFactory() {
|
||||
return new KotlinSingleIntentionActionFactory() {
|
||||
@Override
|
||||
public KotlinQuickFixAction<PsiElement> createAction(Diagnostic diagnostic) {
|
||||
public KotlinQuickFixAction<PsiElement> createAction(@NotNull Diagnostic diagnostic) {
|
||||
KtTypeArgumentList element = QuickFixUtil.getParentElementOfType(diagnostic, KtTypeArgumentList.class);
|
||||
if (element == null) return null;
|
||||
return new RemovePsiElementSimpleFix(element,
|
||||
@@ -104,13 +104,13 @@ public class RemovePsiElementSimpleFix extends KotlinQuickFixAction<PsiElement>
|
||||
public static KotlinSingleIntentionActionFactory createRemoveVariableFactory() {
|
||||
return new KotlinSingleIntentionActionFactory() {
|
||||
@Override
|
||||
public KotlinQuickFixAction<PsiElement> createAction(Diagnostic diagnostic) {
|
||||
public KotlinQuickFixAction<PsiElement> createAction(@NotNull Diagnostic diagnostic) {
|
||||
final KtProperty expression = QuickFixUtil.getParentElementOfType(diagnostic, KtProperty.class);
|
||||
if (expression == null) return null;
|
||||
return new RemovePsiElementSimpleFix(expression,
|
||||
KotlinBundle.message("remove.variable.action", (expression.getName()))) {
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, Editor editor, KtFile file) throws IncorrectOperationException {
|
||||
public void invoke(@NotNull Project project, Editor editor, @NotNull KtFile file) throws IncorrectOperationException {
|
||||
KtExpression initializer = expression.getInitializer();
|
||||
if (initializer != null) {
|
||||
expression.replace(initializer);
|
||||
|
||||
+9
-3
@@ -25,6 +25,7 @@ import org.jetbrains.kotlin.diagnostics.Diagnostic;
|
||||
import org.jetbrains.kotlin.idea.KotlinBundle;
|
||||
import org.jetbrains.kotlin.idea.core.quickfix.QuickFixUtil;
|
||||
import org.jetbrains.kotlin.psi.*;
|
||||
import org.jetbrains.kotlin.psi.psiUtil.PsiUtilsKt;
|
||||
|
||||
public class RemoveRightPartOfBinaryExpressionFix<T extends KtExpression> extends KotlinQuickFixAction<T> implements CleanupFix {
|
||||
private final String message;
|
||||
@@ -34,6 +35,7 @@ public class RemoveRightPartOfBinaryExpressionFix<T extends KtExpression> extend
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public String getText() {
|
||||
return message;
|
||||
@@ -46,7 +48,7 @@ public class RemoveRightPartOfBinaryExpressionFix<T extends KtExpression> extend
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, Editor editor, KtFile file) throws IncorrectOperationException {
|
||||
public void invoke(@NotNull Project project, Editor editor, @NotNull KtFile file) throws IncorrectOperationException {
|
||||
invoke();
|
||||
}
|
||||
|
||||
@@ -67,13 +69,17 @@ public class RemoveRightPartOfBinaryExpressionFix<T extends KtExpression> extend
|
||||
newExpression = (KtExpression) parent.replace(newExpression);
|
||||
}
|
||||
|
||||
if (newExpression == null) {
|
||||
throw new IncorrectOperationException("Unexpected element: " + PsiUtilsKt.getElementTextWithContext(getElement()));
|
||||
}
|
||||
|
||||
return newExpression;
|
||||
}
|
||||
|
||||
public static KotlinSingleIntentionActionFactory createRemoveTypeFromBinaryExpressionFactory(final String message) {
|
||||
return new KotlinSingleIntentionActionFactory() {
|
||||
@Override
|
||||
public KotlinQuickFixAction<KtBinaryExpressionWithTypeRHS> createAction(Diagnostic diagnostic) {
|
||||
public KotlinQuickFixAction<KtBinaryExpressionWithTypeRHS> createAction(@NotNull Diagnostic diagnostic) {
|
||||
KtBinaryExpressionWithTypeRHS expression = QuickFixUtil.getParentElementOfType(diagnostic, KtBinaryExpressionWithTypeRHS.class);
|
||||
if (expression == null) return null;
|
||||
return new RemoveRightPartOfBinaryExpressionFix<KtBinaryExpressionWithTypeRHS>(expression, message);
|
||||
@@ -84,7 +90,7 @@ public class RemoveRightPartOfBinaryExpressionFix<T extends KtExpression> extend
|
||||
public static KotlinSingleIntentionActionFactory createRemoveElvisOperatorFactory() {
|
||||
return new KotlinSingleIntentionActionFactory() {
|
||||
@Override
|
||||
public KotlinQuickFixAction<KtBinaryExpression> createAction(Diagnostic diagnostic) {
|
||||
public KotlinQuickFixAction<KtBinaryExpression> createAction(@NotNull Diagnostic diagnostic) {
|
||||
KtBinaryExpression expression = (KtBinaryExpression) diagnostic.getPsiElement();
|
||||
return new RemoveRightPartOfBinaryExpressionFix<KtBinaryExpression>(expression, KotlinBundle.message("remove.elvis.operator"));
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ public class RemoveSupertypeFix extends KotlinQuickFixAction<KtSuperTypeListEntr
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, Editor editor, KtFile file) throws IncorrectOperationException {
|
||||
public void invoke(@NotNull Project project, Editor editor, @NotNull KtFile file) throws IncorrectOperationException {
|
||||
// Find the preceding comma and delete it as well.
|
||||
// We must ignore whitespaces and comments when looking for the comma.
|
||||
PsiElement prevSibling = superClass.getPrevSibling();
|
||||
@@ -67,7 +67,7 @@ public class RemoveSupertypeFix extends KotlinQuickFixAction<KtSuperTypeListEntr
|
||||
public static KotlinSingleIntentionActionFactory createFactory() {
|
||||
return new KotlinSingleIntentionActionFactory() {
|
||||
@Override
|
||||
public KotlinQuickFixAction<KtSuperTypeListEntry> createAction(Diagnostic diagnostic) {
|
||||
public KotlinQuickFixAction<KtSuperTypeListEntry> createAction(@NotNull Diagnostic diagnostic) {
|
||||
KtSuperTypeListEntry superClass = QuickFixUtil.getParentElementOfType(diagnostic, KtSuperTypeListEntry.class);
|
||||
if (superClass == null) return null;
|
||||
return new RemoveSupertypeFix(superClass);
|
||||
|
||||
@@ -52,7 +52,7 @@ public class RemoveValVarFromParameterFix extends KotlinQuickFixAction<KtValVarK
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void invoke(@NotNull Project project, Editor editor, KtFile file) throws IncorrectOperationException {
|
||||
protected void invoke(@NotNull Project project, Editor editor, @NotNull KtFile file) throws IncorrectOperationException {
|
||||
PsiElement keyword = getElement().getValOrVarKeyword();
|
||||
if (keyword == null) return;
|
||||
keyword.delete();
|
||||
|
||||
+3
-3
@@ -44,7 +44,7 @@ public class RenameParameterToMatchOverriddenMethodFix extends KotlinQuickFixAct
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
|
||||
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiFile file) {
|
||||
if (!super.isAvailable(project, editor, file)) {
|
||||
return false;
|
||||
}
|
||||
@@ -79,7 +79,7 @@ public class RenameParameterToMatchOverriddenMethodFix extends KotlinQuickFixAct
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, Editor editor, KtFile file) throws IncorrectOperationException {
|
||||
public void invoke(@NotNull Project project, Editor editor, @NotNull KtFile file) throws IncorrectOperationException {
|
||||
new RenameProcessor(project, parameter, parameterFromSuperclassName, false, false).run();
|
||||
}
|
||||
|
||||
@@ -88,7 +88,7 @@ public class RenameParameterToMatchOverriddenMethodFix extends KotlinQuickFixAct
|
||||
return new KotlinSingleIntentionActionFactory() {
|
||||
@Nullable
|
||||
@Override
|
||||
public IntentionAction createAction(Diagnostic diagnostic) {
|
||||
public IntentionAction createAction(@NotNull Diagnostic diagnostic) {
|
||||
KtParameter parameter = QuickFixUtil.getParentElementOfType(diagnostic, KtParameter.class);
|
||||
return parameter == null ? null : new RenameParameterToMatchOverriddenMethodFix(parameter);
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ class RenameUnderscoreFix(declaration: KtDeclaration) : KotlinQuickFixAction<KtD
|
||||
}
|
||||
|
||||
override fun getText(): String = "Rename"
|
||||
override fun getFamilyName(): String = getText()
|
||||
override fun getFamilyName(): String = text
|
||||
|
||||
companion object : KotlinSingleIntentionActionFactory() {
|
||||
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
|
||||
|
||||
@@ -28,7 +28,7 @@ import org.jetbrains.kotlin.psi.*
|
||||
|
||||
public abstract class ReplaceCallFix protected constructor(val psiElement: PsiElement) : IntentionAction {
|
||||
|
||||
override fun getFamilyName(): String = getText()
|
||||
override fun getFamilyName(): String = text
|
||||
|
||||
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile): Boolean {
|
||||
if (file is KtFile) {
|
||||
@@ -40,10 +40,10 @@ public abstract class ReplaceCallFix protected constructor(val psiElement: PsiEl
|
||||
override fun invoke(project: Project, editor: Editor?, file: PsiFile) {
|
||||
val callExpression = getCallExpression() ?: return
|
||||
|
||||
val selector = callExpression.getSelectorExpression()
|
||||
val selector = callExpression.selectorExpression
|
||||
if (selector != null) {
|
||||
val newElement = KtPsiFactory(callExpression).createExpression(
|
||||
callExpression.getReceiverExpression().getText() + operation + selector.getText()) as KtQualifiedExpression
|
||||
callExpression.receiverExpression.text + operation + selector.text) as KtQualifiedExpression
|
||||
|
||||
callExpression.replace(newElement)
|
||||
}
|
||||
@@ -62,21 +62,21 @@ public abstract class ReplaceCallFix protected constructor(val psiElement: PsiEl
|
||||
public class ReplaceWithSafeCallFix(psiElement: PsiElement): ReplaceCallFix(psiElement) {
|
||||
override fun getText(): String = "Replace with safe (?.) call"
|
||||
override val operation: String get() = "?."
|
||||
override val classToReplace: Class<out KtQualifiedExpression> get() = javaClass<KtDotQualifiedExpression>()
|
||||
override val classToReplace: Class<out KtQualifiedExpression> get() = KtDotQualifiedExpression::class.java
|
||||
|
||||
companion object : KotlinSingleIntentionActionFactory() {
|
||||
override fun createAction(diagnostic: Diagnostic): IntentionAction
|
||||
= ReplaceWithSafeCallFix(diagnostic.getPsiElement())
|
||||
= ReplaceWithSafeCallFix(diagnostic.psiElement)
|
||||
}
|
||||
}
|
||||
|
||||
public class ReplaceWithDotCallFix(psiElement: PsiElement): ReplaceCallFix(psiElement), CleanupFix {
|
||||
override fun getText(): String = KotlinBundle.message("replace.with.dot.call")
|
||||
override val operation: String get() = "."
|
||||
override val classToReplace: Class<out KtQualifiedExpression> get() = javaClass<KtSafeQualifiedExpression>()
|
||||
override val classToReplace: Class<out KtQualifiedExpression> get() = KtSafeQualifiedExpression::class.java
|
||||
|
||||
companion object : KotlinSingleIntentionActionFactory() {
|
||||
override fun createAction(diagnostic: Diagnostic): IntentionAction
|
||||
= ReplaceWithDotCallFix(diagnostic.getPsiElement())
|
||||
= ReplaceWithDotCallFix(diagnostic.psiElement)
|
||||
}
|
||||
}
|
||||
|
||||
+3
-4
@@ -16,7 +16,6 @@
|
||||
|
||||
package org.jetbrains.kotlin.idea.quickfix
|
||||
|
||||
import com.intellij.codeInsight.intention.IntentionAction
|
||||
import com.intellij.openapi.editor.Editor
|
||||
import com.intellij.openapi.project.Project
|
||||
import org.jetbrains.kotlin.diagnostics.Diagnostic
|
||||
@@ -32,7 +31,7 @@ import org.jetbrains.kotlin.resolve.calls.model.ExpressionValueArgument
|
||||
public class ReplaceJavaAnnotationPositionedArgumentsFix(element: KtAnnotationEntry)
|
||||
: KotlinQuickFixAction<KtAnnotationEntry>(element), CleanupFix {
|
||||
override fun getText(): String = "Replace invalid positioned arguments for annotation"
|
||||
override fun getFamilyName(): String = getText()
|
||||
override fun getFamilyName(): String = text
|
||||
|
||||
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
|
||||
val resolvedCall = element.getResolvedCall(element.analyze()) ?: return
|
||||
@@ -40,10 +39,10 @@ public class ReplaceJavaAnnotationPositionedArgumentsFix(element: KtAnnotationEn
|
||||
|
||||
getJavaAnnotationCallValueArgumentsThatShouldBeNamed(resolvedCall).forEach argumentProcessor@{
|
||||
argument ->
|
||||
val valueArgument = (argument.value as? ExpressionValueArgument)?.getValueArgument() ?: return@argumentProcessor
|
||||
val valueArgument = (argument.value as? ExpressionValueArgument)?.valueArgument ?: return@argumentProcessor
|
||||
val expression = valueArgument.getArgumentExpression() ?: return@argumentProcessor
|
||||
|
||||
valueArgument.asElement().replace(psiFactory.createArgument(expression, argument.getKey().getName()))
|
||||
valueArgument.asElement().replace(psiFactory.createArgument(expression, argument.key.name))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -31,13 +31,13 @@ import org.jetbrains.kotlin.resolve.BindingContext
|
||||
|
||||
public class ReplaceObsoleteLabelSyntaxFix(element: KtAnnotationEntry) : KotlinQuickFixAction<KtAnnotationEntry>(element), CleanupFix {
|
||||
override fun getFamilyName(): String = "Update obsolete label syntax"
|
||||
override fun getText(): String = "Replace with label ${element.getCalleeExpression()?.getText() ?: ""}@"
|
||||
override fun getText(): String = "Replace with label ${element.calleeExpression?.text ?: ""}@"
|
||||
|
||||
override fun invoke(project: Project, editor: Editor?, file: KtFile) = replaceWithLabel(element)
|
||||
|
||||
companion object : KotlinSingleIntentionActionFactory() {
|
||||
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
|
||||
val annotationEntry = diagnostic.getPsiElement().getNonStrictParentOfType<KtAnnotationEntry>() ?: return null
|
||||
val annotationEntry = diagnostic.psiElement.getNonStrictParentOfType<KtAnnotationEntry>() ?: return null
|
||||
|
||||
if (!looksLikeObsoleteLabel(annotationEntry)) return null
|
||||
|
||||
@@ -47,7 +47,7 @@ public class ReplaceObsoleteLabelSyntaxFix(element: KtAnnotationEntry) : KotlinQ
|
||||
public fun createWholeProjectFixFactory(): KotlinSingleIntentionActionFactory = createIntentionFactory factory@ {
|
||||
diagnostic ->
|
||||
|
||||
if (!(diagnostic.getPsiElement().getNonStrictParentOfType<KtAnnotationEntry>()?.looksLikeObsoleteLabelWithReferencesInCode()
|
||||
if (!(diagnostic.psiElement.getNonStrictParentOfType<KtAnnotationEntry>()?.looksLikeObsoleteLabelWithReferencesInCode()
|
||||
?: false)) return@factory null
|
||||
|
||||
WholeProjectForEachElementOfTypeFix.createForMultiTaskOnElement<KtAnnotatedExpression, KtAnnotationEntry>(
|
||||
@@ -58,41 +58,41 @@ public class ReplaceObsoleteLabelSyntaxFix(element: KtAnnotationEntry) : KotlinQ
|
||||
}
|
||||
|
||||
private fun collectTasks(expression: KtAnnotatedExpression) =
|
||||
expression.getAnnotationEntries().filter { it.looksLikeObsoleteLabelWithReferencesInCode() }
|
||||
expression.annotationEntries.filter { it.looksLikeObsoleteLabelWithReferencesInCode() }
|
||||
|
||||
private fun KtAnnotationEntry.looksLikeObsoleteLabelWithReferencesInCode(): Boolean {
|
||||
if (!looksLikeObsoleteLabel(this)) return false
|
||||
|
||||
val baseExpression = (getParent() as? KtAnnotatedExpression)?.getBaseExpression() ?: return false
|
||||
val baseExpression = (parent as? KtAnnotatedExpression)?.baseExpression ?: return false
|
||||
|
||||
val nameExpression = getCalleeExpression()?.getConstructorReferenceExpression() ?: return false
|
||||
val nameExpression = calleeExpression?.constructorReferenceExpression ?: return false
|
||||
val labelName = nameExpression.getReferencedName()
|
||||
|
||||
return baseExpression.anyDescendantOfType<KtExpressionWithLabel> {
|
||||
(it is KtBreakExpression || it is KtContinueExpression || it is KtReturnExpression) &&
|
||||
it.getLabelName() == labelName &&
|
||||
it.getTargetLabel()?.analyze()?.get(BindingContext.LABEL_TARGET, it.getTargetLabel()) == null
|
||||
} && analyze().getDiagnostics().forElement(nameExpression).any { it.getFactory() == Errors.UNRESOLVED_REFERENCE }
|
||||
} && analyze().diagnostics.forElement(nameExpression).any { it.factory == Errors.UNRESOLVED_REFERENCE }
|
||||
}
|
||||
|
||||
public fun looksLikeObsoleteLabel(entry: KtAnnotationEntry): Boolean =
|
||||
entry.getAtSymbol() != null &&
|
||||
entry.getParent() is KtAnnotatedExpression &&
|
||||
(entry.getParent() as KtAnnotatedExpression).getAnnotationEntries().size() == 1 &&
|
||||
entry.getValueArgumentList() == null &&
|
||||
entry.getCalleeExpression()?.getConstructorReferenceExpression()?.getIdentifier() != null
|
||||
entry.atSymbol != null &&
|
||||
entry.parent is KtAnnotatedExpression &&
|
||||
(entry.parent as KtAnnotatedExpression).annotationEntries.size == 1 &&
|
||||
entry.valueArgumentList == null &&
|
||||
entry.calleeExpression?.constructorReferenceExpression?.getIdentifier() != null
|
||||
|
||||
private fun replaceWithLabel(annotation: KtAnnotationEntry) {
|
||||
val labelName = annotation.getCalleeExpression()?.getConstructorReferenceExpression()?.getReferencedName() ?: return
|
||||
val annotatedExpression = annotation.getParent() as? KtAnnotatedExpression ?: return
|
||||
val expression = annotatedExpression.getBaseExpression() ?: return
|
||||
val labelName = annotation.calleeExpression?.constructorReferenceExpression?.getReferencedName() ?: return
|
||||
val annotatedExpression = annotation.parent as? KtAnnotatedExpression ?: return
|
||||
val expression = annotatedExpression.baseExpression ?: return
|
||||
|
||||
if (annotatedExpression.getAnnotationEntries().size() != 1) return
|
||||
if (annotatedExpression.annotationEntries.size != 1) return
|
||||
|
||||
val baseExpressionStart = expression.getTextRange().getStartOffset()
|
||||
val baseExpressionStart = expression.textRange.startOffset
|
||||
|
||||
val textRangeToRetain = TextRange(annotation.getTextRange().getEndOffset(), baseExpressionStart)
|
||||
val textToRetain = textRangeToRetain.substring(annotation.getContainingFile().getText())
|
||||
val textRangeToRetain = TextRange(annotation.textRange.endOffset, baseExpressionStart)
|
||||
val textToRetain = textRangeToRetain.substring(annotation.containingFile.text)
|
||||
|
||||
val labeledExpression = KtPsiFactory(annotation).createExpressionByPattern("$0@$1$2", labelName, textToRetain, expression)
|
||||
|
||||
|
||||
-51
@@ -1,51 +0,0 @@
|
||||
/*
|
||||
* Copyright 2010-2015 JetBrains s.r.o.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.jetbrains.kotlin.idea.quickfix;
|
||||
|
||||
import com.intellij.openapi.editor.Editor;
|
||||
import com.intellij.openapi.project.Project;
|
||||
import com.intellij.util.IncorrectOperationException;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.kotlin.idea.KotlinBundle;
|
||||
import org.jetbrains.kotlin.psi.*;
|
||||
|
||||
public abstract class ReplaceOperationInBinaryExpressionFix<T extends KtExpression> extends KotlinQuickFixAction<T> {
|
||||
private final String operation;
|
||||
|
||||
public ReplaceOperationInBinaryExpressionFix(@NotNull T element, String operation) {
|
||||
super(element);
|
||||
this.operation = operation;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public String getFamilyName() {
|
||||
return KotlinBundle.message("replace.operation.in.binary.expression");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(@NotNull Project project, Editor editor, KtFile file) throws IncorrectOperationException {
|
||||
if (getElement() instanceof KtBinaryExpressionWithTypeRHS) {
|
||||
KtExpression left = ((KtBinaryExpressionWithTypeRHS) getElement()).getLeft();
|
||||
KtTypeReference right = ((KtBinaryExpressionWithTypeRHS) getElement()).getRight();
|
||||
if (right != null) {
|
||||
KtExpression expression = KtPsiFactoryKt.KtPsiFactory(file).createExpression(left.getText() + operation + right.getText());
|
||||
getElement().replace(expression);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,6 @@ import org.jetbrains.kotlin.idea.intentions.SpecifyTypeExplicitlyIntention
|
||||
import org.jetbrains.kotlin.psi.KtCallableDeclaration
|
||||
import org.jetbrains.kotlin.psi.KtNamedFunction
|
||||
import org.jetbrains.kotlin.psi.KtProperty
|
||||
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
|
||||
|
||||
public class SpecifyTypeExplicitlyFix : PsiElementBaseIntentionAction() {
|
||||
override fun getFamilyName() = "Specify type explicitly"
|
||||
@@ -39,19 +38,19 @@ public class SpecifyTypeExplicitlyFix : PsiElementBaseIntentionAction() {
|
||||
override fun isAvailable(project: Project, editor: Editor, element: PsiElement): Boolean {
|
||||
val declaration = declarationByElement(element)
|
||||
if (declaration is KtProperty) {
|
||||
setText("Specify type explicitly")
|
||||
text = "Specify type explicitly"
|
||||
}
|
||||
else if (declaration is KtNamedFunction) {
|
||||
setText("Specify return type explicitly")
|
||||
text = "Specify return type explicitly"
|
||||
}
|
||||
else {
|
||||
return false
|
||||
}
|
||||
|
||||
return !SpecifyTypeExplicitlyIntention.getTypeForDeclaration(declaration).isError()
|
||||
return !SpecifyTypeExplicitlyIntention.getTypeForDeclaration(declaration).isError
|
||||
}
|
||||
|
||||
private fun declarationByElement(element: PsiElement): KtCallableDeclaration? {
|
||||
return PsiTreeUtil.getParentOfType(element, javaClass<KtProperty>(), javaClass<KtNamedFunction>()) as KtCallableDeclaration?
|
||||
return PsiTreeUtil.getParentOfType(element, KtProperty::class.java, KtNamedFunction::class.java) as KtCallableDeclaration?
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,39 +49,39 @@ public object SuperClassNotInitialized : KotlinIntentionActionsFactory() {
|
||||
private val DISPLAY_MAX_PARAMS = 5
|
||||
|
||||
override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
|
||||
val delegator = diagnostic.getPsiElement() as KtSuperTypeEntry
|
||||
val classOrObjectDeclaration = delegator.getParent().getParent() as? KtClassOrObject ?: return emptyList()
|
||||
val delegator = diagnostic.psiElement as KtSuperTypeEntry
|
||||
val classOrObjectDeclaration = delegator.parent.parent as? KtClassOrObject ?: return emptyList()
|
||||
|
||||
val typeRef = delegator.getTypeReference() ?: return emptyList()
|
||||
val typeRef = delegator.typeReference ?: return emptyList()
|
||||
val type = typeRef.analyze()[BindingContext.TYPE, typeRef] ?: return emptyList()
|
||||
if (type.isError()) return emptyList()
|
||||
if (type.isError) return emptyList()
|
||||
|
||||
val superClass = (type.getConstructor().getDeclarationDescriptor() as? ClassDescriptor) ?: return emptyList()
|
||||
val superClass = (type.constructor.declarationDescriptor as? ClassDescriptor) ?: return emptyList()
|
||||
val classDescriptor = delegator.getResolutionFacade().resolveToDescriptor(classOrObjectDeclaration) as ClassDescriptor
|
||||
val constructors = superClass.getConstructors().filter { it.isVisible(classDescriptor) }
|
||||
val constructors = superClass.constructors.filter { it.isVisible(classDescriptor) }
|
||||
if (constructors.isEmpty()) return emptyList() // no accessible constructor
|
||||
|
||||
val fixes = ArrayList<IntentionAction>()
|
||||
|
||||
fixes.add(AddParenthesisFix(delegator, putCaretIntoParenthesis = constructors.singleOrNull()?.getValueParameters()?.isNotEmpty() ?: true))
|
||||
fixes.add(AddParenthesisFix(delegator, putCaretIntoParenthesis = constructors.singleOrNull()?.valueParameters?.isNotEmpty() ?: true))
|
||||
|
||||
if (classOrObjectDeclaration is KtClass) {
|
||||
val superType = classDescriptor.getTypeConstructor().getSupertypes().firstOrNull { it.getConstructor().getDeclarationDescriptor() == superClass }
|
||||
val superType = classDescriptor.typeConstructor.supertypes.firstOrNull { it.constructor.declarationDescriptor == superClass }
|
||||
if (superType != null) {
|
||||
val substitutor = TypeConstructorSubstitution.create(superClass.typeConstructor, superType.arguments).buildSubstitutor()
|
||||
|
||||
val substitutedConstructors = constructors
|
||||
.filter { it.getValueParameters().isNotEmpty() }
|
||||
.filter { it.valueParameters.isNotEmpty() }
|
||||
.map { it.substitute(substitutor) }
|
||||
|
||||
if (substitutedConstructors.isNotEmpty()) {
|
||||
val parameterTypes: List<List<KotlinType>> = substitutedConstructors.map {
|
||||
it.getValueParameters().map { it.getType() }
|
||||
it.valueParameters.map { it.type }
|
||||
}
|
||||
|
||||
fun canRenderOnlyFirstParameters(n: Int) = parameterTypes.map { it.take(n) }.toSet().size() == parameterTypes.size()
|
||||
fun canRenderOnlyFirstParameters(n: Int) = parameterTypes.map { it.take(n) }.toSet().size == parameterTypes.size
|
||||
|
||||
val maxParams = parameterTypes.map { it.size() }.max()!!
|
||||
val maxParams = parameterTypes.map { it.size }.max()!!
|
||||
val maxParamsToDisplay = if (maxParams <= DISPLAY_MAX_PARAMS) {
|
||||
maxParams
|
||||
}
|
||||
@@ -91,8 +91,8 @@ public object SuperClassNotInitialized : KotlinIntentionActionsFactory() {
|
||||
|
||||
for ((constructor, types) in substitutedConstructors.zip(parameterTypes)) {
|
||||
val typesRendered = types.take(maxParamsToDisplay).map { DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(it) }
|
||||
val parameterString = typesRendered.joinToString(", ", "(", if (types.size() <= maxParamsToDisplay) ")" else ",...)")
|
||||
val text = "Add constructor parameters from " + superClass.getName().asString() + parameterString
|
||||
val parameterString = typesRendered.joinToString(", ", "(", if (types.size <= maxParamsToDisplay) ")" else ",...)")
|
||||
val text = "Add constructor parameters from " + superClass.name.asString() + parameterString
|
||||
fixes.addIfNotNull(AddParametersFix.create(delegator, classOrObjectDeclaration, constructor, text))
|
||||
}
|
||||
}
|
||||
@@ -109,16 +109,16 @@ public object SuperClassNotInitialized : KotlinIntentionActionsFactory() {
|
||||
|
||||
override fun getFamilyName() = "Change to constructor invocation" //TODO?
|
||||
|
||||
override fun getText() = getFamilyName()
|
||||
override fun getText() = familyName
|
||||
|
||||
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
|
||||
val newSpecifier = element.replaced(KtPsiFactory(project).createSuperTypeCallEntry(element.getText() + "()"))
|
||||
val newSpecifier = element.replaced(KtPsiFactory(project).createSuperTypeCallEntry(element.text + "()"))
|
||||
|
||||
if (putCaretIntoParenthesis) {
|
||||
if (editor != null) {
|
||||
val offset = newSpecifier.getValueArgumentList()!!.getLeftParenthesis()!!.endOffset
|
||||
val offset = newSpecifier.valueArgumentList!!.leftParenthesis!!.endOffset
|
||||
editor.moveCaret(offset)
|
||||
if (!ApplicationManager.getApplication().isUnitTestMode()) {
|
||||
if (!ApplicationManager.getApplication().isUnitTestMode) {
|
||||
ShowParameterInfoHandler.invoke(project, editor, file, offset - 1, null)
|
||||
}
|
||||
}
|
||||
@@ -141,7 +141,7 @@ public object SuperClassNotInitialized : KotlinIntentionActionsFactory() {
|
||||
superConstructor: ConstructorDescriptor,
|
||||
text: String
|
||||
): AddParametersFix? {
|
||||
val superParameters = superConstructor.getValueParameters()
|
||||
val superParameters = superConstructor.valueParameters
|
||||
assert(superParameters.isNotEmpty())
|
||||
|
||||
if (superParameters.any { it.type.isError }) return null
|
||||
@@ -158,11 +158,11 @@ public object SuperClassNotInitialized : KotlinIntentionActionsFactory() {
|
||||
}
|
||||
argumentText.append(if (varargElementType != null) "*$nameRendered" else nameRendered)
|
||||
|
||||
val nameString = parameter.getName().asString()
|
||||
val existingParameter = oldParameters.firstOrNull { it.getName() == nameString }
|
||||
val nameString = parameter.name.asString()
|
||||
val existingParameter = oldParameters.firstOrNull { it.name == nameString }
|
||||
if (existingParameter != null) {
|
||||
val type = (existingParameter.resolveToDescriptor() as ValueParameterDescriptor).getType()
|
||||
if (type.isSubtypeOf(parameter.getType())) continue // use existing parameter
|
||||
val type = (existingParameter.resolveToDescriptor() as ValueParameterDescriptor).type
|
||||
if (type.isSubtypeOf(parameter.type)) continue // use existing parameter
|
||||
}
|
||||
|
||||
val parameterText = if (varargElementType != null)
|
||||
|
||||
@@ -38,7 +38,7 @@ import org.jetbrains.kotlin.utils.singletonOrEmptyList
|
||||
import java.util.*
|
||||
|
||||
public abstract class WholeProjectModalAction<TData : Any>(val title: String) : IntentionAction {
|
||||
private val LOG = Logger.getInstance(javaClass<WholeProjectModalAction<*>>());
|
||||
private val LOG = Logger.getInstance(WholeProjectModalAction::class.java);
|
||||
|
||||
override final fun startInWriteAction() = false
|
||||
|
||||
@@ -55,9 +55,9 @@ public abstract class WholeProjectModalAction<TData : Any>(val title: String) :
|
||||
val files = PluginJetFilesProvider.allFilesInProject(project)
|
||||
|
||||
for ((i, currentFile) in files.withIndex()) {
|
||||
indicator.setText("Checking file $i of ${files.size()}...")
|
||||
indicator.setText2(currentFile.getVirtualFile().getPath())
|
||||
indicator.setFraction((i + 1) / files.size().toDouble())
|
||||
indicator.text = "Checking file $i of ${files.size}..."
|
||||
indicator.text2 = currentFile.virtualFile.path
|
||||
indicator.fraction = (i + 1) / files.size.toDouble()
|
||||
try {
|
||||
val data = collectDataForFile(project, currentFile)
|
||||
if (data != null) filesToData[currentFile] = data
|
||||
@@ -76,11 +76,11 @@ public abstract class WholeProjectModalAction<TData : Any>(val title: String) :
|
||||
|
||||
private fun applyAll(project: Project, filesToData: Map<KtFile, TData>) {
|
||||
UIUtil.invokeLaterIfNeeded {
|
||||
project.executeCommand(getText()) {
|
||||
project.executeCommand(text) {
|
||||
runWriteAction {
|
||||
filesToData.forEach {
|
||||
try {
|
||||
applyChangesForFile(project, it.getKey(), it.getValue())
|
||||
applyChangesForFile(project, it.key, it.value)
|
||||
}
|
||||
catch (e: Throwable) {
|
||||
LOG.error(e)
|
||||
|
||||
+88
-90
@@ -72,12 +72,10 @@ import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier
|
||||
import org.jetbrains.kotlin.resolve.scopes.utils.memberScopeAsImportingScope
|
||||
import org.jetbrains.kotlin.types.KotlinType
|
||||
import org.jetbrains.kotlin.types.TypeProjectionImpl
|
||||
import org.jetbrains.kotlin.types.TypeUtils
|
||||
import org.jetbrains.kotlin.types.Variance
|
||||
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
|
||||
import org.jetbrains.kotlin.types.typeUtil.isAnyOrNullableAny
|
||||
import org.jetbrains.kotlin.types.typeUtil.isUnit
|
||||
import org.jetbrains.kotlin.types.typeUtil.makeNullable
|
||||
import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptyList
|
||||
import java.util.*
|
||||
import kotlin.properties.Delegates
|
||||
@@ -99,7 +97,7 @@ class TypeCandidate(val theType: KotlinType, scope: HierarchicalScope? = null) {
|
||||
fun render(typeParameterNameMap: Map<TypeParameterDescriptor, String>, fakeFunction: FunctionDescriptor?) {
|
||||
renderedType = theType.renderShort(typeParameterNameMap);
|
||||
renderedTypeParameters = typeParameters.map {
|
||||
RenderedTypeParameter(it, it.getContainingDeclaration() == fakeFunction, typeParameterNameMap[it]!!)
|
||||
RenderedTypeParameter(it, it.containingDeclaration == fakeFunction, typeParameterNameMap[it]!!)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -249,24 +247,24 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
}
|
||||
is CallablePlacement.WithReceiver -> {
|
||||
receiverClassDescriptor =
|
||||
placement.receiverTypeCandidate.theType.getConstructor().getDeclarationDescriptor()
|
||||
placement.receiverTypeCandidate.theType.constructor.declarationDescriptor
|
||||
val classDeclaration = receiverClassDescriptor?.let { DescriptorToSourceUtils.getSourceFromDescriptor(it) }
|
||||
containingElement = if (!config.isExtension && classDeclaration != null) classDeclaration else config.currentFile
|
||||
}
|
||||
else -> throw IllegalArgumentException("Unexpected placement: $placement")
|
||||
}
|
||||
val receiverType = receiverClassDescriptor?.getDefaultType()
|
||||
val receiverType = receiverClassDescriptor?.defaultType
|
||||
|
||||
val project = config.currentFile.getProject()
|
||||
val project = config.currentFile.project
|
||||
|
||||
if (containingElement.getContainingFile() != config.currentFile) {
|
||||
if (containingElement.containingFile != config.currentFile) {
|
||||
NavigationUtil.activateFileWithPsiElement(containingElement)
|
||||
}
|
||||
|
||||
if (containingElement is KtElement) {
|
||||
jetFileToEdit = containingElement.getContainingKtFile()
|
||||
if (jetFileToEdit != config.currentFile) {
|
||||
containingFileEditor = FileEditorManager.getInstance(project).getSelectedTextEditor()!!
|
||||
containingFileEditor = FileEditorManager.getInstance(project).selectedTextEditor!!
|
||||
}
|
||||
else {
|
||||
containingFileEditor = config.currentEditor!!
|
||||
@@ -282,11 +280,11 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
}
|
||||
}
|
||||
containingFileEditor = dialog.editor
|
||||
with(containingFileEditor.getSettings()) {
|
||||
setAdditionalColumnsCount(config.currentEditor!!.getSettings().getRightMargin(project))
|
||||
setAdditionalLinesCount(5)
|
||||
with(containingFileEditor.settings) {
|
||||
additionalColumnsCount = config.currentEditor!!.settings.getRightMargin(project)
|
||||
additionalLinesCount = 5
|
||||
}
|
||||
jetFileToEdit = PsiDocumentManager.getInstance(project).getPsiFile(containingFileEditor.getDocument()) as KtFile
|
||||
jetFileToEdit = PsiDocumentManager.getInstance(project).getPsiFile(containingFileEditor.document) as KtFile
|
||||
jetFileToEdit.analysisContext = config.currentFile
|
||||
dialogWithEditor = dialog
|
||||
}
|
||||
@@ -303,11 +301,11 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
val typeArgumentsForFakeFunction = callableInfo.typeParameterInfos
|
||||
.map {
|
||||
val typeCandidates = computeTypeCandidates(it)
|
||||
assert (typeCandidates.size() == 1) { "Ambiguous type candidates for type parameter $it: $typeCandidates" }
|
||||
assert (typeCandidates.size == 1) { "Ambiguous type candidates for type parameter $it: $typeCandidates" }
|
||||
typeCandidates.first().theType
|
||||
}
|
||||
.subtract(substitutionMap.keySet())
|
||||
fakeFunction = createFakeFunctionDescriptor(scope, typeArgumentsForFakeFunction.size())
|
||||
.subtract(substitutionMap.keys)
|
||||
fakeFunction = createFakeFunctionDescriptor(scope, typeArgumentsForFakeFunction.size)
|
||||
collectSubstitutionsForCallableTypeParameters(fakeFunction, typeArgumentsForFakeFunction, substitutionMap)
|
||||
mandatoryTypeParametersAsCandidates = receiverTypeCandidate.singletonOrEmptyList() + typeArgumentsForFakeFunction.map { TypeCandidate(substitutionMap[it]!!, scope) }
|
||||
}
|
||||
@@ -353,7 +351,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
assert (receiverClassDescriptor is JavaClassDescriptor) { "Unexpected receiver class: $receiverClassDescriptor" }
|
||||
|
||||
val projections = ((receiverClassDescriptor as JavaClassDescriptor).declaredTypeParameters)
|
||||
.map { TypeProjectionImpl(it.getDefaultType()) }
|
||||
.map { TypeProjectionImpl(it.defaultType) }
|
||||
val memberScope = receiverClassDescriptor.getMemberScope(projections)
|
||||
|
||||
return LexicalScopeImpl(memberScope.memberScopeAsImportingScope(), receiverClassDescriptor, false, null,
|
||||
@@ -368,19 +366,19 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
) {
|
||||
if (placement is CallablePlacement.NoReceiver) return
|
||||
|
||||
val classTypeParameters = receiverType?.getArguments() ?: Collections.emptyList()
|
||||
val ownerTypeArguments = (placement as? CallablePlacement.WithReceiver)?.receiverTypeCandidate?.theType?.getArguments()
|
||||
val classTypeParameters = receiverType?.arguments ?: Collections.emptyList()
|
||||
val ownerTypeArguments = (placement as? CallablePlacement.WithReceiver)?.receiverTypeCandidate?.theType?.arguments
|
||||
?: Collections.emptyList()
|
||||
assert(ownerTypeArguments.size() == classTypeParameters.size())
|
||||
ownerTypeArguments.zip(classTypeParameters).forEach { result[it.first.getType()] = it.second.getType() }
|
||||
assert(ownerTypeArguments.size == classTypeParameters.size)
|
||||
ownerTypeArguments.zip(classTypeParameters).forEach { result[it.first.type] = it.second.type }
|
||||
}
|
||||
|
||||
private fun collectSubstitutionsForCallableTypeParameters(
|
||||
fakeFunction: FunctionDescriptor,
|
||||
typeArguments: Set<KotlinType>,
|
||||
result: MutableMap<KotlinType, KotlinType>) {
|
||||
for ((typeArgument, typeParameter) in typeArguments.zip(fakeFunction.getTypeParameters())) {
|
||||
result[typeArgument] = typeParameter.getDefaultType()
|
||||
for ((typeArgument, typeParameter) in typeArguments.zip(fakeFunction.typeParameters)) {
|
||||
result[typeArgument] = typeParameter.defaultType
|
||||
}
|
||||
}
|
||||
|
||||
@@ -481,7 +479,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
val safeName = name.quoteIfNeeded()
|
||||
when (kind) {
|
||||
ClassKind.ENUM_ENTRY -> {
|
||||
if (!(targetParent is KtClass && targetParent.isEnum())) throw AssertionError("Enum class expected: ${targetParent.getText()}")
|
||||
if (!(targetParent is KtClass && targetParent.isEnum())) throw AssertionError("Enum class expected: ${targetParent.text}")
|
||||
val hasParameters = targetParent.getPrimaryConstructorParameters().isNotEmpty()
|
||||
psiFactory.createEnumEntry("$safeName${if (hasParameters) "()" else " "}")
|
||||
}
|
||||
@@ -506,7 +504,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
}
|
||||
|
||||
if (assignmentToReplace != null) {
|
||||
(declaration as KtProperty).setInitializer(assignmentToReplace.getRight())
|
||||
(declaration as KtProperty).setInitializer(assignmentToReplace.right)
|
||||
return assignmentToReplace.replace(declaration) as KtCallableDeclaration
|
||||
}
|
||||
|
||||
@@ -519,7 +517,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
siblingsLoop@
|
||||
for (sibling in decl.siblings(forward = after, withItself = false)) {
|
||||
when (sibling) {
|
||||
is PsiWhiteSpace -> lineBreaksPresent += (sibling.getText() ?: "").count { it == '\n' }
|
||||
is PsiWhiteSpace -> lineBreaksPresent += (sibling.text ?: "").count { it == '\n' }
|
||||
else -> {
|
||||
neighbor = sibling
|
||||
break@siblingsLoop
|
||||
@@ -527,7 +525,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
}
|
||||
}
|
||||
|
||||
val neighborType = neighbor?.getNode()?.getElementType()
|
||||
val neighborType = neighbor?.node?.elementType
|
||||
val lineBreaksNeeded = when {
|
||||
neighborType == KtTokens.LBRACE || neighborType == KtTokens.RBRACE -> 1
|
||||
neighbor is KtDeclaration && (neighbor !is KtProperty || decl !is KtProperty) -> 2
|
||||
@@ -539,7 +537,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
|
||||
fun addNextToOriginalElementContainer(addBefore: Boolean): KtNamedDeclaration {
|
||||
val actualContainer = (containingElement as? KtClassOrObject)?.getBody() ?: containingElement
|
||||
val sibling = config.originalElement.parentsWithSelf.first { it.getParent() == actualContainer }
|
||||
val sibling = config.originalElement.parentsWithSelf.first { it.parent == actualContainer }
|
||||
return if (addBefore) {
|
||||
actualContainer.addBefore(declaration, sibling)
|
||||
}
|
||||
@@ -552,7 +550,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
containingElement.isAncestor(config.originalElement, true) -> {
|
||||
val insertToBlock = containingElement is KtBlockExpression
|
||||
if (insertToBlock) {
|
||||
val parent = containingElement.getParent()
|
||||
val parent = containingElement.parent
|
||||
if (parent is KtFunctionLiteral) {
|
||||
if (!parent.isMultiLine()) {
|
||||
parent.addBefore(newLine, containingElement)
|
||||
@@ -567,9 +565,9 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
|
||||
containingElement is PsiClass -> {
|
||||
if (declaration is KtSecondaryConstructor) {
|
||||
val wrappingClass = psiFactory.createClass("class ${containingElement.getName()} {\n}")
|
||||
val wrappingClass = psiFactory.createClass("class ${containingElement.name} {\n}")
|
||||
addDeclarationToClassOrObject(wrappingClass, declaration)
|
||||
(jetFileToEdit.add(wrappingClass) as KtClass).getDeclarations().first() as KtNamedDeclaration
|
||||
(jetFileToEdit.add(wrappingClass) as KtClass).declarations.first() as KtNamedDeclaration
|
||||
}
|
||||
else {
|
||||
jetFileToEdit.add(declaration) as KtNamedDeclaration
|
||||
@@ -579,10 +577,10 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
containingElement is KtClassOrObject -> {
|
||||
addDeclarationToClassOrObject(containingElement, declaration)
|
||||
}
|
||||
else -> throw AssertionError("Invalid containing element: ${containingElement.getText()}")
|
||||
else -> throw AssertionError("Invalid containing element: ${containingElement.text}")
|
||||
}
|
||||
|
||||
val parent = declarationInPlace.getParent()
|
||||
val parent = declarationInPlace.parent
|
||||
calcNecessaryEmptyLines(declarationInPlace, false).let {
|
||||
if (it > 0) parent.addBefore(psiFactory.createNewLine(it), declarationInPlace)
|
||||
}
|
||||
@@ -599,8 +597,8 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
val classBody = classOrObject.getOrCreateBody()
|
||||
return if (declaration is KtNamedFunction) {
|
||||
val anchor = PsiTreeUtil.skipSiblingsBackward(
|
||||
classBody.rBrace ?: classBody.getLastChild()!!,
|
||||
javaClass<PsiWhiteSpace>()
|
||||
classBody.rBrace ?: classBody.lastChild!!,
|
||||
PsiWhiteSpace::class.java
|
||||
)
|
||||
classBody.addAfter(declaration, anchor) as KtNamedDeclaration
|
||||
}
|
||||
@@ -622,7 +620,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
}
|
||||
|
||||
val validator = CollectingNameValidator { scope.findClassifier(Name.identifier(it), NoLookupLocation.FROM_IDE) == null }
|
||||
val typeParameterNames = allTypeParametersNotInScope.map { KotlinNameSuggester.suggestNameByName(it.getName().asString(), validator) }
|
||||
val typeParameterNames = allTypeParametersNotInScope.map { KotlinNameSuggester.suggestNameByName(it.name.asString(), validator) }
|
||||
|
||||
return allTypeParametersNotInScope.zip(typeParameterNames).toMap()
|
||||
}
|
||||
@@ -641,8 +639,8 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
val returnTypeRef = declaration.getReturnTypeReference()
|
||||
if (returnTypeRef != null) {
|
||||
val returnType = typeCandidates[callableInfo.returnTypeInfo]!!.getTypeByRenderedType(
|
||||
returnTypeRef.getText()
|
||||
?: throw AssertionError("Expression for return type shouldn't be empty: declaration = ${declaration.getText()}")
|
||||
returnTypeRef.text
|
||||
?: throw AssertionError("Expression for return type shouldn't be empty: declaration = ${declaration.text}")
|
||||
)
|
||||
if (returnType != null) {
|
||||
// user selected a given type
|
||||
@@ -653,13 +651,13 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
|
||||
val valueParameters = declaration.getValueParameters()
|
||||
val parameterIndicesToShorten = ArrayList<Int>()
|
||||
assert(valueParameters.size() == parameterTypeExpressions.size())
|
||||
assert(valueParameters.size == parameterTypeExpressions.size)
|
||||
for ((i, parameter) in valueParameters.asSequence().withIndex()) {
|
||||
val parameterTypeRef = parameter.getTypeReference()
|
||||
val parameterTypeRef = parameter.typeReference
|
||||
if (parameterTypeRef != null) {
|
||||
val parameterType = parameterTypeExpressions[i].typeCandidates.getTypeByRenderedType(
|
||||
parameterTypeRef.getText()
|
||||
?: throw AssertionError("Expression for parameter type shouldn't be empty: declaration = ${declaration.getText()}")
|
||||
parameterTypeRef.text
|
||||
?: throw AssertionError("Expression for parameter type shouldn't be empty: declaration = ${declaration.text}")
|
||||
)
|
||||
if (parameterType != null) {
|
||||
replaceWithLongerName(parameterTypeRef, parameterType)
|
||||
@@ -669,25 +667,25 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
}
|
||||
|
||||
val expandedValueParameters = declaration.getValueParameters()
|
||||
parameterIndicesToShorten.mapNotNullTo(typeRefsToShorten) { expandedValueParameters[it].getTypeReference() }
|
||||
parameterIndicesToShorten.mapNotNullTo(typeRefsToShorten) { expandedValueParameters[it].typeReference }
|
||||
|
||||
return typeRefsToShorten
|
||||
}
|
||||
|
||||
private fun setupFunctionBody(func: KtFunction) {
|
||||
val oldBody = func.getBodyExpression() ?: return
|
||||
val oldBody = func.bodyExpression ?: return
|
||||
|
||||
val templateName = when (func) {
|
||||
is KtSecondaryConstructor -> TEMPLATE_FROM_USAGE_SECONDARY_CONSTRUCTOR_BODY
|
||||
is KtNamedFunction -> TEMPLATE_FROM_USAGE_FUNCTION_BODY
|
||||
else -> throw AssertionError("Unexpected declaration: " + func.getElementTextWithContext())
|
||||
}
|
||||
val fileTemplate = FileTemplateManager.getInstance(func.getProject())!!.getCodeTemplate(templateName)
|
||||
val fileTemplate = FileTemplateManager.getInstance(func.project)!!.getCodeTemplate(templateName)
|
||||
val properties = Properties()
|
||||
properties.setProperty(FileTemplate.ATTRIBUTE_RETURN_TYPE, if (skipReturnType) "Unit" else func.getTypeReference()!!.getText())
|
||||
properties.setProperty(FileTemplate.ATTRIBUTE_RETURN_TYPE, if (skipReturnType) "Unit" else func.typeReference!!.text)
|
||||
receiverClassDescriptor?.let {
|
||||
properties.setProperty(FileTemplate.ATTRIBUTE_CLASS_NAME, DescriptorUtils.getFqName(it).asString())
|
||||
properties.setProperty(FileTemplate.ATTRIBUTE_SIMPLE_CLASS_NAME, it.getName().asString())
|
||||
properties.setProperty(FileTemplate.ATTRIBUTE_SIMPLE_CLASS_NAME, it.name.asString())
|
||||
}
|
||||
if (callableInfo.name.isNotEmpty()) {
|
||||
properties.setProperty(ATTRIBUTE_FUNCTION_NAME, callableInfo.name)
|
||||
@@ -709,9 +707,9 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
}
|
||||
|
||||
private fun setupCallTypeArguments(callElement: KtCallElement, typeParameters: List<TypeParameterDescriptor>) {
|
||||
val oldTypeArgumentList = callElement.getTypeArgumentList() ?: return
|
||||
val oldTypeArgumentList = callElement.typeArgumentList ?: return
|
||||
val renderedTypeArgs = typeParameters.map { typeParameter ->
|
||||
val type = substitutions.first { it.byType.getConstructor().getDeclarationDescriptor() == typeParameter }.forType
|
||||
val type = substitutions.first { it.byType.constructor.declarationDescriptor == typeParameter }.forType
|
||||
IdeDescriptorRenderers.SOURCE_CODE.renderType(type)
|
||||
}
|
||||
if (renderedTypeArgs.isEmpty()) {
|
||||
@@ -719,7 +717,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
}
|
||||
else {
|
||||
oldTypeArgumentList.replace(KtPsiFactory(callElement).createTypeArguments(renderedTypeArgs.joinToString(", ", "<", ">")))
|
||||
elementsToShorten.add(callElement.getTypeArgumentList()!!)
|
||||
elementsToShorten.add(callElement.typeArgumentList!!)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -731,19 +729,19 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
val expression: TypeExpression
|
||||
when (declaration) {
|
||||
is KtCallableDeclaration -> {
|
||||
elementToReplace = declaration.getTypeReference()
|
||||
elementToReplace = declaration.typeReference
|
||||
expression = TypeExpression.ForTypeReference(candidates)
|
||||
}
|
||||
is KtClassOrObject -> {
|
||||
elementToReplace = declaration.getSuperTypeListEntries().firstOrNull()
|
||||
expression = TypeExpression.ForDelegationSpecifier(candidates)
|
||||
}
|
||||
else -> throw AssertionError("Unexpected declaration kind: ${declaration.getText()}")
|
||||
else -> throw AssertionError("Unexpected declaration kind: ${declaration.text}")
|
||||
}
|
||||
if (elementToReplace == null) return null
|
||||
|
||||
if (candidates.size() == 1) {
|
||||
builder.replaceElement(elementToReplace, (expression.calculateResult(null) as TextResult).getText())
|
||||
if (candidates.size == 1) {
|
||||
builder.replaceElement(elementToReplace, (expression.calculateResult(null) as TextResult).text)
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -753,7 +751,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
|
||||
private fun setupValVarTemplate(builder: TemplateBuilder, property: KtProperty) {
|
||||
if (!(callableInfo as PropertyInfo).writable) {
|
||||
builder.replaceElement(property.getValOrVarKeyword(), ValVarExpression)
|
||||
builder.replaceElement(property.valOrVarKeyword, ValVarExpression)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -763,10 +761,10 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
): TypeParameterListExpression? {
|
||||
when (declaration) {
|
||||
is KtObjectDeclaration -> return null
|
||||
!is KtTypeParameterListOwner -> throw AssertionError("Unexpected declaration kind: ${declaration.getText()}")
|
||||
!is KtTypeParameterListOwner -> throw AssertionError("Unexpected declaration kind: ${declaration.text}")
|
||||
}
|
||||
|
||||
val typeParameterList = (declaration as KtTypeParameterListOwner).getTypeParameterList() ?: return null
|
||||
val typeParameterList = (declaration as KtTypeParameterListOwner).typeParameterList ?: return null
|
||||
|
||||
val typeParameterMap = HashMap<String, List<RenderedTypeParameter>>()
|
||||
|
||||
@@ -794,12 +792,12 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
}
|
||||
|
||||
private fun setupParameterTypeTemplates(builder: TemplateBuilder, parameterList: List<KtParameter>): List<TypeExpression> {
|
||||
assert(parameterList.size() == callableInfo.parameterInfos.size())
|
||||
assert(parameterList.size == callableInfo.parameterInfos.size)
|
||||
|
||||
val typeParameters = ArrayList<TypeExpression>()
|
||||
for ((parameter, jetParameter) in callableInfo.parameterInfos.zip(parameterList)) {
|
||||
val parameterTypeExpression = TypeExpression.ForTypeReference(typeCandidates[parameter.typeInfo]!!)
|
||||
val parameterTypeRef = jetParameter.getTypeReference()!!
|
||||
val parameterTypeRef = jetParameter.typeReference!!
|
||||
builder.replaceElement(parameterTypeRef, parameterTypeExpression)
|
||||
|
||||
// add parameter name to the template
|
||||
@@ -821,7 +819,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
|
||||
// add expression to builder
|
||||
val parameterNameExpression = ParameterNameExpression(possibleNames, parameterTypeToNamesMap)
|
||||
val parameterNameIdentifier = jetParameter.getNameIdentifier()!!
|
||||
val parameterNameIdentifier = jetParameter.nameIdentifier!!
|
||||
builder.replaceElement(parameterNameIdentifier, parameterNameExpression)
|
||||
|
||||
typeParameters.add(parameterTypeExpression)
|
||||
@@ -838,15 +836,15 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
fun convertToJava(targetClass: PsiClass): PsiMember? {
|
||||
val psiFactory = KtPsiFactory(declaration)
|
||||
|
||||
psiFactory.createPackageDirectiveIfNeeded(config.currentFile.getPackageFqName())?.let {
|
||||
declaration.getContainingFile().addBefore(it, null)
|
||||
psiFactory.createPackageDirectiveIfNeeded(config.currentFile.packageFqName)?.let {
|
||||
declaration.containingFile.addBefore(it, null)
|
||||
}
|
||||
|
||||
val adjustedDeclaration = when (declaration) {
|
||||
is KtNamedFunction, is KtProperty -> {
|
||||
val klass = psiFactory.createClass("class Foo {}")
|
||||
klass.getBody()!!.add(declaration)
|
||||
(declaration.replace(klass) as KtClass).getBody()!!.getDeclarations().first()
|
||||
(declaration.replace(klass) as KtClass).getBody()!!.declarations.first()
|
||||
}
|
||||
else -> declaration
|
||||
}
|
||||
@@ -870,11 +868,11 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
val targetClass = DescriptorToSourceUtils.getSourceFromDescriptor(receiverClassDescriptor) as? PsiClass
|
||||
if (targetClass == null || !targetClass.canRefactor()) return false
|
||||
|
||||
val project = declaration.getProject()
|
||||
val project = declaration.project
|
||||
|
||||
val newJavaMember = convertToJava(targetClass) ?: return false
|
||||
|
||||
val modifierList = newJavaMember.getModifierList()!!
|
||||
val modifierList = newJavaMember.modifierList!!
|
||||
if (newJavaMember is PsiMethod || newJavaMember is PsiClass) {
|
||||
modifierList.setModifierProperty(PsiModifier.FINAL, false)
|
||||
}
|
||||
@@ -889,26 +887,26 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
|
||||
JavaCodeStyleManager.getInstance(project).shortenClassReferences(newJavaMember);
|
||||
|
||||
val descriptor = OpenFileDescriptor(project, targetClass.getContainingFile().getVirtualFile())
|
||||
val descriptor = OpenFileDescriptor(project, targetClass.containingFile.virtualFile)
|
||||
val targetEditor = FileEditorManager.getInstance(project).openTextEditor(descriptor, true)!!
|
||||
|
||||
when (newJavaMember) {
|
||||
is PsiMethod -> CreateFromUsageUtils.setupEditor(newJavaMember, targetEditor)
|
||||
is PsiField -> targetEditor.getCaretModel().moveToOffset(newJavaMember.endOffset - 1)
|
||||
is PsiField -> targetEditor.caretModel.moveToOffset(newJavaMember.endOffset - 1)
|
||||
is PsiClass -> {
|
||||
val constructor = newJavaMember.getConstructors().firstOrNull()
|
||||
val superStatement = constructor?.getBody()?.getStatements()?.firstOrNull() as? PsiExpressionStatement
|
||||
val superCall = superStatement?.getExpression() as? PsiMethodCallExpression
|
||||
val constructor = newJavaMember.constructors.firstOrNull()
|
||||
val superStatement = constructor?.body?.statements?.firstOrNull() as? PsiExpressionStatement
|
||||
val superCall = superStatement?.expression as? PsiMethodCallExpression
|
||||
if (superCall != null) {
|
||||
val lParen = superCall.getArgumentList().getFirstChild()
|
||||
targetEditor.getCaretModel().moveToOffset(lParen.endOffset)
|
||||
val lParen = superCall.argumentList.firstChild
|
||||
targetEditor.caretModel.moveToOffset(lParen.endOffset)
|
||||
}
|
||||
else {
|
||||
targetEditor.getCaretModel().moveToOffset(newJavaMember.startOffset)
|
||||
targetEditor.caretModel.moveToOffset(newJavaMember.startOffset)
|
||||
}
|
||||
}
|
||||
}
|
||||
targetEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE)
|
||||
targetEditor.scrollingModel.scrollToCaret(ScrollType.RELATIVE)
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -918,8 +916,8 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
val defaultValueType = typeCandidates[callableInfo.returnTypeInfo]!!.firstOrNull()?.theType
|
||||
val defaultValue = defaultValueType?.let { CodeInsightUtils.defaultInitializer(it) } ?: "null"
|
||||
val initializer = declaration.setInitializer(KtPsiFactory(declaration).createExpression(defaultValue))!!
|
||||
val range = initializer.getTextRange()
|
||||
containingFileEditor.getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset())
|
||||
val range = initializer.textRange
|
||||
containingFileEditor.selectionModel.setSelection(range.startOffset, range.endOffset)
|
||||
return
|
||||
}
|
||||
setupEditorSelection(containingFileEditor, declaration)
|
||||
@@ -928,17 +926,17 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
// build templates
|
||||
fun buildAndRunTemplate(onFinish: () -> Unit) {
|
||||
val declarationSkeleton = createDeclarationSkeleton()
|
||||
val project = declarationSkeleton.getProject()
|
||||
val project = declarationSkeleton.project
|
||||
val declarationPointer = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(declarationSkeleton)
|
||||
|
||||
// build templates
|
||||
PsiDocumentManager.getInstance(project).commitAllDocuments()
|
||||
PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(containingFileEditor.getDocument())
|
||||
PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(containingFileEditor.document)
|
||||
|
||||
val caretModel = containingFileEditor.getCaretModel()
|
||||
caretModel.moveToOffset(jetFileToEdit.getNode().getStartOffset())
|
||||
val caretModel = containingFileEditor.caretModel
|
||||
caretModel.moveToOffset(jetFileToEdit.node.startOffset)
|
||||
|
||||
val declaration = declarationPointer.getElement()!!
|
||||
val declaration = declarationPointer.element!!
|
||||
|
||||
val declarationMarker = containingFileEditor.document.createRangeMarker(declaration.textRange)
|
||||
|
||||
@@ -961,26 +959,26 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
|
||||
// the template built by TemplateBuilderImpl is ordered by element position, but we want types to be first, so hack it
|
||||
val templateImpl = builder.buildInlineTemplate() as TemplateImpl
|
||||
val variables = templateImpl.getVariables()!!
|
||||
val variables = templateImpl.variables!!
|
||||
if (variables.isNotEmpty()) {
|
||||
val typeParametersVar = if (expression != null) variables.remove(0) else null
|
||||
for (i in 0..(callableInfo.parameterInfos.size() - 1)) {
|
||||
val typeParametersVar = if (expression != null) variables.removeAt(0) else null
|
||||
for (i in 0..(callableInfo.parameterInfos.size - 1)) {
|
||||
Collections.swap(variables, i * 2, i * 2 + 1)
|
||||
}
|
||||
typeParametersVar?.let { variables.add(it) }
|
||||
}
|
||||
|
||||
// TODO: Disabled shortening names because it causes some tests fail. Refactor code to use automatic reference shortening
|
||||
templateImpl.setToShortenLongNames(false)
|
||||
templateImpl.isToShortenLongNames = false
|
||||
|
||||
// run the template
|
||||
TemplateManager.getInstance(project).startTemplate(containingFileEditor, templateImpl, object : TemplateEditingAdapter() {
|
||||
private fun finishTemplate(brokenOff: Boolean) {
|
||||
try {
|
||||
PsiDocumentManager.getInstance(project).commitDocument(containingFileEditor.getDocument())
|
||||
PsiDocumentManager.getInstance(project).commitDocument(containingFileEditor.document)
|
||||
|
||||
dialogWithEditor?.close(DialogWrapper.OK_EXIT_CODE)
|
||||
if (brokenOff && !ApplicationManager.getApplication().isUnitTestMode()) return
|
||||
if (brokenOff && !ApplicationManager.getApplication().isUnitTestMode) return
|
||||
|
||||
// file templates
|
||||
val newDeclaration = PsiTreeUtil.findElementOfClassAtOffset(jetFileToEdit,
|
||||
@@ -1025,7 +1023,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
}
|
||||
|
||||
fun showDialogIfNeeded() {
|
||||
if (!ApplicationManager.getApplication().isUnitTestMode() && dialogWithEditor != null && !finished) {
|
||||
if (!ApplicationManager.getApplication().isUnitTestMode && dialogWithEditor != null && !finished) {
|
||||
dialogWithEditor.show()
|
||||
}
|
||||
}
|
||||
@@ -1034,9 +1032,9 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
|
||||
|
||||
internal fun KtNamedDeclaration.getReturnTypeReference(): KtTypeReference? {
|
||||
return when (this) {
|
||||
is KtCallableDeclaration -> getTypeReference()
|
||||
is KtClassOrObject -> getSuperTypeListEntries().firstOrNull()?.getTypeReference()
|
||||
else -> throw AssertionError("Unexpected declaration kind: ${getText()}")
|
||||
is KtCallableDeclaration -> typeReference
|
||||
is KtClassOrObject -> getSuperTypeListEntries().firstOrNull()?.typeReference
|
||||
else -> throw AssertionError("Unexpected declaration kind: $text")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
-1
@@ -18,7 +18,6 @@ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder
|
||||
|
||||
import com.intellij.psi.PsiElement
|
||||
import com.intellij.util.ArrayUtil
|
||||
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
|
||||
import org.jetbrains.kotlin.idea.core.KotlinNameSuggester
|
||||
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass.ClassInfo
|
||||
import org.jetbrains.kotlin.psi.KtElement
|
||||
|
||||
+23
-23
@@ -48,7 +48,7 @@ internal class ParameterNameExpression(
|
||||
|
||||
override fun calculateResult(context: ExpressionContext?): Result? {
|
||||
val lookupItems = calculateLookupItems(context)!!
|
||||
return TextResult(if (lookupItems.isEmpty()) "" else lookupItems.first().getLookupString())
|
||||
return TextResult(if (lookupItems.isEmpty()) "" else lookupItems.first().lookupString)
|
||||
}
|
||||
|
||||
override fun calculateQuickResult(context: ExpressionContext?) = calculateResult(context)
|
||||
@@ -58,25 +58,25 @@ internal class ParameterNameExpression(
|
||||
val names = LinkedHashSet(this.names.toList())
|
||||
|
||||
// find the parameter list
|
||||
val project = context.getProject()!!
|
||||
val offset = context.getStartOffset()
|
||||
val project = context.project!!
|
||||
val offset = context.startOffset
|
||||
PsiDocumentManager.getInstance(project).commitAllDocuments()
|
||||
val editor = context.getEditor()!!
|
||||
val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()) as KtFile
|
||||
val editor = context.editor!!
|
||||
val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) as KtFile
|
||||
val elementAt = file.findElementAt(offset)
|
||||
val declaration = PsiTreeUtil.getParentOfType(elementAt, javaClass<KtFunction>(), javaClass<KtClass>()) ?: return arrayOf()
|
||||
val declaration = PsiTreeUtil.getParentOfType(elementAt, KtFunction::class.java, KtClass::class.java) ?: return arrayOf()
|
||||
val parameterList = when (declaration) {
|
||||
is KtFunction -> declaration.getValueParameterList()!!
|
||||
is KtFunction -> declaration.valueParameterList!!
|
||||
is KtClass -> declaration.getPrimaryConstructorParameterList()!!
|
||||
else -> throw AssertionError("Unexpected declaration: ${declaration.getText()}")
|
||||
else -> throw AssertionError("Unexpected declaration: ${declaration.text}")
|
||||
}
|
||||
|
||||
// add names based on selected type
|
||||
val parameter = elementAt?.getStrictParentOfType<KtParameter>()
|
||||
if (parameter != null) {
|
||||
val parameterTypeRef = parameter.getTypeReference()
|
||||
val parameterTypeRef = parameter.typeReference
|
||||
if (parameterTypeRef != null) {
|
||||
val suggestedNamesBasedOnType = parameterTypeToNamesMap[parameterTypeRef.getText()]
|
||||
val suggestedNamesBasedOnType = parameterTypeToNamesMap[parameterTypeRef.text]
|
||||
if (suggestedNamesBasedOnType != null) {
|
||||
names.addAll(suggestedNamesBasedOnType)
|
||||
}
|
||||
@@ -84,8 +84,8 @@ internal class ParameterNameExpression(
|
||||
}
|
||||
|
||||
// remember other parameter names for later use
|
||||
val parameterNames = parameterList.getParameters().mapNotNullTo(HashSet<String>()) { jetParameter ->
|
||||
if (jetParameter == parameter) null else jetParameter.getName()
|
||||
val parameterNames = parameterList.parameters.mapNotNullTo(HashSet<String>()) { jetParameter ->
|
||||
if (jetParameter == parameter) null else jetParameter.name
|
||||
}
|
||||
|
||||
// add fallback parameter name
|
||||
@@ -111,8 +111,8 @@ internal abstract class TypeExpression(public val typeCandidates: List<TypeCandi
|
||||
class ForDelegationSpecifier(typeCandidates: List<TypeCandidate>) : TypeExpression(typeCandidates) {
|
||||
override val cachedLookupElements: Array<LookupElement> =
|
||||
typeCandidates.map {
|
||||
val descriptor = it.theType.getConstructor().getDeclarationDescriptor() as ClassDescriptor
|
||||
val text = it.renderedType!! + if (descriptor.getKind() == ClassKind.INTERFACE) "" else "()"
|
||||
val descriptor = it.theType.constructor.declarationDescriptor as ClassDescriptor
|
||||
val text = it.renderedType!! + if (descriptor.kind == ClassKind.INTERFACE) "" else "()"
|
||||
LookupElementBuilder.create(it, text)
|
||||
}.toTypedArray()
|
||||
}
|
||||
@@ -121,7 +121,7 @@ internal abstract class TypeExpression(public val typeCandidates: List<TypeCandi
|
||||
|
||||
override fun calculateResult(context: ExpressionContext?): Result {
|
||||
val lookupItems = calculateLookupItems(context)
|
||||
return TextResult(if (lookupItems.size() == 0) "" else lookupItems[0].getLookupString())
|
||||
return TextResult(if (lookupItems.size == 0) "" else lookupItems[0].lookupString)
|
||||
}
|
||||
|
||||
override fun calculateQuickResult(context: ExpressionContext?) = calculateResult(context)
|
||||
@@ -142,21 +142,21 @@ internal class TypeParameterListExpression(private val mandatoryTypeParameters:
|
||||
|
||||
override fun calculateResult(context: ExpressionContext?): Result {
|
||||
context!!
|
||||
val project = context.getProject()!!
|
||||
val offset = context.getStartOffset()
|
||||
val project = context.project!!
|
||||
val offset = context.startOffset
|
||||
|
||||
PsiDocumentManager.getInstance(project).commitAllDocuments()
|
||||
val editor = context.getEditor()!!
|
||||
val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()) as KtFile
|
||||
val editor = context.editor!!
|
||||
val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) as KtFile
|
||||
val elementAt = file.findElementAt(offset)
|
||||
val declaration = elementAt?.getStrictParentOfType<KtNamedDeclaration>() ?: return TextResult("")
|
||||
|
||||
val renderedTypeParameters = LinkedHashSet<RenderedTypeParameter>()
|
||||
renderedTypeParameters.addAll(mandatoryTypeParameters)
|
||||
for (parameter in declaration.getValueParameters()) {
|
||||
val parameterTypeRef = parameter.getTypeReference()
|
||||
val parameterTypeRef = parameter.typeReference
|
||||
if (parameterTypeRef != null) {
|
||||
val typeParameterNamesFromParameter = parameterTypeToTypeParameterNamesMap[parameterTypeRef.getText()]
|
||||
val typeParameterNamesFromParameter = parameterTypeToTypeParameterNamesMap[parameterTypeRef.text]
|
||||
if (typeParameterNamesFromParameter != null) {
|
||||
renderedTypeParameters.addAll(typeParameterNamesFromParameter)
|
||||
}
|
||||
@@ -164,14 +164,14 @@ internal class TypeParameterListExpression(private val mandatoryTypeParameters:
|
||||
}
|
||||
val returnTypeRef = declaration.getReturnTypeReference()
|
||||
if (returnTypeRef != null) {
|
||||
val typeParameterNamesFromReturnType = parameterTypeToTypeParameterNamesMap[returnTypeRef.getText()]
|
||||
val typeParameterNamesFromReturnType = parameterTypeToTypeParameterNamesMap[returnTypeRef.text]
|
||||
if (typeParameterNamesFromReturnType != null) {
|
||||
renderedTypeParameters.addAll(typeParameterNamesFromReturnType)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
val sortedRenderedTypeParameters = renderedTypeParameters.sortedBy { if (it.fake) it.typeParameter.getIndex() else -1 }
|
||||
val sortedRenderedTypeParameters = renderedTypeParameters.sortedBy { if (it.fake) it.typeParameter.index else -1 }
|
||||
currentTypeParameters = sortedRenderedTypeParameters.map { it.typeParameter }
|
||||
|
||||
return TextResult(
|
||||
|
||||
+24
-24
@@ -43,7 +43,7 @@ import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
|
||||
import java.util.*
|
||||
|
||||
internal operator fun KotlinType.contains(inner: KotlinType): Boolean {
|
||||
return KotlinTypeChecker.DEFAULT.equalTypes(this, inner) || getArguments().any { inner in it.getType() }
|
||||
return KotlinTypeChecker.DEFAULT.equalTypes(this, inner) || arguments.any { inner in it.type }
|
||||
}
|
||||
|
||||
private fun KotlinType.render(typeParameterNameMap: Map<TypeParameterDescriptor, String>, fq: Boolean): String {
|
||||
@@ -122,7 +122,7 @@ fun KtExpression.guessTypes(
|
||||
if (coerceUnusedToUnit
|
||||
&& this !is KtDeclaration
|
||||
&& isUsedAsStatement(context)
|
||||
&& getNonStrictParentOfType<KtAnnotationEntry>() == null) return arrayOf(module.builtIns.getUnitType())
|
||||
&& getNonStrictParentOfType<KtAnnotationEntry>() == null) return arrayOf(module.builtIns.unitType)
|
||||
|
||||
// if we know the actual type of the expression
|
||||
val theType1 = context.getType(this)
|
||||
@@ -136,21 +136,21 @@ fun KtExpression.guessTypes(
|
||||
val theType2 = context[BindingContext.EXPECTED_EXPRESSION_TYPE, this]
|
||||
if (theType2 != null) return arrayOf(theType2)
|
||||
|
||||
val parent = getParent()
|
||||
val parent = parent
|
||||
return when {
|
||||
this is KtTypeConstraint -> {
|
||||
// expression itself is a type assertion
|
||||
val constraint = this
|
||||
arrayOf(context[BindingContext.TYPE, constraint.getBoundTypeReference()]!!)
|
||||
arrayOf(context[BindingContext.TYPE, constraint.boundTypeReference]!!)
|
||||
}
|
||||
parent is KtTypeConstraint -> {
|
||||
// expression is on the left side of a type assertion
|
||||
val constraint = parent
|
||||
arrayOf(context[BindingContext.TYPE, constraint.getBoundTypeReference()]!!)
|
||||
arrayOf(context[BindingContext.TYPE, constraint.boundTypeReference]!!)
|
||||
}
|
||||
this is KtDestructuringDeclarationEntry -> {
|
||||
// expression is on the lhs of a multi-declaration
|
||||
val typeRef = getTypeReference()
|
||||
val typeRef = typeReference
|
||||
if (typeRef != null) {
|
||||
// and has a specified type
|
||||
arrayOf(context[BindingContext.TYPE, typeRef]!!)
|
||||
@@ -162,7 +162,7 @@ fun KtExpression.guessTypes(
|
||||
}
|
||||
this is KtParameter -> {
|
||||
// expression is a parameter (e.g. declared in a for-loop)
|
||||
val typeRef = getTypeReference()
|
||||
val typeRef = typeReference
|
||||
if (typeRef != null) {
|
||||
// and has a specified type
|
||||
arrayOf(context[BindingContext.TYPE, typeRef]!!)
|
||||
@@ -172,10 +172,10 @@ fun KtExpression.guessTypes(
|
||||
guessType(context)
|
||||
}
|
||||
}
|
||||
parent is KtProperty && parent.isLocal() -> {
|
||||
parent is KtProperty && parent.isLocal -> {
|
||||
// the expression is the RHS of a variable assignment with a specified type
|
||||
val variable = parent
|
||||
val typeRef = variable.getTypeReference()
|
||||
val typeRef = variable.typeReference
|
||||
if (typeRef != null) {
|
||||
// and has a specified type
|
||||
arrayOf(context[BindingContext.TYPE, typeRef]!!)
|
||||
@@ -186,17 +186,17 @@ fun KtExpression.guessTypes(
|
||||
}
|
||||
}
|
||||
parent is KtPropertyDelegate -> {
|
||||
val variableDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, parent.getParent() as KtProperty] as VariableDescriptor
|
||||
val delegateClassName = if (variableDescriptor.isVar()) "ReadWriteProperty" else "ReadOnlyProperty"
|
||||
val variableDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, parent.parent as KtProperty] as VariableDescriptor
|
||||
val delegateClassName = if (variableDescriptor.isVar) "ReadWriteProperty" else "ReadOnlyProperty"
|
||||
val delegateClass = module.resolveTopLevelClass(FqName("kotlin.properties.$delegateClassName"), NoLookupLocation.FROM_IDE)
|
||||
?: return arrayOf(module.builtIns.getAnyType())
|
||||
val receiverType = (variableDescriptor.getExtensionReceiverParameter() ?: variableDescriptor.getDispatchReceiverParameter())?.getType()
|
||||
?: module.builtIns.getNullableNothingType()
|
||||
val typeArguments = listOf(TypeProjectionImpl(receiverType), TypeProjectionImpl(variableDescriptor.getType()))
|
||||
?: return arrayOf(module.builtIns.anyType)
|
||||
val receiverType = (variableDescriptor.extensionReceiverParameter ?: variableDescriptor.dispatchReceiverParameter)?.type
|
||||
?: module.builtIns.nullableNothingType
|
||||
val typeArguments = listOf(TypeProjectionImpl(receiverType), TypeProjectionImpl(variableDescriptor.type))
|
||||
arrayOf(TypeUtils.substituteProjectionsForParameters(delegateClass, typeArguments))
|
||||
}
|
||||
parent is KtStringTemplateEntryWithExpression && parent.getExpression() == this -> {
|
||||
arrayOf(module.builtIns.getStringType())
|
||||
parent is KtStringTemplateEntryWithExpression && parent.expression == this -> {
|
||||
arrayOf(module.builtIns.stringType)
|
||||
}
|
||||
else -> {
|
||||
pseudocode?.getElementValue(this)?.let {
|
||||
@@ -207,7 +207,7 @@ fun KtExpression.guessTypes(
|
||||
}
|
||||
|
||||
private fun KtNamedDeclaration.guessType(context: BindingContext): Array<KotlinType> {
|
||||
val expectedTypes = SearchUtils.findAllReferences(this, getUseScope())!!.mapNotNullTo(HashSet<KotlinType>()) { ref ->
|
||||
val expectedTypes = SearchUtils.findAllReferences(this, useScope)!!.mapNotNullTo(HashSet<KotlinType>()) { ref ->
|
||||
if (ref is KtSimpleNameReference) {
|
||||
context[BindingContext.EXPECTED_EXPRESSION_TYPE, ref.expression]
|
||||
}
|
||||
@@ -235,7 +235,7 @@ private fun KtNamedDeclaration.guessType(context: BindingContext): Array<KotlinT
|
||||
internal class KotlinTypeSubstitution(public val forType: KotlinType, public val byType: KotlinType)
|
||||
|
||||
internal fun KotlinType.substitute(substitution: KotlinTypeSubstitution, variance: Variance): KotlinType {
|
||||
val nullable = isMarkedNullable()
|
||||
val nullable = isMarkedNullable
|
||||
val currentType = makeNotNullable()
|
||||
|
||||
if (when (variance) {
|
||||
@@ -246,18 +246,18 @@ internal fun KotlinType.substitute(substitution: KotlinTypeSubstitution, varianc
|
||||
return TypeUtils.makeNullableAsSpecified(substitution.byType, nullable)
|
||||
}
|
||||
else {
|
||||
val newArguments = getArguments().zip(getConstructor().getParameters()).map { pair ->
|
||||
val newArguments = arguments.zip(constructor.parameters).map { pair ->
|
||||
val (projection, typeParameter) = pair
|
||||
TypeProjectionImpl(Variance.INVARIANT, projection.getType().substitute(substitution, typeParameter.getVariance()))
|
||||
TypeProjectionImpl(Variance.INVARIANT, projection.type.substitute(substitution, typeParameter.variance))
|
||||
}
|
||||
return KotlinTypeImpl.create(getAnnotations(), getConstructor(), isMarkedNullable(), newArguments, getMemberScope())
|
||||
return KotlinTypeImpl.create(annotations, constructor, isMarkedNullable, newArguments, memberScope)
|
||||
}
|
||||
}
|
||||
|
||||
fun KtExpression.getExpressionForTypeGuess() = getAssignmentByLHS()?.getRight() ?: this
|
||||
fun KtExpression.getExpressionForTypeGuess() = getAssignmentByLHS()?.right ?: this
|
||||
|
||||
fun KtCallElement.getTypeInfoForTypeArguments(): List<TypeInfo> {
|
||||
return getTypeArguments().mapNotNull { it.getTypeReference()?.let { TypeInfo(it, Variance.INVARIANT) } }
|
||||
return typeArguments.mapNotNull { it.typeReference?.let { TypeInfo(it, Variance.INVARIANT) } }
|
||||
}
|
||||
|
||||
fun KtCallExpression.getParameterInfos(): List<ParameterInfo> {
|
||||
|
||||
+5
-5
@@ -64,7 +64,7 @@ sealed class CreateCallableFromCallActionFactory<E : KtExpression>(
|
||||
val diagElement = diagnostic.psiElement
|
||||
if (PsiTreeUtil.getParentOfType(
|
||||
diagElement,
|
||||
javaClass<KtTypeReference>(), javaClass<KtAnnotationEntry>(), javaClass<KtImportDirective>()
|
||||
KtTypeReference::class.java, KtAnnotationEntry::class.java, KtImportDirective::class.java
|
||||
) != null) return null
|
||||
|
||||
return when (diagnostic.factory) {
|
||||
@@ -108,9 +108,9 @@ sealed class CreateCallableFromCallActionFactory<E : KtExpression>(
|
||||
}
|
||||
|
||||
private fun getReceiverTypeInfo(context: BindingContext, project: Project, receiver: Receiver?): TypeInfo? {
|
||||
return when {
|
||||
receiver == null -> TypeInfo.Empty
|
||||
receiver is Qualifier -> {
|
||||
return when (receiver) {
|
||||
null -> TypeInfo.Empty
|
||||
is Qualifier -> {
|
||||
val qualifierType = context.getType(receiver.expression)
|
||||
if (qualifierType != null) return TypeInfo(qualifierType, Variance.IN_VARIANCE)
|
||||
|
||||
@@ -123,7 +123,7 @@ sealed class CreateCallableFromCallActionFactory<E : KtExpression>(
|
||||
if (javaClass == null || !javaClass.canRefactor()) return null
|
||||
TypeInfo.StaticContextRequired(TypeInfo(javaClassifier.defaultType, Variance.IN_VARIANCE))
|
||||
}
|
||||
receiver is ReceiverValue -> TypeInfo(receiver.type, Variance.IN_VARIANCE)
|
||||
is ReceiverValue -> TypeInfo(receiver.type, Variance.IN_VARIANCE)
|
||||
else -> throw AssertionError("Unexpected receiver: $receiver")
|
||||
}
|
||||
}
|
||||
|
||||
+4
-4
@@ -52,12 +52,12 @@ public abstract class CreateCallableFromUsageFixBase<E : KtElement>(
|
||||
) : CreateFromUsageFixBase<E>(originalExpression) {
|
||||
init {
|
||||
assert (callableInfos.isNotEmpty()) { "No CallableInfos: ${originalExpression.getElementTextWithContext()}" }
|
||||
if (callableInfos.size() > 1) {
|
||||
if (callableInfos.size > 1) {
|
||||
val receiverSet = callableInfos.mapTo(HashSet<TypeInfo>()) { it.receiverTypeInfo }
|
||||
if (receiverSet.size() > 1) throw AssertionError("All functions must have common receiver: $receiverSet")
|
||||
if (receiverSet.size > 1) throw AssertionError("All functions must have common receiver: $receiverSet")
|
||||
|
||||
val possibleContainerSet = callableInfos.mapTo(HashSet<List<KtElement>>()) { it.possibleContainers }
|
||||
if (possibleContainerSet.size() > 1) throw AssertionError("All functions must have common containers: $possibleContainerSet")
|
||||
if (possibleContainerSet.size > 1) throw AssertionError("All functions must have common containers: $possibleContainerSet")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,7 +88,7 @@ public abstract class CreateCallableFromUsageFixBase<E : KtElement>(
|
||||
if (it.name.isNotEmpty()) "$kind '${it.name}'" else kind
|
||||
}
|
||||
|
||||
return StringBuilder {
|
||||
return StringBuilder().apply {
|
||||
append("Create ")
|
||||
|
||||
val receiverInfo = callableInfos.first().receiverTypeInfo
|
||||
|
||||
+2
-2
@@ -30,8 +30,8 @@ import org.jetbrains.kotlin.types.Variance
|
||||
|
||||
object CreateComponentFunctionActionFactory : CreateCallableMemberFromUsageFactory<KtDestructuringDeclaration>() {
|
||||
override fun getElementOfInterest(diagnostic: Diagnostic): KtDestructuringDeclaration? {
|
||||
QuickFixUtil.getParentElementOfType(diagnostic, javaClass<KtDestructuringDeclaration>())?.let { return it }
|
||||
return QuickFixUtil.getParentElementOfType(diagnostic, javaClass<KtForExpression>())?.destructuringParameter
|
||||
QuickFixUtil.getParentElementOfType(diagnostic, KtDestructuringDeclaration::class.java)?.let { return it }
|
||||
return QuickFixUtil.getParentElementOfType(diagnostic, KtForExpression::class.java)?.destructuringParameter
|
||||
}
|
||||
|
||||
override fun createCallableInfo(element: KtDestructuringDeclaration, diagnostic: Diagnostic): CallableInfo? {
|
||||
|
||||
+1
-2
@@ -17,17 +17,16 @@
|
||||
package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable
|
||||
|
||||
import com.intellij.psi.PsiClass
|
||||
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
|
||||
import org.jetbrains.kotlin.descriptors.ClassDescriptor
|
||||
import org.jetbrains.kotlin.descriptors.ClassKind
|
||||
import org.jetbrains.kotlin.diagnostics.Diagnostic
|
||||
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptor
|
||||
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
|
||||
import org.jetbrains.kotlin.idea.refactoring.canRefactor
|
||||
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.CallableInfo
|
||||
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.ParameterInfo
|
||||
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.SecondaryConstructorInfo
|
||||
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo
|
||||
import org.jetbrains.kotlin.idea.refactoring.canRefactor
|
||||
import org.jetbrains.kotlin.psi.KtClass
|
||||
import org.jetbrains.kotlin.psi.KtConstructorDelegationCall
|
||||
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
|
||||
|
||||
+1
-1
@@ -28,7 +28,7 @@ import java.util.Collections
|
||||
|
||||
object CreateGetFunctionActionFactory : CreateCallableMemberFromUsageFactory<KtArrayAccessExpression>() {
|
||||
override fun getElementOfInterest(diagnostic: Diagnostic): KtArrayAccessExpression? {
|
||||
return QuickFixUtil.getParentElementOfType(diagnostic, javaClass<KtArrayAccessExpression>())
|
||||
return QuickFixUtil.getParentElementOfType(diagnostic, KtArrayAccessExpression::class.java)
|
||||
}
|
||||
|
||||
override fun createCallableInfo(element: KtArrayAccessExpression, diagnostic: Diagnostic): CallableInfo? {
|
||||
|
||||
+1
-1
@@ -30,7 +30,7 @@ import org.jetbrains.kotlin.util.OperatorNameConventions
|
||||
|
||||
object CreateHasNextFunctionActionFactory : CreateCallableMemberFromUsageFactory<KtForExpression>() {
|
||||
override fun getElementOfInterest(diagnostic: Diagnostic): KtForExpression? {
|
||||
return QuickFixUtil.getParentElementOfType(diagnostic, javaClass<KtForExpression>())
|
||||
return QuickFixUtil.getParentElementOfType(diagnostic, KtForExpression::class.java)
|
||||
}
|
||||
|
||||
override fun createCallableInfo(element: KtForExpression, diagnostic: Diagnostic): CallableInfo? {
|
||||
|
||||
+2
-3
@@ -16,7 +16,6 @@
|
||||
|
||||
package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable
|
||||
|
||||
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
|
||||
import org.jetbrains.kotlin.diagnostics.Diagnostic
|
||||
import org.jetbrains.kotlin.idea.caches.resolve.analyzeFullyAndGetResult
|
||||
import org.jetbrains.kotlin.idea.core.quickfix.QuickFixUtil
|
||||
@@ -35,7 +34,7 @@ import java.util.*
|
||||
|
||||
object CreateIteratorFunctionActionFactory : CreateCallableMemberFromUsageFactory<KtForExpression>() {
|
||||
override fun getElementOfInterest(diagnostic: Diagnostic): KtForExpression? {
|
||||
return QuickFixUtil.getParentElementOfType(diagnostic, javaClass<KtForExpression>())
|
||||
return QuickFixUtil.getParentElementOfType(diagnostic, KtForExpression::class.java)
|
||||
}
|
||||
|
||||
override fun createCallableInfo(element: KtForExpression, diagnostic: Diagnostic): CallableInfo? {
|
||||
@@ -48,7 +47,7 @@ object CreateIteratorFunctionActionFactory : CreateCallableMemberFromUsageFactor
|
||||
|
||||
val returnJetType = moduleDescriptor.builtIns.iterator.defaultType
|
||||
val returnJetTypeParameterTypes = variableExpr.guessTypes(bindingContext, moduleDescriptor)
|
||||
if (returnJetTypeParameterTypes.size() != 1) return null
|
||||
if (returnJetTypeParameterTypes.size != 1) return null
|
||||
|
||||
val returnJetTypeParameterType = TypeProjectionImpl(returnJetTypeParameterTypes[0])
|
||||
val returnJetTypeArguments = Collections.singletonList(returnJetTypeParameterType)
|
||||
|
||||
+1
-1
@@ -30,7 +30,7 @@ import org.jetbrains.kotlin.util.OperatorNameConventions
|
||||
|
||||
object CreateNextFunctionActionFactory : CreateCallableMemberFromUsageFactory<KtForExpression>() {
|
||||
override fun getElementOfInterest(diagnostic: Diagnostic): KtForExpression? {
|
||||
return QuickFixUtil.getParentElementOfType(diagnostic, javaClass<KtForExpression>())
|
||||
return QuickFixUtil.getParentElementOfType(diagnostic, KtForExpression::class.java)
|
||||
}
|
||||
|
||||
override fun createCallableInfo(element: KtForExpression, diagnostic: Diagnostic): CallableInfo? {
|
||||
|
||||
+2
-2
@@ -36,7 +36,7 @@ import java.util.*
|
||||
|
||||
object CreateSetFunctionActionFactory : CreateCallableMemberFromUsageFactory<KtArrayAccessExpression>() {
|
||||
override fun getElementOfInterest(diagnostic: Diagnostic): KtArrayAccessExpression? {
|
||||
return QuickFixUtil.getParentElementOfType(diagnostic, javaClass<KtArrayAccessExpression>())
|
||||
return QuickFixUtil.getParentElementOfType(diagnostic, KtArrayAccessExpression::class.java)
|
||||
}
|
||||
|
||||
override fun createCallableInfo(element: KtArrayAccessExpression, diagnostic: Diagnostic): CallableInfo? {
|
||||
@@ -48,7 +48,7 @@ object CreateSetFunctionActionFactory : CreateCallableMemberFromUsageFactory<KtA
|
||||
val parameters = element.indexExpressions.mapTo(ArrayList<ParameterInfo>()) {
|
||||
ParameterInfo(TypeInfo(it, Variance.IN_VARIANCE))
|
||||
}
|
||||
val assignmentExpr = QuickFixUtil.getParentElementOfType(diagnostic, javaClass<KtOperationExpression>()) ?: return null
|
||||
val assignmentExpr = QuickFixUtil.getParentElementOfType(diagnostic, KtOperationExpression::class.java) ?: return null
|
||||
val valType = when (assignmentExpr) {
|
||||
is KtBinaryExpression -> {
|
||||
TypeInfo(assignmentExpr.right ?: return null, Variance.IN_VARIANCE)
|
||||
|
||||
+3
-3
@@ -34,8 +34,8 @@ public object CreateClassFromCallWithConstructorCalleeActionFactory : CreateClas
|
||||
|
||||
val callElement = PsiTreeUtil.getParentOfType(
|
||||
diagElement,
|
||||
javaClass<KtAnnotationEntry>(),
|
||||
javaClass<KtSuperTypeCallEntry>()
|
||||
KtAnnotationEntry::class.java,
|
||||
KtSuperTypeCallEntry::class.java
|
||||
) as? KtCallElement ?: return null
|
||||
|
||||
val callee = callElement.calleeExpression as? KtConstructorCalleeExpression ?: return null
|
||||
@@ -66,7 +66,7 @@ public object CreateClassFromCallWithConstructorCalleeActionFactory : CreateClas
|
||||
|
||||
val anyType = module.builtIns.nullableAnyType
|
||||
val valueArguments = element.valueArguments
|
||||
val defaultParamName = if (valueArguments.size() == 1) "value" else null
|
||||
val defaultParamName = if (valueArguments.size == 1) "value" else null
|
||||
val parameterInfos = valueArguments.map {
|
||||
ParameterInfo(
|
||||
it.getArgumentExpression()?.let { TypeInfo(it, Variance.IN_VARIANCE) } ?: TypeInfo(anyType, Variance.IN_VARIANCE),
|
||||
|
||||
+2
-3
@@ -16,7 +16,6 @@
|
||||
|
||||
package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass
|
||||
|
||||
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
|
||||
import org.jetbrains.kotlin.diagnostics.Diagnostic
|
||||
import org.jetbrains.kotlin.idea.caches.resolve.analyzeFullyAndGetResult
|
||||
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.ParameterInfo
|
||||
@@ -28,7 +27,7 @@ import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis
|
||||
import org.jetbrains.kotlin.resolve.calls.callUtil.getCall
|
||||
import org.jetbrains.kotlin.types.Variance
|
||||
import org.jetbrains.kotlin.utils.addToStdlib.singletonList
|
||||
import java.util.Collections
|
||||
import java.util.*
|
||||
|
||||
public object CreateClassFromConstructorCallActionFactory: CreateClassFromUsageFactory<KtCallExpression>() {
|
||||
override fun getElementOfInterest(diagnostic: Diagnostic): KtCallExpression? {
|
||||
@@ -81,7 +80,7 @@ public object CreateClassFromConstructorCallActionFactory: CreateClassFromUsageF
|
||||
val inner = isInnerClassExpected(call)
|
||||
|
||||
val valueArguments = callExpr.valueArguments
|
||||
val defaultParamName = if (inAnnotationEntry && valueArguments.size() == 1) "value" else null
|
||||
val defaultParamName = if (inAnnotationEntry && valueArguments.size == 1) "value" else null
|
||||
val anyType = moduleDescriptor.builtIns.nullableAnyType
|
||||
val parameterInfos = valueArguments.map {
|
||||
ParameterInfo(
|
||||
|
||||
+3
-5
@@ -16,23 +16,21 @@
|
||||
|
||||
package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass
|
||||
|
||||
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
|
||||
import org.jetbrains.kotlin.diagnostics.Diagnostic
|
||||
import org.jetbrains.kotlin.idea.caches.resolve.analyze
|
||||
import org.jetbrains.kotlin.idea.caches.resolve.analyzeAndGetResult
|
||||
import org.jetbrains.kotlin.idea.core.quickfix.QuickFixUtil
|
||||
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo
|
||||
import org.jetbrains.kotlin.psi.KtConstructorCalleeExpression
|
||||
import org.jetbrains.kotlin.psi.KtSuperTypeEntry
|
||||
import org.jetbrains.kotlin.psi.KtFile
|
||||
import org.jetbrains.kotlin.psi.KtSuperTypeEntry
|
||||
import org.jetbrains.kotlin.psi.KtUserType
|
||||
import org.jetbrains.kotlin.resolve.BindingContext
|
||||
import org.jetbrains.kotlin.types.Variance
|
||||
import java.util.Collections
|
||||
import java.util.*
|
||||
|
||||
public object CreateClassFromTypeReferenceActionFactory : CreateClassFromUsageFactory<KtUserType>() {
|
||||
override fun getElementOfInterest(diagnostic: Diagnostic): KtUserType? {
|
||||
return QuickFixUtil.getParentElementOfType(diagnostic, javaClass<KtUserType>())
|
||||
return QuickFixUtil.getParentElementOfType(diagnostic, KtUserType::class.java)
|
||||
}
|
||||
|
||||
override fun getPossibleClassKinds(element: KtUserType, diagnostic: Diagnostic): List<ClassKind> {
|
||||
|
||||
+1
-1
@@ -87,7 +87,7 @@ public class CreateClassFromUsageFix<E : KtElement>(
|
||||
directories.firstOrNull { ModuleUtilCore.findModuleForPsiElement(it) == currentModule }
|
||||
?: directories.firstOrNull()
|
||||
|
||||
val targetDirectory = if (directories.size() > 1 && !ApplicationManager.getApplication().isUnitTestMode) {
|
||||
val targetDirectory = if (directories.size > 1 && !ApplicationManager.getApplication().isUnitTestMode) {
|
||||
DirectoryChooserUtil.chooseDirectory(directories.toTypedArray(), preferredDirectory, project, HashMap())
|
||||
}
|
||||
else {
|
||||
|
||||
+21
-20
@@ -51,44 +51,44 @@ internal fun getTargetParentByQualifier(
|
||||
file: KtFile,
|
||||
isQualified: Boolean,
|
||||
qualifierDescriptor: DeclarationDescriptor?): PsiElement? {
|
||||
val project = file.getProject()
|
||||
val targetParent: PsiElement = when {
|
||||
val project = file.project
|
||||
val targetParent: PsiElement? = when {
|
||||
!isQualified ->
|
||||
file
|
||||
qualifierDescriptor is ClassDescriptor ->
|
||||
DescriptorToSourceUtilsIde.getAnyDeclaration(project, qualifierDescriptor)
|
||||
qualifierDescriptor is PackageViewDescriptor ->
|
||||
if (qualifierDescriptor.fqName != file.getPackageFqName()) {
|
||||
if (qualifierDescriptor.fqName != file.packageFqName) {
|
||||
JavaPsiFacade.getInstance(project).findPackage(qualifierDescriptor.fqName.asString())
|
||||
}
|
||||
else file as PsiElement // KT-9972
|
||||
else file // KT-9972
|
||||
else ->
|
||||
null
|
||||
} ?: return null
|
||||
return if (targetParent.canRefactor()) return targetParent else null
|
||||
}
|
||||
return if (targetParent?.canRefactor() ?: false) return targetParent else null
|
||||
}
|
||||
|
||||
internal fun getTargetParentByCall(call: Call, file: KtFile, context: BindingContext): PsiElement? {
|
||||
val receiver = call.getExplicitReceiver()
|
||||
val receiver = call.explicitReceiver
|
||||
return when (receiver) {
|
||||
null -> getTargetParentByQualifier(file, false, null)
|
||||
is Qualifier -> getTargetParentByQualifier(file, true, context[BindingContext.REFERENCE_TARGET, receiver.referenceExpression])
|
||||
is ReceiverValue -> getTargetParentByQualifier(file, true, receiver.getType().getConstructor().getDeclarationDescriptor())
|
||||
is ReceiverValue -> getTargetParentByQualifier(file, true, receiver.type.constructor.declarationDescriptor)
|
||||
else -> throw AssertionError("Unexpected receiver: $receiver")
|
||||
}
|
||||
}
|
||||
|
||||
internal fun isInnerClassExpected(call: Call) = call.getExplicitReceiver() is ReceiverValue
|
||||
internal fun isInnerClassExpected(call: Call) = call.explicitReceiver is ReceiverValue
|
||||
|
||||
internal fun KtExpression.getInheritableTypeInfo(
|
||||
context: BindingContext,
|
||||
moduleDescriptor: ModuleDescriptor,
|
||||
containingDeclaration: PsiElement): Pair<TypeInfo, (ClassKind) -> Boolean> {
|
||||
val types = guessTypes(context, moduleDescriptor, coerceUnusedToUnit = false)
|
||||
if (types.size() != 1) return TypeInfo.Empty to { classKind -> true }
|
||||
if (types.size != 1) return TypeInfo.Empty to { classKind -> true }
|
||||
|
||||
val type = types.first()
|
||||
val descriptor = type.getConstructor().getDeclarationDescriptor() ?: return TypeInfo.Empty to { classKind -> false }
|
||||
val descriptor = type.constructor.declarationDescriptor ?: return TypeInfo.Empty to { classKind -> false }
|
||||
|
||||
val canHaveSubtypes = !(type.constructor.isFinal || type.containsStarProjections())
|
||||
val isEnum = DescriptorUtils.isEnumClass(descriptor)
|
||||
@@ -100,7 +100,7 @@ internal fun KtExpression.getInheritableTypeInfo(
|
||||
when (classKind) {
|
||||
ClassKind.ENUM_ENTRY -> isEnum && containingDeclaration == DescriptorToSourceUtils.descriptorToDeclaration(descriptor)
|
||||
ClassKind.INTERFACE -> containingDeclaration !is PsiClass
|
||||
|| (descriptor as? ClassDescriptor)?.getKind() == ClassDescriptorKind.INTERFACE
|
||||
|| (descriptor as? ClassDescriptor)?.kind == ClassDescriptorKind.INTERFACE
|
||||
else -> canHaveSubtypes
|
||||
}
|
||||
}
|
||||
@@ -110,21 +110,22 @@ internal fun KtSimpleNameExpression.getCreatePackageFixIfApplicable(targetParent
|
||||
val name = getReferencedName()
|
||||
if (!name.checkPackageName()) return null
|
||||
|
||||
val basePackage: PsiPackage? = when (targetParent) {
|
||||
is KtFile -> JavaPsiFacade.getInstance(targetParent.getProject()).findPackage(targetParent.getPackageFqName().asString())
|
||||
is PsiPackage -> targetParent
|
||||
else -> null
|
||||
}
|
||||
val basePackage: PsiPackage? =
|
||||
when (targetParent) {
|
||||
is KtFile -> JavaPsiFacade.getInstance(targetParent.project).findPackage(targetParent.packageFqName.asString())
|
||||
is PsiPackage -> targetParent
|
||||
else -> null
|
||||
}
|
||||
if (basePackage == null) return null
|
||||
|
||||
val baseName = basePackage.getQualifiedName()
|
||||
val baseName = basePackage.qualifiedName
|
||||
val fullName = if (baseName.isNotEmpty()) "$baseName.$name" else name
|
||||
|
||||
val javaFix = CreateClassOrPackageFix.createFix(fullName, getResolveScope(), this, basePackage, null, null, null) ?: return null
|
||||
val javaFix = CreateClassOrPackageFix.createFix(fullName, resolveScope, this, basePackage, null, null, null) ?: return null
|
||||
|
||||
return object: DelegatingIntentionAction(javaFix) {
|
||||
override fun getFamilyName(): String = KotlinBundle.message("create.from.usage.family")
|
||||
|
||||
override fun getText(): String = "Create package '${fullName}'"
|
||||
override fun getText(): String = "Create package '$fullName'"
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -38,7 +38,7 @@ import java.util.*
|
||||
|
||||
object CreateLocalVariableActionFactory: KotlinSingleIntentionActionFactory() {
|
||||
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
|
||||
val refExpr = QuickFixUtil.getParentElementOfType(diagnostic, javaClass<KtNameReferenceExpression>()) ?: return null
|
||||
val refExpr = QuickFixUtil.getParentElementOfType(diagnostic, KtNameReferenceExpression::class.java) ?: return null
|
||||
if (refExpr.getQualifiedElement() != refExpr) return null
|
||||
if (refExpr.getParentOfTypeAndBranch<KtCallableReferenceExpression> { callableReference } != null) return null
|
||||
|
||||
|
||||
+2
-2
@@ -32,7 +32,7 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
|
||||
|
||||
public object CreateParameterByNamedArgumentActionFactory: CreateParameterFromUsageFactory<KtValueArgument>() {
|
||||
override fun getElementOfInterest(diagnostic: Diagnostic): KtValueArgument? {
|
||||
val argument = QuickFixUtil.getParentElementOfType(diagnostic, javaClass<KtValueArgument>()) ?: return null
|
||||
val argument = QuickFixUtil.getParentElementOfType(diagnostic, KtValueArgument::class.java) ?: return null
|
||||
return if (argument.isNamed()) argument else null
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ public object CreateParameterByNamedArgumentActionFactory: CreateParameterFromUs
|
||||
|
||||
val anyType = functionDescriptor.builtIns.anyType
|
||||
val paramType = argumentExpression?.guessTypes(context, result.moduleDescriptor)?.let {
|
||||
when (it.size()) {
|
||||
when (it.size) {
|
||||
0 -> anyType
|
||||
1 -> it.first()
|
||||
else -> return null
|
||||
|
||||
+2
-2
@@ -44,7 +44,7 @@ import java.util.*
|
||||
|
||||
object CreateParameterByRefActionFactory : CreateParameterFromUsageFactory<KtSimpleNameExpression>() {
|
||||
override fun getElementOfInterest(diagnostic: Diagnostic): KtSimpleNameExpression? {
|
||||
val refExpr = QuickFixUtil.getParentElementOfType(diagnostic, javaClass<KtNameReferenceExpression>()) ?: return null
|
||||
val refExpr = QuickFixUtil.getParentElementOfType(diagnostic, KtNameReferenceExpression::class.java) ?: return null
|
||||
if (refExpr.getQualifiedElement() != refExpr) return null
|
||||
if (refExpr.getParentOfTypeAndBranch<KtCallableReferenceExpression> { callableReference } != null) return null
|
||||
return refExpr
|
||||
@@ -58,7 +58,7 @@ object CreateParameterByRefActionFactory : CreateParameterFromUsageFactory<KtSim
|
||||
val varExpected = element.getAssignmentByLHS() != null
|
||||
|
||||
val paramType = element.getExpressionForTypeGuess().guessTypes(context, moduleDescriptor).let {
|
||||
when (it.size()) {
|
||||
when (it.size) {
|
||||
0 -> moduleDescriptor.builtIns.anyType
|
||||
1 -> it.first()
|
||||
else -> return null
|
||||
|
||||
@@ -27,7 +27,7 @@ import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
|
||||
|
||||
inline fun <reified T : PsiElement> Diagnostic.createIntentionForFirstParentOfType(
|
||||
factory: (T) -> KotlinQuickFixAction<T>?
|
||||
) = getPsiElement().getNonStrictParentOfType<T>()?.let(factory)
|
||||
) = psiElement.getNonStrictParentOfType<T>()?.let(factory)
|
||||
|
||||
|
||||
fun createIntentionFactory(
|
||||
@@ -38,5 +38,5 @@ fun createIntentionFactory(
|
||||
|
||||
public fun KtPrimaryConstructor.addConstructorKeyword(): PsiElement? {
|
||||
val keyword = KtPsiFactory(this).createConstructorKeyword()
|
||||
return addAfter(keyword, getModifierList() ?: return null)
|
||||
return addAfter(keyword, modifierList ?: return null)
|
||||
}
|
||||
|
||||
+2
-2
@@ -208,7 +208,7 @@ private fun ConstructedExpressionWrapper.processValueParameterUsages(
|
||||
|
||||
//TODO: sometimes we need to add explicit type arguments here because we don't have expected type in the new context
|
||||
|
||||
if (argument.expression.shouldKeepValue(usages.size())) {
|
||||
if (argument.expression.shouldKeepValue(usages.size)) {
|
||||
introduceValuesForParameters.add(IntroduceValueForParameter(parameter, argument.expression, argument.expressionType))
|
||||
}
|
||||
}
|
||||
@@ -227,7 +227,7 @@ private fun ConstructedExpressionWrapper.processTypeParameterUsages(resolvedCall
|
||||
val callElement = resolvedCall.call.callElement
|
||||
val callExpression = callElement as? KtCallExpression
|
||||
val explicitTypeArgs = callExpression?.typeArgumentList?.arguments
|
||||
if (explicitTypeArgs != null && explicitTypeArgs.size() != typeParameters.size()) return
|
||||
if (explicitTypeArgs != null && explicitTypeArgs.size != typeParameters.size) return
|
||||
|
||||
for ((index, typeParameter) in typeParameters.withIndex()) {
|
||||
val parameterName = typeParameter.name
|
||||
|
||||
+1
-1
@@ -100,7 +100,7 @@ public class DeprecatedSymbolUsageInWholeProjectFix(
|
||||
//TODO: keep the import if we don't know how to replace some of the usages
|
||||
val importDirective = usage.getStrictParentOfType<KtImportDirective>()
|
||||
if (importDirective != null) {
|
||||
if (!importDirective.isAllUnder && importDirective.targetDescriptors().size() == 1) {
|
||||
if (!importDirective.isAllUnder && importDirective.targetDescriptors().size == 1) {
|
||||
importsToDelete.add(importDirective)
|
||||
}
|
||||
continue
|
||||
|
||||
Reference in New Issue
Block a user