You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Main.java 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. /* *******************************************************************
  2. * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
  3. * All rights reserved.
  4. * This program and the accompanying materials are made available
  5. * under the terms of the Eclipse Public License v 2.0
  6. * which accompanies this distribution and is available at
  7. * https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.txt
  8. *
  9. * Contributors:
  10. * PARC initial implementation
  11. * ******************************************************************/
  12. package org.aspectj.tools.ajc;
  13. import java.io.File;
  14. import java.io.FileOutputStream;
  15. import java.io.IOException;
  16. import java.io.PrintStream;
  17. import java.util.Arrays;
  18. import java.util.Date;
  19. import java.util.List;
  20. import org.aspectj.ajdt.internal.core.builder.AjBuildManager;
  21. import org.aspectj.bridge.AbortException;
  22. import org.aspectj.bridge.ICommand;
  23. import org.aspectj.bridge.IMessage;
  24. import org.aspectj.bridge.IMessage.Kind;
  25. import org.aspectj.bridge.IMessageHandler;
  26. import org.aspectj.bridge.IMessageHolder;
  27. import org.aspectj.bridge.ISourceLocation;
  28. import org.aspectj.bridge.Message;
  29. import org.aspectj.bridge.MessageHandler;
  30. import org.aspectj.bridge.MessageUtil;
  31. import org.aspectj.bridge.ReflectionFactory;
  32. import org.aspectj.bridge.Version;
  33. import org.aspectj.bridge.context.CompilationAndWeavingContext;
  34. import org.aspectj.util.FileUtil;
  35. import org.aspectj.util.LangUtil;
  36. import org.aspectj.weaver.Dump;
  37. /**
  38. * Programmatic and command-line interface to AspectJ compiler. The compiler is an ICommand obtained by reflection. Not thread-safe.
  39. * By default, messages are printed as they are emitted; info messages go to the output stream, and warnings and errors go to the
  40. * error stream.
  41. * <p>
  42. * Clients can handle all messages by registering a holder:
  43. *
  44. * <pre>
  45. * Main main = new Main();
  46. * IMessageHolder holder = new MessageHandler();
  47. * main.setHolder(holder);
  48. * </pre>
  49. *
  50. * Clients can get control after each command completes by installing a Runnable:
  51. *
  52. * <pre>
  53. * main.setCompletionRunner(new Runnable() {..});
  54. * </pre>
  55. *
  56. */
  57. public class Main {
  58. /** Header used when rendering exceptions for users */
  59. public static final String THROWN_PREFIX = "Exception thrown from AspectJ " + Version.getText() + LangUtil.EOL + "" + LangUtil.EOL
  60. + "This might be logged as a bug already -- find current bugs at" + LangUtil.EOL
  61. + " http://bugs.eclipse.org/bugs/buglist.cgi?product=AspectJ&component=Compiler" + LangUtil.EOL + "" + LangUtil.EOL
  62. + "Bugs for exceptions thrown have titles File:line from the top stack, " + LangUtil.EOL
  63. + "e.g., \"SomeFile.java:243\"" + LangUtil.EOL + "" + LangUtil.EOL
  64. + "If you don't find the exception below in a bug, please add a new bug" + LangUtil.EOL
  65. + "at http://bugs.eclipse.org/bugs/enter_bug.cgi?product=AspectJ" + LangUtil.EOL
  66. + "To make the bug a priority, please include a test program" + LangUtil.EOL + "that can reproduce this exception."
  67. + LangUtil.EOL;
  68. private static final String OUT_OF_MEMORY_MSG = "AspectJ " + Version.getText() + " ran out of memory during compilation:"
  69. + LangUtil.EOL + LangUtil.EOL + "Please increase the memory available to ajc by editing the ajc script " + LangUtil.EOL
  70. + "found in your AspectJ installation directory. The -Xmx parameter value" + LangUtil.EOL
  71. + "should be increased from 64M (default) to 128M or even 256M." + LangUtil.EOL + LangUtil.EOL
  72. + "See the AspectJ FAQ available from the documentation link" + LangUtil.EOL
  73. + "on the AspectJ home page at http://www.eclipse.org/aspectj";
  74. private static final String MESSAGE_HOLDER_OPTION = "-messageHolder";
  75. /** @param args the String[] of command-line arguments */
  76. public static void main(String[] args) throws IOException {
  77. new Main().runMain(args, true);
  78. }
  79. /**
  80. * Convenience method to run ajc and collect String lists of messages. This can be reflectively invoked with the List collecting
  81. * parameters supplied by a parent class loader. The String messages take the same form as command-line messages.
  82. * This method does not catch unchecked exceptions thrown by the compiler.
  83. *
  84. * @param args the String[] args to pass to the compiler
  85. * @param useSystemExit if true and errors, return System.exit(errs)
  86. * @param fails the List sink, if any, for String failure (or worse) messages
  87. * @param errors the List sink, if any, for String error messages
  88. * @param warnings the List sink, if any, for String warning messages
  89. * @param infos the List sink, if any, for String info messages
  90. * @param usages the List sink, if any, for String usage messages
  91. * @return number of messages reported with level ERROR or above
  92. */
  93. public static int bareMain(
  94. String[] args, boolean useSystemExit,
  95. List<String> fails, List<String> errors, List<String> warnings, List<String> infos, List<String> usages
  96. ) {
  97. Main main = new Main();
  98. MessageHandler holder = new MessageHandler();
  99. main.setHolder(holder);
  100. try {
  101. main.runMain(args, useSystemExit);
  102. } finally {
  103. readMessages(holder, IMessage.FAIL, true, fails);
  104. readMessages(holder, IMessage.ERROR, false, errors);
  105. readMessages(holder, IMessage.WARNING, false, warnings);
  106. readMessages(holder, IMessage.INFO, false, infos);
  107. readMessages(holder, IMessage.USAGE, false, usages);
  108. }
  109. return holder.numMessages(IMessage.ERROR, true);
  110. }
  111. /** Read messages of a given kind into a List as String */
  112. private static void readMessages(IMessageHolder holder, IMessage.Kind kind, boolean orGreater, List<String> sink) {
  113. if ((null == sink) || (null == holder)) {
  114. return;
  115. }
  116. IMessage[] messages = holder.getMessages(kind, orGreater);
  117. if (!LangUtil.isEmpty(messages)) {
  118. for (IMessage message : messages) {
  119. sink.add(MessagePrinter.render(message));
  120. }
  121. }
  122. }
  123. /**
  124. * @return String rendering throwable as compiler error for user/console, including information on how to report as a bug.
  125. * @throws NullPointerException if thrown is null
  126. */
  127. public static String renderExceptionForUser(Throwable thrown) {
  128. String m = thrown.getMessage();
  129. return THROWN_PREFIX + (null != m ? m + "\n" : "") + "\n" + CompilationAndWeavingContext.getCurrentContext()
  130. + LangUtil.renderException(thrown, true);
  131. }
  132. private static String parmInArgs(String flag, String[] args) {
  133. int loc = 1 + (null == args ? -1 : Arrays.asList(args).indexOf(flag));
  134. return ((0 == loc) || (args.length <= loc) ? null : args[loc]);
  135. }
  136. private static boolean flagInArgs(String flag, String[] args) {
  137. return ((null != args) && (Arrays.asList(args).contains(flag)));
  138. }
  139. /**
  140. * append nothing if numItems is 0, numItems + label + (numItems > 1? "s" : "") otherwise, prefixing with " " if sink has
  141. * content
  142. */
  143. private static void appendNLabel(StringBuffer sink, String label, int numItems) {
  144. if (0 == numItems) {
  145. return;
  146. }
  147. if (0 < sink.length()) {
  148. sink.append(", ");
  149. }
  150. sink.append(numItems).append(" ");
  151. if (!LangUtil.isEmpty(label)) {
  152. sink.append(label);
  153. }
  154. if (1 < numItems) {
  155. sink.append("s");
  156. }
  157. }
  158. /** control iteration/continuation for command (compiler) */
  159. protected CommandController controller;
  160. /** ReflectionFactory identifier for command (compiler) */
  161. protected String commandName;
  162. protected ICommand command;
  163. /** client-set message sink */
  164. private IMessageHolder clientHolder;
  165. /** internally-set message sink */
  166. protected final MessageHandler ourHandler;
  167. private int lastFails;
  168. private int lastErrors;
  169. /** if not null, run this synchronously after each compile completes */
  170. private Runnable completionRunner;
  171. public Main() {
  172. controller = new CommandController();
  173. commandName = ReflectionFactory.ECLIPSE;
  174. CompilationAndWeavingContext.setMultiThreaded(false);
  175. try {
  176. String value = System.getProperty("aspectj.multithreaded");
  177. if (value != null && value.equalsIgnoreCase("true")) {
  178. CompilationAndWeavingContext.setMultiThreaded(true);
  179. }
  180. } catch (Exception e) {
  181. // silent
  182. }
  183. ourHandler = new MessageHandler(true);
  184. }
  185. public MessageHandler getMessageHandler() {
  186. return ourHandler;
  187. }
  188. // for unit testing...
  189. void setController(CommandController controller) {
  190. this.controller = controller;
  191. }
  192. public void setCommand(ICommand command) {
  193. this.command = command;
  194. }
  195. /**
  196. * Run without throwing exceptions but optionally using System.exit(..). This sets up a message handler which emits messages
  197. * immediately, so report(boolean, IMessageHandler) only reports total number of errors or warnings.
  198. *
  199. * @param args the String[] command line for the compiler
  200. * @param useSystemExit if true, use System.exit(int) to complete unless one of the args is -noExit. and signal result (0 no
  201. * exceptions/error, &lt;0 exceptions, &gt;0 compiler errors).
  202. */
  203. public void runMain(String[] args, boolean useSystemExit) {
  204. // Urk - default no check for AJDT, enabled here for Ant, command-line
  205. AjBuildManager.enableRuntimeVersionCheck(this);
  206. final boolean verbose = flagInArgs("-verbose", args);
  207. final boolean timers = flagInArgs("-timers", args);
  208. if (null == this.clientHolder) {
  209. this.clientHolder = checkForCustomMessageHolder(args);
  210. }
  211. IMessageHolder holder = clientHolder;
  212. if (null == holder) {
  213. holder = ourHandler;
  214. if (verbose) {
  215. ourHandler.setInterceptor(MessagePrinter.VERBOSE);
  216. } else {
  217. ourHandler.ignore(IMessage.INFO);
  218. ourHandler.setInterceptor(MessagePrinter.TERSE);
  219. }
  220. }
  221. // make sure we handle out of memory gracefully...
  222. try {
  223. // byte[] b = new byte[100000000]; for testing OoME only!
  224. long stime = System.currentTimeMillis();
  225. // uncomment next line to pause before startup (attach jconsole)
  226. // try {Thread.sleep(5000); }catch(Exception e) {}
  227. run(args, holder);
  228. long etime = System.currentTimeMillis();
  229. if (timers) {
  230. System.out.println("Compiler took " + (etime - stime) + "ms");
  231. }
  232. holder.handleMessage(MessageUtil.info("Compiler took " + (etime - stime) + "ms"));
  233. // uncomment next line to pause at end (keeps jconsole alive!)
  234. // try { System.in.read(); } catch (Exception e) {}
  235. } catch (OutOfMemoryError outOfMemory) {
  236. IMessage outOfMemoryMessage = new Message(OUT_OF_MEMORY_MSG, null, true);
  237. holder.handleMessage(outOfMemoryMessage);
  238. System.exit(-1); // we can't reasonably continue from this point.
  239. } finally {
  240. CompilationAndWeavingContext.reset();
  241. Dump.reset();
  242. }
  243. boolean skipExit = false;
  244. if (useSystemExit && !LangUtil.isEmpty(args)) { // sigh - pluck -noExit
  245. for (String arg : args) {
  246. if ("-noExit".equals(arg)) {
  247. skipExit = true;
  248. break;
  249. }
  250. }
  251. }
  252. if (useSystemExit && !skipExit) {
  253. systemExit(holder);
  254. }
  255. }
  256. // put calls around run() call above to allowing connecting jconsole
  257. // private void pause(int ms) {
  258. // try {
  259. // System.err.println("Pausing for "+ms+"ms");
  260. // System.gc();
  261. // Thread.sleep(ms);
  262. // System.gc();
  263. // System.err.println("Continuing");
  264. // } catch (Exception e) {}
  265. // }
  266. /**
  267. * @param args
  268. */
  269. private IMessageHolder checkForCustomMessageHolder(String[] args) {
  270. IMessageHolder holder = null;
  271. final String customMessageHolder = parmInArgs(MESSAGE_HOLDER_OPTION, args);
  272. if (customMessageHolder != null) {
  273. try {
  274. holder = (IMessageHolder) Class.forName(customMessageHolder).getDeclaredConstructor().newInstance();
  275. } catch (Exception ex) {
  276. throw new AbortException("Failed to create custom message holder of class '" + customMessageHolder + "' : " + ex);
  277. }
  278. }
  279. return holder;
  280. }
  281. /**
  282. * Run without using System.exit(..), putting all messages in holder:
  283. * <ul>
  284. * <li>ERROR: compiler error</li>
  285. * <li>WARNING: compiler warning</li>
  286. * <li>FAIL: command error (bad arguments, exception thrown)</li>
  287. * </ul>
  288. * This handles incremental behavior:
  289. * <ul>
  290. * <li>If args include "-incremental", repeat for every input char until 'q' is entered.
  291. * <li>If args include "-incrementalTagFile {file}", repeat every time we detect that {file} modification time has changed.</li>
  292. * <li>Either way, list files recompiled each time if args includes "-verbose".</li>
  293. * <li>Exit when the commmand/compiler throws any Throwable.</li>
  294. * </ul>
  295. * When complete, this contains all the messages of the final run of the command and/or any FAIL messages produced in running
  296. * the command, including any Throwable thrown by the command itself.
  297. *
  298. * @param args the String[] command line for the compiler
  299. * @param holder the MessageHandler sink for messages.
  300. */
  301. public void run(String[] args, IMessageHolder holder) {
  302. PrintStream logStream = null;
  303. FileOutputStream fos = null;
  304. String logFileName = parmInArgs("-log", args);
  305. if (null != logFileName) {
  306. File logFile = new File(logFileName);
  307. try {
  308. logFile.createNewFile();
  309. fos = new FileOutputStream(logFileName, true);
  310. logStream = new PrintStream(fos, true);
  311. } catch (Exception e) {
  312. fail(holder, "Couldn't open log file: " + logFileName, e);
  313. }
  314. Date now = new Date();
  315. logStream.println(now);
  316. if (flagInArgs("-verbose", args)) {
  317. ourHandler.setInterceptor(new LogModeMessagePrinter(true, logStream));
  318. } else {
  319. ourHandler.ignore(IMessage.INFO);
  320. ourHandler.setInterceptor(new LogModeMessagePrinter(false, logStream));
  321. }
  322. holder = ourHandler;
  323. }
  324. if (LangUtil.isEmpty(args)) {
  325. args = new String[] { "-?" };
  326. } else if (controller.running()) {
  327. fail(holder, "already running with controller: " + controller, null);
  328. return;
  329. }
  330. args = controller.init(args, holder);
  331. if (0 < holder.numMessages(IMessage.ERROR, true)) {
  332. return;
  333. }
  334. if (command == null) {
  335. command = ReflectionFactory.makeCommand(commandName, holder);
  336. }
  337. if (0 < holder.numMessages(IMessage.ERROR, true)) {
  338. return;
  339. }
  340. try {
  341. outer: while (true) {
  342. boolean passed = command.runCommand(args, holder);
  343. if (report(passed, holder) && controller.incremental()) {
  344. while (controller.doRepeatCommand(command)) {
  345. holder.clearMessages();
  346. if (controller.buildFresh()) {
  347. continue outer;
  348. } else {
  349. passed = command.repeatCommand(holder);
  350. }
  351. if (!report(passed, holder)) {
  352. break;
  353. }
  354. }
  355. }
  356. break;
  357. }
  358. } catch (AbortException ae) {
  359. if (ae.isSilent()) {
  360. quit();
  361. } else {
  362. IMessage message = ae.getIMessage();
  363. Throwable thrown = ae.getThrown();
  364. if (null == thrown) { // toss AbortException wrapper
  365. if (null != message) {
  366. holder.handleMessage(message);
  367. } else {
  368. fail(holder, "abort without message", ae);
  369. }
  370. } else if (null == message) {
  371. fail(holder, "aborted", thrown);
  372. } else {
  373. String mssg = MessageUtil.MESSAGE_MOST.renderToString(message);
  374. fail(holder, mssg, thrown);
  375. }
  376. }
  377. } catch (Throwable t) {
  378. fail(holder, "unexpected exception", t);
  379. } finally {
  380. if (logStream != null) {
  381. logStream.close();
  382. }
  383. if (fos != null) {
  384. try {
  385. fos.close();
  386. } catch (IOException e) {
  387. fail(holder, "unexpected exception", e);
  388. }
  389. }
  390. command = null;
  391. }
  392. }
  393. /** call this to stop after the next iteration of incremental compile */
  394. public void quit() {
  395. controller.quit();
  396. }
  397. /**
  398. * Set holder to be passed all messages. When holder is set, messages will not be printed by default.
  399. *
  400. * @param holder the IMessageHolder sink for all messages (use null to restore default behavior)
  401. */
  402. public void setHolder(IMessageHolder holder) {
  403. clientHolder = holder;
  404. }
  405. public IMessageHolder getHolder() {
  406. return clientHolder;
  407. }
  408. /**
  409. * Install a Runnable to be invoked synchronously after each compile completes.
  410. *
  411. * @param runner the Runnable to invoke - null to disable
  412. */
  413. public void setCompletionRunner(Runnable runner) {
  414. this.completionRunner = runner;
  415. }
  416. /**
  417. * Call System.exit(int) with values derived from the number of failures/aborts or errors in messages.
  418. *
  419. * @param messages the IMessageHolder to interrogate.
  420. */
  421. protected void systemExit(IMessageHolder messages) {
  422. int num = lastFails; // messages.numMessages(IMessage.FAIL, true);
  423. if (0 < num) {
  424. System.exit(-num);
  425. }
  426. num = lastErrors; // messages.numMessages(IMessage.ERROR, false);
  427. if (0 < num) {
  428. System.exit(num);
  429. }
  430. System.exit(0);
  431. }
  432. /** Messages to the user */
  433. protected void outMessage(String message) { // XXX coordinate with MessagePrinter
  434. System.out.print(message);
  435. System.out.flush();
  436. }
  437. /**
  438. * Report results from a (possibly-incremental) compile run. This delegates to any reportHandler or otherwise prints summary
  439. * counts of errors/warnings to System.err (if any errors) or System.out (if only warnings). WARNING: this silently ignores
  440. * other messages like FAIL, but clears the handler of all messages when returning true. XXX false
  441. *
  442. * This implementation ignores the pass parameter but clears the holder after reporting on the assumption messages were
  443. * handled/printed already. (ignoring UnsupportedOperationException from holder.clearMessages()).
  444. *
  445. * @param pass true result of the command
  446. * @param holder IMessageHolder with messages from the command
  447. * @return false if the process should abort
  448. */
  449. protected boolean report(boolean pass, IMessageHolder holder) {
  450. lastFails = holder.numMessages(IMessage.FAIL, true);
  451. boolean result = (0 == lastFails);
  452. final Runnable runner = completionRunner;
  453. if (null != runner) {
  454. runner.run();
  455. }
  456. if (holder == ourHandler) {
  457. lastErrors = holder.numMessages(IMessage.ERROR, false);
  458. int warnings = holder.numMessages(IMessage.WARNING, false);
  459. StringBuffer sb = new StringBuffer();
  460. appendNLabel(sb, "fail|abort", lastFails);
  461. appendNLabel(sb, "error", lastErrors);
  462. appendNLabel(sb, "warning", warnings);
  463. if (0 < sb.length()) {
  464. PrintStream out = (0 < (lastErrors + lastFails) ? System.err : System.out);
  465. out.println(""); // XXX "wrote class file" messages no eol?
  466. out.println(sb);
  467. }
  468. }
  469. return result;
  470. }
  471. /** convenience API to make fail messages (without MessageUtils's fail prefix) */
  472. protected static void fail(IMessageHandler handler, String message, Throwable thrown) {
  473. handler.handleMessage(new Message(message, IMessage.FAIL, thrown, null));
  474. }
  475. /**
  476. * interceptor IMessageHandler to print as we go. This formats all messages to the user.
  477. */
  478. public static class MessagePrinter implements IMessageHandler {
  479. public static final IMessageHandler VERBOSE = new MessagePrinter(true);
  480. public static final IMessageHandler TERSE = new MessagePrinter(false);
  481. final boolean verbose;
  482. protected MessagePrinter(boolean verbose) {
  483. this.verbose = verbose;
  484. }
  485. /**
  486. * Print errors and warnings to System.err, and optionally info to System.out, rendering message String only.
  487. *
  488. * @return false always
  489. */
  490. @Override
  491. public boolean handleMessage(IMessage message) {
  492. if (null != message) {
  493. PrintStream out = getStreamFor(message.getKind());
  494. if (null != out) {
  495. out.println(render(message));
  496. }
  497. }
  498. return false;
  499. }
  500. /**
  501. * Render message differently. If abort, then prefix stack trace with feedback request. If the actual message is empty, then
  502. * use toString on the whole. Prefix message part with file:line; If it has context, suffix message with context.
  503. *
  504. * @param message the IMessage to render
  505. * @return String rendering IMessage (never null)
  506. */
  507. public static String render(IMessage message) {
  508. // IMessage.Kind kind = message.getKind();
  509. StringBuilder sb = new StringBuilder();
  510. String text = message.getMessage();
  511. if (text.equals(AbortException.NO_MESSAGE_TEXT)) {
  512. text = null;
  513. }
  514. boolean toString = (LangUtil.isEmpty(text));
  515. if (toString) {
  516. text = message.toString();
  517. }
  518. ISourceLocation loc = message.getSourceLocation();
  519. String context = null;
  520. if (null != loc) {
  521. File file = loc.getSourceFile();
  522. if (null != file) {
  523. String name = file.getName();
  524. if (!toString || (!text.contains(name))) {
  525. sb.append(FileUtil.getBestPath(file));
  526. if (loc.getLine() > 0) {
  527. sb.append(":" + loc.getLine());
  528. }
  529. int col = loc.getColumn();
  530. if (0 < col) {
  531. sb.append(":").append(col);
  532. }
  533. sb.append(" ");
  534. }
  535. }
  536. context = loc.getContext();
  537. }
  538. // per Wes' suggestion on dev...
  539. if (message.getKind() == IMessage.ERROR) {
  540. sb.append("[error] ");
  541. } else if (message.getKind() == IMessage.WARNING) {
  542. sb.append("[warning] ");
  543. }
  544. sb.append(text);
  545. if (null != context) {
  546. sb.append(LangUtil.EOL);
  547. sb.append(context);
  548. }
  549. String details = message.getDetails();
  550. if (details != null) {
  551. sb.append(LangUtil.EOL);
  552. sb.append('\t');
  553. sb.append(details);
  554. }
  555. Throwable thrown = message.getThrown();
  556. if (null != thrown) {
  557. sb.append(LangUtil.EOL);
  558. sb.append(Main.renderExceptionForUser(thrown));
  559. }
  560. if (message.getExtraSourceLocations().isEmpty()) {
  561. return sb.toString();
  562. } else {
  563. return MessageUtil.addExtraSourceLocations(message, sb.toString());
  564. }
  565. }
  566. @Override
  567. public boolean isIgnoring(IMessage.Kind kind) {
  568. return (null != getStreamFor(kind));
  569. }
  570. /**
  571. * No-op
  572. *
  573. * @see org.aspectj.bridge.IMessageHandler#isIgnoring(org.aspectj.bridge.IMessage.Kind)
  574. * @param kind
  575. */
  576. @Override
  577. public void dontIgnore(IMessage.Kind kind) {
  578. }
  579. /**
  580. * @return System.err for FAIL, ABORT, ERROR, and WARNING, System.out for INFO if -verbose and WEAVEINFO if -showWeaveInfo.
  581. */
  582. protected PrintStream getStreamFor(IMessage.Kind kind) {
  583. if (IMessage.WARNING.isSameOrLessThan(kind)) {
  584. return System.err;
  585. } else if (verbose && IMessage.INFO.equals(kind)) {
  586. return System.out;
  587. } else if (IMessage.USAGE.equals(kind)) {
  588. return System.out;
  589. } else if (IMessage.WEAVEINFO.equals(kind)) {
  590. return System.out;
  591. } else {
  592. return null;
  593. }
  594. }
  595. /**
  596. * No-op
  597. *
  598. * @see org.aspectj.bridge.IMessageHandler#ignore(org.aspectj.bridge.IMessage.Kind)
  599. * @param kind
  600. */
  601. @Override
  602. public void ignore(Kind kind) {
  603. }
  604. }
  605. public static class LogModeMessagePrinter extends MessagePrinter {
  606. protected final PrintStream logStream;
  607. public LogModeMessagePrinter(boolean verbose, PrintStream logStream) {
  608. super(verbose);
  609. this.logStream = logStream;
  610. }
  611. @Override
  612. protected PrintStream getStreamFor(IMessage.Kind kind) {
  613. if (IMessage.WARNING.isSameOrLessThan(kind)) {
  614. return logStream;
  615. } else if (verbose && IMessage.INFO.equals(kind)) {
  616. return logStream;
  617. } else if (IMessage.WEAVEINFO.equals(kind)) {
  618. return logStream;
  619. } else {
  620. return null;
  621. }
  622. }
  623. }
  624. /** controller for repeatable command delays until input or file changed or removed */
  625. public static class CommandController {
  626. public static String TAG_FILE_OPTION = "-XincrementalFile";
  627. public static String INCREMENTAL_OPTION = "-incremental";
  628. /** maximum 10-minute delay between filesystem checks */
  629. public static long MAX_DELAY = 1000 * 600;
  630. /** default 5-second delay between filesystem checks */
  631. public static long DEFAULT_DELAY = 1000 * 5;
  632. /** @see init(String[]) */
  633. private static final String[][] OPTIONS = new String[][] {
  634. new String[] { INCREMENTAL_OPTION },
  635. new String[] { TAG_FILE_OPTION, null }
  636. };
  637. /** true between init(String[]) and doRepeatCommand() that returns false */
  638. private boolean running;
  639. /** true after quit() called */
  640. private boolean quit;
  641. /** true if incremental mode, waiting for input other than 'q' */
  642. private boolean incremental;
  643. /** true if incremental mode, waiting for file to change (repeat) or disappear (quit) */
  644. private File tagFile;
  645. /** last modification time for tagFile as of last command - 0 to start */
  646. private long fileModTime;
  647. /** delay between filesystem checks for tagFile modification time */
  648. private long delay;
  649. /** true just after user types 'r' for rebuild */
  650. private boolean buildFresh;
  651. public CommandController() {
  652. delay = DEFAULT_DELAY;
  653. }
  654. /**
  655. * @param args read and strip incremental args from this
  656. * @param sink IMessageHandler for error messages
  657. * @return String[] remainder of args
  658. */
  659. public String[] init(String[] args, IMessageHandler sink) {
  660. running = true;
  661. // String[] unused;
  662. if (!LangUtil.isEmpty(args)) {
  663. String[][] options = LangUtil.copyStrings(OPTIONS);
  664. /* unused = */LangUtil.extractOptions(args, options);
  665. incremental = (null != options[0][0]);
  666. if (null != options[1][0]) {
  667. File file = new File(options[1][1]);
  668. if (!file.exists()) {
  669. MessageUtil.abort(sink, "tag file does not exist: " + file);
  670. } else {
  671. tagFile = file;
  672. fileModTime = tagFile.lastModified();
  673. }
  674. }
  675. }
  676. return args;
  677. }
  678. /**
  679. * @return true if init(String[]) called but doRepeatCommand has not returned false
  680. */
  681. public boolean running() {
  682. return running;
  683. }
  684. /** @param delay milliseconds between filesystem checks */
  685. public void setDelay(long delay) {
  686. if ((delay > -1) && (delay < MAX_DELAY)) {
  687. this.delay = delay;
  688. }
  689. }
  690. /** @return true if INCREMENTAL_OPTION or TAG_FILE_OPTION was in args */
  691. public boolean incremental() {
  692. return (incremental || (null != tagFile));
  693. }
  694. /** @return true if INCREMENTAL_OPTION was in args */
  695. public boolean commandLineIncremental() {
  696. return incremental;
  697. }
  698. public void quit() {
  699. if (!quit) {
  700. quit = true;
  701. }
  702. }
  703. /** @return true just after user typed 'r' */
  704. boolean buildFresh() {
  705. return buildFresh;
  706. }
  707. /** @return false if we should quit, true to do another command */
  708. boolean doRepeatCommand(ICommand command) {
  709. if (!running) {
  710. return false;
  711. }
  712. boolean result = false;
  713. if (quit) {
  714. result = false;
  715. } else if (incremental) {
  716. try {
  717. if (buildFresh) { // reset before input request
  718. buildFresh = false;
  719. }
  720. System.out.println(" press enter to recompile, r to rebuild, q to quit: ");
  721. System.out.flush();
  722. // boolean doMore = false;
  723. // seek for one q or a series of [\n\r]...
  724. do {
  725. int input = System.in.read();
  726. if ('q' == input) {
  727. break; // result = false;
  728. } else if ('r' == input) {
  729. buildFresh = true;
  730. result = true;
  731. } else if (('\n' == input) || ('\r' == input)) {
  732. result = true;
  733. } // else eat anything else
  734. } while (!result);
  735. System.in.skip(Integer.MAX_VALUE);
  736. } catch (IOException e) { // XXX silence for error?
  737. result = false;
  738. }
  739. } else if (null != tagFile) {
  740. long curModTime;
  741. while (true) {
  742. if (!tagFile.exists()) {
  743. result = false;
  744. break;
  745. } else if (fileModTime == (curModTime = tagFile.lastModified())) {
  746. fileCheckDelay();
  747. } else {
  748. fileModTime = curModTime;
  749. result = true;
  750. break;
  751. }
  752. }
  753. } // else, not incremental - false
  754. if (!result && running) {
  755. running = false;
  756. }
  757. return result;
  758. }
  759. /** delay between filesystem checks, returning if quit is set */
  760. protected void fileCheckDelay() {
  761. // final Thread thread = Thread.currentThread();
  762. long targetTime = System.currentTimeMillis() + delay;
  763. // long curTime;
  764. while (targetTime > System.currentTimeMillis()) {
  765. if (quit) {
  766. return;
  767. }
  768. try {
  769. Thread.sleep(300);
  770. } // 1/3-second delta for quit check
  771. catch (InterruptedException e) {
  772. }
  773. }
  774. }
  775. }
  776. }