public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
   final PsiDocTag myTag =
       PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiDocTag.class);
   if (myTag == null) return;
   if (!CodeInsightUtilBase.preparePsiElementForWrite(myTag)) return;
   myTag.delete();
 }
 @Override
 @NotNull
 public PsiDocTag[] findTagsByName(String name) {
   ArrayList<PsiDocTag> array = new ArrayList<PsiDocTag>();
   PsiDocTag[] tags = getTags();
   name = "@" + name;
   for (PsiDocTag tag : tags) {
     if (tag.getNameElement().getText().equals(name)) {
       array.add(tag);
     }
   }
   return array.toArray(new PsiDocTag[array.size()]);
 }
Пример #3
0
 @Override
 public PsiType resolve(PsiDocTag psiDocTag) {
   PsiDocTagValue value = psiDocTag.getValueElement();
   if (value != null) {
     String exceptionName = value.getText();
     if (exceptionName != null) {
       PsiClass psiClass = javaPsiFacade.findClass(exceptionName, globalSearchScope);
       if (psiClass != null) {
         return elementFactory.createType(psiClass);
       } else {
         PsiClass[] classesByName =
             shortNamesCache.getClassesByName(exceptionName, globalSearchScope);
         PsiClass encapsulatingClass = PsiTreeUtil.getParentOfType(psiDocTag, PsiClass.class);
         if (encapsulatingClass != null && classesByName.length > 0) {
           String packageName =
               ClassUtil.extractPackageName(encapsulatingClass.getQualifiedName());
           PsiClass closestClass =
               PsiClassSelector.selectClassByPackage(packageName, classesByName);
           return elementFactory.createType(closestClass);
         }
         logger.log(Level.WARNING, "No classes found with name: " + exceptionName);
       }
     }
   }
   return null;
 }
  private void fixJavadocForConstructor(PsiClass psiClass) {
    final PsiDocComment docComment = method.getDocComment();
    if (docComment != null) {
      final List<PsiDocTag> mergedTags = new ArrayList<PsiDocTag>();
      final PsiDocTag[] paramTags = docComment.findTagsByName("param");
      for (PsiDocTag paramTag : paramTags) {
        final PsiElement[] dataElements = paramTag.getDataElements();
        if (dataElements.length > 0) {
          if (dataElements[0] instanceof PsiDocParamRef) {
            final PsiReference reference = dataElements[0].getReference();
            if (reference != null) {
              final PsiElement resolve = reference.resolve();
              if (resolve instanceof PsiParameter) {
                final int parameterIndex =
                    method.getParameterList().getParameterIndex((PsiParameter) resolve);
                if (ArrayUtil.find(paramsToMerge, parameterIndex) < 0) continue;
              }
            }
          }
          mergedTags.add((PsiDocTag) paramTag.copy());
        }
      }

      PsiMethod compatibleParamObjectConstructor = null;
      if (myExistingClassCompatibleConstructor != null
          && myExistingClassCompatibleConstructor.getDocComment() == null) {
        compatibleParamObjectConstructor = myExistingClassCompatibleConstructor;
      } else if (!myUseExistingClass) {
        compatibleParamObjectConstructor = psiClass.getConstructors()[0];
      }

      if (compatibleParamObjectConstructor != null) {
        PsiDocComment psiDocComment =
            JavaPsiFacade.getElementFactory(myProject).createDocCommentFromText("/**\n*/");
        psiDocComment =
            (PsiDocComment)
                compatibleParamObjectConstructor.addBefore(
                    psiDocComment, compatibleParamObjectConstructor.getFirstChild());

        for (PsiDocTag tag : mergedTags) {
          psiDocComment.add(tag);
        }
      }
    }
  }
 @Override
 public void invoke(
     @NotNull final Project project, final Editor editor, @NotNull final PsiElement element)
     throws IncorrectOperationException {
   PsiDocCommentOwner container = getContainer(element);
   assert container != null;
   if (!CodeInsightUtilBase.preparePsiElementForWrite(container)) return;
   if (use15Suppressions(container)) {
     final PsiModifierList modifierList = container.getModifierList();
     if (modifierList != null) {
       addSuppressAnnotation(project, editor, container, container, getID(container));
     }
   } else {
     PsiDocComment docComment = container.getDocComment();
     PsiManager manager = PsiManager.getInstance(project);
     if (docComment == null) {
       String commentText =
           "/** @" + SuppressionUtil.SUPPRESS_INSPECTIONS_TAG_NAME + " " + getID(container) + "*/";
       docComment =
           JavaPsiFacade.getInstance(manager.getProject())
               .getElementFactory()
               .createDocCommentFromText(commentText);
       PsiElement firstChild = container.getFirstChild();
       container.addBefore(docComment, firstChild);
     } else {
       PsiDocTag noInspectionTag =
           docComment.findTagByName(SuppressionUtil.SUPPRESS_INSPECTIONS_TAG_NAME);
       if (noInspectionTag != null) {
         String tagText = noInspectionTag.getText() + ", " + getID(container);
         noInspectionTag.replace(
             JavaPsiFacade.getInstance(manager.getProject())
                 .getElementFactory()
                 .createDocTagFromText(tagText));
       } else {
         String tagText =
             "@" + SuppressionUtil.SUPPRESS_INSPECTIONS_TAG_NAME + " " + getID(container);
         docComment.add(
             JavaPsiFacade.getInstance(manager.getProject())
                 .getElementFactory()
                 .createDocTagFromText(tagText));
       }
     }
   }
   DaemonCodeAnalyzer.getInstance(project).restart();
 }
  @Override
  public PsiDocTag findTagByName(String name) {
    if (getFirstChildNode().getElementType() == JavaDocElementType.DOC_COMMENT) {
      if (getFirstChildNode().getText().indexOf(name) < 0) return null;
    }

    for (ASTNode child = getFirstChildNode(); child != null; child = child.getTreeNext()) {
      if (child.getElementType() == DOC_TAG) {
        PsiDocTag tag = (PsiDocTag) SourceTreeToPsiMap.treeElementToPsi(child);
        final CharSequence nameText = ((LeafElement) tag.getNameElement()).getChars();

        if (nameText.length() > 0
            && nameText.charAt(0) == '@'
            && CharArrayUtil.regionMatches(nameText, 1, name)) {
          return tag;
        }
      }
    }

    return null;
  }
Пример #7
0
 private static Collection<String> extractAnnotationValuesFromJavaDoc(
     PsiDocTag tag, String parameter) {
   if (tag == null) return Collections.emptyList();
   Collection<String> results = new ArrayList<>();
   Matcher matcher =
       Pattern.compile("\\@testng.test(?:.*)" + parameter + "\\s*=\\s*\"(.*?)\".*")
           .matcher(tag.getText());
   if (matcher.matches()) {
     String[] groups = matcher.group(1).split("[,\\s]");
     for (String group : groups) {
       final String trimmed = group.trim();
       if (trimmed.length() > 0) {
         results.add(trimmed);
       }
     }
   }
   return results;
 }
Пример #8
0
  public static String extractTagValue(PsiDocTag docTag) {
    StringBuilder resp = new StringBuilder();
    PsiElement[] childs = docTag.getChildren();

    boolean endAsteriskReached = false;
    // +1 to skip name of the docTag
    // +1 to skip whitespace
    for (int i = 2; !endAsteriskReached && i < childs.length; i++) {
      PsiElement child = childs[i];
      if ((child instanceof PsiDocToken
              && ((PsiDocToken) child).getTokenType()
                  == JavaDocTokenType.DOC_COMMENT_LEADING_ASTERISKS)
          || (child instanceof PsiWhiteSpace && child.getText().startsWith("\n"))) {
        endAsteriskReached = true;
        //            } else if(child instanceof com.intellij.psi.PsiWhiteSpace){
        //                resp.append(child.getText())
      } else {
        resp.append(child.getText());
      }
    }

    return resp.toString();
  }
  private static AllowedValues parseBeanInfo(@NotNull PsiModifierListOwner owner) {
    PsiMethod method = null;
    if (owner instanceof PsiParameter) {
      PsiParameter parameter = (PsiParameter) owner;
      PsiElement scope = parameter.getDeclarationScope();
      if (!(scope instanceof PsiMethod)) return null;
      PsiElement nav = scope.getNavigationElement();
      if (!(nav instanceof PsiMethod)) return null;
      method = (PsiMethod) nav;
      if (method.isConstructor()) {
        // not a property, try the @ConstructorProperties({"prop"})
        PsiAnnotation annotation =
            AnnotationUtil.findAnnotation(method, "java.beans.ConstructorProperties");
        if (annotation == null) return null;
        PsiAnnotationMemberValue value = annotation.findAttributeValue("value");
        if (!(value instanceof PsiArrayInitializerMemberValue)) return null;
        PsiAnnotationMemberValue[] initializers =
            ((PsiArrayInitializerMemberValue) value).getInitializers();
        PsiElement parent = parameter.getParent();
        if (!(parent instanceof PsiParameterList)) return null;
        int index = ((PsiParameterList) parent).getParameterIndex(parameter);
        if (index >= initializers.length) return null;
        PsiAnnotationMemberValue initializer = initializers[index];
        if (!(initializer instanceof PsiLiteralExpression)) return null;
        Object val = ((PsiLiteralExpression) initializer).getValue();
        if (!(val instanceof String)) return null;
        PsiMethod setter =
            PropertyUtil.findPropertySetter(
                method.getContainingClass(), (String) val, false, false);
        if (setter == null) return null;
        // try the @beaninfo of the corresponding setter
        method = (PsiMethod) setter.getNavigationElement();
      }
    } else if (owner instanceof PsiMethod) {
      PsiElement nav = owner.getNavigationElement();
      if (!(nav instanceof PsiMethod)) return null;
      method = (PsiMethod) nav;
    }
    if (method == null) return null;

    PsiClass aClass = method.getContainingClass();
    if (aClass == null) return null;
    if (PropertyUtil.isSimplePropertyGetter(method)) {
      List<PsiMethod> setters =
          PropertyUtil.getSetters(aClass, PropertyUtil.getPropertyNameByGetter(method));
      if (setters.size() != 1) return null;
      method = setters.get(0);
    }
    if (!PropertyUtil.isSimplePropertySetter(method)) return null;
    PsiDocComment doc = method.getDocComment();
    if (doc == null) return null;
    PsiDocTag beaninfo = doc.findTagByName("beaninfo");
    if (beaninfo == null) return null;
    String data =
        StringUtil.join(
            beaninfo.getDataElements(),
            new Function<PsiElement, String>() {
              @Override
              public String fun(PsiElement element) {
                return element.getText();
              }
            },
            "\n");
    int enumIndex = StringUtil.indexOfSubstringEnd(data, "enum:");
    if (enumIndex == -1) return null;
    data = data.substring(enumIndex);
    int colon = data.indexOf(":");
    int last = colon == -1 ? data.length() : data.substring(0, colon).lastIndexOf("\n");
    data = data.substring(0, last);

    List<PsiAnnotationMemberValue> values = new ArrayList<PsiAnnotationMemberValue>();
    for (String line : StringUtil.splitByLines(data)) {
      List<String> words = StringUtil.split(line, " ", true, true);
      if (words.size() != 2) continue;
      String ref = words.get(1);
      PsiExpression constRef =
          JavaPsiFacade.getElementFactory(aClass.getProject())
              .createExpressionFromText(ref, aClass);
      if (!(constRef instanceof PsiReferenceExpression)) continue;
      PsiReferenceExpression expr = (PsiReferenceExpression) constRef;
      values.add(expr);
    }
    if (values.isEmpty()) return null;
    PsiAnnotationMemberValue[] array = values.toArray(new PsiAnnotationMemberValue[values.size()]);
    return new AllowedValues(array, false);
  }
  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()])));
  }
  public String generateDocumentationContentStub(PsiComment contextComment) {
    if (!(contextComment instanceof GrDocComment)) {
      return null;
    }

    final GrDocCommentOwner owner = GrDocCommentUtil.findDocOwner((GrDocComment) contextComment);
    if (owner == null) return null;

    Project project = contextComment.getProject();
    final CodeDocumentationAwareCommenter commenter =
        (CodeDocumentationAwareCommenter)
            LanguageCommenters.INSTANCE.forLanguage(owner.getLanguage());

    StringBuilder builder = StringBuilderSpinAllocator.alloc();
    try {
      if (owner instanceof GrMethod) {
        final GrMethod method = (GrMethod) owner;
        final GrParameter[] parameters = method.getParameters();
        final Map<String, String> param2Description = new HashMap<String, String>();
        final PsiMethod[] superMethods = method.findSuperMethods();

        for (PsiMethod superMethod : superMethods) {
          final PsiDocComment comment = superMethod.getDocComment();
          if (comment != null) {
            final PsiDocTag[] params = comment.findTagsByName("param");
            for (PsiDocTag param : params) {
              final PsiElement[] dataElements = param.getDataElements();
              if (dataElements != null) {
                String paramName = null;
                for (PsiElement dataElement : dataElements) {
                  if (dataElement instanceof PsiDocParamRef) {
                    paramName = dataElement.getReference().getCanonicalText();
                    break;
                  }
                }
                if (paramName != null) {
                  param2Description.put(paramName, param.getText());
                }
              }
            }
          }
        }
        for (PsiParameter parameter : parameters) {
          String description = param2Description.get(parameter.getName());
          if (description != null) {
            builder.append(CodeDocumentationUtil.createDocCommentLine("", project, commenter));
            if (description.indexOf('\n') > -1)
              description = description.substring(0, description.lastIndexOf('\n'));
            builder.append(description);
          } else {
            builder.append(
                CodeDocumentationUtil.createDocCommentLine(PARAM_TAG, project, commenter));
            builder.append(parameter.getName());
          }
          builder.append(LINE_SEPARATOR);
        }

        final PsiType returnType = method.getInferredReturnType();
        if ((returnType != null || method.getModifierList().hasModifierProperty(GrModifier.DEF))
            && returnType != PsiType.VOID) {
          builder.append(
              CodeDocumentationUtil.createDocCommentLine(RETURN_TAG, project, commenter));
          builder.append(LINE_SEPARATOR);
        }

        final PsiClassType[] references = method.getThrowsList().getReferencedTypes();
        for (PsiClassType reference : references) {
          builder.append(
              CodeDocumentationUtil.createDocCommentLine(THROWS_TAG, project, commenter));
          builder.append(reference.getClassName());
          builder.append(LINE_SEPARATOR);
        }
      } else if (owner instanceof GrTypeDefinition) {
        final PsiTypeParameterList typeParameterList = ((PsiClass) owner).getTypeParameterList();
        if (typeParameterList != null) {
          createTypeParamsListComment(builder, project, commenter, typeParameterList);
        }
      }
      return builder.length() > 0 ? builder.toString() : null;
    } finally {
      StringBuilderSpinAllocator.dispose(builder);
    }
  }