protected HighlightSeverity getSeverity(@NotNull RefElement element) {
    final PsiElement psiElement = element.getPointer().getContainingFile();
    if (psiElement != null) {
      final GlobalInspectionContextImpl context = getContext();
      final String shortName = getSeverityDelegateName();
      final Tools tools = context.getTools().get(shortName);
      if (tools != null) {
        for (ScopeToolState state : tools.getTools()) {
          InspectionToolWrapper toolWrapper = state.getTool();
          if (toolWrapper == getToolWrapper()) {
            return context
                .getCurrentProfile()
                .getErrorLevel(HighlightDisplayKey.find(shortName), psiElement)
                .getSeverity();
          }
        }
      }

      final InspectionProfile profile =
          InspectionProjectProfileManager.getInstance(context.getProject()).getInspectionProfile();
      final HighlightDisplayLevel level =
          profile.getErrorLevel(HighlightDisplayKey.find(shortName), psiElement);
      return level.getSeverity();
    }
    return null;
  }
    @Override
    public void actionPerformed(AnActionEvent e) {
      final InspectionProjectProfileManager profileManager =
          InspectionProjectProfileManager.getInstance(myProject);
      final InspectionToolWrapper toolWrapper = myTree.getSelectedToolWrapper();
      InspectionProfile inspectionProfile = myInspectionProfile;
      final boolean profileIsDefined = isProfileDefined();
      if (!profileIsDefined) {
        inspectionProfile = guessProfileToSelect(profileManager);
      }

      if (toolWrapper != null) {
        final HighlightDisplayKey key =
            HighlightDisplayKey.find(
                toolWrapper.getShortName()); // do not search for dead code entry point tool
        if (key != null) {
          if (new EditInspectionToolsSettingsAction(key)
                  .editToolSettings(
                      myProject, (InspectionProfileImpl) inspectionProfile, profileIsDefined)
              && profileIsDefined) {
            updateCurrentProfile();
          }
          return;
        }
      }
      if (EditInspectionToolsSettingsAction.editToolSettings(
              myProject, inspectionProfile, profileIsDefined, null)
          && profileIsDefined) {
        updateCurrentProfile();
      }
    }
  @Nullable
  private static HighlightInfo checkCodeRefInner(GrCodeReferenceElement refElement) {
    if (PsiTreeUtil.getParentOfType(refElement, GroovyDocPsiElement.class) != null) return null;

    PsiElement nameElement = refElement.getReferenceNameElement();
    if (nameElement == null) return null;

    if (isResolvedStaticImport(refElement)) return null;

    GroovyResolveResult resolveResult = refElement.advancedResolve();
    final PsiElement resolved = resolveResult.getElement();

    if (!(refElement.getParent() instanceof GrPackageDefinition) && resolved == null) {
      String message = GroovyBundle.message("cannot.resolve", refElement.getReferenceName());
      HighlightInfo info =
          HighlightInfo.newHighlightInfo(HighlightInfoType.WRONG_REF)
              .range(nameElement)
              .descriptionAndTooltip(message)
              .create();

      // todo implement for nested classes
      HighlightDisplayKey displayKey = HighlightDisplayKey.find(SHORT_NAME);
      registerCreateClassByTypeFix(refElement, info, displayKey);
      registerAddImportFixes(refElement, info, displayKey);
      UnresolvedReferenceQuickFixProvider.registerReferenceFixes(
          refElement, new QuickFixActionRegistrarAdapter(info, displayKey));
      OrderEntryFix.registerFixes(new QuickFixActionRegistrarAdapter(info, displayKey), refElement);

      return info;
    }

    return null;
  }
 private static HighlightDisplayLevel getHighlightDisplayLevel(
     final LocalInspectionTool inspectionTool,
     final InspectionProfile inspectionProfile,
     PsiElement file) {
   final HighlightDisplayKey key = HighlightDisplayKey.find(inspectionTool.getShortName());
   return inspectionProfile.isToolEnabled(key, file)
       ? inspectionProfile.getErrorLevel(key, file)
       : HighlightDisplayLevel.DO_NOT_SHOW;
 }
  @Nullable
  private static HighlightInfo checkRefInner(GrReferenceExpression ref) {
    PsiElement refNameElement = ref.getReferenceNameElement();
    if (refNameElement == null) return null;

    boolean cannotBeDynamic = PsiUtil.isCompileStatic(ref) || isPropertyAccessInStaticMethod(ref);
    GroovyResolveResult resolveResult = getBestResolveResult(ref);

    if (resolveResult.getElement() != null) {
      if (!isInspectionEnabled(ref.getContainingFile(), ref.getProject())) return null;

      if (isStaticOk(resolveResult)) return null;
      String message = GroovyBundle.message("cannot.reference.non.static", ref.getReferenceName());
      return createAnnotationForRef(ref, cannotBeDynamic, message);
    }

    if (ResolveUtil.isKeyOfMap(ref) || isClassReference(ref)) {
      return null;
    }

    if (!cannotBeDynamic) {
      if (!isInspectionEnabled(ref.getContainingFile(), ref.getProject())) return null;
      GrUnresolvedAccessInspection inspection =
          getInstance(ref.getContainingFile(), ref.getProject());

      if (!inspection.myHighlightIfGroovyObjectOverridden && areGroovyObjectMethodsOverridden(ref))
        return null;
      if (!inspection.myHighlightIfMissingMethodsDeclared && areMissingMethodsDeclared(ref))
        return null;

      if (GroovySuppressableInspectionTool.isElementToolSuppressedIn(ref, SHORT_NAME)) return null;
    }

    if (cannotBeDynamic || shouldHighlightAsUnresolved(ref)) {
      HighlightInfo info =
          createAnnotationForRef(
              ref, cannotBeDynamic, GroovyBundle.message("cannot.resolve", ref.getReferenceName()));
      LOG.assertTrue(info != null);

      HighlightDisplayKey displayKey = HighlightDisplayKey.find(SHORT_NAME);
      if (ref.getParent() instanceof GrMethodCall) {
        registerStaticImportFix(ref, info, displayKey);
      } else {
        registerCreateClassByTypeFix(ref, info, displayKey);
        registerAddImportFixes(ref, info, displayKey);
      }

      registerReferenceFixes(ref, info, cannotBeDynamic, displayKey);
      UnresolvedReferenceQuickFixProvider.registerReferenceFixes(
          ref, new QuickFixActionRegistrarAdapter(info, displayKey));
      OrderEntryFix.registerFixes(new QuickFixActionRegistrarAdapter(info, displayKey), ref);
      return info;
    }

    return null;
  }
  private static void addEmptyIntentionIfNeeded(@Nullable HighlightInfo info) {
    if (info != null) {
      int s1 = info.quickFixActionMarkers != null ? info.quickFixActionMarkers.size() : 0;
      int s2 = info.quickFixActionRanges != null ? info.quickFixActionRanges.size() : 0;

      if (s1 + s2 == 0) {
        EmptyIntentionAction emptyIntentionAction =
            new EmptyIntentionAction("Access to unresolved expression");
        QuickFixAction.registerQuickFixAction(
            info, emptyIntentionAction, HighlightDisplayKey.find(SHORT_NAME));
      }
    }
  }
  private boolean initialize() {
    if (myBaseProfile != null) {
      myBaseProfile.initInspectionTools();
    }

    final List<InspectionTool> tools;
    try {
      tools = myRegistrar.createTools();
    } catch (ProcessCanceledException e) {
      return false;
    }
    for (InspectionTool tool : tools) {
      final String shortName = tool.getShortName();
      HighlightDisplayKey key = HighlightDisplayKey.find(shortName);
      if (key == null) {
        if (tool instanceof LocalInspectionToolWrapper) {
          key =
              HighlightDisplayKey.register(
                  shortName,
                  tool.getDisplayName(),
                  ((LocalInspectionToolWrapper) tool).getID(),
                  ((LocalInspectionToolWrapper) tool).getAlternativeID());
        } else {
          key = HighlightDisplayKey.register(shortName, tool.getDisplayName());
        }
      }

      LOG.assertTrue(key != null, shortName + " ; number of initialized tools: " + myTools.size());
      final ToolsImpl toolsList =
          new ToolsImpl(
              tool,
              myBaseProfile != null ? myBaseProfile.getErrorLevel(key) : tool.getDefaultLevel(),
              !myLockedProfile
                  && (myBaseProfile != null
                      ? myBaseProfile.isToolEnabled(key)
                      : tool.isEnabledByDefault()));
      final Element element = myDeinstalledInspectionsSettings.remove(tool.getShortName());
      if (element != null) {
        try {
          toolsList.readExternal(element, this);
        } catch (InvalidDataException e) {
          LOG.error(e);
        }
      }
      myTools.put(tool.getShortName(), toolsList);
    }
    if (mySource != null) {
      copyToolsConfigurations(mySource);
    }
    return true;
  }
Beispiel #8
0
 private static void enableInspectionTool(
     final Map<String, InspectionTool> availableLocalTools, InspectionTool wrapper) {
   final String shortName = wrapper.getShortName();
   final HighlightDisplayKey key = HighlightDisplayKey.find(shortName);
   if (key == null) {
     HighlightDisplayKey.register(
         shortName,
         wrapper.getDisplayName(),
         wrapper instanceof LocalInspectionToolWrapper
             ? ((LocalInspectionToolWrapper) wrapper).getTool().getID()
             : wrapper.getShortName());
   }
   availableLocalTools.put(shortName, wrapper);
 }
 private static void appendFixes(
     @Nullable TextRange fixedRange,
     @NotNull HighlightInfo info,
     @Nullable List<Annotation.QuickFixInfo> fixes) {
   if (fixes != null) {
     for (final Annotation.QuickFixInfo quickFixInfo : fixes) {
       TextRange range = fixedRange != null ? fixedRange : quickFixInfo.textRange;
       HighlightDisplayKey key =
           quickFixInfo.key != null
               ? quickFixInfo.key
               : HighlightDisplayKey.find(ANNOTATOR_INSPECTION_SHORT_NAME);
       info.registerFix(
           quickFixInfo.quickFix, null, HighlightDisplayKey.getDisplayNameByKey(key), range, key);
     }
   }
 }
 private static void appendFixes(
     @Nullable TextRange fixedRange, HighlightInfo info, List<Annotation.QuickFixInfo> fixes) {
   if (fixes != null) {
     for (final Annotation.QuickFixInfo quickFixInfo : fixes) {
       QuickFixAction.registerQuickFixAction(
           info,
           fixedRange != null ? fixedRange : quickFixInfo.textRange,
           quickFixInfo.quickFix,
           quickFixInfo.key != null
               ? quickFixInfo.key
               : HighlightDisplayKey.find(
                   DefaultHighlightVisitorBasedInspection.AnnotatorBasedInspection
                       .ANNOTATOR_SHORT_NAME));
     }
   }
 }
  private void checkRequiredAttributes(
      XmlTag tag, String name, XmlElementDescriptor elementDescriptor) {
    XmlAttributeDescriptor[] attributeDescriptors = elementDescriptor.getAttributesDescriptors(tag);
    Set<String> requiredAttributes = null;

    for (XmlAttributeDescriptor attribute : attributeDescriptors) {
      if (attribute != null && attribute.isRequired()) {
        if (requiredAttributes == null) {
          requiredAttributes = new HashSet<String>();
        }
        requiredAttributes.add(attribute.getName(tag));
      }
    }

    if (requiredAttributes != null) {
      for (final String attrName : requiredAttributes) {
        if (tag.getAttribute(attrName, "") == null
            && !XmlExtension.getExtension(tag.getContainingFile())
                .isRequiredAttributeImplicitlyPresent(tag, attrName)) {

          final InsertRequiredAttributeFix insertRequiredAttributeIntention =
              new InsertRequiredAttributeFix(tag, attrName, null);
          final String localizedMessage =
              XmlErrorMessages.message("element.doesnt.have.required.attribute", name, attrName);
          final InspectionProfile profile =
              InspectionProjectProfileManager.getInstance(tag.getProject()).getInspectionProfile();
          final LocalInspectionToolWrapper toolWrapper =
              (LocalInspectionToolWrapper)
                  profile.getInspectionTool(RequiredAttributesInspection.SHORT_NAME, tag);
          if (toolWrapper != null) {
            RequiredAttributesInspection inspection =
                (RequiredAttributesInspection) toolWrapper.getTool();
            reportOneTagProblem(
                tag,
                attrName,
                localizedMessage,
                insertRequiredAttributeIntention,
                HighlightDisplayKey.find(RequiredAttributesInspection.SHORT_NAME),
                inspection,
                XmlEntitiesInspection.NOT_REQUIRED_ATTRIBUTE);
          }
        }
      }
    }
  }
 private void appendSuppressSection(final StringBuffer buf) {
   final InspectionTool tool = getTool();
   if (tool != null) {
     final HighlightDisplayKey key = HighlightDisplayKey.find(tool.getShortName());
     if (key != null) { // dummy entry points
       final SuppressActionWrapper.SuppressTreeAction[] suppressActions =
           new SuppressActionWrapper(
                   myView.getProject(), tool, myView.getTree().getSelectionPaths())
               .getChildren(null);
       if (suppressActions.length > 0) {
         final List<AnAction> activeSuppressActions = new ArrayList<AnAction>();
         for (SuppressActionWrapper.SuppressTreeAction suppressAction : suppressActions) {
           if (suppressAction.isAvailable()) {
             activeSuppressActions.add(suppressAction);
           }
         }
         if (!activeSuppressActions.isEmpty()) {
           int idx = 0;
           @NonNls final String br = "<br>";
           buf.append(br);
           HTMLComposerImpl.appendHeading(
               buf, InspectionsBundle.message("inspection.export.results.suppress"));
           for (AnAction suppressAction : activeSuppressActions) {
             buf.append(br);
             if (idx == activeSuppressActions.size() - 1) {
               buf.append(br);
             }
             HTMLComposer.appendAfterHeaderIndention(buf);
             @NonNls
             final String href =
                 "<a HREF=\"file://bred.txt#suppress:"
                     + idx
                     + "\">"
                     + suppressAction.getTemplatePresentation().getText()
                     + "</a>";
             buf.append(href);
             idx++;
           }
         }
       }
     }
   }
 }
  private void popupInvoked(Component component, int x, int y) {
    final TreePath path = myTree.getLeadSelectionPath();

    if (path == null) return;

    final DefaultActionGroup actions = new DefaultActionGroup();
    final ActionManager actionManager = ActionManager.getInstance();
    actions.add(actionManager.getAction(IdeActions.ACTION_EDIT_SOURCE));
    actions.add(actionManager.getAction(IdeActions.ACTION_FIND_USAGES));

    actions.add(myIncludeAction);
    actions.add(myExcludeAction);

    actions.addSeparator();

    final InspectionToolWrapper toolWrapper = myTree.getSelectedToolWrapper();
    if (toolWrapper != null) {
      final QuickFixAction[] quickFixes = myProvider.getQuickFixes(toolWrapper, myTree);
      if (quickFixes != null) {
        for (QuickFixAction quickFixe : quickFixes) {
          actions.add(quickFixe);
        }
      }
      final HighlightDisplayKey key = HighlightDisplayKey.find(toolWrapper.getShortName());
      if (key == null) return; // e.g. DummyEntryPointsTool

      // options
      actions.addSeparator();
      actions.add(new EditSettingsAction());
      final List<AnAction> options = new InspectionsOptionsToolbarAction(this).createActions();
      for (AnAction action : options) {
        actions.add(action);
      }
    }

    actions.addSeparator();
    actions.add(actionManager.getAction(IdeActions.GROUP_VERSION_CONTROLS));

    final ActionPopupMenu menu =
        actionManager.createActionPopupMenu(ActionPlaces.CODE_INSPECTION, actions);
    menu.getComponent().show(component, x, y);
  }
 private void addRemoveTestsScope(Project project, boolean add) {
   final InspectionProjectProfileManager profileManager =
       InspectionProjectProfileManager.getInstance(project);
   final InspectionProfileImpl profile =
       (InspectionProfileImpl) profileManager.getCurrentProfile();
   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();
 }
 public void convert(Element element) {
   initInspectionTools();
   final Element scopes = element.getChild(DefaultProjectProfileManager.SCOPES);
   if (scopes != null) {
     final List children = scopes.getChildren(SCOPE);
     if (children != null) {
       for (Object s : children) {
         Element scopeElement = (Element) s;
         final String profile =
             scopeElement.getAttributeValue(DefaultProjectProfileManager.PROFILE);
         if (profile != null) {
           final InspectionProfileImpl inspectionProfile =
               (InspectionProfileImpl) getProfileManager().getProfile(profile);
           if (inspectionProfile != null) {
             final NamedScope scope =
                 getProfileManager()
                     .getScopesManager()
                     .getScope(scopeElement.getAttributeValue(NAME));
             if (scope != null) {
               for (InspectionProfileEntry entry : inspectionProfile.getInspectionTools(null)) {
                 final HighlightDisplayKey key = HighlightDisplayKey.find(entry.getShortName());
                 try {
                   getTools(entry.getShortName())
                       .addTool(
                           scope,
                           copyToolSettings((InspectionTool) entry),
                           inspectionProfile.isToolEnabled(key),
                           inspectionProfile.getErrorLevel(key, (NamedScope) null));
                 } catch (Exception e) {
                   LOG.error(e);
                 }
               }
             }
           }
         }
       }
       reduceConvertedScopes();
     }
   }
 }
 private boolean buildTree() {
   InspectionProfile profile = myInspectionProfile;
   boolean isGroupedBySeverity = myGlobalInspectionContext.getUIOptions().GROUP_BY_SEVERITY;
   myGroups.clear();
   final Map<String, Tools> tools = myGlobalInspectionContext.getTools();
   boolean resultsFound = false;
   for (Tools currentTools : tools.values()) {
     InspectionToolWrapper defaultToolWrapper = currentTools.getDefaultState().getTool();
     final HighlightDisplayKey key = HighlightDisplayKey.find(defaultToolWrapper.getShortName());
     for (ScopeToolState state : myProvider.getTools(currentTools)) {
       InspectionToolWrapper toolWrapper = state.getTool();
       if (myProvider.checkReportedProblems(myGlobalInspectionContext, toolWrapper)) {
         addTool(
             toolWrapper,
             ((InspectionProfileImpl) profile)
                 .getErrorLevel(key, state.getScope(myProject), myProject),
             isGroupedBySeverity);
         resultsFound = true;
       }
     }
   }
   return resultsFound;
 }
 private static HighlightDisplayLevel getHighlightDisplayLevel(
     Project project, GrReferenceElement ref) {
   final InspectionProfile profile =
       InspectionProjectProfileManager.getInstance(project).getInspectionProfile();
   return profile.getErrorLevel(HighlightDisplayKey.find(SHORT_NAME), ref);
 }
 @Override
 public void register(IntentionAction action) {
   myKey = HighlightDisplayKey.find(SHORT_NAME);
   QuickFixAction.registerQuickFixAction(myInfo, action, myKey);
 }
 public InspectionNode(
     @NotNull InspectionToolWrapper toolWrapper, @NotNull InspectionProfile profile) {
   super(toolWrapper);
   myKey = HighlightDisplayKey.find(toolWrapper.getShortName());
   myProfile = profile;
 }
 private static boolean isInspectionEnabled(PsiFile file, Project project) {
   final InspectionProfile profile =
       InspectionProjectProfileManager.getInstance(project).getInspectionProfile();
   final HighlightDisplayKey unusedDefKey = HighlightDisplayKey.find(SHORT_NAME);
   return profile.isToolEnabled(unusedDefKey, file);
 }
  private void exportResults(
      @NotNull final CommonProblemDescriptor[] descriptors,
      @NotNull RefEntity refEntity,
      @NotNull Element parentNode) {
    for (CommonProblemDescriptor descriptor : descriptors) {
      @NonNls final String template = descriptor.getDescriptionTemplate();
      int line =
          descriptor instanceof ProblemDescriptor
              ? ((ProblemDescriptor) descriptor).getLineNumber()
              : -1;
      final PsiElement psiElement =
          descriptor instanceof ProblemDescriptor
              ? ((ProblemDescriptor) descriptor).getPsiElement()
              : null;
      @NonNls
      String problemText =
          StringUtil.replace(
              StringUtil.replace(
                  template,
                  "#ref",
                  psiElement != null
                      ? ProblemDescriptorUtil.extractHighlightedText(descriptor, psiElement)
                      : ""),
              " #loc ",
              " ");

      Element element = refEntity.getRefManager().export(refEntity, parentNode, line);
      if (element == null) return;
      @NonNls
      Element problemClassElement =
          new Element(InspectionsBundle.message("inspection.export.results.problem.element.tag"));
      problemClassElement.addContent(myToolWrapper.getDisplayName());

      final HighlightSeverity severity;
      if (refEntity instanceof RefElement) {
        final RefElement refElement = (RefElement) refEntity;
        severity = getSeverity(refElement);
      } else {
        final InspectionProfile profile =
            InspectionProjectProfileManager.getInstance(getContext().getProject())
                .getInspectionProfile();
        final HighlightDisplayLevel level =
            profile.getErrorLevel(
                HighlightDisplayKey.find(myToolWrapper.getShortName()), psiElement);
        severity = level.getSeverity();
      }

      if (severity != null) {
        ProblemHighlightType problemHighlightType =
            descriptor instanceof ProblemDescriptor
                ? ((ProblemDescriptor) descriptor).getHighlightType()
                : ProblemHighlightType.GENERIC_ERROR_OR_WARNING;
        final String attributeKey =
            getTextAttributeKey(getRefManager().getProject(), severity, problemHighlightType);
        problemClassElement.setAttribute("severity", severity.myName);
        problemClassElement.setAttribute("attribute_key", attributeKey);
      }

      element.addContent(problemClassElement);
      if (myToolWrapper instanceof GlobalInspectionToolWrapper) {
        final GlobalInspectionTool globalInspectionTool =
            ((GlobalInspectionToolWrapper) myToolWrapper).getTool();
        final QuickFix[] fixes = descriptor.getFixes();
        if (fixes != null) {
          @NonNls Element hintsElement = new Element("hints");
          for (QuickFix fix : fixes) {
            final String hint = globalInspectionTool.getHint(fix);
            if (hint != null) {
              @NonNls Element hintElement = new Element("hint");
              hintElement.setAttribute("value", hint);
              hintsElement.addContent(hintElement);
            }
          }
          element.addContent(hintsElement);
        }
      }
      try {
        Element descriptionElement =
            new Element(InspectionsBundle.message("inspection.export.results.description.tag"));
        descriptionElement.addContent(problemText);
        element.addContent(descriptionElement);
      } catch (IllegalDataException e) {
        //noinspection HardCodedStringLiteral,UseOfSystemOutOrSystemErr
        System.out.println(
            "Cannot save results for "
                + refEntity.getName()
                + ", inspection which caused problem: "
                + myToolWrapper.getShortName());
      }
    }
  }