Wed, 17 Jul 2013 19:16:12 -0700
8020664: doclint gives incorrect warnings on normal package statements
Reviewed-by: mcimadamore
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.File;
29 import java.io.IOException;
30 import java.io.PrintWriter;
31 import java.util.ArrayList;
32 import java.util.List;
34 import javax.lang.model.element.Name;
35 import javax.tools.Diagnostic;
36 import javax.tools.JavaFileObject;
37 import javax.tools.StandardLocation;
39 import com.sun.source.doctree.DocCommentTree;
40 import com.sun.source.tree.ClassTree;
41 import com.sun.source.tree.CompilationUnitTree;
42 import com.sun.source.tree.MethodTree;
43 import com.sun.source.tree.Tree;
44 import com.sun.source.tree.VariableTree;
45 import com.sun.source.util.JavacTask;
46 import com.sun.source.util.Plugin;
47 import com.sun.source.util.TaskEvent;
48 import com.sun.source.util.TaskListener;
49 import com.sun.source.util.TreePath;
50 import com.sun.source.util.TreePathScanner;
51 import com.sun.tools.javac.api.JavacTaskImpl;
52 import com.sun.tools.javac.api.JavacTool;
53 import com.sun.tools.javac.file.JavacFileManager;
54 import com.sun.tools.javac.main.JavaCompiler;
55 import com.sun.tools.javac.util.Context;
57 /**
58 * Multi-function entry point for the doc check utility.
59 *
60 * This class can be invoked in the following ways:
61 * <ul>
62 * <li>From the command line
63 * <li>From javac, as a plugin
64 * <li>Directly, via a simple API
65 * </ul>
66 *
67 * <p><b>This is NOT part of any supported API.
68 * If you write code that depends on this, you do so at your own
69 * risk. This code and its internal interfaces are subject to change
70 * or deletion without notice.</b></p>
71 */
72 public class DocLint implements Plugin {
74 public static final String XMSGS_OPTION = "-Xmsgs";
75 public static final String XMSGS_CUSTOM_PREFIX = "-Xmsgs:";
76 private static final String STATS = "-stats";
77 public static final String XIMPLICIT_HEADERS = "-XimplicitHeaders:";
79 // <editor-fold defaultstate="collapsed" desc="Command-line entry point">
80 public static void main(String... args) {
81 DocLint dl = new DocLint();
82 try {
83 dl.run(args);
84 } catch (BadArgs e) {
85 System.err.println(e.getMessage());
86 System.exit(1);
87 } catch (IOException e) {
88 System.err.println(dl.localize("dc.main.ioerror", e.getLocalizedMessage()));
89 System.exit(2);
90 }
91 }
93 // </editor-fold>
95 // <editor-fold defaultstate="collapsed" desc="Simple API">
97 public class BadArgs extends Exception {
98 private static final long serialVersionUID = 0;
99 BadArgs(String code, Object... args) {
100 super(localize(code, args));
101 this.code = code;
102 this.args = args;
103 }
105 final String code;
106 final Object[] args;
107 }
109 /**
110 * Simple API entry point.
111 */
112 public void run(String... args) throws BadArgs, IOException {
113 PrintWriter out = new PrintWriter(System.out);
114 try {
115 run(out, args);
116 } finally {
117 out.flush();
118 }
119 }
121 public void run(PrintWriter out, String... args) throws BadArgs, IOException {
122 env = new Env();
123 processArgs(args);
125 if (needHelp)
126 showHelp(out);
128 if (javacFiles.isEmpty()) {
129 if (!needHelp)
130 out.println(localize("dc.main.no.files.given"));
131 }
133 JavacTool tool = JavacTool.create();
135 JavacFileManager fm = new JavacFileManager(new Context(), false, null);
136 fm.setSymbolFileEnabled(false);
137 fm.setLocation(StandardLocation.PLATFORM_CLASS_PATH, javacBootClassPath);
138 fm.setLocation(StandardLocation.CLASS_PATH, javacClassPath);
139 fm.setLocation(StandardLocation.SOURCE_PATH, javacSourcePath);
141 JavacTask task = tool.getTask(out, fm, null, javacOpts, null,
142 fm.getJavaFileObjectsFromFiles(javacFiles));
143 Iterable<? extends CompilationUnitTree> units = task.parse();
144 ((JavacTaskImpl) task).enter();
146 env.init(task);
147 checker = new Checker(env);
149 DeclScanner ds = new DeclScanner() {
150 @Override
151 void visitDecl(Tree tree, Name name) {
152 TreePath p = getCurrentPath();
153 DocCommentTree dc = env.trees.getDocCommentTree(p);
155 if (p.getLeaf() == p.getCompilationUnit()) {
156 JavaFileObject fo = p.getCompilationUnit().getSourceFile();
157 boolean pkgInfo = fo.isNameCompatible("package-info", JavaFileObject.Kind.SOURCE);
158 if (!pkgInfo) {
159 if (dc == null)
160 return;
161 env.setCurrent(p, dc);
162 env.messages.report(Messages.Group.REFERENCE, Diagnostic.Kind.WARNING, p.getLeaf(),
163 "dc.unexpected.comment");
164 }
165 }
167 checker.scan(dc, p);
168 }
169 };
171 ds.scan(units, null);
173 reportStats(out);
175 Context ctx = ((JavacTaskImpl) task).getContext();
176 JavaCompiler c = JavaCompiler.instance(ctx);
177 c.printCount("error", c.errorCount());
178 c.printCount("warn", c.warningCount());
179 }
181 void processArgs(String... args) throws BadArgs {
182 javacOpts = new ArrayList<>();
183 javacFiles = new ArrayList<>();
185 if (args.length == 0)
186 needHelp = true;
188 for (int i = 0; i < args.length; i++) {
189 String arg = args[i];
190 if (arg.matches("-Xmax(errs|warns)") && i + 1 < args.length) {
191 if (args[++i].matches("[0-9]+")) {
192 javacOpts.add(arg);
193 javacOpts.add(args[i]);
194 } else {
195 throw new BadArgs("dc.bad.value.for.option", arg, args[i]);
196 }
197 } else if (arg.equals(STATS)) {
198 env.messages.setStatsEnabled(true);
199 } else if (arg.equals("-bootclasspath") && i + 1 < args.length) {
200 javacBootClassPath = splitPath(args[++i]);
201 } else if (arg.equals("-classpath") && i + 1 < args.length) {
202 javacClassPath = splitPath(args[++i]);
203 } else if (arg.equals("-cp") && i + 1 < args.length) {
204 javacClassPath = splitPath(args[++i]);
205 } else if (arg.equals("-sourcepath") && i + 1 < args.length) {
206 javacSourcePath = splitPath(args[++i]);
207 } else if (arg.equals(XMSGS_OPTION)) {
208 env.messages.setOptions(null);
209 } else if (arg.startsWith(XMSGS_CUSTOM_PREFIX)) {
210 env.messages.setOptions(arg.substring(arg.indexOf(":") + 1));
211 } else if (arg.equals("-h") || arg.equals("-help") || arg.equals("--help")
212 || arg.equals("-?") || arg.equals("-usage")) {
213 needHelp = true;
214 } else if (arg.startsWith("-")) {
215 throw new BadArgs("dc.bad.option", arg);
216 } else {
217 while (i < args.length)
218 javacFiles.add(new File(args[i++]));
219 }
220 }
221 }
223 void showHelp(PrintWriter out) {
224 String msg = localize("dc.main.usage");
225 for (String line: msg.split("\n"))
226 out.println(line);
227 }
229 List<File> splitPath(String path) {
230 List<File> files = new ArrayList<>();
231 for (String f: path.split(File.pathSeparator)) {
232 if (f.length() > 0)
233 files.add(new File(f));
234 }
235 return files;
236 }
238 List<File> javacBootClassPath;
239 List<File> javacClassPath;
240 List<File> javacSourcePath;
241 List<String> javacOpts;
242 List<File> javacFiles;
243 boolean needHelp = false;
245 // </editor-fold>
247 // <editor-fold defaultstate="collapsed" desc="javac Plugin">
249 @Override
250 public String getName() {
251 return "doclint";
252 }
254 @Override
255 public void init(JavacTask task, String... args) {
256 init(task, args, true);
257 }
259 // </editor-fold>
261 // <editor-fold defaultstate="collapsed" desc="Embedding API">
263 public void init(JavacTask task, String[] args, boolean addTaskListener) {
264 env = new Env();
265 for (int i = 0; i < args.length; i++) {
266 String arg = args[i];
267 if (arg.equals(XMSGS_OPTION)) {
268 env.messages.setOptions(null);
269 } else if (arg.startsWith(XMSGS_CUSTOM_PREFIX)) {
270 env.messages.setOptions(arg.substring(arg.indexOf(":") + 1));
271 } else if (arg.matches(XIMPLICIT_HEADERS + "[1-6]")) {
272 char ch = arg.charAt(arg.length() - 1);
273 env.setImplicitHeaders(Character.digit(ch, 10));
274 } else
275 throw new IllegalArgumentException(arg);
276 }
277 env.init(task);
279 checker = new Checker(env);
281 if (addTaskListener) {
282 final DeclScanner ds = new DeclScanner() {
283 @Override
284 void visitDecl(Tree tree, Name name) {
285 TreePath p = getCurrentPath();
286 DocCommentTree dc = env.trees.getDocCommentTree(p);
288 checker.scan(dc, p);
289 }
290 };
292 TaskListener tl = new TaskListener() {
293 @Override
294 public void started(TaskEvent e) {
295 }
297 @Override
298 public void finished(TaskEvent e) {
299 switch (e.getKind()) {
300 case ENTER:
301 ds.scan(e.getCompilationUnit(), null);
302 }
303 }
304 };
306 task.addTaskListener(tl);
307 }
308 }
310 public void scan(TreePath p) {
311 DocCommentTree dc = env.trees.getDocCommentTree(p);
312 checker.scan(dc, p);
313 }
315 public void reportStats(PrintWriter out) {
316 env.messages.reportStats(out);
317 }
319 // </editor-fold>
321 Env env;
322 Checker checker;
324 public static boolean isValidOption(String opt) {
325 if (opt.equals(XMSGS_OPTION))
326 return true;
327 if (opt.startsWith(XMSGS_CUSTOM_PREFIX))
328 return Messages.Options.isValidOptions(opt.substring(XMSGS_CUSTOM_PREFIX.length()));
329 return false;
330 }
332 private String localize(String code, Object... args) {
333 Messages m = (env != null) ? env.messages : new Messages(null);
334 return m.localize(code, args);
335 }
337 // <editor-fold defaultstate="collapsed" desc="DeclScanner">
339 static abstract class DeclScanner extends TreePathScanner<Void, Void> {
340 abstract void visitDecl(Tree tree, Name name);
342 @Override
343 public Void visitCompilationUnit(CompilationUnitTree tree, Void ignore) {
344 if (tree.getPackageName() != null) {
345 visitDecl(tree, null);
346 }
347 return super.visitCompilationUnit(tree, ignore);
348 }
350 @Override
351 public Void visitClass(ClassTree tree, Void ignore) {
352 visitDecl(tree, tree.getSimpleName());
353 return super.visitClass(tree, ignore);
354 }
356 @Override
357 public Void visitMethod(MethodTree tree, Void ignore) {
358 visitDecl(tree, tree.getName());
359 //return super.visitMethod(tree, ignore);
360 return null;
361 }
363 @Override
364 public Void visitVariable(VariableTree tree, Void ignore) {
365 visitDecl(tree, tree.getName());
366 return super.visitVariable(tree, ignore);
367 }
368 }
370 // </editor-fold>
372 }