001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2017 the original author or authors. 004// 005// This library is free software; you can redistribute it and/or 006// modify it under the terms of the GNU Lesser General Public 007// License as published by the Free Software Foundation; either 008// version 2.1 of the License, or (at your option) any later version. 009// 010// This library is distributed in the hope that it will be useful, 011// but WITHOUT ANY WARRANTY; without even the implied warranty of 012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 013// Lesser General Public License for more details. 014// 015// You should have received a copy of the GNU Lesser General Public 016// License along with this library; if not, write to the Free Software 017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 018//////////////////////////////////////////////////////////////////////////////// 019 020package com.puppycrawl.tools.checkstyle.checks.javadoc; 021 022import java.util.ArrayList; 023import java.util.Arrays; 024import java.util.Collections; 025import java.util.HashSet; 026import java.util.Iterator; 027import java.util.List; 028import java.util.ListIterator; 029import java.util.Set; 030import java.util.regex.Matcher; 031import java.util.regex.Pattern; 032 033import com.puppycrawl.tools.checkstyle.api.DetailAST; 034import com.puppycrawl.tools.checkstyle.api.FileContents; 035import com.puppycrawl.tools.checkstyle.api.FullIdent; 036import com.puppycrawl.tools.checkstyle.api.Scope; 037import com.puppycrawl.tools.checkstyle.api.TextBlock; 038import com.puppycrawl.tools.checkstyle.api.TokenTypes; 039import com.puppycrawl.tools.checkstyle.checks.AbstractTypeAwareCheck; 040import com.puppycrawl.tools.checkstyle.utils.CheckUtils; 041import com.puppycrawl.tools.checkstyle.utils.CommonUtils; 042import com.puppycrawl.tools.checkstyle.utils.ScopeUtils; 043 044/** 045 * Checks the Javadoc of a method or constructor. 046 * 047 * @author Oliver Burn 048 * @author Rick Giles 049 * @author o_sukhodoslky 050 */ 051@SuppressWarnings("deprecation") 052public class JavadocMethodCheck extends AbstractTypeAwareCheck { 053 054 /** 055 * A key is pointing to the warning message text in "messages.properties" 056 * file. 057 */ 058 public static final String MSG_JAVADOC_MISSING = "javadoc.missing"; 059 060 /** 061 * A key is pointing to the warning message text in "messages.properties" 062 * file. 063 */ 064 public static final String MSG_CLASS_INFO = "javadoc.classInfo"; 065 066 /** 067 * A key is pointing to the warning message text in "messages.properties" 068 * file. 069 */ 070 public static final String MSG_UNUSED_TAG_GENERAL = "javadoc.unusedTagGeneral"; 071 072 /** 073 * A key is pointing to the warning message text in "messages.properties" 074 * file. 075 */ 076 public static final String MSG_INVALID_INHERIT_DOC = "javadoc.invalidInheritDoc"; 077 078 /** 079 * A key is pointing to the warning message text in "messages.properties" 080 * file. 081 */ 082 public static final String MSG_UNUSED_TAG = "javadoc.unusedTag"; 083 084 /** 085 * A key is pointing to the warning message text in "messages.properties" 086 * file. 087 */ 088 public static final String MSG_EXPECTED_TAG = "javadoc.expectedTag"; 089 090 /** 091 * A key is pointing to the warning message text in "messages.properties" 092 * file. 093 */ 094 public static final String MSG_RETURN_EXPECTED = "javadoc.return.expected"; 095 096 /** 097 * A key is pointing to the warning message text in "messages.properties" 098 * file. 099 */ 100 public static final String MSG_DUPLICATE_TAG = "javadoc.duplicateTag"; 101 102 /** Compiled regexp to match Javadoc tags that take an argument. */ 103 private static final Pattern MATCH_JAVADOC_ARG = 104 CommonUtils.createPattern("@(throws|exception|param)\\s+(\\S+)\\s+\\S*"); 105 106 /** Compiled regexp to match first part of multilineJavadoc tags. */ 107 private static final Pattern MATCH_JAVADOC_ARG_MULTILINE_START = 108 CommonUtils.createPattern("@(throws|exception|param)\\s+(\\S+)\\s*$"); 109 110 /** Compiled regexp to look for a continuation of the comment. */ 111 private static final Pattern MATCH_JAVADOC_MULTILINE_CONT = 112 CommonUtils.createPattern("(\\*/|@|[^\\s\\*])"); 113 114 /** Multiline finished at end of comment. */ 115 private static final String END_JAVADOC = "*/"; 116 /** Multiline finished at next Javadoc. */ 117 private static final String NEXT_TAG = "@"; 118 119 /** Compiled regexp to match Javadoc tags with no argument. */ 120 private static final Pattern MATCH_JAVADOC_NOARG = 121 CommonUtils.createPattern("@(return|see)\\s+\\S"); 122 /** Compiled regexp to match first part of multilineJavadoc tags. */ 123 private static final Pattern MATCH_JAVADOC_NOARG_MULTILINE_START = 124 CommonUtils.createPattern("@(return|see)\\s*$"); 125 /** Compiled regexp to match Javadoc tags with no argument and {}. */ 126 private static final Pattern MATCH_JAVADOC_NOARG_CURLY = 127 CommonUtils.createPattern("\\{\\s*@(inheritDoc)\\s*\\}"); 128 129 /** Default value of minimal amount of lines in method to demand documentation presence.*/ 130 private static final int DEFAULT_MIN_LINE_COUNT = -1; 131 132 /** The visibility scope where Javadoc comments are checked. */ 133 private Scope scope = Scope.PRIVATE; 134 135 /** The visibility scope where Javadoc comments shouldn't be checked. */ 136 private Scope excludeScope; 137 138 /** Minimal amount of lines in method to demand documentation presence.*/ 139 private int minLineCount = DEFAULT_MIN_LINE_COUNT; 140 141 /** 142 * Controls whether to allow documented exceptions that are not declared if 143 * they are a subclass of java.lang.RuntimeException. 144 */ 145 // -@cs[AbbreviationAsWordInName] We can not change it as, 146 // check's property is part of API (used in configurations). 147 private boolean allowUndeclaredRTE; 148 149 /** 150 * Allows validating throws tags. 151 */ 152 private boolean validateThrows; 153 154 /** 155 * Controls whether to allow documented exceptions that are subclass of one 156 * of declared exception. Defaults to false (backward compatibility). 157 */ 158 private boolean allowThrowsTagsForSubclasses; 159 160 /** 161 * Controls whether to ignore errors when a method has parameters but does 162 * not have matching param tags in the javadoc. Defaults to false. 163 */ 164 private boolean allowMissingParamTags; 165 166 /** 167 * Controls whether to ignore errors when a method declares that it throws 168 * exceptions but does not have matching throws tags in the javadoc. 169 * Defaults to false. 170 */ 171 private boolean allowMissingThrowsTags; 172 173 /** 174 * Controls whether to ignore errors when a method returns non-void type 175 * but does not have a return tag in the javadoc. Defaults to false. 176 */ 177 private boolean allowMissingReturnTag; 178 179 /** 180 * Controls whether to ignore errors when there is no javadoc. Defaults to 181 * false. 182 */ 183 private boolean allowMissingJavadoc; 184 185 /** 186 * Controls whether to allow missing Javadoc on accessor methods for 187 * properties (setters and getters). 188 */ 189 private boolean allowMissingPropertyJavadoc; 190 191 /** List of annotations that could allow missed documentation. */ 192 private List<String> allowedAnnotations = Collections.singletonList("Override"); 193 194 /** Method names that match this pattern do not require javadoc blocks. */ 195 private Pattern ignoreMethodNamesRegex; 196 197 /** 198 * Set regex for matching method names to ignore. 199 * @param pattern a pattern. 200 */ 201 public void setIgnoreMethodNamesRegex(Pattern pattern) { 202 ignoreMethodNamesRegex = pattern; 203 } 204 205 /** 206 * Sets minimal amount of lines in method. 207 * @param value user's value. 208 */ 209 public void setMinLineCount(int value) { 210 minLineCount = value; 211 } 212 213 /** 214 * Allow validating throws tag. 215 * @param value user's value. 216 */ 217 public void setValidateThrows(boolean value) { 218 validateThrows = value; 219 } 220 221 /** 222 * Sets list of annotations. 223 * @param userAnnotations user's value. 224 */ 225 public void setAllowedAnnotations(String... userAnnotations) { 226 allowedAnnotations = Arrays.asList(userAnnotations); 227 } 228 229 /** 230 * Set the scope. 231 * 232 * @param scope a scope. 233 */ 234 public void setScope(Scope scope) { 235 this.scope = scope; 236 } 237 238 /** 239 * Set the excludeScope. 240 * 241 * @param excludeScope a scope. 242 */ 243 public void setExcludeScope(Scope excludeScope) { 244 this.excludeScope = excludeScope; 245 } 246 247 /** 248 * Controls whether to allow documented exceptions that are not declared if 249 * they are a subclass of java.lang.RuntimeException. 250 * 251 * @param flag a {@code Boolean} value 252 */ 253 // -@cs[AbbreviationAsWordInName] We can not change it as, 254 // check's property is part of API (used in configurations). 255 public void setAllowUndeclaredRTE(boolean flag) { 256 allowUndeclaredRTE = flag; 257 } 258 259 /** 260 * Controls whether to allow documented exception that are subclass of one 261 * of declared exceptions. 262 * 263 * @param flag a {@code Boolean} value 264 */ 265 public void setAllowThrowsTagsForSubclasses(boolean flag) { 266 allowThrowsTagsForSubclasses = flag; 267 } 268 269 /** 270 * Controls whether to allow a method which has parameters to omit matching 271 * param tags in the javadoc. Defaults to false. 272 * 273 * @param flag a {@code Boolean} value 274 */ 275 public void setAllowMissingParamTags(boolean flag) { 276 allowMissingParamTags = flag; 277 } 278 279 /** 280 * Controls whether to allow a method which declares that it throws 281 * exceptions to omit matching throws tags in the javadoc. Defaults to 282 * false. 283 * 284 * @param flag a {@code Boolean} value 285 */ 286 public void setAllowMissingThrowsTags(boolean flag) { 287 allowMissingThrowsTags = flag; 288 } 289 290 /** 291 * Controls whether to allow a method which returns non-void type to omit 292 * the return tag in the javadoc. Defaults to false. 293 * 294 * @param flag a {@code Boolean} value 295 */ 296 public void setAllowMissingReturnTag(boolean flag) { 297 allowMissingReturnTag = flag; 298 } 299 300 /** 301 * Controls whether to ignore errors when there is no javadoc. Defaults to 302 * false. 303 * 304 * @param flag a {@code Boolean} value 305 */ 306 public void setAllowMissingJavadoc(boolean flag) { 307 allowMissingJavadoc = flag; 308 } 309 310 /** 311 * Controls whether to ignore errors when there is no javadoc for a 312 * property accessor (setter/getter methods). Defaults to false. 313 * 314 * @param flag a {@code Boolean} value 315 */ 316 public void setAllowMissingPropertyJavadoc(final boolean flag) { 317 allowMissingPropertyJavadoc = flag; 318 } 319 320 @Override 321 public int[] getDefaultTokens() { 322 return getAcceptableTokens(); 323 } 324 325 @Override 326 public int[] getAcceptableTokens() { 327 return new int[] { 328 TokenTypes.PACKAGE_DEF, 329 TokenTypes.IMPORT, 330 TokenTypes.CLASS_DEF, 331 TokenTypes.ENUM_DEF, 332 TokenTypes.INTERFACE_DEF, 333 TokenTypes.METHOD_DEF, 334 TokenTypes.CTOR_DEF, 335 TokenTypes.ANNOTATION_FIELD_DEF, 336 }; 337 } 338 339 @Override 340 public boolean isCommentNodesRequired() { 341 return true; 342 } 343 344 @Override 345 protected final void processAST(DetailAST ast) { 346 final Scope theScope = calculateScope(ast); 347 if (shouldCheck(ast, theScope)) { 348 final FileContents contents = getFileContents(); 349 final TextBlock textBlock = contents.getJavadocBefore(ast.getLineNo()); 350 351 if (textBlock == null) { 352 if (!isMissingJavadocAllowed(ast)) { 353 log(ast, MSG_JAVADOC_MISSING); 354 } 355 } 356 else { 357 checkComment(ast, textBlock); 358 } 359 } 360 } 361 362 /** 363 * Some javadoc. 364 * @param methodDef Some javadoc. 365 * @return Some javadoc. 366 */ 367 private boolean hasAllowedAnnotations(DetailAST methodDef) { 368 final DetailAST modifiersNode = methodDef.findFirstToken(TokenTypes.MODIFIERS); 369 DetailAST annotationNode = modifiersNode.findFirstToken(TokenTypes.ANNOTATION); 370 while (annotationNode != null && annotationNode.getType() == TokenTypes.ANNOTATION) { 371 DetailAST identNode = annotationNode.findFirstToken(TokenTypes.IDENT); 372 if (identNode == null) { 373 identNode = annotationNode.findFirstToken(TokenTypes.DOT) 374 .findFirstToken(TokenTypes.IDENT); 375 } 376 if (allowedAnnotations.contains(identNode.getText())) { 377 return true; 378 } 379 annotationNode = annotationNode.getNextSibling(); 380 } 381 return false; 382 } 383 384 /** 385 * Some javadoc. 386 * @param methodDef Some javadoc. 387 * @return Some javadoc. 388 */ 389 private static int getMethodsNumberOfLine(DetailAST methodDef) { 390 final int numberOfLines; 391 final DetailAST lcurly = methodDef.getLastChild(); 392 final DetailAST rcurly = lcurly.getLastChild(); 393 394 if (lcurly.getFirstChild() == rcurly) { 395 numberOfLines = 1; 396 } 397 else { 398 numberOfLines = rcurly.getLineNo() - lcurly.getLineNo() - 1; 399 } 400 return numberOfLines; 401 } 402 403 @Override 404 protected final void logLoadError(Token ident) { 405 logLoadErrorImpl(ident.getLineNo(), ident.getColumnNo(), 406 MSG_CLASS_INFO, 407 JavadocTagInfo.THROWS.getText(), ident.getText()); 408 } 409 410 /** 411 * The JavadocMethodCheck is about to report a missing Javadoc. 412 * This hook can be used by derived classes to allow a missing javadoc 413 * in some situations. The default implementation checks 414 * {@code allowMissingJavadoc} and 415 * {@code allowMissingPropertyJavadoc} properties, do not forget 416 * to call {@code super.isMissingJavadocAllowed(ast)} in case 417 * you want to keep this logic. 418 * @param ast the tree node for the method or constructor. 419 * @return True if this method or constructor doesn't need Javadoc. 420 */ 421 protected boolean isMissingJavadocAllowed(final DetailAST ast) { 422 return allowMissingJavadoc 423 || allowMissingPropertyJavadoc 424 && (CheckUtils.isSetterMethod(ast) || CheckUtils.isGetterMethod(ast)) 425 || matchesSkipRegex(ast) 426 || isContentsAllowMissingJavadoc(ast); 427 } 428 429 /** 430 * Checks if the Javadoc can be missing if the method or constructor is 431 * below the minimum line count or has a special annotation. 432 * 433 * @param ast the tree node for the method or constructor. 434 * @return True if this method or constructor doesn't need Javadoc. 435 */ 436 private boolean isContentsAllowMissingJavadoc(DetailAST ast) { 437 return (ast.getType() == TokenTypes.METHOD_DEF || ast.getType() == TokenTypes.CTOR_DEF) 438 && (getMethodsNumberOfLine(ast) <= minLineCount || hasAllowedAnnotations(ast)); 439 } 440 441 /** 442 * Checks if the given method name matches the regex. In that case 443 * we skip enforcement of javadoc for this method 444 * @param methodDef {@link TokenTypes#METHOD_DEF METHOD_DEF} 445 * @return true if given method name matches the regex. 446 */ 447 private boolean matchesSkipRegex(DetailAST methodDef) { 448 if (ignoreMethodNamesRegex != null) { 449 final DetailAST ident = methodDef.findFirstToken(TokenTypes.IDENT); 450 final String methodName = ident.getText(); 451 452 final Matcher matcher = ignoreMethodNamesRegex.matcher(methodName); 453 if (matcher.matches()) { 454 return true; 455 } 456 } 457 return false; 458 } 459 460 /** 461 * Whether we should check this node. 462 * 463 * @param ast a given node. 464 * @param nodeScope the scope of the node. 465 * @return whether we should check a given node. 466 */ 467 private boolean shouldCheck(final DetailAST ast, final Scope nodeScope) { 468 final Scope surroundingScope = ScopeUtils.getSurroundingScope(ast); 469 470 return (excludeScope == null 471 || nodeScope != excludeScope 472 && surroundingScope != excludeScope) 473 && nodeScope.isIn(scope) 474 && surroundingScope.isIn(scope); 475 } 476 477 /** 478 * Checks the Javadoc for a method. 479 * 480 * @param ast the token for the method 481 * @param comment the Javadoc comment 482 */ 483 private void checkComment(DetailAST ast, TextBlock comment) { 484 final List<JavadocTag> tags = getMethodTags(comment); 485 486 if (!hasShortCircuitTag(ast, tags)) { 487 final Iterator<JavadocTag> it = tags.iterator(); 488 if (ast.getType() == TokenTypes.ANNOTATION_FIELD_DEF) { 489 checkReturnTag(tags, ast.getLineNo(), true); 490 } 491 else { 492 // Check for inheritDoc 493 boolean hasInheritDocTag = false; 494 while (!hasInheritDocTag && it.hasNext()) { 495 hasInheritDocTag = it.next().isInheritDocTag(); 496 } 497 final boolean reportExpectedTags = !hasInheritDocTag && !hasAllowedAnnotations(ast); 498 499 checkParamTags(tags, ast, reportExpectedTags); 500 checkThrowsTags(tags, getThrows(ast), reportExpectedTags); 501 if (CheckUtils.isNonVoidMethod(ast)) { 502 checkReturnTag(tags, ast.getLineNo(), reportExpectedTags); 503 } 504 } 505 506 // Dump out all unused tags 507 tags.stream().filter(javadocTag -> !javadocTag.isSeeOrInheritDocTag()) 508 .forEach(javadocTag -> log(javadocTag.getLineNo(), MSG_UNUSED_TAG_GENERAL)); 509 } 510 } 511 512 /** 513 * Validates whether the Javadoc has a short circuit tag. Currently this is 514 * the inheritTag. Any errors are logged. 515 * 516 * @param ast the construct being checked 517 * @param tags the list of Javadoc tags associated with the construct 518 * @return true if the construct has a short circuit tag. 519 */ 520 private boolean hasShortCircuitTag(final DetailAST ast, 521 final List<JavadocTag> tags) { 522 // Check if it contains {@inheritDoc} tag 523 if (tags.size() != 1 524 || !tags.get(0).isInheritDocTag()) { 525 return false; 526 } 527 528 // Invalid if private, a constructor, or a static method 529 if (!JavadocTagInfo.INHERIT_DOC.isValidOn(ast)) { 530 log(ast, MSG_INVALID_INHERIT_DOC); 531 } 532 533 return true; 534 } 535 536 /** 537 * Returns the scope for the method/constructor at the specified AST. If 538 * the method is in an interface or annotation block, the scope is assumed 539 * to be public. 540 * 541 * @param ast the token of the method/constructor 542 * @return the scope of the method/constructor 543 */ 544 private static Scope calculateScope(final DetailAST ast) { 545 final DetailAST mods = ast.findFirstToken(TokenTypes.MODIFIERS); 546 final Scope declaredScope = ScopeUtils.getScopeFromMods(mods); 547 548 if (ScopeUtils.isInInterfaceOrAnnotationBlock(ast)) { 549 return Scope.PUBLIC; 550 } 551 else { 552 return declaredScope; 553 } 554 } 555 556 /** 557 * Returns the tags in a javadoc comment. Only finds throws, exception, 558 * param, return and see tags. 559 * 560 * @param comment the Javadoc comment 561 * @return the tags found 562 */ 563 private static List<JavadocTag> getMethodTags(TextBlock comment) { 564 final String[] lines = comment.getText(); 565 final List<JavadocTag> tags = new ArrayList<>(); 566 int currentLine = comment.getStartLineNo() - 1; 567 final int startColumnNumber = comment.getStartColNo(); 568 569 for (int i = 0; i < lines.length; i++) { 570 currentLine++; 571 final Matcher javadocArgMatcher = 572 MATCH_JAVADOC_ARG.matcher(lines[i]); 573 final Matcher javadocNoargMatcher = 574 MATCH_JAVADOC_NOARG.matcher(lines[i]); 575 final Matcher noargCurlyMatcher = 576 MATCH_JAVADOC_NOARG_CURLY.matcher(lines[i]); 577 final Matcher argMultilineStart = 578 MATCH_JAVADOC_ARG_MULTILINE_START.matcher(lines[i]); 579 final Matcher noargMultilineStart = 580 MATCH_JAVADOC_NOARG_MULTILINE_START.matcher(lines[i]); 581 582 if (javadocArgMatcher.find()) { 583 final int col = calculateTagColumn(javadocArgMatcher, i, startColumnNumber); 584 tags.add(new JavadocTag(currentLine, col, javadocArgMatcher.group(1), 585 javadocArgMatcher.group(2))); 586 } 587 else if (javadocNoargMatcher.find()) { 588 final int col = calculateTagColumn(javadocNoargMatcher, i, startColumnNumber); 589 tags.add(new JavadocTag(currentLine, col, javadocNoargMatcher.group(1))); 590 } 591 else if (noargCurlyMatcher.find()) { 592 final int col = calculateTagColumn(noargCurlyMatcher, i, startColumnNumber); 593 tags.add(new JavadocTag(currentLine, col, noargCurlyMatcher.group(1))); 594 } 595 else if (argMultilineStart.find()) { 596 final int col = calculateTagColumn(argMultilineStart, i, startColumnNumber); 597 tags.addAll(getMultilineArgTags(argMultilineStart, col, lines, i, currentLine)); 598 } 599 else if (noargMultilineStart.find()) { 600 tags.addAll(getMultilineNoArgTags(noargMultilineStart, lines, i, currentLine)); 601 } 602 } 603 return tags; 604 } 605 606 /** 607 * Calculates column number using Javadoc tag matcher. 608 * @param javadocTagMatcher found javadoc tag matcher 609 * @param lineNumber line number of Javadoc tag in comment 610 * @param startColumnNumber column number of Javadoc comment beginning 611 * @return column number 612 */ 613 private static int calculateTagColumn(Matcher javadocTagMatcher, 614 int lineNumber, int startColumnNumber) { 615 int col = javadocTagMatcher.start(1) - 1; 616 if (lineNumber == 0) { 617 col += startColumnNumber; 618 } 619 return col; 620 } 621 622 /** 623 * Gets multiline Javadoc tags with arguments. 624 * @param argMultilineStart javadoc tag Matcher 625 * @param column column number of Javadoc tag 626 * @param lines comment text lines 627 * @param lineIndex line number that contains the javadoc tag 628 * @param tagLine javadoc tag line number in file 629 * @return javadoc tags with arguments 630 */ 631 private static List<JavadocTag> getMultilineArgTags(final Matcher argMultilineStart, 632 final int column, final String[] lines, final int lineIndex, final int tagLine) { 633 final List<JavadocTag> tags = new ArrayList<>(); 634 final String param1 = argMultilineStart.group(1); 635 final String param2 = argMultilineStart.group(2); 636 int remIndex = lineIndex + 1; 637 while (remIndex < lines.length) { 638 final Matcher multilineCont = MATCH_JAVADOC_MULTILINE_CONT.matcher(lines[remIndex]); 639 if (multilineCont.find()) { 640 remIndex = lines.length; 641 final String lFin = multilineCont.group(1); 642 if (!lFin.equals(NEXT_TAG) 643 && !lFin.equals(END_JAVADOC)) { 644 tags.add(new JavadocTag(tagLine, column, param1, param2)); 645 } 646 } 647 remIndex++; 648 } 649 return tags; 650 } 651 652 /** 653 * Gets multiline Javadoc tags with no arguments. 654 * @param noargMultilineStart javadoc tag Matcher 655 * @param lines comment text lines 656 * @param lineIndex line number that contains the javadoc tag 657 * @param tagLine javadoc tag line number in file 658 * @return javadoc tags with no arguments 659 */ 660 private static List<JavadocTag> getMultilineNoArgTags(final Matcher noargMultilineStart, 661 final String[] lines, final int lineIndex, final int tagLine) { 662 final String param1 = noargMultilineStart.group(1); 663 final int col = noargMultilineStart.start(1) - 1; 664 final List<JavadocTag> tags = new ArrayList<>(); 665 int remIndex = lineIndex + 1; 666 while (remIndex < lines.length) { 667 final Matcher multilineCont = MATCH_JAVADOC_MULTILINE_CONT 668 .matcher(lines[remIndex]); 669 if (multilineCont.find()) { 670 remIndex = lines.length; 671 final String lFin = multilineCont.group(1); 672 if (!lFin.equals(NEXT_TAG) 673 && !lFin.equals(END_JAVADOC)) { 674 tags.add(new JavadocTag(tagLine, col, param1)); 675 } 676 } 677 remIndex++; 678 } 679 680 return tags; 681 } 682 683 /** 684 * Computes the parameter nodes for a method. 685 * 686 * @param ast the method node. 687 * @return the list of parameter nodes for ast. 688 */ 689 private static List<DetailAST> getParameters(DetailAST ast) { 690 final DetailAST params = ast.findFirstToken(TokenTypes.PARAMETERS); 691 final List<DetailAST> returnValue = new ArrayList<>(); 692 693 DetailAST child = params.getFirstChild(); 694 while (child != null) { 695 if (child.getType() == TokenTypes.PARAMETER_DEF) { 696 final DetailAST ident = child.findFirstToken(TokenTypes.IDENT); 697 if (ident != null) { 698 returnValue.add(ident); 699 } 700 } 701 child = child.getNextSibling(); 702 } 703 return returnValue; 704 } 705 706 /** 707 * Computes the exception nodes for a method. 708 * 709 * @param ast the method node. 710 * @return the list of exception nodes for ast. 711 */ 712 private List<ExceptionInfo> getThrows(DetailAST ast) { 713 final List<ExceptionInfo> returnValue = new ArrayList<>(); 714 final DetailAST throwsAST = ast 715 .findFirstToken(TokenTypes.LITERAL_THROWS); 716 if (throwsAST != null) { 717 DetailAST child = throwsAST.getFirstChild(); 718 while (child != null) { 719 if (child.getType() == TokenTypes.IDENT 720 || child.getType() == TokenTypes.DOT) { 721 final FullIdent ident = FullIdent.createFullIdent(child); 722 final ExceptionInfo exceptionInfo = new ExceptionInfo( 723 createClassInfo(new Token(ident), getCurrentClassName())); 724 returnValue.add(exceptionInfo); 725 } 726 child = child.getNextSibling(); 727 } 728 } 729 return returnValue; 730 } 731 732 /** 733 * Checks a set of tags for matching parameters. 734 * 735 * @param tags the tags to check 736 * @param parent the node which takes the parameters 737 * @param reportExpectedTags whether we should report if do not find 738 * expected tag 739 */ 740 private void checkParamTags(final List<JavadocTag> tags, 741 final DetailAST parent, boolean reportExpectedTags) { 742 final List<DetailAST> params = getParameters(parent); 743 final List<DetailAST> typeParams = CheckUtils 744 .getTypeParameters(parent); 745 746 // Loop over the tags, checking to see they exist in the params. 747 final ListIterator<JavadocTag> tagIt = tags.listIterator(); 748 while (tagIt.hasNext()) { 749 final JavadocTag tag = tagIt.next(); 750 751 if (!tag.isParamTag()) { 752 continue; 753 } 754 755 tagIt.remove(); 756 757 final String arg1 = tag.getFirstArg(); 758 boolean found = removeMatchingParam(params, arg1); 759 760 if (CommonUtils.startsWithChar(arg1, '<') && CommonUtils.endsWithChar(arg1, '>')) { 761 found = searchMatchingTypeParameter(typeParams, 762 arg1.substring(1, arg1.length() - 1)); 763 764 } 765 766 // Handle extra JavadocTag 767 if (!found) { 768 log(tag.getLineNo(), tag.getColumnNo(), MSG_UNUSED_TAG, 769 "@param", arg1); 770 } 771 } 772 773 // Now dump out all type parameters/parameters without tags :- unless 774 // the user has chosen to suppress these problems 775 if (!allowMissingParamTags && reportExpectedTags) { 776 for (DetailAST param : params) { 777 log(param, MSG_EXPECTED_TAG, 778 JavadocTagInfo.PARAM.getText(), param.getText()); 779 } 780 781 for (DetailAST typeParam : typeParams) { 782 log(typeParam, MSG_EXPECTED_TAG, 783 JavadocTagInfo.PARAM.getText(), 784 "<" + typeParam.findFirstToken(TokenTypes.IDENT).getText() 785 + ">"); 786 } 787 } 788 } 789 790 /** 791 * Returns true if required type found in type parameters. 792 * @param typeParams 793 * list of type parameters 794 * @param requiredTypeName 795 * name of required type 796 * @return true if required type found in type parameters. 797 */ 798 private static boolean searchMatchingTypeParameter(List<DetailAST> typeParams, 799 String requiredTypeName) { 800 // Loop looking for matching type param 801 final Iterator<DetailAST> typeParamsIt = typeParams.iterator(); 802 boolean found = false; 803 while (typeParamsIt.hasNext()) { 804 final DetailAST typeParam = typeParamsIt.next(); 805 if (typeParam.findFirstToken(TokenTypes.IDENT).getText() 806 .equals(requiredTypeName)) { 807 found = true; 808 typeParamsIt.remove(); 809 break; 810 } 811 } 812 return found; 813 } 814 815 /** 816 * Remove parameter from params collection by name. 817 * @param params collection of DetailAST parameters 818 * @param paramName name of parameter 819 * @return true if parameter found and removed 820 */ 821 private static boolean removeMatchingParam(List<DetailAST> params, String paramName) { 822 boolean found = false; 823 final Iterator<DetailAST> paramIt = params.iterator(); 824 while (paramIt.hasNext()) { 825 final DetailAST param = paramIt.next(); 826 if (param.getText().equals(paramName)) { 827 found = true; 828 paramIt.remove(); 829 break; 830 } 831 } 832 return found; 833 } 834 835 /** 836 * Checks for only one return tag. All return tags will be removed from the 837 * supplied list. 838 * 839 * @param tags the tags to check 840 * @param lineNo the line number of the expected tag 841 * @param reportExpectedTags whether we should report if do not find 842 * expected tag 843 */ 844 private void checkReturnTag(List<JavadocTag> tags, int lineNo, 845 boolean reportExpectedTags) { 846 // Loop over tags finding return tags. After the first one, report an 847 // error. 848 boolean found = false; 849 final ListIterator<JavadocTag> it = tags.listIterator(); 850 while (it.hasNext()) { 851 final JavadocTag javadocTag = it.next(); 852 if (javadocTag.isReturnTag()) { 853 if (found) { 854 log(javadocTag.getLineNo(), javadocTag.getColumnNo(), 855 MSG_DUPLICATE_TAG, 856 JavadocTagInfo.RETURN.getText()); 857 } 858 found = true; 859 it.remove(); 860 } 861 } 862 863 // Handle there being no @return tags :- unless 864 // the user has chosen to suppress these problems 865 if (!found && !allowMissingReturnTag && reportExpectedTags) { 866 log(lineNo, MSG_RETURN_EXPECTED); 867 } 868 } 869 870 /** 871 * Checks a set of tags for matching throws. 872 * 873 * @param tags the tags to check 874 * @param throwsList the throws to check 875 * @param reportExpectedTags whether we should report if do not find 876 * expected tag 877 */ 878 private void checkThrowsTags(List<JavadocTag> tags, 879 List<ExceptionInfo> throwsList, boolean reportExpectedTags) { 880 // Loop over the tags, checking to see they exist in the throws. 881 // The foundThrows used for performance only 882 final Set<String> foundThrows = new HashSet<>(); 883 final ListIterator<JavadocTag> tagIt = tags.listIterator(); 884 while (tagIt.hasNext()) { 885 final JavadocTag tag = tagIt.next(); 886 887 if (!tag.isThrowsTag()) { 888 continue; 889 } 890 tagIt.remove(); 891 892 // Loop looking for matching throw 893 final String documentedEx = tag.getFirstArg(); 894 final Token token = new Token(tag.getFirstArg(), tag.getLineNo(), tag 895 .getColumnNo()); 896 final AbstractClassInfo documentedClassInfo = createClassInfo(token, 897 getCurrentClassName()); 898 final boolean found = foundThrows.contains(documentedEx) 899 || isInThrows(throwsList, documentedClassInfo, foundThrows); 900 901 // Handle extra JavadocTag. 902 if (!found) { 903 boolean reqd = true; 904 if (allowUndeclaredRTE) { 905 reqd = !isUnchecked(documentedClassInfo.getClazz()); 906 } 907 908 if (reqd && validateThrows) { 909 log(tag.getLineNo(), tag.getColumnNo(), 910 MSG_UNUSED_TAG, 911 JavadocTagInfo.THROWS.getText(), tag.getFirstArg()); 912 913 } 914 } 915 } 916 // Now dump out all throws without tags :- unless 917 // the user has chosen to suppress these problems 918 if (!allowMissingThrowsTags && reportExpectedTags) { 919 throwsList.stream().filter(exceptionInfo -> !exceptionInfo.isFound()) 920 .forEach(exceptionInfo -> { 921 final Token token = exceptionInfo.getName(); 922 log(token.getLineNo(), token.getColumnNo(), 923 MSG_EXPECTED_TAG, 924 JavadocTagInfo.THROWS.getText(), token.getText()); 925 }); 926 } 927 } 928 929 /** 930 * Verifies that documented exception is in throws. 931 * 932 * @param throwsList list of throws 933 * @param documentedClassInfo documented exception class info 934 * @param foundThrows previously found throws 935 * @return true if documented exception is in throws. 936 */ 937 private boolean isInThrows(List<ExceptionInfo> throwsList, 938 AbstractClassInfo documentedClassInfo, Set<String> foundThrows) { 939 boolean found = false; 940 ExceptionInfo foundException = null; 941 942 // First look for matches on the exception name 943 final ListIterator<ExceptionInfo> throwIt = throwsList.listIterator(); 944 while (!found && throwIt.hasNext()) { 945 final ExceptionInfo exceptionInfo = throwIt.next(); 946 947 if (exceptionInfo.getName().getText().equals( 948 documentedClassInfo.getName().getText())) { 949 found = true; 950 foundException = exceptionInfo; 951 } 952 } 953 954 // Now match on the exception type 955 final ListIterator<ExceptionInfo> exceptionInfoIt = throwsList.listIterator(); 956 while (!found && exceptionInfoIt.hasNext()) { 957 final ExceptionInfo exceptionInfo = exceptionInfoIt.next(); 958 959 if (documentedClassInfo.getClazz() == exceptionInfo.getClazz()) { 960 found = true; 961 foundException = exceptionInfo; 962 } 963 else if (allowThrowsTagsForSubclasses) { 964 found = isSubclass(documentedClassInfo.getClazz(), exceptionInfo.getClazz()); 965 } 966 } 967 968 if (foundException != null) { 969 foundException.setFound(); 970 foundThrows.add(documentedClassInfo.getName().getText()); 971 } 972 973 return found; 974 } 975 976 /** Stores useful information about declared exception. */ 977 private static class ExceptionInfo { 978 /** Class information associated with this exception. */ 979 private final AbstractClassInfo classInfo; 980 /** Does the exception have throws tag associated with. */ 981 private boolean found; 982 983 /** 984 * Creates new instance for {@code FullIdent}. 985 * 986 * @param classInfo class info 987 */ 988 ExceptionInfo(AbstractClassInfo classInfo) { 989 this.classInfo = classInfo; 990 } 991 992 /** Mark that the exception has associated throws tag. */ 993 private void setFound() { 994 found = true; 995 } 996 997 /** 998 * Checks that the exception has throws tag associated with it. 999 * @return whether the exception has throws tag associated with 1000 */ 1001 private boolean isFound() { 1002 return found; 1003 } 1004 1005 /** 1006 * Gets exception name. 1007 * @return exception's name 1008 */ 1009 private Token getName() { 1010 return classInfo.getName(); 1011 } 1012 1013 /** 1014 * Gets exception class. 1015 * @return class for this exception 1016 */ 1017 private Class<?> getClazz() { 1018 return classInfo.getClazz(); 1019 } 1020 } 1021}