@Nullable
  private LocalQuickFix[] createNPEFixes(
      PsiExpression qualifier, PsiExpression expression, boolean onTheFly) {
    if (qualifier == null || expression == null) return null;
    if (qualifier instanceof PsiMethodCallExpression) return null;
    if (qualifier instanceof PsiLiteralExpression
        && ((PsiLiteralExpression) qualifier).getValue() == null) return null;

    try {
      final List<LocalQuickFix> fixes = new SmartList<LocalQuickFix>();

      if (PsiUtil.getLanguageLevel(qualifier).isAtLeast(LanguageLevel.JDK_1_4)) {
        final Project project = qualifier.getProject();
        final PsiElementFactory elementFactory =
            JavaPsiFacade.getInstance(project).getElementFactory();
        final PsiBinaryExpression binary =
            (PsiBinaryExpression) elementFactory.createExpressionFromText("a != null", null);
        binary.getLOperand().replace(qualifier);
        fixes.add(new AddAssertStatementFix(binary));
      }

      addSurroundWithIfFix(qualifier, fixes, onTheFly);

      if (ReplaceWithTernaryOperatorFix.isAvailable(qualifier, expression)) {
        fixes.add(new ReplaceWithTernaryOperatorFix(qualifier));
      }
      return fixes.toArray(new LocalQuickFix[fixes.size()]);
    } catch (IncorrectOperationException e) {
      LOG.error(e);
      return null;
    }
  }
  @Nullable
  private ProblemDescriptor[] checkMember(
      final PsiDocCommentOwner docCommentOwner,
      final InspectionManager manager,
      final boolean isOnTheFly) {
    final ArrayList<ProblemDescriptor> problems = new ArrayList<ProblemDescriptor>();
    final PsiDocComment docComment = docCommentOwner.getDocComment();
    if (docComment == null) return null;

    final Set<PsiJavaCodeReferenceElement> references = new HashSet<PsiJavaCodeReferenceElement>();
    docComment.accept(getVisitor(references, docCommentOwner, problems, manager, isOnTheFly));
    for (PsiJavaCodeReferenceElement reference : references) {
      final List<PsiClass> classesToImport = new ImportClassFix(reference).getClassesToImport();
      final PsiElement referenceNameElement = reference.getReferenceNameElement();
      problems.add(
          manager.createProblemDescriptor(
              referenceNameElement != null ? referenceNameElement : reference,
              cannotResolveSymbolMessage("<code>" + reference.getText() + "</code>"),
              !isOnTheFly || classesToImport.isEmpty() ? null : new AddImportFix(classesToImport),
              ProblemHighlightType.LIKE_UNKNOWN_SYMBOL,
              isOnTheFly));
    }

    return problems.isEmpty() ? null : problems.toArray(new ProblemDescriptor[problems.size()]);
  }
    private void reportMissingOnClickProblem(
        OnClickConverter.MyReference reference,
        PsiClass activity,
        String methodName,
        boolean incorrectSignature) {
      String activityName = activity.getName();

      if (activityName == null) {
        activityName = "";
      }
      final String message =
          incorrectSignature
              ? AndroidBundle.message(
                  "android.inspections.on.click.missing.incorrect.signature",
                  methodName,
                  activityName)
              : AndroidBundle.message(
                  "android.inspections.on.click.missing.problem", methodName, activityName);

      final LocalQuickFix[] fixes =
          StringUtil.isJavaIdentifier(methodName)
              ? new LocalQuickFix[] {new MyQuickFix(methodName, reference.getConverter(), activity)}
              : LocalQuickFix.EMPTY_ARRAY;

      myResult.add(
          myInspectionManager.createProblemDescriptor(
              reference.getElement(),
              reference.getRangeInElement(),
              message,
              ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
              myOnTheFly,
              fixes));
    }
 public void applyFix(
     @NotNull final Project project, @NotNull final ProblemDescriptor descriptor) {
   final PsiElement element =
       PsiTreeUtil.getParentOfType(
           descriptor.getPsiElement(), PsiJavaCodeReferenceElement.class);
   if (element instanceof PsiJavaCodeReferenceElement) {
     final PsiJavaCodeReferenceElement referenceElement = (PsiJavaCodeReferenceElement) element;
     Collections.sort(
         myClassesToImport, new PsiProximityComparator(referenceElement.getElement()));
     final JList list =
         new JBList(myClassesToImport.toArray(new PsiClass[myClassesToImport.size()]));
     list.setCellRenderer(new FQNameCellRenderer());
     final Runnable runnable =
         new Runnable() {
           public void run() {
             if (!element.isValid()) return;
             final int index = list.getSelectedIndex();
             if (index < 0) return;
             new WriteCommandAction(project, element.getContainingFile()) {
               protected void run(final Result result) throws Throwable {
                 final PsiClass psiClass = myClassesToImport.get(index);
                 if (psiClass.isValid()) {
                   PsiDocumentManager.getInstance(project).commitAllDocuments();
                   referenceElement.bindToElement(psiClass);
                 }
               }
             }.execute();
           }
         };
     final AsyncResult<DataContext> asyncResult =
         DataManager.getInstance().getDataContextFromFocus();
     asyncResult.doWhenDone(
         new AsyncResult.Handler<DataContext>() {
           @Override
           public void run(DataContext dataContext) {
             final Editor editor = PlatformDataKeys.EDITOR.getData(dataContext);
             assert editor != null; // available for on the fly mode only
             new PopupChooserBuilder(list)
                 .setTitle(QuickFixBundle.message("class.to.import.chooser.title"))
                 .setItemChoosenCallback(runnable)
                 .createPopup()
                 .showInBestPositionFor(editor);
           }
         });
   }
 }
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
      final Editor editor =
          PlatformDataKeys.EDITOR.getData(DataManager.getInstance().getDataContext());
      assert editor != null;
      final TextRange textRange = ((ProblemDescriptorImpl) descriptor).getTextRange();
      editor.getSelectionModel().setSelection(textRange.getStartOffset(), textRange.getEndOffset());

      final String word = editor.getSelectionModel().getSelectedText();

      if (word == null || StringUtil.isEmptyOrSpaces(word)) {
        return;
      }
      final List<LookupElement> items = new ArrayList<LookupElement>();
      for (String variant : myUnboundParams) {
        items.add(LookupElementBuilder.create(variant));
      }
      LookupManager.getInstance(project)
          .showLookup(editor, items.toArray(new LookupElement[items.size()]));
    }
  @NotNull
  private static Collection<PsiClass> findRelatedActivities(
      @NotNull XmlFile file,
      @NotNull AndroidFacet facet,
      @NotNull DomFileDescription<?> description) {
    if (description instanceof LayoutDomFileDescription) {
      final Computable<List<GotoRelatedItem>> computable =
          AndroidGotoRelatedProvider.getLazyItemsForXmlFile(file, facet);

      if (computable == null) {
        return Collections.emptyList();
      }
      final List<GotoRelatedItem> items = computable.compute();

      if (items.isEmpty()) {
        return Collections.emptyList();
      }
      final PsiClass activityClass = findActivityClass(facet.getModule());

      if (activityClass == null) {
        return Collections.emptyList();
      }
      final List<PsiClass> result = new ArrayList<PsiClass>();

      for (GotoRelatedItem item : items) {
        final PsiElement element = item.getElement();

        if (element instanceof PsiClass) {
          final PsiClass aClass = (PsiClass) element;

          if (aClass.isInheritor(activityClass, true)) {
            result.add(aClass);
          }
        }
      }
      return result;
    } else {
      return findRelatedActivitiesForMenu(file, facet);
    }
  }
 @Nullable
 public static String checkContract(PsiMethod method, String text) {
   List<MethodContract> contracts;
   try {
     contracts = ControlFlowAnalyzer.parseContract(text);
   } catch (ControlFlowAnalyzer.ParseException e) {
     return e.getMessage();
   }
   int paramCount = method.getParameterList().getParametersCount();
   for (int i = 0; i < contracts.size(); i++) {
     MethodContract contract = contracts.get(i);
     if (contract.arguments.length != paramCount) {
       return "Method takes "
           + paramCount
           + " parameters, while contract clause number "
           + (i + 1)
           + " expects "
           + contract.arguments.length;
     }
   }
   return null;
 }
  public static void visitRefInDocTag(
      final PsiDocTag tag,
      final JavadocManager manager,
      final PsiElement context,
      final ArrayList<ProblemDescriptor> problems,
      final InspectionManager inspectionManager,
      final boolean onTheFly) {
    final String tagName = tag.getName();
    final PsiDocTagValue value = tag.getValueElement();
    if (value == null) return;
    final JavadocTagInfo info = manager.getTagInfo(tagName);
    if (info != null && !info.isValidInContext(context)) return;
    final String message = info == null || !info.isInline() ? null : info.checkTagValue(value);
    if (message != null) {
      problems.add(createDescriptor(value, message, inspectionManager, onTheFly));
    }

    final PsiReference reference = value.getReference();
    if (reference == null) return;
    final PsiElement element = reference.resolve();
    if (element != null) return;
    final int textOffset = value.getTextOffset();
    if (textOffset == value.getTextRange().getEndOffset()) return;
    final PsiDocTagValue valueElement = tag.getValueElement();
    if (valueElement == null) return;

    final CharSequence paramName =
        value
            .getContainingFile()
            .getViewProvider()
            .getContents()
            .subSequence(textOffset, value.getTextRange().getEndOffset());
    final String params = "<code>" + paramName + "</code>";
    final List<LocalQuickFix> fixes = new ArrayList<LocalQuickFix>();
    if (onTheFly && "param".equals(tagName)) {
      final PsiDocCommentOwner commentOwner =
          PsiTreeUtil.getParentOfType(tag, PsiDocCommentOwner.class);
      if (commentOwner instanceof PsiMethod) {
        final PsiMethod method = (PsiMethod) commentOwner;
        final PsiParameter[] parameters = method.getParameterList().getParameters();
        final PsiDocTag[] tags = tag.getContainingComment().getTags();
        final Set<String> unboundParams = new HashSet<String>();
        for (PsiParameter parameter : parameters) {
          if (!JavaDocLocalInspection.isFound(tags, parameter)) {
            unboundParams.add(parameter.getName());
          }
        }
        if (!unboundParams.isEmpty()) {
          fixes.add(new RenameReferenceQuickFix(unboundParams));
        }
      }
    }
    fixes.add(new RemoveTagFix(tagName, paramName));

    problems.add(
        inspectionManager.createProblemDescriptor(
            valueElement,
            reference.getRangeInElement(),
            cannotResolveSymbolMessage(params),
            ProblemHighlightType.LIKE_UNKNOWN_SYMBOL,
            onTheFly,
            fixes.toArray(new LocalQuickFix[fixes.size()])));
  }
    @Override
    public void visitXmlAttributeValue(XmlAttributeValue value) {
      for (PsiReference reference : value.getReferences()) {
        if (!(reference instanceof OnClickConverter.MyReference)) {
          continue;
        }
        final OnClickConverter.MyReference ref = (OnClickConverter.MyReference) reference;
        final String methodName = ref.getValue();

        if (methodName.isEmpty()) {
          continue;
        }
        final ResolveResult[] results = ref.multiResolve(false);
        final Set<PsiClass> resolvedClasses = new HashSet<PsiClass>();
        final Set<PsiClass> resolvedClassesWithMistake = new HashSet<PsiClass>();

        for (ResolveResult result : results) {
          if (result instanceof OnClickConverter.MyResolveResult) {
            final PsiElement element = result.getElement();

            if (element != null) {
              final PsiClass aClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);

              if (aClass != null) {
                resolvedClasses.add(aClass);

                if (!((OnClickConverter.MyResolveResult) result).hasCorrectSignature()) {
                  resolvedClassesWithMistake.add(aClass);
                }
              }
            }
          }
        }
        PsiClass activity = null;
        for (PsiClass relatedActivity : myRelatedActivities) {
          if (!containsOrExtends(resolvedClasses, relatedActivity)) {
            activity = relatedActivity;
            break;
          } else if (activity == null
              && containsOrExtends(resolvedClassesWithMistake, relatedActivity)) {
            activity = relatedActivity;
          }
        }

        if (activity != null) {
          reportMissingOnClickProblem(
              ref, activity, methodName, resolvedClassesWithMistake.contains(activity));
        } else if (results.length == 0) {
          myResult.add(
              myInspectionManager.createProblemDescriptor(
                  value,
                  reference.getRangeInElement(),
                  ProblemsHolder.unresolvedReferenceMessage(reference),
                  ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
                  myOnTheFly));
        } else if (resolvedClassesWithMistake.size() > 0) {
          reportMissingOnClickProblem(
              ref, resolvedClassesWithMistake.iterator().next(), methodName, true);
        }
      }
    }