private void reportNullableReturns(
      DataFlowInstructionVisitor visitor,
      ProblemsHolder holder,
      Set<PsiElement> reportedAnchors,
      @NotNull PsiElement block) {
    final PsiMethod method = getScopeMethod(block);
    if (method == null || NullableStuffInspectionBase.isNullableNotInferred(method, true)) return;

    boolean notNullRequired = NullableNotNullManager.isNotNull(method);
    if (!notNullRequired && !SUGGEST_NULLABLE_ANNOTATIONS) return;

    PsiType returnType = method.getReturnType();
    // no warnings in void lambdas, where the expression is not returned anyway
    if (block instanceof PsiExpression
        && block.getParent() instanceof PsiLambdaExpression
        && returnType == PsiType.VOID) return;

    // no warnings for Void methods, where only null can be possibly returned
    if (returnType == null || returnType.equalsToText(CommonClassNames.JAVA_LANG_VOID)) return;

    for (PsiElement statement : visitor.getProblems(NullabilityProblem.nullableReturn)) {
      assert statement instanceof PsiExpression;
      final PsiExpression expr = (PsiExpression) statement;
      if (!reportedAnchors.add(expr)) continue;

      if (notNullRequired) {
        final String text =
            isNullLiteralExpression(expr)
                ? InspectionsBundle.message("dataflow.message.return.null.from.notnull")
                : InspectionsBundle.message("dataflow.message.return.nullable.from.notnull");
        holder.registerProblem(expr, text);
      } else if (AnnotationUtil.isAnnotatingApplicable(statement)) {
        final NullableNotNullManager manager =
            NullableNotNullManager.getInstance(expr.getProject());
        final String defaultNullable = manager.getDefaultNullable();
        final String presentableNullable = StringUtil.getShortName(defaultNullable);
        final String text =
            isNullLiteralExpression(expr)
                ? InspectionsBundle.message(
                    "dataflow.message.return.null.from.notnullable", presentableNullable)
                : InspectionsBundle.message(
                    "dataflow.message.return.nullable.from.notnullable", presentableNullable);
        final LocalQuickFix[] fixes =
            PsiTreeUtil.getParentOfType(expr, PsiMethod.class, PsiLambdaExpression.class)
                    instanceof PsiLambdaExpression
                ? LocalQuickFix.EMPTY_ARRAY
                : new LocalQuickFix[] {
                  new AnnotateMethodFix(
                      defaultNullable, ArrayUtil.toStringArray(manager.getNotNulls())) {
                    @Override
                    public int shouldAnnotateBaseMethod(
                        PsiMethod method, PsiMethod superMethod, Project project) {
                      return 1;
                    }
                  }
                };
        holder.registerProblem(expr, text, fixes);
      }
    }
  }
  public void showDescription(InspectionTool tool) {
    if (tool.getShortName().length() == 0) {
      showEmpty();
      return;
    }
    @NonNls StringBuffer page = new StringBuffer();
    page.append("<table border='0' cellspacing='0' cellpadding='0' width='100%'>");
    page.append("<tr><td colspan='2'>");
    HTMLComposer.appendHeading(
        page, InspectionsBundle.message("inspection.tool.in.browser.id.title"));
    page.append("</td></tr>");
    page.append("<tr><td width='37'></td>" + "<td>");
    page.append(tool.getShortName());
    page.append("</td></tr>");
    page.append("<tr height='10'></tr>");
    page.append("<tr><td colspan='2'>");
    HTMLComposer.appendHeading(
        page, InspectionsBundle.message("inspection.tool.in.browser.description.title"));
    page.append("</td></tr>");
    page.append("<tr><td width='37'></td>" + "<td>");
    @NonNls final String underConstruction = "<b>" + UNDER_CONSTRUCTION + "</b></html>";
    try {
      @NonNls String description = tool.loadDescription();
      if (description == null) {
        description = underConstruction;
      }
      page.append(UIUtil.getHtmlBody(description));

      page.append("</td></tr></table>");
      myHTMLViewer.setText(XmlStringUtil.wrapInHtml(page));
      setupStyle();
    } finally {
      myCurrentEntity = null;
    }
  }
    @Override
    public void customizeCellRenderer(
        JTree tree,
        Object value,
        boolean selected,
        boolean expanded,
        boolean leaf,
        int row,
        boolean hasFocus) {
      InspectionTreeNode node = (InspectionTreeNode) value;

      append(
          node.toString(),
          patchAttr(
              node,
              appearsBold(node)
                  ? SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES
                  : getMainForegroundAttributes(node)));

      int problemCount = node.getProblemCount();
      if (!leaf) {
        append(
            " " + InspectionsBundle.message("inspection.problem.descriptor.count", problemCount),
            patchAttr(node, SimpleTextAttributes.GRAYED_ATTRIBUTES));
      }

      if (!node.isValid()) {
        append(
            " " + InspectionsBundle.message("inspection.invalid.node.text"),
            patchAttr(node, SimpleTextAttributes.ERROR_ATTRIBUTES));
      } else {
        setIcon(node.getIcon(expanded));
      }
    }
 public RerunAction(JComponent comp) {
   super(
       InspectionsBundle.message("inspection.action.rerun"),
       InspectionsBundle.message("inspection.action.rerun"),
       AllIcons.Actions.Rerun);
   registerCustomShortcutSet(CommonShortcuts.getRerun(), comp);
 }
 private void handleBranchingInstruction(
     ProblemsHolder holder,
     StandardInstructionVisitor visitor,
     Set<Instruction> trueSet,
     Set<Instruction> falseSet,
     HashSet<PsiElement> reportedAnchors,
     BranchingInstruction instruction,
     final boolean onTheFly) {
   PsiElement psiAnchor = instruction.getPsiAnchor();
   boolean underBinary = isAtRHSOfBooleanAnd(psiAnchor);
   if (instruction instanceof InstanceofInstruction
       && visitor.isInstanceofRedundant((InstanceofInstruction) instruction)) {
     if (visitor.canBeNull((BinopInstruction) instruction)) {
       holder.registerProblem(
           psiAnchor,
           InspectionsBundle.message("dataflow.message.redundant.instanceof"),
           new RedundantInstanceofFix());
     } else {
       final LocalQuickFix localQuickFix = createSimplifyBooleanExpressionFix(psiAnchor, true);
       holder.registerProblem(
           psiAnchor,
           InspectionsBundle.message(
               underBinary
                   ? "dataflow.message.constant.condition.when.reached"
                   : "dataflow.message.constant.condition",
               Boolean.toString(true)),
           localQuickFix == null ? null : new LocalQuickFix[] {localQuickFix});
     }
   } else if (psiAnchor instanceof PsiSwitchLabelStatement) {
     if (falseSet.contains(instruction)) {
       holder.registerProblem(
           psiAnchor, InspectionsBundle.message("dataflow.message.unreachable.switch.label"));
     }
   } else if (psiAnchor != null
       && !reportedAnchors.contains(psiAnchor)
       && !isFlagCheck(psiAnchor)) {
     boolean evaluatesToTrue = trueSet.contains(instruction);
     final PsiElement parent = psiAnchor.getParent();
     if (parent instanceof PsiAssignmentExpression
         && ((PsiAssignmentExpression) parent).getLExpression() == psiAnchor) {
       holder.registerProblem(
           psiAnchor,
           InspectionsBundle.message(
               "dataflow.message.pointless.assignment.expression",
               Boolean.toString(evaluatesToTrue)),
           createConditionalAssignmentFixes(
               evaluatesToTrue, (PsiAssignmentExpression) parent, onTheFly));
     } else if (!skipReportingConstantCondition(visitor, psiAnchor, evaluatesToTrue)) {
       final LocalQuickFix fix = createSimplifyBooleanExpressionFix(psiAnchor, evaluatesToTrue);
       String message =
           InspectionsBundle.message(
               underBinary
                   ? "dataflow.message.constant.condition.when.reached"
                   : "dataflow.message.constant.condition",
               Boolean.toString(evaluatesToTrue));
       holder.registerProblem(psiAnchor, message, fix == null ? null : new LocalQuickFix[] {fix});
     }
     reportedAnchors.add(psiAnchor);
   }
 }
    private OptionsPanel() {
      super(new GridBagLayout());

      GridBagConstraints gc = new GridBagConstraints();
      gc.fill = GridBagConstraints.HORIZONTAL;
      gc.weightx = 1;
      gc.weighty = 0;
      gc.anchor = GridBagConstraints.NORTHWEST;

      myPackageLocalForMembersCheckbox =
          new JCheckBox(InspectionsBundle.message("inspection.visibility.option"));
      myPackageLocalForMembersCheckbox.setSelected(SUGGEST_PACKAGE_LOCAL_FOR_MEMBERS);
      myPackageLocalForMembersCheckbox
          .getModel()
          .addChangeListener(
              new ChangeListener() {
                @Override
                public void stateChanged(ChangeEvent e) {
                  SUGGEST_PACKAGE_LOCAL_FOR_MEMBERS = myPackageLocalForMembersCheckbox.isSelected();
                }
              });

      gc.gridy = 0;
      add(myPackageLocalForMembersCheckbox, gc);

      myPackageLocalForTopClassesCheckbox =
          new JCheckBox(InspectionsBundle.message("inspection.visibility.option1"));
      myPackageLocalForTopClassesCheckbox.setSelected(SUGGEST_PACKAGE_LOCAL_FOR_TOP_CLASSES);
      myPackageLocalForTopClassesCheckbox
          .getModel()
          .addChangeListener(
              new ChangeListener() {
                @Override
                public void stateChanged(ChangeEvent e) {
                  SUGGEST_PACKAGE_LOCAL_FOR_TOP_CLASSES =
                      myPackageLocalForTopClassesCheckbox.isSelected();
                }
              });

      gc.gridy = 1;
      add(myPackageLocalForTopClassesCheckbox, gc);

      myPrivateForInnersCheckbox =
          new JCheckBox(InspectionsBundle.message("inspection.visibility.option2"));
      myPrivateForInnersCheckbox.setSelected(SUGGEST_PRIVATE_FOR_INNERS);
      myPrivateForInnersCheckbox
          .getModel()
          .addChangeListener(
              new ChangeListener() {
                @Override
                public void stateChanged(ChangeEvent e) {
                  SUGGEST_PRIVATE_FOR_INNERS = myPrivateForInnersCheckbox.isSelected();
                }
              });

      gc.gridy = 2;
      gc.weighty = 1;
      add(myPrivateForInnersCheckbox, gc);
    }
 public ExportToHTMLDialog(Project project, final boolean canBeOpenInBrowser) {
   super(project, true);
   myProject = project;
   myCanBeOpenInBrowser = canBeOpenInBrowser;
   setOKButtonText(InspectionsBundle.message("inspection.export.save.button"));
   setTitle(InspectionsBundle.message("inspection.export.dialog.title"));
   init();
 }
Example #8
0
    private OptionsPanel() {
      super(new GridBagLayout());

      GridBagConstraints gc = new GridBagConstraints();
      gc.weighty = 0;
      gc.weightx = 1;
      gc.fill = GridBagConstraints.HORIZONTAL;
      gc.anchor = GridBagConstraints.NORTHWEST;

      myReportClassesCheckbox =
          new JCheckBox(InspectionsBundle.message("inspection.can.be.final.option"));
      myReportClassesCheckbox.setSelected(REPORT_CLASSES);
      myReportClassesCheckbox
          .getModel()
          .addChangeListener(
              new ChangeListener() {
                @Override
                public void stateChanged(ChangeEvent e) {
                  REPORT_CLASSES = myReportClassesCheckbox.isSelected();
                }
              });
      gc.gridy = 0;
      add(myReportClassesCheckbox, gc);

      myReportMethodsCheckbox =
          new JCheckBox(InspectionsBundle.message("inspection.can.be.final.option1"));
      myReportMethodsCheckbox.setSelected(REPORT_METHODS);
      myReportMethodsCheckbox
          .getModel()
          .addChangeListener(
              new ChangeListener() {
                @Override
                public void stateChanged(ChangeEvent e) {
                  REPORT_METHODS = myReportMethodsCheckbox.isSelected();
                }
              });
      gc.gridy++;
      add(myReportMethodsCheckbox, gc);

      myReportFieldsCheckbox =
          new JCheckBox(InspectionsBundle.message("inspection.can.be.final.option2"));
      myReportFieldsCheckbox.setSelected(REPORT_FIELDS);
      myReportFieldsCheckbox
          .getModel()
          .addChangeListener(
              new ChangeListener() {
                @Override
                public void stateChanged(ChangeEvent e) {
                  REPORT_FIELDS = myReportFieldsCheckbox.isSelected();
                }
              });

      gc.weighty = 1;
      gc.gridy++;
      add(myReportFieldsCheckbox, gc);
    }
  private static void reportNullableAssignments(
      DataFlowInstructionVisitor visitor, ProblemsHolder holder, Set<PsiElement> reportedAnchors) {
    for (PsiElement expr : visitor.getProblems(NullabilityProblem.assigningToNotNull)) {
      if (!reportedAnchors.add(expr)) continue;

      final String text =
          isNullLiteralExpression(expr)
              ? InspectionsBundle.message("dataflow.message.assigning.null")
              : InspectionsBundle.message("dataflow.message.assigning.nullable");
      holder.registerProblem(expr, text);
    }
  }
Example #10
0
  @RequiredReadAction
  @Override
  public void compose(StringBuffer buf, RefEntity refElement, CommonProblemDescriptor descriptor) {
    CommonProblemDescriptor[] descriptions = myTool.getDescriptions(refElement);

    int problemIdx = 0;
    if (descriptions != null) { // server-side inspections
      problemIdx = -1;
      for (int i = 0; i < descriptions.length; i++) {
        CommonProblemDescriptor description = descriptions[i];
        if (description == descriptor) {
          problemIdx = i;
          break;
        }
      }
      if (problemIdx == -1) return;
    }

    genPageHeader(buf, refElement);
    appendHeading(buf, InspectionsBundle.message("inspection.problem.synopsis"));
    //noinspection HardCodedStringLiteral
    buf.append("<br>");
    appendAfterHeaderIndention(buf);

    composeDescription(descriptor, problemIdx, buf, refElement);

    if (refElement instanceof RefElement && !refElement.isValid()) return;

    final QuickFix[] fixes = descriptor.getFixes();
    if (fixes != null && fixes.length > 0) {
      //noinspection HardCodedStringLiteral
      buf.append("<br><br>");
      appendHeading(buf, InspectionsBundle.message("inspection.problem.resolution"));
      //noinspection HardCodedStringLiteral
      buf.append("<br>");
      appendAfterHeaderIndention(buf);

      int idx = 0;
      for (QuickFix fix : fixes) {
        //noinspection HardCodedStringLiteral
        //noinspection HardCodedStringLiteral
        buf.append("<a HREF=\"file://bred.txt#invokelocal:").append(idx++);
        buf.append("\">");
        buf.append(fix.getName());
        //noinspection HardCodedStringLiteral
        buf.append("</a>");
        //noinspection HardCodedStringLiteral
        buf.append("<br>");
        appendAfterHeaderIndention(buf);
      }
    }
  }
 private void appendNavBar(@NonNls final StringBuffer buf, RefEntity element) {
   buf.append("<a href=\"../index.html\" target=\"_top\">");
   buf.append(InspectionsBundle.message("inspection.export.inspections.link.text"));
   buf.append("</a>  ");
   if (element instanceof RefElement) {
     myComposer.appendElementReference(
         buf,
         getURL(element),
         InspectionsBundle.message("inspection.export.open.source.link.text"),
         "_blank");
   }
   buf.append("<hr>");
 }
  private void reportNullableArguments(
      DataFlowInstructionVisitor visitor, ProblemsHolder holder, Set<PsiElement> reportedAnchors) {
    for (PsiElement expr :
        visitor.getProblems(NullabilityProblem.passingNullableToNotNullParameter)) {
      if (!reportedAnchors.add(expr)) continue;

      final String text =
          isNullLiteralExpression(expr)
              ? InspectionsBundle.message("dataflow.message.passing.null.argument")
              : InspectionsBundle.message("dataflow.message.passing.nullable.argument");
      LocalQuickFix[] fixes =
          createNPEFixes((PsiExpression) expr, (PsiExpression) expr, holder.isOnTheFly());
      holder.registerProblem(expr, text, fixes);
    }
  }
 private void reportFieldAccessMayProduceNpe(
     ProblemsHolder holder, PsiElement elementToAssert, PsiExpression expression) {
   if (expression instanceof PsiArrayAccessExpression) {
     LocalQuickFix[] fix =
         createNPEFixes((PsiExpression) elementToAssert, expression, holder.isOnTheFly());
     holder.registerProblem(
         expression, InspectionsBundle.message("dataflow.message.npe.array.access"), fix);
   } else {
     LocalQuickFix[] fix =
         createNPEFixes((PsiExpression) elementToAssert, expression, holder.isOnTheFly());
     assert elementToAssert != null;
     holder.registerProblem(
         elementToAssert, InspectionsBundle.message("dataflow.message.npe.field.access"), fix);
   }
 }
  @Nullable
  public CommonProblemDescriptor[] checkElement(
      final RefEntity refEntity,
      final AnalysisScope scope,
      final InspectionManager manager,
      final GlobalInspectionContext globalContext,
      final ProblemDescriptionsProcessor processor) {
    if (refEntity instanceof RefMethod) {
      final RefMethod refMethod = (RefMethod) refEntity;

      if (refMethod.isSyntheticJSP()) return null;

      if (refMethod.isExternalOverride()) return null;

      if (!(refMethod.isStatic() || refMethod.isConstructor())
          && !refMethod.getSuperMethods().isEmpty()) return null;

      if ((refMethod.isAbstract() || refMethod.getOwnerClass().isInterface())
          && refMethod.getDerivedMethods().isEmpty()) return null;

      if (RefUtil.isEntryPoint(refMethod)) return null;

      if (refMethod.isAppMain()) return null;

      final ArrayList<RefParameter> unusedParameters = getUnusedParameters(refMethod);

      if (unusedParameters.isEmpty()) return null;

      final List<ProblemDescriptor> result = new ArrayList<ProblemDescriptor>();
      for (RefParameter refParameter : unusedParameters) {
        final PsiIdentifier psiIdentifier = refParameter.getElement().getNameIdentifier();
        if (psiIdentifier != null) {
          result.add(
              manager.createProblemDescriptor(
                  psiIdentifier,
                  refMethod.isAbstract()
                      ? InspectionsBundle.message("inspection.unused.parameter.composer")
                      : InspectionsBundle.message("inspection.unused.parameter.composer1"),
                  new AcceptSuggested(
                      globalContext.getRefManager(), processor, refParameter.toString()),
                  ProblemHighlightType.LIKE_UNUSED_SYMBOL,
                  false));
        }
      }
      return result.toArray(new CommonProblemDescriptor[result.size()]);
    }
    return null;
  }
  private void analyzeDfaWithNestedClosures(
      PsiElement scope,
      ProblemsHolder holder,
      StandardDataFlowRunner dfaRunner,
      Collection<DfaMemoryState> initialStates) {
    final DataFlowInstructionVisitor visitor = new DataFlowInstructionVisitor(dfaRunner);
    final RunnerResult rc =
        dfaRunner.analyzeMethod(scope, visitor, IGNORE_ASSERT_STATEMENTS, initialStates);
    if (rc == RunnerResult.OK) {
      createDescription(dfaRunner, holder, visitor);

      MultiMap<PsiElement, DfaMemoryState> nestedClosures = dfaRunner.getNestedClosures();
      for (PsiElement closure : nestedClosures.keySet()) {
        analyzeDfaWithNestedClosures(closure, holder, dfaRunner, nestedClosures.get(closure));
      }
    } else if (rc == RunnerResult.TOO_COMPLEX) {
      if (scope.getParent() instanceof PsiMethod) {
        PsiMethod method = (PsiMethod) scope.getParent();
        final PsiIdentifier name = method.getNameIdentifier();
        if (name != null) { // Might be null for synthetic methods like JSP page.
          holder.registerProblem(
              name,
              InspectionsBundle.message("dataflow.too.complex"),
              ProblemHighlightType.WEAK_WARNING);
        }
      }
    }
  }
  public static void writeFileImpl(String folder, @NonNls String fileName, CharSequence buf)
      throws IOException {
    ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
    final String fullPath = folder + File.separator + fileName;

    if (indicator != null) {
      ProgressManager.checkCanceled();
      indicator.setText(
          InspectionsBundle.message("inspection.export.generating.html.for", fullPath));
    }

    FileWriter writer = null;
    try {
      File folderFile = new File(folder);
      folderFile.mkdirs();
      new File(fullPath).getParentFile().mkdirs();
      writer = new FileWriter(fullPath);
      writer.write(buf.toString().toCharArray());
    } finally {
      if (writer != null) {
        try {
          writer.close();
        } catch (IOException e) {
          // Cannot do anything in case of exception
        }
      }
    }
  }
Example #17
0
  @RequiredReadAction
  @Override
  public void compose(StringBuffer buf, RefEntity refEntity) {
    genPageHeader(buf, refEntity);
    if (myTool.getDescriptions(refEntity) != null) {
      appendHeading(buf, InspectionsBundle.message("inspection.problem.synopsis"));

      CommonProblemDescriptor[] descriptions = myTool.getDescriptions(refEntity);

      LOG.assertTrue(descriptions != null);

      startList(buf);
      for (int i = 0; i < descriptions.length; i++) {
        final CommonProblemDescriptor description = descriptions[i];

        startListItem(buf);
        composeDescription(description, i, buf, refEntity);
        doneListItem(buf);
      }

      doneList(buf);

      appendResolution(buf, refEntity, quickFixTexts(refEntity, myTool));
    } else {
      appendNoProblems(buf);
    }
  }
 @Override
 public boolean isAvailable(
     @NotNull final Project project, final Editor editor, @NotNull final PsiElement context) {
   PsiDocCommentOwner container = getContainer(context);
   boolean isValid = container != null && !(container instanceof JspHolderMethod);
   if (!isValid) {
     return false;
   }
   myText =
       container instanceof PsiClass
           ? InspectionsBundle.message("suppress.inspection.class")
           : container instanceof PsiMethod
               ? InspectionsBundle.message("suppress.inspection.method")
               : InspectionsBundle.message("suppress.inspection.field");
   return true;
 }
  @Override
  public String getDescription(@NotNull final String refSuffix, @NotNull final Editor editor) {
    final Project project = editor.getProject();
    if (project == null) {
      LOG.error(editor);
      return null;
    }
    if (project.isDisposed()) return null;
    final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
    if (file == null) {
      return null;
    }

    final InspectionProfile profile = InspectionProfileManager.getInstance().getCurrentProfile();
    final InspectionToolWrapper toolWrapper = profile.getInspectionTool(refSuffix, file);
    if (toolWrapper == null) return null;

    String description = toolWrapper.loadDescription();
    if (description == null) {
      LOG.warn("No description for inspection '" + refSuffix + "'");
      description =
          InspectionsBundle.message("inspection.tool.description.under.construction.text");
    }
    return description;
  }
 @Override
 public JComponent createOptionsPanel() {
   final MultipleCheckboxOptionsPanel optionsPanel = new MultipleCheckboxOptionsPanel(this);
   optionsPanel.addCheckbox(
       InspectionGadgetsBundle.message("return.of.null.ignore.private.option"),
       "m_ignorePrivateMethods");
   optionsPanel.addCheckbox(
       InspectionGadgetsBundle.message("return.of.null.arrays.option"), "m_reportArrayMethods");
   optionsPanel.addCheckbox(
       InspectionGadgetsBundle.message("return.of.null.collections.option"),
       "m_reportCollectionMethods");
   optionsPanel.addCheckbox(
       InspectionGadgetsBundle.message("return.of.null.objects.option"), "m_reportObjectMethods");
   final JButton configureAnnotations =
       new JButton(InspectionsBundle.message("configure.annotations.option"));
   configureAnnotations.addActionListener(
       new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
           Project project =
               CommonDataKeys.PROJECT.getData(
                   DataManager.getInstance().getDataContext(optionsPanel));
           if (project == null) project = ProjectManager.getInstance().getDefaultProject();
           new NullableNotNullDialog(project).show();
         }
       });
   optionsPanel.addComponent(configureAnnotations);
   return optionsPanel;
 }
Example #21
0
  private static void docheckClass(final PsiClass aClass, ProblemsHolder holder) {
    if (aClass.isInterface()) return;
    final PsiField[] fields = aClass.getFields();
    final Set<PsiField> candidates = new LinkedHashSet<PsiField>();
    for (PsiField field : fields) {
      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<PsiField>();
    removeReadFields(aClass, candidates, usedFields);

    if (candidates.isEmpty()) return;
    final ImplicitUsageProvider[] implicitUsageProviders =
        Extensions.getExtensions(ImplicitUsageProvider.EP_NAME);

    for (PsiField field : candidates) {
      if (usedFields.contains(field)
          && !hasImplicitReadOrWriteUsage(field, implicitUsageProviders)) {
        final String message =
            InspectionsBundle.message("inspection.field.can.be.local.problem.descriptor");
        holder.registerProblem(field.getNameIdentifier(), message, new MyQuickFix(field));
      }
    }
  }
 private static void checkMethodReference(
     PsiMethodReferenceExpression expression,
     InspectionManager inspectionManager,
     List<ProblemDescriptor> problems) {
   final PsiTypeElement qualifierTypeElement = expression.getQualifierType();
   if (qualifierTypeElement != null) {
     final PsiType psiType = qualifierTypeElement.getType();
     if (psiType instanceof PsiClassType && !(((PsiClassType) psiType).isRaw())) {
       final JavaResolveResult result = expression.advancedResolve(false);
       final PsiElement element = result.getElement();
       if (element instanceof PsiTypeParameterListOwner) {
         final PsiMethodReferenceExpression copy =
             createMethodReference(expression, qualifierTypeElement);
         final JavaResolveResult simplifiedResolve = copy.advancedResolve(false);
         final PsiElement candidate = simplifiedResolve.getElement();
         if (candidate == element) {
           final PsiJavaCodeReferenceElement referenceElement =
               qualifierTypeElement.getInnermostComponentReferenceElement();
           LOG.assertTrue(referenceElement != null, qualifierTypeElement);
           final PsiReferenceParameterList parameterList = referenceElement.getParameterList();
           LOG.assertTrue(parameterList != null);
           final ProblemDescriptor descriptor =
               inspectionManager.createProblemDescriptor(
                   parameterList,
                   InspectionsBundle.message("inspection.redundant.type.problem.descriptor"),
                   new MyMethodReferenceFixAction(),
                   ProblemHighlightType.LIKE_UNUSED_SYMBOL,
                   false);
           problems.add(descriptor);
         }
       }
     }
   }
 }
 private static void checkSillyAssignment(
     PsiAssignmentExpression assignment, ProblemsHolder holder) {
   if (assignment.getOperationTokenType() != JavaTokenType.EQ) return;
   PsiExpression lExpression = assignment.getLExpression();
   PsiExpression rExpression = assignment.getRExpression();
   if (rExpression == null) return;
   lExpression = PsiUtil.deparenthesizeExpression(lExpression);
   rExpression = PsiUtil.deparenthesizeExpression(rExpression);
   if (!(lExpression instanceof PsiReferenceExpression)) return;
   PsiReferenceExpression rRef;
   if (!(rExpression instanceof PsiReferenceExpression)) {
     if (!(rExpression instanceof PsiAssignmentExpression)) return;
     final PsiAssignmentExpression rAssignmentExpression = (PsiAssignmentExpression) rExpression;
     final PsiExpression assignee =
         PsiUtil.deparenthesizeExpression(rAssignmentExpression.getLExpression());
     if (!(assignee instanceof PsiReferenceExpression)) return;
     rRef = (PsiReferenceExpression) assignee;
   } else {
     rRef = (PsiReferenceExpression) rExpression;
   }
   PsiReferenceExpression lRef = (PsiReferenceExpression) lExpression;
   PsiManager manager = assignment.getManager();
   if (!sameInstanceReferences(lRef, rRef, manager)) return;
   final PsiVariable variable = (PsiVariable) lRef.resolve();
   if (variable == null) return;
   holder.registerProblem(
       assignment,
       InspectionsBundle.message("assignment.to.itself.problem.descriptor", variable.getName()),
       ProblemHighlightType.LIKE_UNUSED_SYMBOL);
 }
 private static void reportUnboxedNullables(
     DataFlowInstructionVisitor visitor, ProblemsHolder holder, Set<PsiElement> reportedAnchors) {
   for (PsiElement expr : visitor.getProblems(NullabilityProblem.unboxingNullable)) {
     if (!reportedAnchors.add(expr)) continue;
     holder.registerProblem(expr, InspectionsBundle.message("dataflow.message.unboxing"));
   }
 }
  @Override
  public String getQualifiedName(RefEntity refEntity) {
    if (refEntity == null || refEntity instanceof RefElementImpl && !refEntity.isValid()) {
      return InspectionsBundle.message("inspection.reference.invalid");
    }

    return refEntity.getQualifiedName();
  }
 @Nullable
 @Override
 public JComponent createOptionsPanel() {
   return new SingleCheckboxOptionsPanel(
       InspectionsBundle.message("inspection.duplicate.throws.ignore.subclassing.option"),
       this,
       "ignoreSubclassing");
 }
  public void appendDerivedClasses(StringBuffer buf, RefClass refClass) {
    if (refClass.getSubClasses().size() > 0) {
      if (refClass.isInterface()) {
        HTMLComposerImpl.appendHeading(
            buf, InspectionsBundle.message("inspection.export.results.extended.implemented"));
      } else {
        HTMLComposerImpl.appendHeading(
            buf, InspectionsBundle.message("inspection.export.results.extended"));
      }

      myComposer.startList(buf);
      for (RefClass refDerived : refClass.getSubClasses()) {
        myComposer.appendListItem(buf, refDerived);
      }
      myComposer.doneList(buf);
    }
  }
 private static void reportCastMayFail(ProblemsHolder holder, TypeCastInstruction instruction) {
   PsiTypeCastExpression typeCast = instruction.getCastExpression();
   PsiExpression operand = typeCast.getOperand();
   PsiTypeElement castType = typeCast.getCastType();
   assert castType != null;
   assert operand != null;
   holder.registerProblem(
       castType, InspectionsBundle.message("dataflow.message.cce", operand.getText()));
 }
  protected JComponent createCenterPanel() {
    if (!myCanBeOpenInBrowser) return null;
    OptionGroup optionGroup =
        new OptionGroup(InspectionsBundle.message("inspection.export.options.panel.title"));

    addOptions(optionGroup);

    return optionGroup.createPanel();
  }
  private synchronized void writeOutput(
      @NotNull final CommonProblemDescriptor[] descriptions, @NotNull RefEntity refElement) {
    final Element parentNode = new Element(InspectionsBundle.message("inspection.problems"));
    exportResults(descriptions, refElement, parentNode);
    final List list = parentNode.getChildren();

    @NonNls final String ext = ".xml";
    final String fileName = ourOutputPath + File.separator + myToolWrapper.getShortName() + ext;
    final PathMacroManager pathMacroManager =
        PathMacroManager.getInstance(getContext().getProject());
    PrintWriter printWriter = null;
    try {
      new File(ourOutputPath).mkdirs();
      final File file = new File(fileName);
      final CharArrayWriter writer = new CharArrayWriter();
      if (!file.exists()) {
        writer
            .append("<")
            .append(InspectionsBundle.message("inspection.problems"))
            .append(" " + GlobalInspectionContextBase.LOCAL_TOOL_ATTRIBUTE + "=\"")
            .append(Boolean.toString(myToolWrapper instanceof LocalInspectionToolWrapper))
            .append("\">\n");
      }
      for (Object o : list) {
        final Element element = (Element) o;
        pathMacroManager.collapsePaths(element);
        JDOMUtil.writeElement(element, writer, "\n");
      }
      printWriter =
          new PrintWriter(
              new BufferedWriter(
                  new OutputStreamWriter(
                      new FileOutputStream(fileName, true), CharsetToolkit.UTF8_CHARSET)));
      printWriter.append("\n");
      printWriter.append(writer.toString());
    } catch (IOException e) {
      LOG.error(e);
    } finally {
      if (printWriter != null) {
        printWriter.close();
      }
    }
  }