diff --git a/java-analysis-api/src/main/java/com/intellij/java/analysis/codeInsight/intention/QuickFixFactory.java b/java-analysis-api/src/main/java/com/intellij/java/analysis/codeInsight/intention/QuickFixFactory.java index d266a3343..657a28042 100644 --- a/java-analysis-api/src/main/java/com/intellij/java/analysis/codeInsight/intention/QuickFixFactory.java +++ b/java-analysis-api/src/main/java/com/intellij/java/analysis/codeInsight/intention/QuickFixFactory.java @@ -508,7 +508,7 @@ public abstract LocalQuickFixAndIntentionActionOnPsiElement createAccessStaticVi public abstract IntentionAction createAddMissingEnumBranchesFix(@Nonnull PsiSwitchBlock switchBlock, @Nonnull Set missingCases); @Nonnull - public abstract IntentionAction createAddSwitchDefaultFix(@Nonnull PsiSwitchBlock switchBlock, @Nullable String message); + public abstract IntentionAction createAddSwitchDefaultFix(@Nonnull PsiSwitchBlock switchBlock, @Nonnull LocalizeValue message); @Nonnull public abstract IntentionAction createWrapSwitchRuleStatementsIntoBlockFix(PsiSwitchLabeledRuleStatement rule); diff --git a/java-analysis-impl/src/main/java/com/intellij/java/analysis/impl/codeInsight/daemon/impl/analysis/HighlightUtil.java b/java-analysis-impl/src/main/java/com/intellij/java/analysis/impl/codeInsight/daemon/impl/analysis/HighlightUtil.java index 7173dbf7b..64beb9e14 100644 --- a/java-analysis-impl/src/main/java/com/intellij/java/analysis/impl/codeInsight/daemon/impl/analysis/HighlightUtil.java +++ b/java-analysis-impl/src/main/java/com/intellij/java/analysis/impl/codeInsight/daemon/impl/analysis/HighlightUtil.java @@ -2532,7 +2532,7 @@ public static Collection checkSwitchLabelValues(@Nonnull PsiSwitc if (!missingConstants.isEmpty()) { hlBuilder.registerFix(factory.createAddMissingEnumBranchesFix(switchBlock, missingConstants)); } - hlBuilder.registerFix(factory.createAddSwitchDefaultFix(switchBlock, null)); + hlBuilder.registerFix(factory.createAddSwitchDefaultFix(switchBlock, LocalizeValue.empty())); results.add(hlBuilder.create()); } } diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInsight/daemon/impl/quickfix/OptimizeImportsFix.java b/plugin/src/main/java/com/intellij/java/impl/codeInsight/daemon/impl/quickfix/OptimizeImportsFix.java index 3bf704fa9..ddbbd02f5 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInsight/daemon/impl/quickfix/OptimizeImportsFix.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInsight/daemon/impl/quickfix/OptimizeImportsFix.java @@ -18,45 +18,50 @@ import com.intellij.java.language.psi.PsiJavaFile; import com.intellij.java.language.psi.codeStyle.JavaCodeStyleManager; import consulo.codeEditor.Editor; -import consulo.java.analysis.impl.JavaQuickFixBundle; +import consulo.java.analysis.impl.localize.JavaQuickFixLocalize; import consulo.language.editor.FileModificationService; import consulo.language.editor.intention.SyntheticIntentionAction; import consulo.language.psi.PsiFile; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.logging.Logger; import consulo.project.Project; import jakarta.annotation.Nonnull; public class OptimizeImportsFix implements SyntheticIntentionAction { - private static final Logger LOG = Logger.getInstance(OptimizeImportsFix.class); - - @Override - @Nonnull - public String getText() { - return JavaQuickFixBundle.message("optimize.imports.fix"); - } - - @Override - public boolean isAvailable(@Nonnull Project project, Editor editor, PsiFile file) { - return file.getManager().isInProject(file) && file instanceof PsiJavaFile; - } - - @Override - public void invoke(@Nonnull Project project, Editor editor, PsiFile file) { - if (!(file instanceof PsiJavaFile)) return; - if (!FileModificationService.getInstance().prepareFileForWrite(file)) return; - - try { - JavaCodeStyleManager.getInstance(project).optimizeImports(file); + private static final Logger LOG = Logger.getInstance(OptimizeImportsFix.class); + + @Nonnull + @Override + public LocalizeValue getText() { + return JavaQuickFixLocalize.optimizeImportsFix(); + } + + @Override + public boolean isAvailable(@Nonnull Project project, Editor editor, PsiFile file) { + return file.getManager().isInProject(file) && file instanceof PsiJavaFile; } - catch (IncorrectOperationException e) { - LOG.error(e); + + @Override + public void invoke(@Nonnull Project project, Editor editor, PsiFile file) { + if (!(file instanceof PsiJavaFile)) { + return; + } + if (!FileModificationService.getInstance().prepareFileForWrite(file)) { + return; + } + + try { + JavaCodeStyleManager.getInstance(project).optimizeImports(file); + } + catch (IncorrectOperationException e) { + LOG.error(e); + } } - } - @Override - public boolean startInWriteAction() { - return true; - } + @Override + public boolean startInWriteAction() { + return true; + } } diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInsight/intention/impl/config/QuickFixFactoryImpl.java b/plugin/src/main/java/com/intellij/java/impl/codeInsight/intention/impl/config/QuickFixFactoryImpl.java index 62c204f01..6ed33a356 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInsight/intention/impl/config/QuickFixFactoryImpl.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInsight/intention/impl/config/QuickFixFactoryImpl.java @@ -761,7 +761,7 @@ public IntentionAction createOptimizeImportsFix(final boolean onTheFly) { return new SyntheticIntentionAction() { @Nonnull @Override - public String getText() { + public LocalizeValue getText() { return fix.getText(); } @@ -855,7 +855,7 @@ public LocalQuickFixAndIntentionActionOnPsiElement createDeleteFix(@Nonnull PsiE @Nonnull public LocalQuickFixAndIntentionActionOnPsiElement createDeleteFix(@Nonnull PsiElement element, @Nonnull LocalizeValue text) { - return new DeleteElementFix(element, text.get()); + return new DeleteElementFix(element, text); } @Nonnull @@ -1042,7 +1042,7 @@ public IntentionAction createAddMissingEnumBranchesFix(@Nonnull PsiSwitchBlock s @Nonnull @Override - public IntentionAction createAddSwitchDefaultFix(@Nonnull PsiSwitchBlock switchBlock, @Nullable String message) { + public IntentionAction createAddSwitchDefaultFix(@Nonnull PsiSwitchBlock switchBlock, @Nonnull LocalizeValue message) { return new CreateDefaultBranchFix(switchBlock, message); } diff --git a/plugin/src/main/java/com/intellij/java/impl/codeInspection/inheritance/ChangeSuperClassFix.java b/plugin/src/main/java/com/intellij/java/impl/codeInspection/inheritance/ChangeSuperClassFix.java index 883825fa1..1be24e637 100644 --- a/plugin/src/main/java/com/intellij/java/impl/codeInspection/inheritance/ChangeSuperClassFix.java +++ b/plugin/src/main/java/com/intellij/java/impl/codeInspection/inheritance/ChangeSuperClassFix.java @@ -21,110 +21,107 @@ import consulo.language.editor.WriteCommandAction; import consulo.language.editor.inspection.LocalQuickFix; import consulo.language.editor.inspection.ProblemDescriptor; -import consulo.language.editor.inspection.localize.InspectionLocalize; import consulo.language.editor.intention.LowPriorityAction; import consulo.language.psi.PsiElement; +import consulo.localize.LocalizeValue; import consulo.project.Project; -import org.jetbrains.annotations.TestOnly; - import jakarta.annotation.Nonnull; +import org.jetbrains.annotations.TestOnly; /** * @author Dmitry Batkovich */ public class ChangeSuperClassFix implements LocalQuickFix { - @Nonnull - private final PsiClass myNewSuperClass; - @Nonnull - private final PsiClass myOldSuperClass; - private final int myPercent; + @Nonnull + private final PsiClass myNewSuperClass; + @Nonnull + private final PsiClass myOldSuperClass; + private final int myPercent; - public ChangeSuperClassFix(@Nonnull final PsiClass newSuperClass, final int percent, @Nonnull final PsiClass oldSuperClass) { - myNewSuperClass = newSuperClass; - myOldSuperClass = oldSuperClass; - myPercent = percent; - } + public ChangeSuperClassFix(@Nonnull final PsiClass newSuperClass, final int percent, @Nonnull final PsiClass oldSuperClass) { + myNewSuperClass = newSuperClass; + myOldSuperClass = oldSuperClass; + myPercent = percent; + } - @Nonnull - @TestOnly - public PsiClass getNewSuperClass() { - return myNewSuperClass; - } + @Nonnull + @TestOnly + public PsiClass getNewSuperClass() { + return myNewSuperClass; + } - @TestOnly - public int getPercent() { - return myPercent; - } + @TestOnly + public int getPercent() { + return myPercent; + } - @Nonnull - @Override - public String getName() { - return String.format("Make extends '%s' - %s%%", myNewSuperClass.getQualifiedName(), myPercent); - } + @Nonnull + @Override + public LocalizeValue getName() { + return LocalizeValue.localizeTODO(String.format("Make extends '%s' - %s%%", myNewSuperClass.getQualifiedName(), myPercent)); + } - @Nonnull - @Override - public String getFamilyName() { - return InspectionLocalize.groupNamesInheritanceIssues().get(); - } + @Override + public void applyFix(@Nonnull final Project project, @Nonnull final ProblemDescriptor problemDescriptor) { + changeSuperClass((PsiClass) problemDescriptor.getPsiElement(), myOldSuperClass, myNewSuperClass); + } - @Override - public void applyFix(@Nonnull final Project project, @Nonnull final ProblemDescriptor problemDescriptor) { - changeSuperClass((PsiClass)problemDescriptor.getPsiElement(), myOldSuperClass, myNewSuperClass); - } + /** + * myOldSuperClass and myNewSuperClass can be interfaces or classes in any combination + *

+ * 1. not checks that myOldSuperClass is really super of aClass + * 2. not checks that myNewSuperClass not exists in currently existed supers + */ + private static void changeSuperClass( + @Nonnull final PsiClass aClass, + @Nonnull final PsiClass oldSuperClass, + @Nonnull final PsiClass newSuperClass + ) { + if (!FileModificationService.getInstance().preparePsiElementForWrite(aClass)) { + return; + } - /** - * myOldSuperClass and myNewSuperClass can be interfaces or classes in any combination - *

- * 1. not checks that myOldSuperClass is really super of aClass - * 2. not checks that myNewSuperClass not exists in currently existed supers - */ - private static void changeSuperClass(@Nonnull final PsiClass aClass, - @Nonnull final PsiClass oldSuperClass, - @Nonnull final PsiClass newSuperClass) { - if (!FileModificationService.getInstance().preparePsiElementForWrite(aClass)) return; + new WriteCommandAction.Simple(newSuperClass.getProject(), aClass.getContainingFile()) { + @Override + protected void run() throws Throwable { + PsiElementFactory factory = JavaPsiFacade.getInstance(aClass.getProject()).getElementFactory(); + if (aClass instanceof PsiAnonymousClass) { + ((PsiAnonymousClass) aClass).getBaseClassReference().replace(factory.createClassReferenceElement(newSuperClass)); + } + else if (oldSuperClass.isInterface()) { + final PsiReferenceList interfaceList = aClass.getImplementsList(); + if (interfaceList != null) { + for (final PsiJavaCodeReferenceElement interfaceRef : interfaceList.getReferenceElements()) { + final PsiElement aInterface = interfaceRef.resolve(); + if (aInterface != null && aInterface.isEquivalentTo(oldSuperClass)) { + interfaceRef.delete(); + } + } + } - new WriteCommandAction.Simple(newSuperClass.getProject(), aClass.getContainingFile()) { - @Override - protected void run() throws Throwable { - PsiElementFactory factory = JavaPsiFacade.getInstance(aClass.getProject()).getElementFactory(); - if (aClass instanceof PsiAnonymousClass) { - ((PsiAnonymousClass)aClass).getBaseClassReference().replace(factory.createClassReferenceElement(newSuperClass)); - } - else if (oldSuperClass.isInterface()) { - final PsiReferenceList interfaceList = aClass.getImplementsList(); - if (interfaceList != null) { - for (final PsiJavaCodeReferenceElement interfaceRef : interfaceList.getReferenceElements()) { - final PsiElement aInterface = interfaceRef.resolve(); - if (aInterface != null && aInterface.isEquivalentTo(oldSuperClass)) { - interfaceRef.delete(); - } + final PsiReferenceList extendsList = aClass.getExtendsList(); + if (extendsList != null) { + final PsiJavaCodeReferenceElement newClassReference = factory.createClassReferenceElement(newSuperClass); + if (extendsList.getReferenceElements().length == 0) { + extendsList.add(newClassReference); + } + } + } + else { + final PsiReferenceList extendsList = aClass.getExtendsList(); + if (extendsList != null && extendsList.getReferenceElements().length == 1) { + extendsList.getReferenceElements()[0].delete(); + PsiElement ref = extendsList.add(factory.createClassReferenceElement(newSuperClass)); + JavaCodeStyleManager.getInstance(aClass.getProject()).shortenClassReferences(ref); + } + } } - } + }.execute(); + } - final PsiReferenceList extendsList = aClass.getExtendsList(); - if (extendsList != null) { - final PsiJavaCodeReferenceElement newClassReference = factory.createClassReferenceElement(newSuperClass); - if (extendsList.getReferenceElements().length == 0) { - extendsList.add(newClassReference); - } - } - } - else { - final PsiReferenceList extendsList = aClass.getExtendsList(); - if (extendsList != null && extendsList.getReferenceElements().length == 1) { - extendsList.getReferenceElements()[0].delete(); - PsiElement ref = extendsList.add(factory.createClassReferenceElement(newSuperClass)); - JavaCodeStyleManager.getInstance(aClass.getProject()).shortenClassReferences(ref); - } + public static class LowPriority extends ChangeSuperClassFix implements LowPriorityAction { + public LowPriority(@Nonnull final PsiClass newSuperClass, final int percent, @Nonnull final PsiClass oldSuperClass) { + super(newSuperClass, percent, oldSuperClass); } - } - }.execute(); - } - - public static class LowPriority extends ChangeSuperClassFix implements LowPriorityAction { - public LowPriority(@Nonnull final PsiClass newSuperClass, final int percent, @Nonnull final PsiClass oldSuperClass) { - super(newSuperClass, percent, oldSuperClass); } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/fixes/CreateDefaultBranchFix.java b/plugin/src/main/java/com/intellij/java/impl/ig/fixes/CreateDefaultBranchFix.java index a291ae4b0..37a58544d 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/fixes/CreateDefaultBranchFix.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/fixes/CreateDefaultBranchFix.java @@ -16,131 +16,135 @@ import consulo.language.psi.PsiElement; import consulo.language.psi.util.PsiTreeUtil; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.project.Project; import consulo.util.collection.ArrayUtil; -import org.jetbrains.annotations.Nls; import jakarta.annotation.Nonnull; + import java.io.IOException; import java.util.*; public class CreateDefaultBranchFix extends BaseSwitchFix { - private static final String PLACEHOLDER_NAME = "$EXPRESSION$"; - private final String myMessage; - - public CreateDefaultBranchFix(@Nonnull PsiSwitchBlock block, String message) { - super(block); - myMessage = message; - } - - @Nonnull - @Override - public String getText() { - return myMessage == null ? getName() : myMessage; - } - - @Nls(capitalization = Nls.Capitalization.Sentence) - @Nonnull - @Override - public String getFamilyName() { - return "Insert 'default' branch"; - } + private static final String PLACEHOLDER_NAME = "$EXPRESSION$"; + @Nonnull + private final LocalizeValue myMessage; - @Override - protected void invoke() { - PsiSwitchBlock switchBlock = myBlock.getElement(); - if (switchBlock == null) { - return; - } - PsiCodeBlock body = switchBlock.getBody(); - if (body == null) { - return; - } - if (SwitchUtils.calculateBranchCount(switchBlock) < 0) { - // Default already present for some reason - return; - } - PsiExpression switchExpression = switchBlock.getExpression(); - if (switchExpression == null) { - return; + public CreateDefaultBranchFix(@Nonnull PsiSwitchBlock block, @Nonnull LocalizeValue message) { + super(block); + myMessage = message; } - boolean isRuleBasedFormat = SwitchUtils.isRuleFormatSwitch(switchBlock); - PsiElement anchor = body.getRBrace(); - if (anchor == null) { - return; - } - PsiElement parent = anchor.getParent(); - PsiElementFactory factory = JavaPsiFacade.getElementFactory(anchor.getProject()); - generateStatements(switchBlock, isRuleBasedFormat).stream() - .map(text -> factory.createStatementFromText(text, parent)) - .forEach(statement -> parent.addBefore(statement, anchor)); - adjustEditor(switchBlock); - } - private static void adjustEditor(@Nonnull PsiSwitchBlock block) { - PsiCodeBlock body = block.getBody(); - if (body == null) { - return; + @Nonnull + @Override + public LocalizeValue getText() { + return myMessage == LocalizeValue.empty() ? getName() : myMessage; } - Editor editor = CreateSwitchBranchesUtil.prepareForTemplateAndObtainEditor(block); - if (editor == null) { - return; + + @Nonnull + @Override + public LocalizeValue getName() { + return LocalizeValue.localizeTODO("Insert 'default' branch"); } - PsiStatement lastStatement = ArrayUtil.getLastElement(body.getStatements()); - if (lastStatement instanceof PsiSwitchLabeledRuleStatement) { - lastStatement = ((PsiSwitchLabeledRuleStatement) lastStatement).getBody(); + + @Override + protected void invoke() { + PsiSwitchBlock switchBlock = myBlock.getElement(); + if (switchBlock == null) { + return; + } + PsiCodeBlock body = switchBlock.getBody(); + if (body == null) { + return; + } + if (SwitchUtils.calculateBranchCount(switchBlock) < 0) { + // Default already present for some reason + return; + } + PsiExpression switchExpression = switchBlock.getExpression(); + if (switchExpression == null) { + return; + } + boolean isRuleBasedFormat = SwitchUtils.isRuleFormatSwitch(switchBlock); + PsiElement anchor = body.getRBrace(); + if (anchor == null) { + return; + } + PsiElement parent = anchor.getParent(); + PsiElementFactory factory = JavaPsiFacade.getElementFactory(anchor.getProject()); + generateStatements(switchBlock, isRuleBasedFormat).stream() + .map(text -> factory.createStatementFromText(text, parent)) + .forEach(statement -> parent.addBefore(statement, anchor)); + adjustEditor(switchBlock); } - if (lastStatement != null) { - TemplateBuilder builder = TemplateBuilderFactory.getInstance().createTemplateBuilder(block); - builder.replaceElement(lastStatement, new ConstantNode(lastStatement.getText())); - builder.run(editor, true); + + private static void adjustEditor(@Nonnull PsiSwitchBlock block) { + PsiCodeBlock body = block.getBody(); + if (body == null) { + return; + } + Editor editor = CreateSwitchBranchesUtil.prepareForTemplateAndObtainEditor(block); + if (editor == null) { + return; + } + PsiStatement lastStatement = ArrayUtil.getLastElement(body.getStatements()); + if (lastStatement instanceof PsiSwitchLabeledRuleStatement) { + lastStatement = ((PsiSwitchLabeledRuleStatement) lastStatement).getBody(); + } + if (lastStatement != null) { + TemplateBuilder builder = TemplateBuilderFactory.getInstance().createTemplateBuilder(block); + builder.replaceElement(lastStatement, new ConstantNode(lastStatement.getText())); + builder.run(editor, true); + } } - } - private static final String ATTRIBUTE_EXPRESSION = "EXPRESSION"; - private static final String ATTRIBUTE_EXPRESSION_TYPE = "EXPRESSION_TYPE"; + private static final String ATTRIBUTE_EXPRESSION = "EXPRESSION"; + private static final String ATTRIBUTE_EXPRESSION_TYPE = "EXPRESSION_TYPE"; - private static List generateStatements(PsiSwitchBlock switchBlock, boolean isRuleBasedFormat) { - Project project = switchBlock.getProject(); - FileTemplate branchTemplate = FileTemplateManager.getInstance(project).getCodeTemplate(JavaTemplateUtil.TEMPLATE_SWITCH_DEFAULT_BRANCH); - Properties props = FileTemplateManager.getInstance(project).getDefaultProperties(); - PsiExpression expression = switchBlock.getExpression(); - props.setProperty(ATTRIBUTE_EXPRESSION, PLACEHOLDER_NAME); - PsiType expressionType = expression == null ? null : expression.getType(); - props.setProperty(ATTRIBUTE_EXPRESSION_TYPE, expressionType == null ? "" : expressionType.getCanonicalText()); - PsiStatement statement; - try { - String text = branchTemplate.getText(props); - if (text.trim().isEmpty()) { - if (switchBlock instanceof PsiSwitchExpression) { - String value = TypeUtils.getDefaultValue(((PsiSwitchExpression) switchBlock).getType()); - text = isRuleBasedFormat ? value + ";" : "break " + value + ";"; + private static List generateStatements(PsiSwitchBlock switchBlock, boolean isRuleBasedFormat) { + Project project = switchBlock.getProject(); + FileTemplate branchTemplate = + FileTemplateManager.getInstance(project).getCodeTemplate(JavaTemplateUtil.TEMPLATE_SWITCH_DEFAULT_BRANCH); + Properties props = FileTemplateManager.getInstance(project).getDefaultProperties(); + PsiExpression expression = switchBlock.getExpression(); + props.setProperty(ATTRIBUTE_EXPRESSION, PLACEHOLDER_NAME); + PsiType expressionType = expression == null ? null : expression.getType(); + props.setProperty(ATTRIBUTE_EXPRESSION_TYPE, expressionType == null ? "" : expressionType.getCanonicalText()); + PsiStatement statement; + try { + String text = branchTemplate.getText(props); + if (text.trim().isEmpty()) { + if (switchBlock instanceof PsiSwitchExpression) { + String value = TypeUtils.getDefaultValue(((PsiSwitchExpression) switchBlock).getType()); + text = isRuleBasedFormat ? value + ";" : "break " + value + ";"; + } + } + statement = JavaPsiFacade.getElementFactory(project).createStatementFromText("{" + text + "}", switchBlock); + if (expression != null) { + PsiElement[] refs = PsiTreeUtil.collectElements( + statement, e -> e instanceof PsiReferenceExpression && e.textMatches(PLACEHOLDER_NAME)); + for (PsiElement ref : refs) { + // This would add parentheses when necessary + ref.replace(expression); + } + } } - } - statement = JavaPsiFacade.getElementFactory(project).createStatementFromText("{" + text + "}", switchBlock); - if (expression != null) { - PsiElement[] refs = PsiTreeUtil.collectElements( - statement, e -> e instanceof PsiReferenceExpression && e.textMatches(PLACEHOLDER_NAME)); - for (PsiElement ref : refs) { - // This would add parentheses when necessary - ref.replace(expression); + catch (IOException | IncorrectOperationException e) { + throw new IncorrectOperationException("Incorrect file template", (Throwable) e); + } + PsiStatement stripped = ControlFlowUtils.stripBraces(statement); + if (!isRuleBasedFormat || stripped instanceof PsiThrowStatement || stripped instanceof PsiExpressionStatement) { + statement = stripped; + } + if (isRuleBasedFormat) { + return Collections.singletonList("default -> " + statement.getText()); + } + else { + PsiStatement lastStatement = ArrayUtil.getLastElement(Objects.requireNonNull(switchBlock.getBody()).getStatements()); + if (lastStatement != null && ControlFlowUtils.statementMayCompleteNormally(lastStatement)) { + return Arrays.asList("break;", "default:", statement.getText()); + } + return Arrays.asList("default:", statement.getText()); } - } - } catch (IOException | IncorrectOperationException e) { - throw new IncorrectOperationException("Incorrect file template", (Throwable) e); - } - PsiStatement stripped = ControlFlowUtils.stripBraces(statement); - if (!isRuleBasedFormat || stripped instanceof PsiThrowStatement || stripped instanceof PsiExpressionStatement) { - statement = stripped; - } - if (isRuleBasedFormat) { - return Collections.singletonList("default -> " + statement.getText()); - } else { - PsiStatement lastStatement = ArrayUtil.getLastElement(Objects.requireNonNull(switchBlock.getBody()).getStatements()); - if (lastStatement != null && ControlFlowUtils.statementMayCompleteNormally(lastStatement)) { - return Arrays.asList("break;", "default:", statement.getText()); - } - return Arrays.asList("default:", statement.getText()); } - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/fixes/CreateMissingSwitchBranchesFix.java b/plugin/src/main/java/com/intellij/java/impl/ig/fixes/CreateMissingSwitchBranchesFix.java index 5b1f30131..13e8e6229 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/fixes/CreateMissingSwitchBranchesFix.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/fixes/CreateMissingSwitchBranchesFix.java @@ -4,76 +4,58 @@ import com.intellij.java.impl.ig.psiutils.CreateSwitchBranchesUtil; import com.intellij.java.impl.ig.psiutils.SwitchUtils; import com.intellij.java.language.psi.*; +import consulo.localize.LocalizeValue; import consulo.util.collection.ContainerUtil; +import jakarta.annotation.Nonnull; import one.util.streamex.StreamEx; -import org.jetbrains.annotations.Nls; -import jakarta.annotation.Nonnull; import java.util.List; import java.util.Set; import java.util.function.Function; -public class CreateMissingSwitchBranchesFix extends BaseSwitchFix -{ - private final Set myNames; - - public CreateMissingSwitchBranchesFix(@Nonnull PsiSwitchBlock block, Set names) - { - super(block); - myNames = names; - } - - @Nonnull - @Override - public String getText() - { - return getName(); - } - - @Nls(capitalization = Nls.Capitalization.Sentence) - @Nonnull - @Override - public String getName() - { - return CreateSwitchBranchesUtil.getActionName(myNames); - } - - @Nls(capitalization = Nls.Capitalization.Sentence) - @Nonnull - @Override - public String getFamilyName() - { - return "Create enum switch branches"; - } - - @Override - protected void invoke() - { - PsiSwitchBlock switchBlock = myBlock.getElement(); - if(switchBlock == null) - { - return; - } - final PsiExpression switchExpression = switchBlock.getExpression(); - if(switchExpression == null) - { - return; - } - final PsiClassType switchType = (PsiClassType) switchExpression.getType(); - if(switchType == null) - { - return; - } - final PsiClass enumClass = switchType.resolve(); - if(enumClass == null) - { - return; - } - List allEnumConstants = StreamEx.of(enumClass.getAllFields()).select(PsiEnumConstant.class).map(PsiField::getName).toList(); - Function> caseExtractor = - label -> ContainerUtil.map(SwitchUtils.findEnumConstants(label), PsiEnumConstant::getName); - List addedLabels = CreateSwitchBranchesUtil - .createMissingBranches(switchBlock, allEnumConstants, myNames, caseExtractor); - CreateSwitchBranchesUtil.createTemplate(switchBlock, addedLabels); - } +public class CreateMissingSwitchBranchesFix extends BaseSwitchFix { + private final Set myNames; + + public CreateMissingSwitchBranchesFix(@Nonnull PsiSwitchBlock block, Set names) { + super(block); + myNames = names; + } + + @Nonnull + @Override + public LocalizeValue getText() { + return getName(); + } + + @Nonnull + @Override + public LocalizeValue getName() { + return CreateSwitchBranchesUtil.getActionName(myNames); + } + + @Override + protected void invoke() { + PsiSwitchBlock switchBlock = myBlock.getElement(); + if (switchBlock == null) { + return; + } + final PsiExpression switchExpression = switchBlock.getExpression(); + if (switchExpression == null) { + return; + } + final PsiClassType switchType = (PsiClassType) switchExpression.getType(); + if (switchType == null) { + return; + } + final PsiClass enumClass = switchType.resolve(); + if (enumClass == null) { + return; + } + List allEnumConstants = StreamEx.of(enumClass.getAllFields()).select(PsiEnumConstant.class).map(PsiField::getName).toList(); + Function> caseExtractor = + label -> ContainerUtil.map(SwitchUtils.findEnumConstants(label), PsiEnumConstant::getName); + List addedLabels = CreateSwitchBranchesUtil + .createMissingBranches(switchBlock, allEnumConstants, myNames, caseExtractor); + CreateSwitchBranchesUtil.createTemplate(switchBlock, addedLabels); + } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/fixes/SuppressForTestsScopeFix.java b/plugin/src/main/java/com/intellij/java/impl/ig/fixes/SuppressForTestsScopeFix.java index af4b7ba74..d2dd376fb 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/fixes/SuppressForTestsScopeFix.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/fixes/SuppressForTestsScopeFix.java @@ -28,6 +28,7 @@ import consulo.language.editor.rawHighlight.HighlightDisplayKey; import consulo.language.editor.rawHighlight.HighlightDisplayLevel; import consulo.language.psi.PsiElement; +import consulo.localize.LocalizeValue; import consulo.project.Project; import consulo.undoRedo.BasicUndoableAction; import consulo.undoRedo.ProjectUndoManager; @@ -39,65 +40,64 @@ * @author Bas Leijdekkers */ public class SuppressForTestsScopeFix extends InspectionGadgetsFix { + private final AbstractBaseJavaLocalInspectionTool myInspection; - private final AbstractBaseJavaLocalInspectionTool myInspection; - - private SuppressForTestsScopeFix(AbstractBaseJavaLocalInspectionTool inspection) { - myInspection = inspection; - } - - @Nullable - public static SuppressForTestsScopeFix build(AbstractBaseJavaLocalInspectionTool inspection, PsiElement context) { - if (!TestUtils.isInTestSourceContent(context)) { - return null; + private SuppressForTestsScopeFix(AbstractBaseJavaLocalInspectionTool inspection) { + myInspection = inspection; } - return new SuppressForTestsScopeFix(inspection); - } - @Nonnull - @Override - public String getFamilyName() { - return InspectionGadgetsLocalize.suppressForTestsScopeQuickfix().get(); - } + @Nullable + public static SuppressForTestsScopeFix build(AbstractBaseJavaLocalInspectionTool inspection, PsiElement context) { + if (!TestUtils.isInTestSourceContent(context)) { + return null; + } + return new SuppressForTestsScopeFix(inspection); + } - @Override - public boolean startInWriteAction() { - return false; - } + @Nonnull + @Override + public LocalizeValue getName() { + return InspectionGadgetsLocalize.suppressForTestsScopeQuickfix(); + } - @Override - protected void doFix(final Project project, ProblemDescriptor descriptor) { - addRemoveTestsScope(project, true); - final VirtualFile vFile = descriptor.getPsiElement().getContainingFile().getVirtualFile(); - ProjectUndoManager.getInstance(project).undoableActionPerformed(new BasicUndoableAction(vFile) { - @Override - public void undo() { - addRemoveTestsScope(project, false); - } + @Override + public boolean startInWriteAction() { + return false; + } - @Override - public void redo() { + @Override + protected void doFix(final Project project, ProblemDescriptor descriptor) { addRemoveTestsScope(project, true); - } - }); - } + final VirtualFile vFile = descriptor.getPsiElement().getContainingFile().getVirtualFile(); + ProjectUndoManager.getInstance(project).undoableActionPerformed(new BasicUndoableAction(vFile) { + @Override + public void undo() { + addRemoveTestsScope(project, false); + } - private void addRemoveTestsScope(Project project, boolean add) { - final InspectionProfile profile = InspectionProjectProfileManager.getInstance(project).getInspectionProfile(); - final String shortName = myInspection.getShortName(); - final InspectionToolWrapper tool = profile.getInspectionTool(shortName, project); - if (tool == null) { - return; - } - if (add) { - final NamedScope namedScope = NamedScopesHolder.getScope(project, "Tests"); - final HighlightDisplayKey key = HighlightDisplayKey.find(shortName); - final HighlightDisplayLevel level = profile.getErrorLevel(key, namedScope, project); - profile.addScope(tool, namedScope, level, false, project); + @Override + public void redo() { + addRemoveTestsScope(project, true); + } + }); } - else { - profile.removeScope(shortName, "Tests", project); + + private void addRemoveTestsScope(Project project, boolean add) { + final InspectionProfile profile = InspectionProjectProfileManager.getInstance(project).getInspectionProfile(); + final String shortName = myInspection.getShortName(); + final InspectionToolWrapper tool = profile.getInspectionTool(shortName, project); + if (tool == null) { + return; + } + if (add) { + final NamedScope namedScope = NamedScopesHolder.getScope(project, "Tests"); + final HighlightDisplayKey key = HighlightDisplayKey.find(shortName); + final HighlightDisplayLevel level = profile.getErrorLevel(key, namedScope, project); + profile.addScope(tool, namedScope, level, false, project); + } + else { + profile.removeScope(shortName, "Tests", project); + } + profile.scopesChanged(); } - profile.scopesChanged(); - } } diff --git a/plugin/src/main/java/com/intellij/java/impl/ig/psiutils/CreateSwitchBranchesUtil.java b/plugin/src/main/java/com/intellij/java/impl/ig/psiutils/CreateSwitchBranchesUtil.java index 8b22438be..04f303039 100644 --- a/plugin/src/main/java/com/intellij/java/impl/ig/psiutils/CreateSwitchBranchesUtil.java +++ b/plugin/src/main/java/com/intellij/java/impl/ig/psiutils/CreateSwitchBranchesUtil.java @@ -15,6 +15,7 @@ import consulo.language.psi.PsiElement; import consulo.language.psi.PsiFile; import consulo.language.psi.util.PsiTreeUtil; +import consulo.localize.LocalizeValue; import consulo.project.Project; import consulo.util.collection.ContainerUtil; import consulo.util.lang.Couple; @@ -30,199 +31,211 @@ import java.util.function.Function; public class CreateSwitchBranchesUtil { - /** - * @param names names of individual branches to create (non-empty) - * @return a name of the action which creates missing switch branches. - */ - @Nonnull - public static String getActionName(Collection names) { - if (names.size() == 1) { - return "Create missing switch branch '" + names.iterator().next() + "'"; + /** + * @param names names of individual branches to create (non-empty) + * @return a name of the action which creates missing switch branches. + */ + @Nonnull + public static LocalizeValue getActionName(Collection names) { + if (names.size() == 1) { + return LocalizeValue.localizeTODO("Create missing switch branch '" + names.iterator().next() + "'"); + } + return LocalizeValue.localizeTODO("Create missing branches: " + formatMissingBranches(names)); } - return "Create missing branches: " + formatMissingBranches(names); - } - - /** - * @param names names of individual branches to create (non-empty) - * @return a string which contains all the names (probably abbreviated if too long) - */ - public static String formatMissingBranches(Collection names) { - return StreamEx.of(names).map(name -> name.startsWith("'") || name.startsWith("\"") ? name : "'" + name + "'").mapLast("and "::concat) - .collect(Joining.with(", ").maxChars(50).cutAfterDelimiter()); - } - /** - * Create missing switch branches - * - * @param switchBlock a switch block to process - * @param allNames an ordered list of all expected switch branches (e.g. list of all possible enum values) - * @param missingNames a collection of missing branch names which should be created - * @param caseExtractor a function which extracts list of the case string representations from the given switch label. - * The resulting strings should appear in the allNames list if the label matches the same constant, - * thus some kind of normalization could be necessary. - * @return a list of created branches - */ - public static List createMissingBranches(@Nonnull PsiSwitchBlock switchBlock, - @Nonnull List allNames, - @Nonnull Collection missingNames, - @Nonnull Function> caseExtractor) { - boolean isRuleBasedFormat = SwitchUtils.isRuleFormatSwitch(switchBlock); - final PsiCodeBlock body = switchBlock.getBody(); - if (body == null) { - // replace entire switch statement if no code block is present - @NonNls final StringBuilder newStatementText = new StringBuilder(); - CommentTracker commentTracker = new CommentTracker(); - final PsiExpression switchExpression = switchBlock.getExpression(); - newStatementText.append("switch(").append(switchExpression == null ? "" : commentTracker.text(switchExpression)).append("){"); - for (String missingName : missingNames) { - newStatementText.append(String.join("", generateStatements(missingName, switchBlock, isRuleBasedFormat))); - } - newStatementText.append('}'); - PsiSwitchBlock block = (PsiSwitchBlock) commentTracker.replaceAndRestoreComments(switchBlock, newStatementText.toString()); - return PsiTreeUtil.getChildrenOfTypeAsList(block.getBody(), PsiSwitchLabelStatementBase.class); + /** + * @param names names of individual branches to create (non-empty) + * @return a string which contains all the names (probably abbreviated if too long) + */ + public static String formatMissingBranches(Collection names) { + return StreamEx.of(names) + .map(name -> name.startsWith("'") || name.startsWith("\"") ? name : "'" + name + "'") + .mapLast("and "::concat) + .collect(Joining.with(", ").maxChars(50).cutAfterDelimiter()); } - Map prevToNext = - StreamEx.of(allNames).pairMap(Couple::of).toMap(c -> c.getFirst(), c -> c.getSecond()); - List missingLabels = StreamEx.of(allNames).filter(missingNames::contains).toList(); - String nextLabel = getNextLabel(prevToNext, missingLabels); - PsiElement bodyElement = body.getFirstBodyElement(); - List addedLabels = new ArrayList<>(); - while (bodyElement != null) { - PsiSwitchLabelStatementBase label = ObjectUtil.tryCast(bodyElement, PsiSwitchLabelStatementBase.class); - if (label != null) { - List constants = caseExtractor.apply(label); - while (nextLabel != null && constants.contains(nextLabel)) { - addedLabels.add(addSwitchLabelStatementBefore(missingLabels.get(0), bodyElement, switchBlock, isRuleBasedFormat)); - missingLabels.remove(0); - if (missingLabels.isEmpty()) { - break; - } - nextLabel = getNextLabel(prevToNext, missingLabels); + + /** + * Create missing switch branches + * + * @param switchBlock a switch block to process + * @param allNames an ordered list of all expected switch branches (e.g. list of all possible enum values) + * @param missingNames a collection of missing branch names which should be created + * @param caseExtractor a function which extracts list of the case string representations from the given switch label. + * The resulting strings should appear in the allNames list if the label matches the same constant, + * thus some kind of normalization could be necessary. + * @return a list of created branches + */ + public static List createMissingBranches( + @Nonnull PsiSwitchBlock switchBlock, + @Nonnull List allNames, + @Nonnull Collection missingNames, + @Nonnull Function> caseExtractor + ) { + boolean isRuleBasedFormat = SwitchUtils.isRuleFormatSwitch(switchBlock); + final PsiCodeBlock body = switchBlock.getBody(); + if (body == null) { + // replace entire switch statement if no code block is present + @NonNls final StringBuilder newStatementText = new StringBuilder(); + CommentTracker commentTracker = new CommentTracker(); + final PsiExpression switchExpression = switchBlock.getExpression(); + newStatementText.append("switch(").append(switchExpression == null ? "" : commentTracker.text(switchExpression)).append("){"); + for (String missingName : missingNames) { + newStatementText.append(String.join("", generateStatements(missingName, switchBlock, isRuleBasedFormat))); + } + newStatementText.append('}'); + PsiSwitchBlock block = (PsiSwitchBlock) commentTracker.replaceAndRestoreComments(switchBlock, newStatementText.toString()); + return PsiTreeUtil.getChildrenOfTypeAsList(block.getBody(), PsiSwitchLabelStatementBase.class); } - if (label.isDefaultCase()) { - for (String missingEnumElement : missingLabels) { - addedLabels.add(addSwitchLabelStatementBefore(missingEnumElement, bodyElement, switchBlock, isRuleBasedFormat)); - } - missingLabels.clear(); - break; + Map prevToNext = + StreamEx.of(allNames).pairMap(Couple::of).toMap(c -> c.getFirst(), c -> c.getSecond()); + List missingLabels = StreamEx.of(allNames).filter(missingNames::contains).toList(); + String nextLabel = getNextLabel(prevToNext, missingLabels); + PsiElement bodyElement = body.getFirstBodyElement(); + List addedLabels = new ArrayList<>(); + while (bodyElement != null) { + PsiSwitchLabelStatementBase label = ObjectUtil.tryCast(bodyElement, PsiSwitchLabelStatementBase.class); + if (label != null) { + List constants = caseExtractor.apply(label); + while (nextLabel != null && constants.contains(nextLabel)) { + addedLabels.add(addSwitchLabelStatementBefore(missingLabels.get(0), bodyElement, switchBlock, isRuleBasedFormat)); + missingLabels.remove(0); + if (missingLabels.isEmpty()) { + break; + } + nextLabel = getNextLabel(prevToNext, missingLabels); + } + if (label.isDefaultCase()) { + for (String missingEnumElement : missingLabels) { + addedLabels.add(addSwitchLabelStatementBefore(missingEnumElement, bodyElement, switchBlock, isRuleBasedFormat)); + } + missingLabels.clear(); + break; + } + } + bodyElement = bodyElement.getNextSibling(); } - } - bodyElement = bodyElement.getNextSibling(); + if (!missingLabels.isEmpty()) { + final PsiElement lastChild = body.getLastChild(); + for (String missingEnumElement : missingLabels) { + addedLabels.add(addSwitchLabelStatementBefore(missingEnumElement, lastChild, switchBlock, isRuleBasedFormat)); + } + } + return addedLabels; } - if (!missingLabels.isEmpty()) { - final PsiElement lastChild = body.getLastChild(); - for (String missingEnumElement : missingLabels) { - addedLabels.add(addSwitchLabelStatementBefore(missingEnumElement, lastChild, switchBlock, isRuleBasedFormat)); - } + + /** + * If necessary, starts a template to modify the bodies of created switch branches + * + * @param block parent switch block + * @param addedLabels list of created labels (returned from {@link #createMissingBranches(PsiSwitchBlock, List, Collection, Function)}). + */ + public static void createTemplate(@Nonnull PsiSwitchBlock block, List addedLabels) { + if (!(block instanceof PsiSwitchExpression)) { + return; + } + Editor editor = prepareForTemplateAndObtainEditor(block); + if (editor == null) { + return; + } + TemplateBuilder builder = TemplateBuilderFactory.getInstance().createTemplateBuilder(block); + List elementsToReplace = getElementsToReplace(addedLabels); + for (PsiExpression expression : elementsToReplace) { + builder.replaceElement(expression, new ConstantNode(expression.getText())); + } + builder.run(editor, true); } - return addedLabels; - } - /** - * If necessary, starts a template to modify the bodies of created switch branches - * - * @param block parent switch block - * @param addedLabels list of created labels (returned from {@link #createMissingBranches(PsiSwitchBlock, List, Collection, Function)}). - */ - public static void createTemplate(@Nonnull PsiSwitchBlock block, List addedLabels) { - if (!(block instanceof PsiSwitchExpression)) - return; - Editor editor = prepareForTemplateAndObtainEditor(block); - if (editor == null) - return; - TemplateBuilder builder = TemplateBuilderFactory.getInstance().createTemplateBuilder(block); - List elementsToReplace = getElementsToReplace(addedLabels); - for (PsiExpression expression : elementsToReplace) { - builder.replaceElement(expression, new ConstantNode(expression.getText())); + @Nonnull + private static List getElementsToReplace(@Nonnull List labels) { + List elementsToReplace = new ArrayList<>(); + for (PsiSwitchLabelStatementBase label : labels) { + if (label instanceof PsiSwitchLabeledRuleStatement) { + PsiStatement body = ((PsiSwitchLabeledRuleStatement) label).getBody(); + if (body instanceof PsiExpressionStatement) { + ContainerUtil.addIfNotNull(elementsToReplace, ((PsiExpressionStatement) body).getExpression()); + } + } + else { + PsiElement next = PsiTreeUtil.skipWhitespacesAndCommentsForward(label); + if (next instanceof PsiYieldStatement) { + ContainerUtil.addIfNotNull(elementsToReplace, ((PsiYieldStatement) next).getExpression()); + } + } + } + return elementsToReplace; } - builder.run(editor, true); - } - @Nonnull - private static List getElementsToReplace(@Nonnull List labels) { - List elementsToReplace = new ArrayList<>(); - for (PsiSwitchLabelStatementBase label : labels) { - if (label instanceof PsiSwitchLabeledRuleStatement) { - PsiStatement body = ((PsiSwitchLabeledRuleStatement) label).getBody(); - if (body instanceof PsiExpressionStatement) { - ContainerUtil.addIfNotNull(elementsToReplace, ((PsiExpressionStatement) body).getExpression()); + private static List generateStatements(String name, PsiSwitchBlock switchBlock, boolean isRuleBasedFormat) { + if (switchBlock instanceof PsiSwitchExpression) { + String value = TypeUtils.getDefaultValue(((PsiSwitchExpression) switchBlock).getType()); + if (isRuleBasedFormat) { + return Collections.singletonList("case " + name + " -> " + value + ";"); + } + else { + return Arrays.asList("case " + name + ":", "yield " + value + ";"); + } } - } else { - PsiElement next = PsiTreeUtil.skipWhitespacesAndCommentsForward(label); - if (next instanceof PsiYieldStatement) { - ContainerUtil.addIfNotNull(elementsToReplace, ((PsiYieldStatement) next).getExpression()); + if (isRuleBasedFormat) { + return Collections.singletonList("case " + name + " -> {}"); } - } + return Arrays.asList("case " + name + ":", "break;"); } - return elementsToReplace; - } - private static List generateStatements(String name, PsiSwitchBlock switchBlock, boolean isRuleBasedFormat) { - if (switchBlock instanceof PsiSwitchExpression) { - String value = TypeUtils.getDefaultValue(((PsiSwitchExpression) switchBlock).getType()); - if (isRuleBasedFormat) { - return Collections.singletonList("case " + name + " -> " + value + ";"); - } else { - return Arrays.asList("case " + name + ":", "yield " + value + ";"); - } - } - if (isRuleBasedFormat) { - return Collections.singletonList("case " + name + " -> {}"); + private static PsiSwitchLabelStatementBase addSwitchLabelStatementBefore( + String labelExpression, + PsiElement anchor, + PsiSwitchBlock switchBlock, + boolean isRuleBasedFormat + ) { + if (anchor instanceof PsiSwitchLabelStatement) { + PsiElement sibling = PsiTreeUtil.skipWhitespacesBackward(anchor); + while (sibling instanceof PsiSwitchLabelStatement) { + anchor = sibling; + sibling = PsiTreeUtil.skipWhitespacesBackward(anchor); + } + } + PsiElement correctedAnchor = anchor; + final PsiElement parent = anchor.getParent(); + final PsiElementFactory factory = JavaPsiFacade.getElementFactory(anchor.getProject()); + PsiSwitchLabelStatementBase result = null; + for (String text : generateStatements(labelExpression, switchBlock, isRuleBasedFormat)) { + PsiStatement statement = factory.createStatementFromText(text, parent); + PsiElement inserted = parent.addBefore(statement, correctedAnchor); + if (inserted instanceof PsiSwitchLabelStatementBase) { + result = (PsiSwitchLabelStatementBase) inserted; + } + } + return result; } - return Arrays.asList("case " + name + ":", "break;"); - } - private static PsiSwitchLabelStatementBase addSwitchLabelStatementBefore(String labelExpression, - PsiElement anchor, - PsiSwitchBlock switchBlock, - boolean isRuleBasedFormat) { - if (anchor instanceof PsiSwitchLabelStatement) { - PsiElement sibling = PsiTreeUtil.skipWhitespacesBackward(anchor); - while (sibling instanceof PsiSwitchLabelStatement) { - anchor = sibling; - sibling = PsiTreeUtil.skipWhitespacesBackward(anchor); - } - } - PsiElement correctedAnchor = anchor; - final PsiElement parent = anchor.getParent(); - final PsiElementFactory factory = JavaPsiFacade.getElementFactory(anchor.getProject()); - PsiSwitchLabelStatementBase result = null; - for (String text : generateStatements(labelExpression, switchBlock, isRuleBasedFormat)) { - PsiStatement statement = factory.createStatementFromText(text, parent); - PsiElement inserted = parent.addBefore(statement, correctedAnchor); - if (inserted instanceof PsiSwitchLabelStatementBase) { - result = (PsiSwitchLabelStatementBase) inserted; - } + private static String getNextLabel(Map nextLabels, List missingLabels) { + String nextLabel = nextLabels.get(missingLabels.get(0)); + while (missingLabels.contains(nextLabel)) { + nextLabel = nextLabels.get(nextLabel); + } + return nextLabel; } - return result; - } - private static String getNextLabel(Map nextLabels, List missingLabels) { - String nextLabel = nextLabels.get(missingLabels.get(0)); - while (missingLabels.contains(nextLabel)) { - nextLabel = nextLabels.get(nextLabel); + /** + * Prepares the document for starting the template and returns the editor. + * + * @param element any element from the document + * @return an editor, or null if not found. + */ + @Nullable + public static Editor prepareForTemplateAndObtainEditor(@Nonnull PsiElement element) { + PsiFile file = element.getContainingFile(); + Project project = file.getProject(); + Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor(); + if (editor == null) { + return null; + } + Document document = editor.getDocument(); + PsiFile topLevelFile = InjectedLanguageManager.getInstance(project).getTopLevelFile(file); + if (topLevelFile == null || document != topLevelFile.getViewProvider().getDocument()) { + return null; + } + PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document); + return editor; } - return nextLabel; - } - - /** - * Prepares the document for starting the template and returns the editor. - * - * @param element any element from the document - * @return an editor, or null if not found. - */ - @Nullable - public static Editor prepareForTemplateAndObtainEditor(@Nonnull PsiElement element) { - PsiFile file = element.getContainingFile(); - Project project = file.getProject(); - Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor(); - if (editor == null) - return null; - Document document = editor.getDocument(); - PsiFile topLevelFile = InjectedLanguageManager.getInstance(project).getTopLevelFile(file); - if (topLevelFile == null || document != topLevelFile.getViewProvider().getDocument()) - return null; - PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document); - return editor; - } }