Thu, 18 Apr 2013 20:00:14 -0700
8012656: cache frequently used name strings for DocImpl classes
Reviewed-by: darcy
1 /*
2 * Copyright (c) 1997, 2012, 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.javadoc;
28 import java.io.File;
29 import java.io.FileNotFoundException;
30 import java.io.IOException;
31 import java.io.PrintWriter;
32 import java.util.ArrayList;
33 import java.util.Collection;
34 import java.util.Collections;
36 import javax.tools.JavaFileManager;
37 import javax.tools.JavaFileObject;
39 import com.sun.javadoc.*;
40 import com.sun.tools.javac.main.CommandLine;
41 import com.sun.tools.javac.util.ClientCodeException;
42 import com.sun.tools.javac.util.Context;
43 import com.sun.tools.javac.util.List;
44 import com.sun.tools.javac.util.ListBuffer;
45 import com.sun.tools.javac.util.Log;
46 import com.sun.tools.javac.util.Options;
47 import static com.sun.tools.javac.code.Flags.*;
49 /**
50 * Main program of Javadoc.
51 * Previously named "Main".
52 *
53 * <p><b>This is NOT part of any supported API.
54 * If you write code that depends on this, you do so at your own risk.
55 * This code and its internal interfaces are subject to change or
56 * deletion without notice.</b>
57 *
58 * @since 1.2
59 * @author Robert Field
60 * @author Neal Gafter (rewrite)
61 */
62 public class Start extends ToolOption.Helper {
63 /** Context for this invocation. */
64 private final Context context;
66 private final String defaultDocletClassName;
67 private final ClassLoader docletParentClassLoader;
69 private static final String javadocName = "javadoc";
71 private static final String standardDocletClassName =
72 "com.sun.tools.doclets.standard.Standard";
74 private long defaultFilter = PUBLIC | PROTECTED;
76 private final Messager messager;
78 private DocletInvoker docletInvoker;
80 /**
81 * In API mode, exceptions thrown while calling the doclet are
82 * propagated using ClientCodeException.
83 */
84 private boolean apiMode;
86 Start(String programName,
87 PrintWriter errWriter,
88 PrintWriter warnWriter,
89 PrintWriter noticeWriter,
90 String defaultDocletClassName) {
91 this(programName, errWriter, warnWriter, noticeWriter, defaultDocletClassName, null);
92 }
94 Start(String programName,
95 PrintWriter errWriter,
96 PrintWriter warnWriter,
97 PrintWriter noticeWriter,
98 String defaultDocletClassName,
99 ClassLoader docletParentClassLoader) {
100 context = new Context();
101 messager = new Messager(context, programName, errWriter, warnWriter, noticeWriter);
102 this.defaultDocletClassName = defaultDocletClassName;
103 this.docletParentClassLoader = docletParentClassLoader;
104 }
106 Start(String programName, String defaultDocletClassName) {
107 this(programName, defaultDocletClassName, null);
108 }
110 Start(String programName, String defaultDocletClassName,
111 ClassLoader docletParentClassLoader) {
112 context = new Context();
113 messager = new Messager(context, programName);
114 this.defaultDocletClassName = defaultDocletClassName;
115 this.docletParentClassLoader = docletParentClassLoader;
116 }
118 Start(String programName, ClassLoader docletParentClassLoader) {
119 this(programName, standardDocletClassName, docletParentClassLoader);
120 }
122 Start(String programName) {
123 this(programName, standardDocletClassName);
124 }
126 Start(ClassLoader docletParentClassLoader) {
127 this(javadocName, docletParentClassLoader);
128 }
130 Start() {
131 this(javadocName);
132 }
134 public Start(Context context) {
135 context.getClass(); // null check
136 this.context = context;
137 apiMode = true;
138 defaultDocletClassName = standardDocletClassName;
139 docletParentClassLoader = null;
141 Log log = context.get(Log.logKey);
142 if (log instanceof Messager)
143 messager = (Messager) log;
144 else {
145 PrintWriter out = context.get(Log.outKey);
146 messager = (out == null) ? new Messager(context, javadocName)
147 : new Messager(context, javadocName, out, out, out);
148 }
149 }
151 /**
152 * Usage
153 */
154 @Override
155 void usage() {
156 usage(true);
157 }
160 /**
161 * Usage
162 */
163 private void usage(boolean exit) {
164 // RFE: it would be better to replace the following with code to
165 // write a header, then help for each option, then a footer.
166 messager.notice("main.usage");
168 // let doclet print usage information (does nothing on error)
169 if (docletInvoker != null) {
170 docletInvoker.optionLength("-help");
171 }
173 if (exit) exit();
174 }
176 @Override
177 void Xusage() {
178 Xusage(true);
179 }
181 /**
182 * Usage
183 */
184 private void Xusage(boolean exit) {
185 messager.notice("main.Xusage");
186 if (exit) exit();
187 }
189 /**
190 * Exit
191 */
192 private void exit() {
193 messager.exit();
194 }
197 /**
198 * Main program - external wrapper
199 */
200 int begin(String... argv) {
201 boolean ok = begin(null, argv, Collections.<JavaFileObject> emptySet());
202 return ok ? 0 : 1;
203 }
205 public boolean begin(Class<?> docletClass, Iterable<String> options, Iterable<? extends JavaFileObject> fileObjects) {
206 Collection<String> opts = new ArrayList<String>();
207 for (String opt: options) opts.add(opt);
208 return begin(docletClass, opts.toArray(new String[opts.size()]), fileObjects);
209 }
211 private boolean begin(Class<?> docletClass, String[] options, Iterable<? extends JavaFileObject> fileObjects) {
212 boolean failed = false;
214 try {
215 failed = !parseAndExecute(docletClass, options, fileObjects);
216 } catch (Messager.ExitJavadoc exc) {
217 // ignore, we just exit this way
218 } catch (OutOfMemoryError ee) {
219 messager.error(Messager.NOPOS, "main.out.of.memory");
220 failed = true;
221 } catch (ClientCodeException e) {
222 // simply rethrow these exceptions, to be caught and handled by JavadocTaskImpl
223 throw e;
224 } catch (Error ee) {
225 ee.printStackTrace(System.err);
226 messager.error(Messager.NOPOS, "main.fatal.error");
227 failed = true;
228 } catch (Exception ee) {
229 ee.printStackTrace(System.err);
230 messager.error(Messager.NOPOS, "main.fatal.exception");
231 failed = true;
232 } finally {
233 messager.exitNotice();
234 messager.flush();
235 }
236 failed |= messager.nerrors() > 0;
237 failed |= rejectWarnings && messager.nwarnings() > 0;
238 return !failed;
239 }
241 /**
242 * Main program - internal
243 */
244 private boolean parseAndExecute(
245 Class<?> docletClass,
246 String[] argv,
247 Iterable<? extends JavaFileObject> fileObjects) throws IOException {
248 long tm = System.currentTimeMillis();
250 ListBuffer<String> javaNames = new ListBuffer<String>();
252 // Preprocess @file arguments
253 try {
254 argv = CommandLine.parse(argv);
255 } catch (FileNotFoundException e) {
256 messager.error(Messager.NOPOS, "main.cant.read", e.getMessage());
257 exit();
258 } catch (IOException e) {
259 e.printStackTrace(System.err);
260 exit();
261 }
264 JavaFileManager fileManager = context.get(JavaFileManager.class);
265 setDocletInvoker(docletClass, fileManager, argv);
267 compOpts = Options.instance(context);
269 // Parse arguments
270 for (int i = 0 ; i < argv.length ; i++) {
271 String arg = argv[i];
273 ToolOption o = ToolOption.get(arg);
274 if (o != null) {
275 // hack: this restriction should be removed
276 if (o == ToolOption.LOCALE && i > 0)
277 usageError("main.locale_first");
279 if (o.hasArg) {
280 oneArg(argv, i++);
281 o.process(this, argv[i]);
282 } else {
283 setOption(arg);
284 o.process(this);
285 }
287 } else if (arg.startsWith("-XD")) {
288 // hidden javac options
289 String s = arg.substring("-XD".length());
290 int eq = s.indexOf('=');
291 String key = (eq < 0) ? s : s.substring(0, eq);
292 String value = (eq < 0) ? s : s.substring(eq+1);
293 compOpts.put(key, value);
294 }
295 // call doclet for its options
296 // other arg starts with - is invalid
297 else if (arg.startsWith("-")) {
298 int optionLength;
299 optionLength = docletInvoker.optionLength(arg);
300 if (optionLength < 0) {
301 // error already displayed
302 exit();
303 } else if (optionLength == 0) {
304 // option not found
305 usageError("main.invalid_flag", arg);
306 } else {
307 // doclet added option
308 if ((i + optionLength) > argv.length) {
309 usageError("main.requires_argument", arg);
310 }
311 ListBuffer<String> args = new ListBuffer<String>();
312 for (int j = 0; j < optionLength-1; ++j) {
313 args.append(argv[++i]);
314 }
315 setOption(arg, args.toList());
316 }
317 } else {
318 javaNames.append(arg);
319 }
320 }
321 compOpts.notifyListeners();
323 if (javaNames.isEmpty() && subPackages.isEmpty() && isEmpty(fileObjects)) {
324 usageError("main.No_packages_or_classes_specified");
325 }
327 if (!docletInvoker.validOptions(options.toList())) {
328 // error message already displayed
329 exit();
330 }
332 JavadocTool comp = JavadocTool.make0(context);
333 if (comp == null) return false;
335 if (showAccess == null) {
336 setFilter(defaultFilter);
337 }
339 LanguageVersion languageVersion = docletInvoker.languageVersion();
340 RootDocImpl root = comp.getRootDocImpl(
341 docLocale,
342 encoding,
343 showAccess,
344 javaNames.toList(),
345 options.toList(),
346 fileObjects,
347 breakiterator,
348 subPackages.toList(),
349 excludedPackages.toList(),
350 docClasses,
351 // legacy?
352 languageVersion == null || languageVersion == LanguageVersion.JAVA_1_1,
353 quiet);
355 // release resources
356 comp = null;
358 // pass off control to the doclet
359 boolean ok = root != null;
360 if (ok) ok = docletInvoker.start(root);
362 // We're done.
363 if (compOpts.get("-verbose") != null) {
364 tm = System.currentTimeMillis() - tm;
365 messager.notice("main.done_in", Long.toString(tm));
366 }
368 return ok;
369 }
371 private <T> boolean isEmpty(Iterable<T> iter) {
372 return !iter.iterator().hasNext();
373 }
375 /**
376 * Init the doclet invoker.
377 * The doclet class may be given explicitly, or via the -doclet option in
378 * argv.
379 * If the doclet class is not given explicitly, it will be loaded from
380 * the file manager's DOCLET_PATH location, if available, or via the
381 * -doclet path option in argv.
382 * @param docletClass The doclet class. May be null.
383 * @param fileManager The file manager used to get the class loader to load
384 * the doclet class if required. May be null.
385 * @param argv Args containing -doclet and -docletpath, in case they are required.
386 */
387 private void setDocletInvoker(Class<?> docletClass, JavaFileManager fileManager, String[] argv) {
388 if (docletClass != null) {
389 docletInvoker = new DocletInvoker(messager, docletClass, apiMode);
390 // TODO, check no -doclet, -docletpath
391 return;
392 }
394 String docletClassName = null;
395 String docletPath = null;
397 // Parse doclet specifying arguments
398 for (int i = 0 ; i < argv.length ; i++) {
399 String arg = argv[i];
400 if (arg.equals(ToolOption.DOCLET.opt)) {
401 oneArg(argv, i++);
402 if (docletClassName != null) {
403 usageError("main.more_than_one_doclet_specified_0_and_1",
404 docletClassName, argv[i]);
405 }
406 docletClassName = argv[i];
407 } else if (arg.equals(ToolOption.DOCLETPATH.opt)) {
408 oneArg(argv, i++);
409 if (docletPath == null) {
410 docletPath = argv[i];
411 } else {
412 docletPath += File.pathSeparator + argv[i];
413 }
414 }
415 }
417 if (docletClassName == null) {
418 docletClassName = defaultDocletClassName;
419 }
421 // attempt to find doclet
422 docletInvoker = new DocletInvoker(messager, fileManager,
423 docletClassName, docletPath,
424 docletParentClassLoader,
425 apiMode);
426 }
428 /**
429 * Set one arg option.
430 * Error and exit if one argument is not provided.
431 */
432 private void oneArg(String[] args, int index) {
433 if ((index + 1) < args.length) {
434 setOption(args[index], args[index+1]);
435 } else {
436 usageError("main.requires_argument", args[index]);
437 }
438 }
440 @Override
441 void usageError(String key, Object... args) {
442 messager.error(Messager.NOPOS, key, args);
443 usage(true);
444 }
446 /**
447 * indicate an option with no arguments was given.
448 */
449 private void setOption(String opt) {
450 String[] option = { opt };
451 options.append(option);
452 }
454 /**
455 * indicate an option with one argument was given.
456 */
457 private void setOption(String opt, String argument) {
458 String[] option = { opt, argument };
459 options.append(option);
460 }
462 /**
463 * indicate an option with the specified list of arguments was given.
464 */
465 private void setOption(String opt, List<String> arguments) {
466 String[] args = new String[arguments.length() + 1];
467 int k = 0;
468 args[k++] = opt;
469 for (List<String> i = arguments; i.nonEmpty(); i=i.tail) {
470 args[k++] = i.head;
471 }
472 options.append(args);
473 }
474 }