Mon, 14 Oct 2013 12:38:09 -0700
8026368: doclint does not report empty tags when tag closed implicitly
Reviewed-by: darcy
1 /*
2 * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
26 package com.sun.tools.doclint;
28 import java.io.IOException;
29 import java.io.StringWriter;
30 import java.net.URI;
31 import java.net.URISyntaxException;
32 import java.util.Deque;
33 import java.util.EnumSet;
34 import java.util.HashMap;
35 import java.util.HashSet;
36 import java.util.LinkedList;
37 import java.util.List;
38 import java.util.Map;
39 import java.util.Set;
40 import java.util.regex.Matcher;
41 import java.util.regex.Pattern;
43 import javax.lang.model.element.Element;
44 import javax.lang.model.element.ElementKind;
45 import javax.lang.model.element.ExecutableElement;
46 import javax.lang.model.element.Name;
47 import javax.lang.model.element.VariableElement;
48 import javax.lang.model.type.TypeKind;
49 import javax.lang.model.type.TypeMirror;
50 import javax.tools.Diagnostic.Kind;
51 import javax.tools.JavaFileObject;
53 import com.sun.source.doctree.AttributeTree;
54 import com.sun.source.doctree.AuthorTree;
55 import com.sun.source.doctree.DocCommentTree;
56 import com.sun.source.doctree.DocRootTree;
57 import com.sun.source.doctree.DocTree;
58 import com.sun.source.doctree.EndElementTree;
59 import com.sun.source.doctree.EntityTree;
60 import com.sun.source.doctree.ErroneousTree;
61 import com.sun.source.doctree.IdentifierTree;
62 import com.sun.source.doctree.InheritDocTree;
63 import com.sun.source.doctree.LinkTree;
64 import com.sun.source.doctree.LiteralTree;
65 import com.sun.source.doctree.ParamTree;
66 import com.sun.source.doctree.ReferenceTree;
67 import com.sun.source.doctree.ReturnTree;
68 import com.sun.source.doctree.SerialDataTree;
69 import com.sun.source.doctree.SerialFieldTree;
70 import com.sun.source.doctree.SinceTree;
71 import com.sun.source.doctree.StartElementTree;
72 import com.sun.source.doctree.TextTree;
73 import com.sun.source.doctree.ThrowsTree;
74 import com.sun.source.doctree.ValueTree;
75 import com.sun.source.doctree.VersionTree;
76 import com.sun.source.util.DocTreePath;
77 import com.sun.source.util.DocTreePathScanner;
78 import com.sun.source.util.TreePath;
79 import com.sun.tools.doclint.HtmlTag.AttrKind;
80 import com.sun.tools.javac.tree.DocPretty;
81 import static com.sun.tools.doclint.Messages.Group.*;
84 /**
85 * Validate a doc comment.
86 *
87 * <p><b>This is NOT part of any supported API.
88 * If you write code that depends on this, you do so at your own
89 * risk. This code and its internal interfaces are subject to change
90 * or deletion without notice.</b></p>
91 */
92 public class Checker extends DocTreePathScanner<Void, Void> {
93 final Env env;
95 Set<Element> foundParams = new HashSet<>();
96 Set<TypeMirror> foundThrows = new HashSet<>();
97 Map<Element, Set<String>> foundAnchors = new HashMap<>();
98 boolean foundInheritDoc = false;
99 boolean foundReturn = false;
101 public enum Flag {
102 TABLE_HAS_CAPTION,
103 HAS_ELEMENT,
104 HAS_INLINE_TAG,
105 HAS_TEXT,
106 REPORTED_BAD_INLINE
107 }
109 static class TagStackItem {
110 final DocTree tree; // typically, but not always, StartElementTree
111 final HtmlTag tag;
112 final Set<HtmlTag.Attr> attrs;
113 final Set<Flag> flags;
114 TagStackItem(DocTree tree, HtmlTag tag) {
115 this.tree = tree;
116 this.tag = tag;
117 attrs = EnumSet.noneOf(HtmlTag.Attr.class);
118 flags = EnumSet.noneOf(Flag.class);
119 }
120 @Override
121 public String toString() {
122 return String.valueOf(tag);
123 }
124 }
126 private Deque<TagStackItem> tagStack; // TODO: maybe want to record starting tree as well
127 private HtmlTag currHeaderTag;
129 private final int implicitHeaderLevel;
131 // <editor-fold defaultstate="collapsed" desc="Top level">
133 Checker(Env env) {
134 env.getClass();
135 this.env = env;
136 tagStack = new LinkedList<>();
137 implicitHeaderLevel = env.implicitHeaderLevel;
138 }
140 public Void scan(DocCommentTree tree, TreePath p) {
141 env.setCurrent(p, tree);
143 boolean isOverridingMethod = !env.currOverriddenMethods.isEmpty();
145 if (p.getLeaf() == p.getCompilationUnit()) {
146 // If p points to a compilation unit, the implied declaration is the
147 // package declaration (if any) for the compilation unit.
148 // Handle this case specially, because doc comments are only
149 // expected in package-info files.
150 JavaFileObject fo = p.getCompilationUnit().getSourceFile();
151 boolean isPkgInfo = fo.isNameCompatible("package-info", JavaFileObject.Kind.SOURCE);
152 if (tree == null) {
153 if (isPkgInfo)
154 reportMissing("dc.missing.comment");
155 return null;
156 } else {
157 if (!isPkgInfo)
158 reportReference("dc.unexpected.comment");
159 }
160 } else {
161 if (tree == null) {
162 if (!isSynthetic() && !isOverridingMethod)
163 reportMissing("dc.missing.comment");
164 return null;
165 }
166 }
168 tagStack.clear();
169 currHeaderTag = null;
171 foundParams.clear();
172 foundThrows.clear();
173 foundInheritDoc = false;
174 foundReturn = false;
176 scan(new DocTreePath(p, tree), null);
178 if (!isOverridingMethod) {
179 switch (env.currElement.getKind()) {
180 case METHOD:
181 case CONSTRUCTOR: {
182 ExecutableElement ee = (ExecutableElement) env.currElement;
183 checkParamsDocumented(ee.getTypeParameters());
184 checkParamsDocumented(ee.getParameters());
185 switch (ee.getReturnType().getKind()) {
186 case VOID:
187 case NONE:
188 break;
189 default:
190 if (!foundReturn
191 && !foundInheritDoc
192 && !env.types.isSameType(ee.getReturnType(), env.java_lang_Void)) {
193 reportMissing("dc.missing.return");
194 }
195 }
196 checkThrowsDocumented(ee.getThrownTypes());
197 }
198 }
199 }
201 return null;
202 }
204 private void reportMissing(String code, Object... args) {
205 env.messages.report(MISSING, Kind.WARNING, env.currPath.getLeaf(), code, args);
206 }
208 private void reportReference(String code, Object... args) {
209 env.messages.report(REFERENCE, Kind.WARNING, env.currPath.getLeaf(), code, args);
210 }
212 @Override
213 public Void visitDocComment(DocCommentTree tree, Void ignore) {
214 super.visitDocComment(tree, ignore);
215 for (TagStackItem tsi: tagStack) {
216 warnIfEmpty(tsi, null);
217 if (tsi.tree.getKind() == DocTree.Kind.START_ELEMENT
218 && tsi.tag.endKind == HtmlTag.EndKind.REQUIRED) {
219 StartElementTree t = (StartElementTree) tsi.tree;
220 env.messages.error(HTML, t, "dc.tag.not.closed", t.getName());
221 }
222 }
223 return null;
224 }
225 // </editor-fold>
227 // <editor-fold defaultstate="collapsed" desc="Text and entities.">
229 @Override
230 public Void visitText(TextTree tree, Void ignore) {
231 if (hasNonWhitespace(tree)) {
232 checkAllowsText(tree);
233 markEnclosingTag(Flag.HAS_TEXT);
234 }
235 return null;
236 }
238 @Override
239 public Void visitEntity(EntityTree tree, Void ignore) {
240 checkAllowsText(tree);
241 markEnclosingTag(Flag.HAS_TEXT);
242 String name = tree.getName().toString();
243 if (name.startsWith("#")) {
244 int v = name.toLowerCase().startsWith("#x")
245 ? Integer.parseInt(name.substring(2), 16)
246 : Integer.parseInt(name.substring(1), 10);
247 if (!Entity.isValid(v)) {
248 env.messages.error(HTML, tree, "dc.entity.invalid", name);
249 }
250 } else if (!Entity.isValid(name)) {
251 env.messages.error(HTML, tree, "dc.entity.invalid", name);
252 }
253 return null;
254 }
256 void checkAllowsText(DocTree tree) {
257 TagStackItem top = tagStack.peek();
258 if (top != null
259 && top.tree.getKind() == DocTree.Kind.START_ELEMENT
260 && !top.tag.acceptsText()) {
261 if (top.flags.add(Flag.REPORTED_BAD_INLINE)) {
262 env.messages.error(HTML, tree, "dc.text.not.allowed",
263 ((StartElementTree) top.tree).getName());
264 }
265 }
266 }
268 // </editor-fold>
270 // <editor-fold defaultstate="collapsed" desc="HTML elements">
272 @Override
273 public Void visitStartElement(StartElementTree tree, Void ignore) {
274 final Name treeName = tree.getName();
275 final HtmlTag t = HtmlTag.get(treeName);
276 if (t == null) {
277 env.messages.error(HTML, tree, "dc.tag.unknown", treeName);
278 } else {
279 boolean done = false;
280 for (TagStackItem tsi: tagStack) {
281 if (tsi.tag.accepts(t)) {
282 while (tagStack.peek() != tsi) {
283 warnIfEmpty(tagStack.peek(), null);
284 tagStack.pop();
285 }
286 done = true;
287 break;
288 } else if (tsi.tag.endKind != HtmlTag.EndKind.OPTIONAL) {
289 done = true;
290 break;
291 }
292 }
293 if (!done && HtmlTag.BODY.accepts(t)) {
294 while (!tagStack.isEmpty()) {
295 warnIfEmpty(tagStack.peek(), null);
296 tagStack.pop();
297 }
298 }
300 markEnclosingTag(Flag.HAS_ELEMENT);
301 checkStructure(tree, t);
303 // tag specific checks
304 switch (t) {
305 // check for out of sequence headers, such as <h1>...</h1> <h3>...</h3>
306 case H1: case H2: case H3: case H4: case H5: case H6:
307 checkHeader(tree, t);
308 break;
309 }
311 if (t.flags.contains(HtmlTag.Flag.NO_NEST)) {
312 for (TagStackItem i: tagStack) {
313 if (t == i.tag) {
314 env.messages.warning(HTML, tree, "dc.tag.nested.not.allowed", treeName);
315 break;
316 }
317 }
318 }
319 }
321 // check for self closing tags, such as <a id="name"/>
322 if (tree.isSelfClosing()) {
323 env.messages.error(HTML, tree, "dc.tag.self.closing", treeName);
324 }
326 try {
327 TagStackItem parent = tagStack.peek();
328 TagStackItem top = new TagStackItem(tree, t);
329 tagStack.push(top);
331 super.visitStartElement(tree, ignore);
333 // handle attributes that may or may not have been found in start element
334 if (t != null) {
335 switch (t) {
336 case CAPTION:
337 if (parent != null && parent.tag == HtmlTag.TABLE)
338 parent.flags.add(Flag.TABLE_HAS_CAPTION);
339 break;
341 case IMG:
342 if (!top.attrs.contains(HtmlTag.Attr.ALT))
343 env.messages.error(ACCESSIBILITY, tree, "dc.no.alt.attr.for.image");
344 break;
345 }
346 }
348 return null;
349 } finally {
351 if (t == null || t.endKind == HtmlTag.EndKind.NONE)
352 tagStack.pop();
353 }
354 }
356 private void checkStructure(StartElementTree tree, HtmlTag t) {
357 Name treeName = tree.getName();
358 TagStackItem top = tagStack.peek();
359 switch (t.blockType) {
360 case BLOCK:
361 if (top == null || top.tag.accepts(t))
362 return;
364 switch (top.tree.getKind()) {
365 case START_ELEMENT: {
366 if (top.tag.blockType == HtmlTag.BlockType.INLINE) {
367 Name name = ((StartElementTree) top.tree).getName();
368 env.messages.error(HTML, tree, "dc.tag.not.allowed.inline.element",
369 treeName, name);
370 return;
371 }
372 }
373 break;
375 case LINK:
376 case LINK_PLAIN: {
377 String name = top.tree.getKind().tagName;
378 env.messages.error(HTML, tree, "dc.tag.not.allowed.inline.tag",
379 treeName, name);
380 return;
381 }
382 }
383 break;
385 case INLINE:
386 if (top == null || top.tag.accepts(t))
387 return;
388 break;
390 case LIST_ITEM:
391 case TABLE_ITEM:
392 if (top != null) {
393 // reset this flag so subsequent bad inline content gets reported
394 top.flags.remove(Flag.REPORTED_BAD_INLINE);
395 if (top.tag.accepts(t))
396 return;
397 }
398 break;
400 case OTHER:
401 env.messages.error(HTML, tree, "dc.tag.not.allowed", treeName);
402 return;
403 }
405 env.messages.error(HTML, tree, "dc.tag.not.allowed.here", treeName);
406 }
408 private void checkHeader(StartElementTree tree, HtmlTag tag) {
409 // verify the new tag
410 if (getHeaderLevel(tag) > getHeaderLevel(currHeaderTag) + 1) {
411 if (currHeaderTag == null) {
412 env.messages.error(ACCESSIBILITY, tree, "dc.tag.header.sequence.1", tag);
413 } else {
414 env.messages.error(ACCESSIBILITY, tree, "dc.tag.header.sequence.2",
415 tag, currHeaderTag);
416 }
417 }
419 currHeaderTag = tag;
420 }
422 private int getHeaderLevel(HtmlTag tag) {
423 if (tag == null)
424 return implicitHeaderLevel;
425 switch (tag) {
426 case H1: return 1;
427 case H2: return 2;
428 case H3: return 3;
429 case H4: return 4;
430 case H5: return 5;
431 case H6: return 6;
432 default: throw new IllegalArgumentException();
433 }
434 }
436 @Override
437 public Void visitEndElement(EndElementTree tree, Void ignore) {
438 final Name treeName = tree.getName();
439 final HtmlTag t = HtmlTag.get(treeName);
440 if (t == null) {
441 env.messages.error(HTML, tree, "dc.tag.unknown", treeName);
442 } else if (t.endKind == HtmlTag.EndKind.NONE) {
443 env.messages.error(HTML, tree, "dc.tag.end.not.permitted", treeName);
444 } else {
445 boolean done = false;
446 while (!tagStack.isEmpty()) {
447 TagStackItem top = tagStack.peek();
448 if (t == top.tag) {
449 switch (t) {
450 case TABLE:
451 if (!top.attrs.contains(HtmlTag.Attr.SUMMARY)
452 && !top.flags.contains(Flag.TABLE_HAS_CAPTION)) {
453 env.messages.error(ACCESSIBILITY, tree,
454 "dc.no.summary.or.caption.for.table");
455 }
456 }
457 warnIfEmpty(top, tree);
458 tagStack.pop();
459 done = true;
460 break;
461 } else if (top.tag == null || top.tag.endKind != HtmlTag.EndKind.REQUIRED) {
462 tagStack.pop();
463 } else {
464 boolean found = false;
465 for (TagStackItem si: tagStack) {
466 if (si.tag == t) {
467 found = true;
468 break;
469 }
470 }
471 if (found && top.tree.getKind() == DocTree.Kind.START_ELEMENT) {
472 env.messages.error(HTML, top.tree, "dc.tag.start.unmatched",
473 ((StartElementTree) top.tree).getName());
474 tagStack.pop();
475 } else {
476 env.messages.error(HTML, tree, "dc.tag.end.unexpected", treeName);
477 done = true;
478 break;
479 }
480 }
481 }
483 if (!done && tagStack.isEmpty()) {
484 env.messages.error(HTML, tree, "dc.tag.end.unexpected", treeName);
485 }
486 }
488 return super.visitEndElement(tree, ignore);
489 }
491 void warnIfEmpty(TagStackItem tsi, DocTree endTree) {
492 if (tsi.tag != null && tsi.tree instanceof StartElementTree) {
493 if (tsi.tag.flags.contains(HtmlTag.Flag.EXPECT_CONTENT)
494 && !tsi.flags.contains(Flag.HAS_TEXT)
495 && !tsi.flags.contains(Flag.HAS_ELEMENT)
496 && !tsi.flags.contains(Flag.HAS_INLINE_TAG)) {
497 DocTree tree = (endTree != null) ? endTree : tsi.tree;
498 Name treeName = ((StartElementTree) tsi.tree).getName();
499 env.messages.warning(HTML, tree, "dc.tag.empty", treeName);
500 }
501 }
502 }
504 // </editor-fold>
506 // <editor-fold defaultstate="collapsed" desc="HTML attributes">
508 @Override @SuppressWarnings("fallthrough")
509 public Void visitAttribute(AttributeTree tree, Void ignore) {
510 HtmlTag currTag = tagStack.peek().tag;
511 if (currTag != null) {
512 Name name = tree.getName();
513 HtmlTag.Attr attr = currTag.getAttr(name);
514 if (attr != null) {
515 boolean first = tagStack.peek().attrs.add(attr);
516 if (!first)
517 env.messages.error(HTML, tree, "dc.attr.repeated", name);
518 }
519 AttrKind k = currTag.getAttrKind(name);
520 switch (k) {
521 case OK:
522 break;
524 case INVALID:
525 env.messages.error(HTML, tree, "dc.attr.unknown", name);
526 break;
528 case OBSOLETE:
529 env.messages.warning(ACCESSIBILITY, tree, "dc.attr.obsolete", name);
530 break;
532 case USE_CSS:
533 env.messages.warning(ACCESSIBILITY, tree, "dc.attr.obsolete.use.css", name);
534 break;
535 }
537 if (attr != null) {
538 switch (attr) {
539 case NAME:
540 if (currTag != HtmlTag.A) {
541 break;
542 }
543 // fallthrough
544 case ID:
545 String value = getAttrValue(tree);
546 if (value == null) {
547 env.messages.error(HTML, tree, "dc.anchor.value.missing");
548 } else {
549 if (!validName.matcher(value).matches()) {
550 env.messages.error(HTML, tree, "dc.invalid.anchor", value);
551 }
552 if (!checkAnchor(value)) {
553 env.messages.error(HTML, tree, "dc.anchor.already.defined", value);
554 }
555 }
556 break;
558 case HREF:
559 if (currTag == HtmlTag.A) {
560 String v = getAttrValue(tree);
561 if (v == null || v.isEmpty()) {
562 env.messages.error(HTML, tree, "dc.attr.lacks.value");
563 } else {
564 Matcher m = docRoot.matcher(v);
565 if (m.matches()) {
566 String rest = m.group(2);
567 if (!rest.isEmpty())
568 checkURI(tree, rest);
569 } else {
570 checkURI(tree, v);
571 }
572 }
573 }
574 break;
576 case VALUE:
577 if (currTag == HtmlTag.LI) {
578 String v = getAttrValue(tree);
579 if (v == null || v.isEmpty()) {
580 env.messages.error(HTML, tree, "dc.attr.lacks.value");
581 } else if (!validNumber.matcher(v).matches()) {
582 env.messages.error(HTML, tree, "dc.attr.not.number");
583 }
584 }
585 break;
586 }
587 }
588 }
590 // TODO: basic check on value
592 return super.visitAttribute(tree, ignore);
593 }
595 private boolean checkAnchor(String name) {
596 Element e = getEnclosingPackageOrClass(env.currElement);
597 if (e == null)
598 return true;
599 Set<String> set = foundAnchors.get(e);
600 if (set == null)
601 foundAnchors.put(e, set = new HashSet<>());
602 return set.add(name);
603 }
605 private Element getEnclosingPackageOrClass(Element e) {
606 while (e != null) {
607 switch (e.getKind()) {
608 case CLASS:
609 case ENUM:
610 case INTERFACE:
611 case PACKAGE:
612 return e;
613 default:
614 e = e.getEnclosingElement();
615 }
616 }
617 return e;
618 }
620 // http://www.w3.org/TR/html401/types.html#type-name
621 private static final Pattern validName = Pattern.compile("[A-Za-z][A-Za-z0-9-_:.]*");
623 private static final Pattern validNumber = Pattern.compile("-?[0-9]+");
625 // pattern to remove leading {@docRoot}/?
626 private static final Pattern docRoot = Pattern.compile("(?i)(\\{@docRoot *\\}/?)?(.*)");
628 private String getAttrValue(AttributeTree tree) {
629 if (tree.getValue() == null)
630 return null;
632 StringWriter sw = new StringWriter();
633 try {
634 new DocPretty(sw).print(tree.getValue());
635 } catch (IOException e) {
636 // cannot happen
637 }
638 // ignore potential use of entities for now
639 return sw.toString();
640 }
642 private void checkURI(AttributeTree tree, String uri) {
643 try {
644 URI u = new URI(uri);
645 } catch (URISyntaxException e) {
646 env.messages.error(HTML, tree, "dc.invalid.uri", uri);
647 }
648 }
649 // </editor-fold>
651 // <editor-fold defaultstate="collapsed" desc="javadoc tags">
653 @Override
654 public Void visitAuthor(AuthorTree tree, Void ignore) {
655 warnIfEmpty(tree, tree.getName());
656 return super.visitAuthor(tree, ignore);
657 }
659 @Override
660 public Void visitDocRoot(DocRootTree tree, Void ignore) {
661 markEnclosingTag(Flag.HAS_INLINE_TAG);
662 return super.visitDocRoot(tree, ignore);
663 }
665 @Override
666 public Void visitInheritDoc(InheritDocTree tree, Void ignore) {
667 markEnclosingTag(Flag.HAS_INLINE_TAG);
668 // TODO: verify on overridden method
669 foundInheritDoc = true;
670 return super.visitInheritDoc(tree, ignore);
671 }
673 @Override
674 public Void visitLink(LinkTree tree, Void ignore) {
675 markEnclosingTag(Flag.HAS_INLINE_TAG);
676 // simulate inline context on tag stack
677 HtmlTag t = (tree.getKind() == DocTree.Kind.LINK)
678 ? HtmlTag.CODE : HtmlTag.SPAN;
679 tagStack.push(new TagStackItem(tree, t));
680 try {
681 return super.visitLink(tree, ignore);
682 } finally {
683 tagStack.pop();
684 }
685 }
687 @Override
688 public Void visitLiteral(LiteralTree tree, Void ignore) {
689 markEnclosingTag(Flag.HAS_INLINE_TAG);
690 if (tree.getKind() == DocTree.Kind.CODE) {
691 for (TagStackItem tsi: tagStack) {
692 if (tsi.tag == HtmlTag.CODE) {
693 env.messages.warning(HTML, tree, "dc.tag.code.within.code");
694 break;
695 }
696 }
697 }
698 return super.visitLiteral(tree, ignore);
699 }
701 @Override
702 @SuppressWarnings("fallthrough")
703 public Void visitParam(ParamTree tree, Void ignore) {
704 boolean typaram = tree.isTypeParameter();
705 IdentifierTree nameTree = tree.getName();
706 Element paramElement = nameTree != null ? env.trees.getElement(new DocTreePath(getCurrentPath(), nameTree)) : null;
708 if (paramElement == null) {
709 switch (env.currElement.getKind()) {
710 case CLASS: case INTERFACE: {
711 if (!typaram) {
712 env.messages.error(REFERENCE, tree, "dc.invalid.param");
713 break;
714 }
715 }
716 case METHOD: case CONSTRUCTOR: {
717 env.messages.error(REFERENCE, nameTree, "dc.param.name.not.found");
718 break;
719 }
721 default:
722 env.messages.error(REFERENCE, tree, "dc.invalid.param");
723 break;
724 }
725 } else {
726 foundParams.add(paramElement);
727 }
729 warnIfEmpty(tree, tree.getDescription());
730 return super.visitParam(tree, ignore);
731 }
733 private void checkParamsDocumented(List<? extends Element> list) {
734 if (foundInheritDoc)
735 return;
737 for (Element e: list) {
738 if (!foundParams.contains(e)) {
739 CharSequence paramName = (e.getKind() == ElementKind.TYPE_PARAMETER)
740 ? "<" + e.getSimpleName() + ">"
741 : e.getSimpleName();
742 reportMissing("dc.missing.param", paramName);
743 }
744 }
745 }
747 @Override
748 public Void visitReference(ReferenceTree tree, Void ignore) {
749 String sig = tree.getSignature();
750 if (sig.contains("<") || sig.contains(">"))
751 env.messages.error(REFERENCE, tree, "dc.type.arg.not.allowed");
753 Element e = env.trees.getElement(getCurrentPath());
754 if (e == null)
755 env.messages.error(REFERENCE, tree, "dc.ref.not.found");
756 return super.visitReference(tree, ignore);
757 }
759 @Override
760 public Void visitReturn(ReturnTree tree, Void ignore) {
761 Element e = env.trees.getElement(env.currPath);
762 if (e.getKind() != ElementKind.METHOD
763 || ((ExecutableElement) e).getReturnType().getKind() == TypeKind.VOID)
764 env.messages.error(REFERENCE, tree, "dc.invalid.return");
765 foundReturn = true;
766 warnIfEmpty(tree, tree.getDescription());
767 return super.visitReturn(tree, ignore);
768 }
770 @Override
771 public Void visitSerialData(SerialDataTree tree, Void ignore) {
772 warnIfEmpty(tree, tree.getDescription());
773 return super.visitSerialData(tree, ignore);
774 }
776 @Override
777 public Void visitSerialField(SerialFieldTree tree, Void ignore) {
778 warnIfEmpty(tree, tree.getDescription());
779 return super.visitSerialField(tree, ignore);
780 }
782 @Override
783 public Void visitSince(SinceTree tree, Void ignore) {
784 warnIfEmpty(tree, tree.getBody());
785 return super.visitSince(tree, ignore);
786 }
788 @Override
789 public Void visitThrows(ThrowsTree tree, Void ignore) {
790 ReferenceTree exName = tree.getExceptionName();
791 Element ex = env.trees.getElement(new DocTreePath(getCurrentPath(), exName));
792 if (ex == null) {
793 env.messages.error(REFERENCE, tree, "dc.ref.not.found");
794 } else if (isThrowable(ex.asType())) {
795 switch (env.currElement.getKind()) {
796 case CONSTRUCTOR:
797 case METHOD:
798 if (isCheckedException(ex.asType())) {
799 ExecutableElement ee = (ExecutableElement) env.currElement;
800 checkThrowsDeclared(exName, ex.asType(), ee.getThrownTypes());
801 }
802 break;
803 default:
804 env.messages.error(REFERENCE, tree, "dc.invalid.throws");
805 }
806 } else {
807 env.messages.error(REFERENCE, tree, "dc.invalid.throws");
808 }
809 warnIfEmpty(tree, tree.getDescription());
810 return scan(tree.getDescription(), ignore);
811 }
813 private boolean isThrowable(TypeMirror tm) {
814 switch (tm.getKind()) {
815 case DECLARED:
816 case TYPEVAR:
817 return env.types.isAssignable(tm, env.java_lang_Throwable);
818 }
819 return false;
820 }
822 private void checkThrowsDeclared(ReferenceTree tree, TypeMirror t, List<? extends TypeMirror> list) {
823 boolean found = false;
824 for (TypeMirror tl : list) {
825 if (env.types.isAssignable(t, tl)) {
826 foundThrows.add(tl);
827 found = true;
828 }
829 }
830 if (!found)
831 env.messages.error(REFERENCE, tree, "dc.exception.not.thrown", t);
832 }
834 private void checkThrowsDocumented(List<? extends TypeMirror> list) {
835 if (foundInheritDoc)
836 return;
838 for (TypeMirror tl: list) {
839 if (isCheckedException(tl) && !foundThrows.contains(tl))
840 reportMissing("dc.missing.throws", tl);
841 }
842 }
844 @Override
845 public Void visitValue(ValueTree tree, Void ignore) {
846 ReferenceTree ref = tree.getReference();
847 if (ref == null || ref.getSignature().isEmpty()) {
848 if (!isConstant(env.currElement))
849 env.messages.error(REFERENCE, tree, "dc.value.not.allowed.here");
850 } else {
851 Element e = env.trees.getElement(new DocTreePath(getCurrentPath(), ref));
852 if (!isConstant(e))
853 env.messages.error(REFERENCE, tree, "dc.value.not.a.constant");
854 }
856 markEnclosingTag(Flag.HAS_INLINE_TAG);
857 return super.visitValue(tree, ignore);
858 }
860 private boolean isConstant(Element e) {
861 if (e == null)
862 return false;
864 switch (e.getKind()) {
865 case FIELD:
866 Object value = ((VariableElement) e).getConstantValue();
867 return (value != null); // can't distinguish "not a constant" from "constant is null"
868 default:
869 return false;
870 }
871 }
873 @Override
874 public Void visitVersion(VersionTree tree, Void ignore) {
875 warnIfEmpty(tree, tree.getBody());
876 return super.visitVersion(tree, ignore);
877 }
879 @Override
880 public Void visitErroneous(ErroneousTree tree, Void ignore) {
881 env.messages.error(SYNTAX, tree, null, tree.getDiagnostic().getMessage(null));
882 return null;
883 }
884 // </editor-fold>
886 // <editor-fold defaultstate="collapsed" desc="Utility methods">
888 private boolean isCheckedException(TypeMirror t) {
889 return !(env.types.isAssignable(t, env.java_lang_Error)
890 || env.types.isAssignable(t, env.java_lang_RuntimeException));
891 }
893 private boolean isSynthetic() {
894 switch (env.currElement.getKind()) {
895 case CONSTRUCTOR:
896 // A synthetic default constructor has the same pos as the
897 // enclosing class
898 TreePath p = env.currPath;
899 return env.getPos(p) == env.getPos(p.getParentPath());
900 }
901 return false;
902 }
904 void markEnclosingTag(Flag flag) {
905 TagStackItem top = tagStack.peek();
906 if (top != null)
907 top.flags.add(flag);
908 }
910 String toString(TreePath p) {
911 StringBuilder sb = new StringBuilder("TreePath[");
912 toString(p, sb);
913 sb.append("]");
914 return sb.toString();
915 }
917 void toString(TreePath p, StringBuilder sb) {
918 TreePath parent = p.getParentPath();
919 if (parent != null) {
920 toString(parent, sb);
921 sb.append(",");
922 }
923 sb.append(p.getLeaf().getKind()).append(":").append(env.getPos(p)).append(":S").append(env.getStartPos(p));
924 }
926 void warnIfEmpty(DocTree tree, List<? extends DocTree> list) {
927 for (DocTree d: list) {
928 switch (d.getKind()) {
929 case TEXT:
930 if (hasNonWhitespace((TextTree) d))
931 return;
932 break;
933 default:
934 return;
935 }
936 }
937 env.messages.warning(SYNTAX, tree, "dc.empty", tree.getKind().tagName);
938 }
940 boolean hasNonWhitespace(TextTree tree) {
941 String s = tree.getBody();
942 for (int i = 0; i < s.length(); i++) {
943 if (!Character.isWhitespace(s.charAt(i)))
944 return true;
945 }
946 return false;
947 }
949 // </editor-fold>
951 }