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