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.

AjdeCoreBuildManager.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. /********************************************************************
  2. * Copyright (c) 2007 Contributors. All rights reserved.
  3. * This program and the accompanying materials are made available
  4. * under the terms of the Eclipse Public License v1.0
  5. * which accompanies this distribution and is available at
  6. * http://eclipse.org/legal/epl-v10.html
  7. *
  8. * Contributors: IBM Corporation - initial API and implementation
  9. * Helen Hawkins - initial version (bug 148190)
  10. *******************************************************************/
  11. package org.aspectj.ajde.core.internal;
  12. import java.io.File;
  13. import java.util.ArrayList;
  14. import java.util.Collection;
  15. import java.util.Iterator;
  16. import java.util.List;
  17. import java.util.Map;
  18. import java.util.StringTokenizer;
  19. import org.aspectj.ajde.core.AjCompiler;
  20. import org.aspectj.ajde.core.ICompilerConfiguration;
  21. import org.aspectj.ajde.core.IOutputLocationManager;
  22. import org.aspectj.ajdt.ajc.AjdtCommand;
  23. import org.aspectj.ajdt.ajc.BuildArgParser;
  24. import org.aspectj.ajdt.ajc.ConfigParser;
  25. import org.aspectj.ajdt.internal.core.builder.AjBuildConfig;
  26. import org.aspectj.ajdt.internal.core.builder.AjBuildManager;
  27. import org.aspectj.ajdt.internal.core.builder.AjState;
  28. import org.aspectj.ajdt.internal.core.builder.IncrementalStateManager;
  29. import org.aspectj.asm.AsmManager;
  30. import org.aspectj.bridge.AbortException;
  31. import org.aspectj.bridge.CountingMessageHandler;
  32. import org.aspectj.bridge.IMessage;
  33. import org.aspectj.bridge.IMessageHandler;
  34. import org.aspectj.bridge.ISourceLocation;
  35. import org.aspectj.bridge.Message;
  36. import org.aspectj.bridge.SourceLocation;
  37. import org.aspectj.bridge.context.CompilationAndWeavingContext;
  38. import org.aspectj.org.eclipse.jdt.internal.compiler.batch.FileSystem.Classpath;
  39. import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
  40. import org.aspectj.util.LangUtil;
  41. /**
  42. * Build Manager which drives the build for a given AjCompiler. Tools call build on the AjCompiler which drives this.
  43. */
  44. public class AjdeCoreBuildManager {
  45. private final AjCompiler compiler;
  46. private AjdeCoreBuildNotifierAdapter buildEventNotifier = null;
  47. private final AjBuildManager ajBuildManager;
  48. private final IMessageHandler msgHandlerAdapter;
  49. public AjdeCoreBuildManager(AjCompiler compiler) {
  50. this.compiler = compiler;
  51. this.msgHandlerAdapter = new AjdeCoreMessageHandlerAdapter(compiler.getMessageHandler());
  52. this.ajBuildManager = new AjBuildManager(msgHandlerAdapter);
  53. this.ajBuildManager.environmentSupportsIncrementalCompilation(true);
  54. // this static information needs to be set to ensure
  55. // incremental compilation works correctly
  56. IncrementalStateManager.recordIncrementalStates = true;
  57. IncrementalStateManager.debugIncrementalStates = false;
  58. AsmManager.attemptIncrementalModelRepairs = true;
  59. }
  60. public AjBuildManager getAjBuildManager() {
  61. return ajBuildManager;
  62. }
  63. /**
  64. * Execute a full or incremental build
  65. *
  66. * @param fullBuild true if requesting a full build, false if requesting to try an incremental build
  67. */
  68. public void performBuild(boolean fullBuild) {
  69. // If an incremental build is requested, check that we can
  70. if (!fullBuild) {
  71. AjState existingState = IncrementalStateManager.retrieveStateFor(compiler.getId());
  72. if (existingState == null || existingState.getBuildConfig() == null
  73. || ajBuildManager.getState().getBuildConfig() == null) {
  74. // No existing state so we must do a full build
  75. fullBuild = true;
  76. } else {
  77. AsmManager.setLastActiveStructureModel(existingState.getStructureModel());
  78. // AsmManager.getDefault().setRelationshipMap(existingState.getRelationshipMap());
  79. // AsmManager.getDefault().setHierarchy(existingState.getStructureModel());
  80. }
  81. }
  82. try {
  83. reportProgressBegin();
  84. // record the options passed to the compiler if INFO turned on
  85. if (!msgHandlerAdapter.isIgnoring(IMessage.INFO)) {
  86. handleMessage(new Message(getFormattedOptionsString(), IMessage.INFO, null, null));
  87. }
  88. CompilationAndWeavingContext.reset();
  89. if (fullBuild) { // FULL BUILD
  90. AjBuildConfig buildConfig = generateAjBuildConfig();
  91. if (buildConfig == null) {
  92. return;
  93. }
  94. ajBuildManager.batchBuild(buildConfig, msgHandlerAdapter);
  95. } else { // INCREMENTAL BUILD
  96. // Only rebuild the config object if the configuration has changed
  97. AjBuildConfig buildConfig = null;
  98. ICompilerConfiguration compilerConfig = compiler.getCompilerConfiguration();
  99. int changes = compilerConfig.getConfigurationChanges();
  100. if (changes != ICompilerConfiguration.NO_CHANGES) {
  101. // What configuration changes can we cope with? And besides just repairing the config object
  102. // what does it mean for any existing state that we have?
  103. buildConfig = generateAjBuildConfig();
  104. if (buildConfig == null) {
  105. return;
  106. }
  107. } else {
  108. buildConfig = ajBuildManager.getState().getBuildConfig();
  109. buildConfig.setChanged(changes); // pass it through for the state to use it when making decisions
  110. buildConfig.setModifiedFiles(compilerConfig.getProjectSourceFilesChanged());
  111. buildConfig.setClasspathElementsWithModifiedContents(compilerConfig.getClasspathElementsWithModifiedContents());
  112. compilerConfig.configurationRead();
  113. }
  114. ajBuildManager.incrementalBuild(buildConfig, msgHandlerAdapter);
  115. }
  116. IncrementalStateManager.recordSuccessfulBuild(compiler.getId(), ajBuildManager.getState());
  117. } catch (ConfigParser.ParseException pe) {
  118. handleMessage(new Message("Config file entry invalid, file: " + pe.getFile().getPath() + ", line number: "
  119. + pe.getLine(), IMessage.WARNING, null, null));
  120. } catch (AbortException e) {
  121. final IMessage message = e.getIMessage();
  122. if (message == null) {
  123. handleMessage(new Message(LangUtil.unqualifiedClassName(e) + " thrown: " + e.getMessage(), IMessage.ERROR, e, null));
  124. } else {
  125. handleMessage(new Message(message.getMessage() + "\n" + CompilationAndWeavingContext.getCurrentContext(),
  126. IMessage.ERROR, e, null));
  127. }
  128. } catch (Throwable t) {
  129. handleMessage(new Message("Compile error: " + LangUtil.unqualifiedClassName(t) + " thrown: " + "" + t.getMessage(),
  130. IMessage.ABORT, t, null));
  131. } finally {
  132. compiler.getBuildProgressMonitor().finish(ajBuildManager.wasFullBuild());
  133. }
  134. }
  135. /**
  136. * Starts the various notifiers which are interested in the build progress
  137. */
  138. private void reportProgressBegin() {
  139. compiler.getBuildProgressMonitor().begin();
  140. buildEventNotifier = new AjdeCoreBuildNotifierAdapter(compiler.getBuildProgressMonitor());
  141. ajBuildManager.setProgressListener(buildEventNotifier);
  142. }
  143. private String getFormattedOptionsString() {
  144. ICompilerConfiguration compilerConfig = compiler.getCompilerConfiguration();
  145. return "Building with settings: " + "\n-> output paths: "
  146. + formatCollection(compilerConfig.getOutputLocationManager().getAllOutputLocations()) + "\n-> classpath: "
  147. + compilerConfig.getClasspath() + "\n-> -inpath " + formatCollection(compilerConfig.getInpath()) + "\n-> -outjar "
  148. + formatOptionalString(compilerConfig.getOutJar()) + "\n-> -aspectpath "
  149. + formatCollection(compilerConfig.getAspectPath()) + "\n-> -sourcePathResources "
  150. + formatMap(compilerConfig.getSourcePathResources()) + "\n-> non-standard options: "
  151. + compilerConfig.getNonStandardOptions() + "\n-> javaoptions:" + formatMap(compilerConfig.getJavaOptionsMap());
  152. }
  153. private String formatCollection(Collection<?> options) {
  154. if (options == null) {
  155. return "<default>";
  156. }
  157. if (options.isEmpty()) {
  158. return "none";
  159. }
  160. StringBuffer formattedOptions = new StringBuffer();
  161. Iterator<?> it = options.iterator();
  162. while (it.hasNext()) {
  163. String o = it.next().toString();
  164. if (formattedOptions.length() > 0) {
  165. formattedOptions.append(", ");
  166. }
  167. formattedOptions.append(o);
  168. }
  169. return formattedOptions.toString();
  170. }
  171. private String formatMap(Map<String,? extends Object> options) {
  172. if (options == null) {
  173. return "<default>";
  174. }
  175. if (options.isEmpty()) {
  176. return "none";
  177. }
  178. return options.toString();
  179. }
  180. private String formatOptionalString(String s) {
  181. if (s == null) {
  182. return "";
  183. } else {
  184. return s;
  185. }
  186. }
  187. /**
  188. * Generate a new AjBuildConfig from the compiler configuration associated with this AjdeCoreBuildManager or from a
  189. * configuration file.
  190. *
  191. * @return null if invalid configuration, corresponding AjBuildConfig otherwise
  192. */
  193. public AjBuildConfig generateAjBuildConfig() {
  194. File configFile = new File(compiler.getId());
  195. ICompilerConfiguration compilerConfig = compiler.getCompilerConfiguration();
  196. CountingMessageHandler handler = CountingMessageHandler.makeCountingMessageHandler(msgHandlerAdapter);
  197. String[] args = null;
  198. // Retrieve the set of files from either an arg file (@filename) or the compiler configuration
  199. if (configFile.exists() && configFile.isFile()) {
  200. args = new String[] { "@" + configFile.getAbsolutePath() };
  201. } else {
  202. List<String> l = compilerConfig.getProjectSourceFiles();
  203. if (l == null) {
  204. return null;
  205. }
  206. // If the processor options are specified build the command line options for the JDT compiler to see
  207. String processor = compilerConfig.getProcessor();
  208. if (processor != null && processor.length() != 0) {
  209. l.add("-processor");
  210. l.add(processor);
  211. }
  212. String processorPath = compilerConfig.getProcessorPath();
  213. if (processorPath != null && processorPath.length() != 0) {
  214. l.add("-processorpath");
  215. l.add(processorPath);
  216. }
  217. List<String> xmlfiles = compilerConfig.getProjectXmlConfigFiles();
  218. if (xmlfiles != null && !xmlfiles.isEmpty()) {
  219. args = new String[l.size() + xmlfiles.size() + 1];
  220. // TODO speedup
  221. int p = 0;
  222. for (int i = 0; i < l.size(); i++) {
  223. args[p++] = (String) l.get(i);
  224. }
  225. for (int i = 0; i < xmlfiles.size(); i++) {
  226. args[p++] = (String) xmlfiles.get(i);
  227. }
  228. args[p++] = "-xmlConfigured";
  229. } else {
  230. args = (String[]) l.toArray(new String[l.size()]);
  231. }
  232. }
  233. BuildArgParser parser = new BuildArgParser(handler);
  234. AjBuildConfig config = new AjBuildConfig(parser);
  235. parser.populateBuildConfig(config, args, false, configFile);
  236. // Process the CLASSPATH
  237. String propcp = compilerConfig.getClasspath();
  238. if (propcp != null && propcp.length() != 0) {
  239. StringTokenizer st = new StringTokenizer(propcp, File.pathSeparator);
  240. List<String> configClasspath = config.getClasspath();
  241. ArrayList<String> toAdd = new ArrayList<String>();
  242. while (st.hasMoreTokens()) {
  243. String entry = st.nextToken();
  244. if (!configClasspath.contains(entry)) {
  245. toAdd.add(entry);
  246. }
  247. }
  248. if (0 < toAdd.size()) {
  249. ArrayList<String> both = new ArrayList<String>(configClasspath.size() + toAdd.size());
  250. both.addAll(configClasspath);
  251. both.addAll(toAdd);
  252. config.setClasspath(both);
  253. Classpath[] checkedClasspaths = config.getCheckedClasspaths();
  254. ArrayList<Classpath> cps = parser.handleClasspath(toAdd, compilerConfig.getProjectEncoding());
  255. Classpath[] newCheckedClasspaths = new Classpath[checkedClasspaths.length+cps.size()];
  256. System.arraycopy(checkedClasspaths, 0, newCheckedClasspaths, 0, checkedClasspaths.length);
  257. for (int i=0;i<cps.size();i++) {
  258. newCheckedClasspaths[checkedClasspaths.length+i] = cps.get(i);
  259. }
  260. config.setCheckedClasspaths(newCheckedClasspaths);
  261. }
  262. }
  263. // Process the OUTJAR
  264. if (config.getOutputJar() == null) {
  265. String outJar = compilerConfig.getOutJar();
  266. if (outJar != null && outJar.length() != 0) {
  267. config.setOutputJar(new File(outJar));
  268. }
  269. }
  270. // Process the OUTPUT LOCATION MANAGER
  271. IOutputLocationManager outputLocationManager = compilerConfig.getOutputLocationManager();
  272. if (config.getCompilationResultDestinationManager() == null && outputLocationManager != null) {
  273. config.setCompilationResultDestinationManager(new OutputLocationAdapter(outputLocationManager));
  274. }
  275. // Process the INPATH
  276. config.addToInpath(compilerConfig.getInpath());
  277. // bug 168840 - calling 'setInPath(..)' creates BinarySourceFiles which
  278. // are used to see if there have been changes in classes on the inpath
  279. if (config.getInpath() != null) {
  280. config.processInPath();
  281. }
  282. // Process the SOURCE PATH RESOURCES
  283. config.setSourcePathResources(compilerConfig.getSourcePathResources());
  284. // Process the ASPECTPATH
  285. config.addToAspectpath(compilerConfig.getAspectPath());
  286. // Process the JAVA OPTIONS MAP
  287. Map<String,String> jom = compilerConfig.getJavaOptionsMap();
  288. if (jom != null) {
  289. String version = (String) jom.get(CompilerOptions.OPTION_Compliance);
  290. if (version != null && !version.equals(CompilerOptions.VERSION_1_4)) {
  291. config.setBehaveInJava5Way(true);
  292. }
  293. config.getOptions().set(jom);
  294. }
  295. // Process the NON-STANDARD COMPILER OPTIONS
  296. configureNonStandardOptions(config);
  297. compilerConfig.configurationRead();
  298. ISourceLocation location = null;
  299. if (config.getConfigFile() != null) {
  300. location = new SourceLocation(config.getConfigFile(), 0);
  301. }
  302. String message = parser.getOtherMessages(true);
  303. if (null != message) {
  304. IMessage m = new Message(message, IMessage.ERROR, null, location);
  305. handler.handleMessage(m);
  306. }
  307. // always force model generation in AJDE
  308. config.setGenerateModelMode(true);
  309. // always be in incremental mode in AJDE
  310. config.setIncrementalMode(true);
  311. // always force proceedOnError in AJDE
  312. config.setProceedOnError(true);
  313. config.setProjectEncoding(compilerConfig.getProjectEncoding());
  314. config.setProcessor(compilerConfig.getProcessor());
  315. config.setProcessorPath(compilerConfig.getProcessorPath());
  316. return config;
  317. }
  318. /**
  319. * Helper method for configure build options. This reads all command-line options specified in the non-standard options text
  320. * entry and sets any corresponding unset values in config.
  321. */
  322. private void configureNonStandardOptions(AjBuildConfig config) {
  323. String nonStdOptions = compiler.getCompilerConfiguration().getNonStandardOptions();
  324. if (LangUtil.isEmpty(nonStdOptions)) {
  325. return;
  326. }
  327. // Break a string into a string array of non-standard options.
  328. // Allows for one option to include a ' '. i.e. assuming it has been quoted, it
  329. // won't accidentally get treated as a pair of options (can be needed for xlint props file option)
  330. List<String> tokens = new ArrayList<String>();
  331. int ind = nonStdOptions.indexOf('\"');
  332. int ind2 = nonStdOptions.indexOf('\"', ind + 1);
  333. if ((ind > -1) && (ind2 > -1)) { // dont tokenize within double quotes
  334. String pre = nonStdOptions.substring(0, ind);
  335. String quoted = nonStdOptions.substring(ind + 1, ind2);
  336. String post = nonStdOptions.substring(ind2 + 1, nonStdOptions.length());
  337. tokens.addAll(tokenizeString(pre));
  338. tokens.add(quoted);
  339. tokens.addAll(tokenizeString(post));
  340. } else {
  341. tokens.addAll(tokenizeString(nonStdOptions));
  342. }
  343. String[] args = (String[]) tokens.toArray(new String[] {});
  344. // set the non-standard options in an alternate build config
  345. // (we don't want to lose the settings we already have)
  346. CountingMessageHandler counter = CountingMessageHandler.makeCountingMessageHandler(msgHandlerAdapter);
  347. AjBuildConfig altConfig = AjdtCommand.genBuildConfig(args, counter);
  348. if (counter.hasErrors()) {
  349. return;
  350. }
  351. // copy globals where local is not set
  352. config.installGlobals(altConfig);
  353. }
  354. /** Local helper method for splitting option strings */
  355. private List<String> tokenizeString(String str) {
  356. List<String> tokens = new ArrayList<String>();
  357. StringTokenizer tok = new StringTokenizer(str);
  358. while (tok.hasMoreTokens()) {
  359. tokens.add(tok.nextToken());
  360. }
  361. return tokens;
  362. }
  363. /**
  364. * Helper method to ask the messagehandler to handle the given message
  365. */
  366. private void handleMessage(Message msg) {
  367. compiler.getMessageHandler().handleMessage(msg);
  368. }
  369. public void setCustomMungerFactory(Object o) {
  370. ajBuildManager.setCustomMungerFactory(o);
  371. }
  372. public Object getCustomMungerFactory() {
  373. return ajBuildManager.getCustomMungerFactory();
  374. }
  375. public void cleanupEnvironment() {
  376. ajBuildManager.cleanupEnvironment();
  377. }
  378. public AsmManager getStructureModel() {
  379. return ajBuildManager.getStructureModel();
  380. }
  381. }