Search in sources :

Example 41 with LocalQuickFix

use of com.intellij.codeInspection.LocalQuickFix in project intellij-community by JetBrains.

the class MigrateAssertToMatcherAssertTest method testAll.

public void testAll() {
    myFixture.configureByFile(getTestName(true) + ".java");
    myFixture.enableInspections(new MigrateAssertToMatcherAssertInspection());
    for (IntentionAction wrapper : myFixture.getAllQuickFixes()) {
        if (wrapper instanceof QuickFixWrapper) {
            final LocalQuickFix fix = ((QuickFixWrapper) wrapper).getFix();
            if (fix instanceof MigrateAssertToMatcherAssertInspection.MyQuickFix) {
                myFixture.launchAction(wrapper);
            }
        }
    }
    myFixture.checkResultByFile(getTestName(true) + "_after.java");
}
Also used : MigrateAssertToMatcherAssertInspection(com.intellij.refactoring.typeMigration.inspections.MigrateAssertToMatcherAssertInspection) IntentionAction(com.intellij.codeInsight.intention.IntentionAction) LocalQuickFix(com.intellij.codeInspection.LocalQuickFix) QuickFixWrapper(com.intellij.codeInspection.ex.QuickFixWrapper)

Example 42 with LocalQuickFix

use of com.intellij.codeInspection.LocalQuickFix in project intellij-community by JetBrains.

the class MisspelledHeaderInspection method buildVisitor.

@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
    return new PsiElementVisitor() {

        @Override
        public void visitElement(PsiElement element) {
            if (element instanceof Header) {
                Header header = (Header) element;
                String headerName = header.getName();
                SortedSet<Suggestion> matches = new TreeSet<>();
                addMatches(headerName, CUSTOM_HEADERS, matches);
                addMatches(headerName, myRepository.getAllHeaderNames(), matches);
                Suggestion bestMatch = ContainerUtil.getFirstItem(matches);
                if (bestMatch != null && headerName.equals(bestMatch.getWord())) {
                    return;
                }
                List<LocalQuickFix> fixes = new ArrayList<>();
                for (Suggestion match : matches) {
                    fixes.add(new HeaderRenameQuickFix(header, match.getWord()));
                    if (fixes.size() == MAX_SUGGESTIONS)
                        break;
                }
                if (bestMatch == null || bestMatch.getMetrics() > TYPO_DISTANCE) {
                    fixes.add(new CustomHeaderQuickFix(header, CUSTOM_HEADERS));
                }
                holder.registerProblem(header.getNameElement(), ManifestBundle.message("inspection.header.message"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, fixes.toArray(new LocalQuickFix[fixes.size()]));
            }
        }

        private void addMatches(String headerName, Collection<String> headers, SortedSet<Suggestion> matches) {
            for (String candidate : headers) {
                int distance = EditDistance.optimalAlignment(headerName, candidate, false);
                if (distance <= MAX_DISTANCE) {
                    matches.add(new Suggestion(candidate, distance));
                }
            }
        }
    };
}
Also used : LocalQuickFix(com.intellij.codeInspection.LocalQuickFix) PsiElementVisitor(com.intellij.psi.PsiElementVisitor) Suggestion(com.intellij.spellchecker.engine.Suggestion) Header(org.jetbrains.lang.manifest.psi.Header) AbstractCollection(com.intellij.util.xmlb.annotations.AbstractCollection) PsiElement(com.intellij.psi.PsiElement) NotNull(org.jetbrains.annotations.NotNull)

Example 43 with LocalQuickFix

use of com.intellij.codeInspection.LocalQuickFix in project intellij-community by JetBrains.

the class AbstractMemberResolveConverter method getQuickFixes.

public LocalQuickFix[] getQuickFixes(final ConvertContext context) {
    final String targetName = ((GenericValue) context.getInvocationElement()).getStringValue();
    if (!PsiNameHelper.getInstance(context.getProject()).isIdentifier(targetName))
        return super.getQuickFixes(context);
    final PsiClass targetClass = getTargetClass(context);
    if (targetClass == null)
        return super.getQuickFixes(context);
    final PropertyMemberType memberType = getMemberTypes(context)[0];
    final PsiType psiType = getPsiType(context);
    final IntentionAction fix = QuickFixFactory.getInstance().createCreateFieldOrPropertyFix(targetClass, targetName, psiType, memberType);
    return fix instanceof LocalQuickFix ? new LocalQuickFix[] { (LocalQuickFix) fix } : super.getQuickFixes(context);
}
Also used : PropertyMemberType(com.intellij.psi.util.PropertyMemberType) IntentionAction(com.intellij.codeInsight.intention.IntentionAction) LocalQuickFix(com.intellij.codeInspection.LocalQuickFix)

Example 44 with LocalQuickFix

use of com.intellij.codeInspection.LocalQuickFix in project intellij-community by JetBrains.

the class OrderEntryFix method registerFixes.

@Nullable
public static List<LocalQuickFix> registerFixes(@NotNull QuickFixActionRegistrar registrar, @NotNull PsiReference reference) {
    PsiElement psiElement = reference.getElement();
    String shortReferenceName = reference.getRangeInElement().substring(psiElement.getText());
    Project project = psiElement.getProject();
    PsiFile containingFile = psiElement.getContainingFile();
    if (containingFile == null)
        return null;
    VirtualFile refVFile = containingFile.getVirtualFile();
    if (refVFile == null)
        return null;
    ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
    Module currentModule = fileIndex.getModuleForFile(refVFile);
    if (currentModule == null)
        return null;
    if (reference instanceof PsiJavaModuleReference) {
        List<LocalQuickFix> result = ContainerUtil.newSmartList();
        createModuleFixes((PsiJavaModuleReference) reference, currentModule, refVFile, result);
        result.forEach(fix -> registrar.register((IntentionAction) fix));
        return result;
    }
    List<LocalQuickFix> result = ContainerUtil.newSmartList();
    JavaPsiFacade facade = JavaPsiFacade.getInstance(psiElement.getProject());
    registerExternalFixes(registrar, reference, psiElement, shortReferenceName, facade, currentModule, result);
    if (!result.isEmpty()) {
        return result;
    }
    PsiClass[] classes = PsiShortNamesCache.getInstance(project).getClassesByName(shortReferenceName, GlobalSearchScope.allScope(project));
    List<PsiClass> allowedDependencies = filterAllowedDependencies(psiElement, classes);
    if (allowedDependencies.isEmpty()) {
        return result;
    }
    OrderEntryFix moduleDependencyFix = new AddModuleDependencyFix(currentModule, refVFile, allowedDependencies, reference);
    registrar.register(moduleDependencyFix);
    result.add(moduleDependencyFix);
    Set<Object> librariesToAdd = new THashSet<>();
    ModuleFileIndex moduleFileIndex = ModuleRootManager.getInstance(currentModule).getFileIndex();
    for (PsiClass aClass : allowedDependencies) {
        if (!facade.getResolveHelper().isAccessible(aClass, psiElement, aClass))
            continue;
        PsiFile psiFile = aClass.getContainingFile();
        if (psiFile == null)
            continue;
        VirtualFile virtualFile = psiFile.getVirtualFile();
        if (virtualFile == null)
            continue;
        for (OrderEntry orderEntry : fileIndex.getOrderEntriesForFile(virtualFile)) {
            if (orderEntry instanceof LibraryOrderEntry) {
                final LibraryOrderEntry libraryEntry = (LibraryOrderEntry) orderEntry;
                final Library library = libraryEntry.getLibrary();
                if (library == null)
                    continue;
                VirtualFile[] files = library.getFiles(OrderRootType.CLASSES);
                if (files.length == 0)
                    continue;
                final VirtualFile jar = files[0];
                if (jar == null || libraryEntry.isModuleLevel() && !librariesToAdd.add(jar) || !librariesToAdd.add(library))
                    continue;
                OrderEntry entryForFile = moduleFileIndex.getOrderEntryForFile(virtualFile);
                if (entryForFile != null && !(entryForFile instanceof ExportableOrderEntry && ((ExportableOrderEntry) entryForFile).getScope() == DependencyScope.TEST && !moduleFileIndex.isInTestSourceContent(refVFile))) {
                    continue;
                }
                OrderEntryFix platformFix = new AddLibraryToDependenciesFix(currentModule, library, reference, aClass.getQualifiedName());
                registrar.register(platformFix);
                result.add(platformFix);
            }
        }
    }
    return result;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) LocalQuickFix(com.intellij.codeInspection.LocalQuickFix) THashSet(gnu.trove.THashSet) Project(com.intellij.openapi.project.Project) PsiJavaModuleReference(com.intellij.psi.impl.source.PsiJavaModuleReference) IntentionAction(com.intellij.codeInsight.intention.IntentionAction) Library(com.intellij.openapi.roots.libraries.Library) Module(com.intellij.openapi.module.Module) Nullable(org.jetbrains.annotations.Nullable)

Example 45 with LocalQuickFix

use of com.intellij.codeInspection.LocalQuickFix in project intellij-community by JetBrains.

the class FieldCanBeLocalInspectionBase method doCheckClass.

private void doCheckClass(final PsiClass aClass, ProblemsHolder holder, final List<String> excludeAnnos, boolean ignoreFieldsUsedInMultipleMethods) {
    if (aClass.isInterface())
        return;
    final PsiField[] fields = aClass.getFields();
    final Set<PsiField> candidates = new LinkedHashSet<>();
    for (PsiField field : fields) {
        if (AnnotationUtil.isAnnotated(field, excludeAnnos)) {
            continue;
        }
        if (field.hasModifierProperty(PsiModifier.PRIVATE) && !(field.hasModifierProperty(PsiModifier.STATIC) && field.hasModifierProperty(PsiModifier.FINAL))) {
            candidates.add(field);
        }
    }
    removeFieldsReferencedFromInitializers(aClass, candidates);
    if (candidates.isEmpty())
        return;
    final Set<PsiField> usedFields = new THashSet<>();
    removeReadFields(aClass, candidates, usedFields, ignoreFieldsUsedInMultipleMethods);
    if (candidates.isEmpty())
        return;
    final ImplicitUsageProvider[] implicitUsageProviders = Extensions.getExtensions(ImplicitUsageProvider.EP_NAME);
    for (final PsiField field : candidates) {
        if (usedFields.contains(field) && !hasImplicitReadOrWriteUsage(field, implicitUsageProviders)) {
            if (!ReferencesSearch.search(field, new LocalSearchScope(aClass)).forEach(reference -> {
                final PsiElement element = reference.getElement();
                if (element instanceof PsiReferenceExpression) {
                    final PsiElement qualifier = ((PsiReferenceExpression) element).getQualifier();
                    return qualifier == null || qualifier instanceof PsiThisExpression && ((PsiThisExpression) qualifier).getQualifier() == null;
                }
                return true;
            })) {
                continue;
            }
            final String message = InspectionsBundle.message("inspection.field.can.be.local.problem.descriptor");
            final ArrayList<LocalQuickFix> fixes = new ArrayList<>();
            SpecialAnnotationsUtilBase.createAddToSpecialAnnotationFixes(field, qualifiedName -> {
                final LocalQuickFix quickFix = SpecialAnnotationsUtilBase.createAddToSpecialAnnotationsListQuickFix(InspectionGadgetsBundle.message("add.0.to.ignore.if.annotated.by.list.quickfix", qualifiedName), QuickFixBundle.message("fix.add.special.annotation.family"), EXCLUDE_ANNOS, qualifiedName, field);
                fixes.add(quickFix);
                return true;
            });
            final LocalQuickFix fix = createFix();
            if (fix != null) {
                fixes.add(fix);
            }
            holder.registerProblem(field.getNameIdentifier(), message, fixes.toArray(new LocalQuickFix[fixes.size()]));
        }
    }
}
Also used : LocalSearchScope(com.intellij.psi.search.LocalSearchScope) SpecialAnnotationsUtilBase(com.intellij.codeInspection.util.SpecialAnnotationsUtilBase) GroupNames(com.intellij.codeInsight.daemon.GroupNames) JDOMExternalizableStringList(com.intellij.openapi.util.JDOMExternalizableStringList) java.util(java.util) PsiDocTagValue(com.intellij.psi.javadoc.PsiDocTagValue) NonNls(org.jetbrains.annotations.NonNls) THashSet(gnu.trove.THashSet) LocalSearchScope(com.intellij.psi.search.LocalSearchScope) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) InspectionGadgetsBundle(com.siyeh.InspectionGadgetsBundle) Comparing(com.intellij.openapi.util.Comparing) PsiUtil(com.intellij.psi.util.PsiUtil) ImplicitUsageProvider(com.intellij.codeInsight.daemon.ImplicitUsageProvider) LocalQuickFix(com.intellij.codeInspection.LocalQuickFix) ProblemsHolder(com.intellij.codeInspection.ProblemsHolder) QuickFixBundle(com.intellij.codeInsight.daemon.QuickFixBundle) Extensions(com.intellij.openapi.extensions.Extensions) ReferencesSearch(com.intellij.psi.search.searches.ReferencesSearch) InspectionsBundle(com.intellij.codeInspection.InspectionsBundle) PsiDocComment(com.intellij.psi.javadoc.PsiDocComment) BaseJavaBatchLocalInspectionTool(com.intellij.codeInspection.BaseJavaBatchLocalInspectionTool) AnnotationUtil(com.intellij.codeInsight.AnnotationUtil) com.intellij.psi(com.intellij.psi) WriteExternalException(com.intellij.openapi.util.WriteExternalException) NotNull(org.jetbrains.annotations.NotNull) Ref(com.intellij.openapi.util.Ref) Element(org.jdom.Element) com.intellij.psi.controlFlow(com.intellij.psi.controlFlow) LocalQuickFix(com.intellij.codeInspection.LocalQuickFix) THashSet(gnu.trove.THashSet) ImplicitUsageProvider(com.intellij.codeInsight.daemon.ImplicitUsageProvider)

Aggregations

LocalQuickFix (com.intellij.codeInspection.LocalQuickFix)59 NotNull (org.jetbrains.annotations.NotNull)20 PsiElement (com.intellij.psi.PsiElement)16 Nullable (org.jetbrains.annotations.Nullable)11 IntentionAction (com.intellij.codeInsight.intention.IntentionAction)10 ProblemDescriptor (com.intellij.codeInspection.ProblemDescriptor)10 ASTNode (com.intellij.lang.ASTNode)6 Project (com.intellij.openapi.project.Project)6 VirtualFile (com.intellij.openapi.vfs.VirtualFile)6 XmlTag (com.intellij.psi.xml.XmlTag)6 PsiFile (com.intellij.psi.PsiFile)5 PsiReference (com.intellij.psi.PsiReference)5 ArrayList (java.util.ArrayList)5 PsiTreeUtil (com.intellij.psi.util.PsiTreeUtil)4 LocalQuickFixProvider (com.intellij.codeInspection.LocalQuickFixProvider)3 QuickFixWrapper (com.intellij.codeInspection.ex.QuickFixWrapper)3 Pair (com.intellij.openapi.util.Pair)3 TextRange (com.intellij.openapi.util.TextRange)3 XmlAttributeDescriptor (com.intellij.xml.XmlAttributeDescriptor)3 XmlElementDescriptor (com.intellij.xml.XmlElementDescriptor)3