Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

World.java 67KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012
  1. /* *******************************************************************
  2. * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
  3. * 2005 Contributors
  4. * All rights reserved.
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Public License v1.0
  7. * which accompanies this distribution and is available at
  8. * http://www.eclipse.org/legal/epl-v10.html
  9. *
  10. * Contributors:
  11. * PARC initial implementation
  12. * Adrian Colyer, Andy Clement, overhaul for generics, Abraham Nevado
  13. * ******************************************************************/
  14. package org.aspectj.weaver;
  15. import java.lang.ref.Reference;
  16. import java.lang.ref.ReferenceQueue;
  17. import java.lang.ref.SoftReference;
  18. import java.lang.ref.WeakReference;
  19. import java.util.ArrayList;
  20. import java.util.Collections;
  21. import java.util.HashMap;
  22. import java.util.HashSet;
  23. import java.util.Iterator;
  24. import java.util.List;
  25. import java.util.Map;
  26. import java.util.Properties;
  27. import java.util.Set;
  28. import java.util.WeakHashMap;
  29. import org.aspectj.bridge.IMessage;
  30. import org.aspectj.bridge.IMessage.Kind;
  31. import org.aspectj.bridge.IMessageHandler;
  32. import org.aspectj.bridge.ISourceLocation;
  33. import org.aspectj.bridge.Message;
  34. import org.aspectj.bridge.MessageUtil;
  35. import org.aspectj.bridge.context.PinpointingMessageHandler;
  36. import org.aspectj.util.IStructureModel;
  37. import org.aspectj.weaver.ResolvedType.Primitive;
  38. import org.aspectj.weaver.UnresolvedType.TypeKind;
  39. import org.aspectj.weaver.patterns.Declare;
  40. import org.aspectj.weaver.patterns.DeclareAnnotation;
  41. import org.aspectj.weaver.patterns.DeclareParents;
  42. import org.aspectj.weaver.patterns.DeclarePrecedence;
  43. import org.aspectj.weaver.patterns.DeclareSoft;
  44. import org.aspectj.weaver.patterns.DeclareTypeErrorOrWarning;
  45. import org.aspectj.weaver.patterns.Pointcut;
  46. import org.aspectj.weaver.patterns.TypePattern;
  47. import org.aspectj.weaver.tools.PointcutDesignatorHandler;
  48. import org.aspectj.weaver.tools.Trace;
  49. import org.aspectj.weaver.tools.TraceFactory;
  50. /**
  51. * A World is a collection of known types and crosscutting members.
  52. */
  53. public abstract class World implements Dump.INode {
  54. /** handler for any messages produced during resolution etc. */
  55. private IMessageHandler messageHandler = IMessageHandler.SYSTEM_ERR;
  56. /**
  57. * handler for cross-reference information produced during the weaving process
  58. */
  59. private ICrossReferenceHandler xrefHandler = null;
  60. /**
  61. * Currently 'active' scope in which to lookup (resolve) typevariable references
  62. */
  63. private TypeVariableDeclaringElement typeVariableLookupScope;
  64. /** The heart of the world, a map from type signatures to resolved types */
  65. protected TypeMap typeMap = new TypeMap(this); // Signature to ResolvedType
  66. /** New pointcut designators this world supports */
  67. private Set<PointcutDesignatorHandler> pointcutDesignators;
  68. // see pr145963
  69. /** Should we create the hierarchy for binary classes and aspects */
  70. public static boolean createInjarHierarchy = true;
  71. /** Calculator for working out aspect precedence */
  72. private final AspectPrecedenceCalculator precedenceCalculator;
  73. /** All of the type and shadow mungers known to us */
  74. private final CrosscuttingMembersSet crosscuttingMembersSet = new CrosscuttingMembersSet(this);
  75. /** The structure model for the compilation */
  76. private IStructureModel model = null;
  77. /** for processing Xlint messages */
  78. private Lint lint = new Lint(this);
  79. /** XnoInline option setting passed down to weaver */
  80. private boolean XnoInline;
  81. /** XlazyTjp option setting passed down to weaver */
  82. private boolean XlazyTjp;
  83. /** XhasMember option setting passed down to weaver */
  84. private boolean XhasMember = false;
  85. /**
  86. * Xpinpoint controls whether we put out developer info showing the source of messages
  87. */
  88. private boolean Xpinpoint = false;
  89. /** When behaving in a Java 5 way autoboxing is considered */
  90. private boolean behaveInJava5Way = false;
  91. /** Should timing information be reported (as info messages)? */
  92. private boolean timing = false;
  93. private boolean timingPeriodically = true;
  94. /** Determines if this world could be used for multiple compiles */
  95. private boolean incrementalCompileCouldFollow = false;
  96. /** The level of the aspectjrt.jar the code we generate needs to run on */
  97. private String targetAspectjRuntimeLevel = Constants.RUNTIME_LEVEL_DEFAULT;
  98. /** Flags for the new joinpoints that are 'optional' */
  99. private boolean optionalJoinpoint_ArrayConstruction = false; // Command line
  100. // flag:
  101. // "-Xjoinpoints:arrayconstruction"
  102. private boolean optionalJoinpoint_Synchronization = false; // Command line
  103. // flag:
  104. // "-Xjoinpoints:synchronization"
  105. private boolean addSerialVerUID = false;
  106. private Properties extraConfiguration = null;
  107. private boolean checkedAdvancedConfiguration = false;
  108. private boolean synchronizationPointcutsInUse = false;
  109. // Xset'table options
  110. private boolean runMinimalMemory = false;
  111. private boolean transientTjpFields = false;
  112. private boolean runMinimalMemorySet = false;
  113. private boolean shouldPipelineCompilation = true;
  114. private boolean shouldGenerateStackMaps = false;
  115. protected boolean bcelRepositoryCaching = xsetBCEL_REPOSITORY_CACHING_DEFAULT.equalsIgnoreCase("true");
  116. private boolean fastMethodPacking = false;
  117. private int itdVersion = 2; // defaults to 2nd generation itds
  118. // Minimal Model controls whether model entities that are not involved in relationships are deleted post-build
  119. private boolean minimalModel = true;
  120. private boolean useFinal = true;
  121. private boolean targettingRuntime1_6_10 = false;
  122. private boolean completeBinaryTypes = false;
  123. private boolean overWeaving = false;
  124. private static boolean systemPropertyOverWeaving = false;
  125. public boolean forDEBUG_structuralChangesCode = false;
  126. public boolean forDEBUG_bridgingCode = false;
  127. public boolean optimizedMatching = true;
  128. protected long timersPerJoinpoint = 25000;
  129. protected long timersPerType = 250;
  130. public int infoMessagesEnabled = 0; // 0=uninitialized, 1=no, 2=yes
  131. private static Trace trace = TraceFactory.getTraceFactory().getTrace(World.class);
  132. private boolean errorThreshold;
  133. private boolean warningThreshold;
  134. /**
  135. * A list of RuntimeExceptions containing full stack information for every type we couldn't find.
  136. */
  137. private List<RuntimeException> dumpState_cantFindTypeExceptions = null;
  138. static {
  139. try {
  140. String value = System.getProperty("aspectj.overweaving", "false");
  141. if (value.equalsIgnoreCase("true")) {
  142. System.out.println("ASPECTJ: aspectj.overweaving=true: overweaving switched ON");
  143. systemPropertyOverWeaving = true;
  144. }
  145. } catch (Throwable t) {
  146. System.err.println("ASPECTJ: Unable to read system properties");
  147. t.printStackTrace();
  148. }
  149. }
  150. public final Primitive BYTE = new Primitive("B", 1, 0);
  151. public final Primitive CHAR = new Primitive("C", 1, 1);
  152. public final Primitive DOUBLE = new Primitive("D", 2, 2);
  153. public final Primitive FLOAT = new Primitive("F", 1, 3);
  154. public final Primitive INT = new Primitive("I", 1, 4);
  155. public final Primitive LONG = new Primitive("J", 2, 5);
  156. public final Primitive SHORT = new Primitive("S", 1, 6);
  157. public final Primitive BOOLEAN = new Primitive("Z", 1, 7);
  158. public final Primitive VOID = new Primitive("V", 0, 8);
  159. /**
  160. * Insert the primitives
  161. */
  162. protected World() {
  163. super();
  164. // Dump.registerNode(this.getClass(), this);
  165. typeMap.put("B", BYTE);
  166. typeMap.put("S", SHORT);
  167. typeMap.put("I", INT);
  168. typeMap.put("J", LONG);
  169. typeMap.put("F", FLOAT);
  170. typeMap.put("D", DOUBLE);
  171. typeMap.put("C", CHAR);
  172. typeMap.put("Z", BOOLEAN);
  173. typeMap.put("V", VOID);
  174. precedenceCalculator = new AspectPrecedenceCalculator(this);
  175. }
  176. /**
  177. * Dump processing when a fatal error occurs
  178. */
  179. public void accept(Dump.IVisitor visitor) {
  180. // visitor.visitObject("Extra configuration:");
  181. // visitor.visitList(extraConfiguration.);
  182. visitor.visitObject("Shadow mungers:");
  183. visitor.visitList(crosscuttingMembersSet.getShadowMungers());
  184. visitor.visitObject("Type mungers:");
  185. visitor.visitList(crosscuttingMembersSet.getTypeMungers());
  186. visitor.visitObject("Late Type mungers:");
  187. visitor.visitList(crosscuttingMembersSet.getLateTypeMungers());
  188. if (dumpState_cantFindTypeExceptions != null) {
  189. visitor.visitObject("Cant find type problems:");
  190. visitor.visitList(dumpState_cantFindTypeExceptions);
  191. dumpState_cantFindTypeExceptions = null;
  192. }
  193. }
  194. // ==========================================================================
  195. // T Y P E R E S O L U T I O N
  196. // ==========================================================================
  197. /**
  198. * Resolve a type that we require to be present in the world
  199. */
  200. public ResolvedType resolve(UnresolvedType ty) {
  201. return resolve(ty, false);
  202. }
  203. /**
  204. * Attempt to resolve a type - the source location gives you some context in which resolution is taking place. In the case of an
  205. * error where we can't find the type - we can then at least report why (source location) we were trying to resolve it.
  206. */
  207. public ResolvedType resolve(UnresolvedType ty, ISourceLocation isl) {
  208. ResolvedType ret = resolve(ty, true);
  209. if (ResolvedType.isMissing(ty)) {
  210. // IMessage msg = null;
  211. getLint().cantFindType.signal(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE, ty.getName()), isl);
  212. // if (isl!=null) {
  213. // msg = MessageUtil.error(WeaverMessages.format(WeaverMessages.
  214. // CANT_FIND_TYPE,ty.getName()),isl);
  215. // } else {
  216. // msg = MessageUtil.error(WeaverMessages.format(WeaverMessages.
  217. // CANT_FIND_TYPE,ty.getName()));
  218. // }
  219. // messageHandler.handleMessage(msg);
  220. }
  221. return ret;
  222. }
  223. /**
  224. * Convenience method for resolving an array of unresolved types in one hit. Useful for e.g. resolving type parameters in
  225. * signatures.
  226. */
  227. public ResolvedType[] resolve(UnresolvedType[] types) {
  228. if (types == null) {
  229. return ResolvedType.NONE;
  230. }
  231. ResolvedType[] ret = new ResolvedType[types.length];
  232. for (int i = 0; i < types.length; i++) {
  233. ret[i] = resolve(types[i]);
  234. }
  235. return ret;
  236. }
  237. /**
  238. * Resolve a type. This the hub of type resolution. The resolved type is added to the type map by signature.
  239. */
  240. public ResolvedType resolve(UnresolvedType ty, boolean allowMissing) {
  241. // special resolution processing for already resolved types.
  242. if (ty instanceof ResolvedType) {
  243. ResolvedType rty = (ResolvedType) ty;
  244. rty = resolve(rty);
  245. // A TypeVariableReferenceType may look like it is resolved (it extends ResolvedType) but the internal
  246. // type variable may not yet have been resolved
  247. if (!rty.isTypeVariableReference() || ((TypeVariableReferenceType) rty).isTypeVariableResolved()) {
  248. return rty;
  249. }
  250. }
  251. // dispatch back to the type variable reference to resolve its
  252. // constituent parts don't do this for other unresolved types otherwise
  253. // you'll end up in a
  254. // loop
  255. if (ty.isTypeVariableReference()) {
  256. return ty.resolve(this);
  257. }
  258. // if we've already got a resolved type for the signature, just return
  259. // it
  260. // after updating the world
  261. String signature = ty.getSignature();
  262. ResolvedType ret = typeMap.get(signature);
  263. if (ret != null) {
  264. ret.world = this; // Set the world for the RTX
  265. return ret;
  266. } else if (signature.equals("?") || signature.equals("*")) {
  267. // might be a problem here, not sure '?' should make it to here as a
  268. // signature, the
  269. // proper signature for wildcard '?' is '*'
  270. // fault in generic wildcard, can't be done earlier because of init
  271. // issues
  272. // TODO ought to be shared single instance representing this
  273. ResolvedType something = getWildcard();
  274. typeMap.put("?", something);
  275. return something;
  276. }
  277. // no existing resolved type, create one
  278. synchronized (buildingTypeLock) {
  279. if (ty.isArray()) {
  280. ResolvedType componentType = resolve(ty.getComponentType(), allowMissing);
  281. ret = new ArrayReferenceType(signature, "[" + componentType.getErasureSignature(), this, componentType);
  282. } else {
  283. ret = resolveToReferenceType(ty, allowMissing);
  284. if (!allowMissing && ret.isMissing()) {
  285. ret = handleRequiredMissingTypeDuringResolution(ty);
  286. }
  287. if (completeBinaryTypes) {
  288. completeBinaryType(ret);
  289. }
  290. }
  291. }
  292. // Pulling in the type may have already put the right entry in the map
  293. ResolvedType result = typeMap.get(signature);
  294. if (result == null && !ret.isMissing()) {
  295. ret = ensureRawTypeIfNecessary(ret);
  296. typeMap.put(signature, ret);
  297. return ret;
  298. }
  299. if (result == null) {
  300. return ret;
  301. } else {
  302. return result;
  303. }
  304. }
  305. private Object buildingTypeLock = new Object();
  306. // Only need one representation of '?' in a world - can be shared
  307. private BoundedReferenceType wildcard;
  308. private BoundedReferenceType getWildcard() {
  309. if (wildcard == null) {
  310. wildcard = new BoundedReferenceType(this);
  311. }
  312. return wildcard;
  313. }
  314. /**
  315. * Called when a type is resolved - enables its type hierarchy to be finished off before we proceed
  316. */
  317. protected void completeBinaryType(ResolvedType ret) {
  318. }
  319. /**
  320. * Return true if the classloader relating to this world is definetly the one that will define the specified class. Return false
  321. * otherwise or we don't know for certain.
  322. */
  323. public boolean isLocallyDefined(String classname) {
  324. return false;
  325. }
  326. /**
  327. * We tried to resolve a type and couldn't find it...
  328. */
  329. private ResolvedType handleRequiredMissingTypeDuringResolution(UnresolvedType ty) {
  330. // defer the message until someone asks a question of the type that we
  331. // can't answer
  332. // just from the signature.
  333. // MessageUtil.error(messageHandler,
  334. // WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE,ty.getName()));
  335. if (dumpState_cantFindTypeExceptions == null) {
  336. dumpState_cantFindTypeExceptions = new ArrayList<RuntimeException>();
  337. }
  338. if (dumpState_cantFindTypeExceptions.size() < 100) { // limit growth
  339. dumpState_cantFindTypeExceptions.add(new RuntimeException("Can't find type " + ty.getName()));
  340. }
  341. return new MissingResolvedTypeWithKnownSignature(ty.getSignature(), this);
  342. }
  343. /**
  344. * Some TypeFactory operations create resolved types directly, but these won't be in the typeMap - this resolution process puts
  345. * them there. Resolved types are also told their world which is needed for the special autoboxing resolved types.
  346. */
  347. public ResolvedType resolve(ResolvedType ty) {
  348. if (ty.isTypeVariableReference()) {
  349. return ty; // until type variables have proper sigs...
  350. }
  351. ResolvedType resolved = typeMap.get(ty.getSignature());
  352. if (resolved == null) {
  353. resolved = ensureRawTypeIfNecessary(ty);
  354. typeMap.put(ty.getSignature(), resolved);
  355. resolved = ty;
  356. }
  357. resolved.world = this;
  358. return resolved;
  359. }
  360. /**
  361. * When the world is operating in 1.5 mode, the TypeMap should only contain RAW types and never directly generic types. The RAW
  362. * type will contain a reference to the generic type.
  363. *
  364. * @param type a possibly generic type for which the raw needs creating as it is not currently in the world
  365. * @return a type suitable for putting into the world
  366. */
  367. private ResolvedType ensureRawTypeIfNecessary(ResolvedType type) {
  368. if (!isInJava5Mode() || type.isRawType()) {
  369. return type;
  370. }
  371. // Key requirement here is if it is generic, create a RAW entry to be put in the map that points to it
  372. if (type instanceof ReferenceType && ((ReferenceType) type).getDelegate() != null && type.isGenericType()) {
  373. ReferenceType rawType = new ReferenceType(type.getSignature(), this);
  374. rawType.typeKind = UnresolvedType.TypeKind.RAW;
  375. ReferenceTypeDelegate delegate = ((ReferenceType) type).getDelegate();
  376. rawType.setDelegate(delegate);
  377. rawType.setGenericType((ReferenceType) type);
  378. return rawType;
  379. }
  380. // probably parameterized...
  381. return type;
  382. }
  383. /**
  384. * Convenience method for finding a type by name and resolving it in one step.
  385. */
  386. public ResolvedType resolve(String name) {
  387. // trace.enter("resolve", this, new Object[] {name});
  388. ResolvedType ret = resolve(UnresolvedType.forName(name));
  389. // trace.exit("resolve", ret);
  390. return ret;
  391. }
  392. public ReferenceType resolveToReferenceType(String name) {
  393. return (ReferenceType) resolve(name);
  394. }
  395. public ResolvedType resolve(String name, boolean allowMissing) {
  396. return resolve(UnresolvedType.forName(name), allowMissing);
  397. }
  398. /**
  399. * Resolve to a ReferenceType - simple, raw, parameterized, or generic. Raw, parameterized, and generic versions of a type share
  400. * a delegate.
  401. */
  402. private final ResolvedType resolveToReferenceType(UnresolvedType ty, boolean allowMissing) {
  403. if (ty.isParameterizedType()) {
  404. // ======= parameterized types ================
  405. ResolvedType rt = resolveGenericTypeFor(ty, allowMissing);
  406. if (rt.isMissing()) {
  407. return rt;
  408. }
  409. ReferenceType genericType = (ReferenceType) rt;
  410. ReferenceType parameterizedType = TypeFactory.createParameterizedType(genericType, ty.typeParameters, this);
  411. return parameterizedType;
  412. } else if (ty.isGenericType()) {
  413. // ======= generic types ======================
  414. ResolvedType rt = resolveGenericTypeFor(ty, false);
  415. ReferenceType genericType = (ReferenceType) rt;
  416. return genericType;
  417. } else if (ty.isGenericWildcard()) {
  418. // ======= generic wildcard types =============
  419. return resolveGenericWildcardFor((WildcardedUnresolvedType) ty);
  420. } else {
  421. // ======= simple and raw types ===============
  422. String erasedSignature = ty.getErasureSignature();
  423. ReferenceType simpleOrRawType = new ReferenceType(erasedSignature, this);
  424. if (ty.needsModifiableDelegate()) {
  425. simpleOrRawType.setNeedsModifiableDelegate(true);
  426. }
  427. ReferenceTypeDelegate delegate = resolveDelegate(simpleOrRawType);
  428. // 117854
  429. // if (delegate == null) return ResolvedType.MISSING;
  430. if (delegate == null) {
  431. return new MissingResolvedTypeWithKnownSignature(ty.getSignature(), erasedSignature, this);// ResolvedType
  432. // .
  433. // MISSING
  434. // ;
  435. }
  436. if (delegate.isGeneric() && behaveInJava5Way) {
  437. // ======== raw type ===========
  438. simpleOrRawType.typeKind = TypeKind.RAW;
  439. ReferenceType genericType = makeGenericTypeFrom(delegate, simpleOrRawType);
  440. // name =
  441. // ReferenceType.fromTypeX(UnresolvedType.forRawTypeNames(
  442. // ty.getName()),this);
  443. simpleOrRawType.setDelegate(delegate);
  444. genericType.setDelegate(delegate);
  445. simpleOrRawType.setGenericType(genericType);
  446. return simpleOrRawType;
  447. } else {
  448. // ======== simple type =========
  449. simpleOrRawType.setDelegate(delegate);
  450. return simpleOrRawType;
  451. }
  452. }
  453. }
  454. /**
  455. * Attempt to resolve a type that should be a generic type.
  456. */
  457. public ResolvedType resolveGenericTypeFor(UnresolvedType anUnresolvedType, boolean allowMissing) {
  458. // Look up the raw type by signature
  459. String rawSignature = anUnresolvedType.getRawType().getSignature();
  460. ResolvedType rawType = typeMap.get(rawSignature);
  461. if (rawType == null) {
  462. rawType = resolve(UnresolvedType.forSignature(rawSignature), allowMissing);
  463. typeMap.put(rawSignature, rawType);
  464. }
  465. if (rawType.isMissing()) {
  466. return rawType;
  467. }
  468. // Does the raw type know its generic form? (It will if we created the
  469. // raw type from a source type, it won't if its been created just
  470. // through
  471. // being referenced, e.g. java.util.List
  472. ResolvedType genericType = rawType.getGenericType();
  473. // There is a special case to consider here (testGenericsBang_pr95993
  474. // highlights it)
  475. // You may have an unresolvedType for a parameterized type but it
  476. // is backed by a simple type rather than a generic type. This occurs
  477. // for
  478. // inner types of generic types that inherit their enclosing types
  479. // type variables.
  480. if (rawType.isSimpleType() && (anUnresolvedType.typeParameters == null || anUnresolvedType.typeParameters.length == 0)) {
  481. rawType.world = this;
  482. return rawType;
  483. }
  484. if (genericType != null) {
  485. genericType.world = this;
  486. ((ReferenceType) genericType).addDependentType((ReferenceType) rawType);
  487. return genericType;
  488. } else {
  489. // Fault in the generic that underpins the raw type ;)
  490. ReferenceTypeDelegate delegate = resolveDelegate((ReferenceType) rawType);
  491. ReferenceType genericRefType = makeGenericTypeFrom(delegate, ((ReferenceType) rawType));
  492. ((ReferenceType) rawType).setGenericType(genericRefType);
  493. genericRefType.setDelegate(delegate);
  494. ((ReferenceType) rawType).setDelegate(delegate);
  495. return genericRefType;
  496. }
  497. }
  498. private ReferenceType makeGenericTypeFrom(ReferenceTypeDelegate delegate, ReferenceType rawType) {
  499. String genericSig = delegate.getDeclaredGenericSignature();
  500. if (genericSig != null) {
  501. return new ReferenceType(UnresolvedType.forGenericTypeSignature(rawType.getSignature(),
  502. delegate.getDeclaredGenericSignature()), this);
  503. } else {
  504. return new ReferenceType(UnresolvedType.forGenericTypeVariables(rawType.getSignature(), delegate.getTypeVariables()),
  505. this);
  506. }
  507. }
  508. /**
  509. * Go from an unresolved generic wildcard (represented by UnresolvedType) to a resolved version (BoundedReferenceType).
  510. */
  511. private ReferenceType resolveGenericWildcardFor(WildcardedUnresolvedType aType) {
  512. BoundedReferenceType ret = null;
  513. // FIXME asc doesnt take account of additional interface bounds (e.g. ?
  514. // super R & Serializable - can you do that?)
  515. if (aType.isExtends()) {
  516. ReferenceType upperBound = (ReferenceType) resolve(aType.getUpperBound());
  517. ret = new BoundedReferenceType(upperBound, true, this);
  518. } else if (aType.isSuper()) {
  519. ReferenceType lowerBound = (ReferenceType) resolve(aType.getLowerBound());
  520. ret = new BoundedReferenceType(lowerBound, false, this);
  521. } else {
  522. // must be ? on its own!
  523. ret = getWildcard();
  524. }
  525. return ret;
  526. }
  527. /**
  528. * Find the ReferenceTypeDelegate behind this reference type so that it can fulfill its contract.
  529. */
  530. protected abstract ReferenceTypeDelegate resolveDelegate(ReferenceType ty);
  531. /**
  532. * Special resolution for "core" types like OBJECT. These are resolved just like any other type, but if they are not found it is
  533. * more serious and we issue an error message immediately.
  534. */
  535. // OPTIMIZE streamline path for core types? They are just simple types,
  536. // could look straight in the typemap?
  537. public ResolvedType getCoreType(UnresolvedType tx) {
  538. ResolvedType coreTy = resolve(tx, true);
  539. if (coreTy.isMissing()) {
  540. MessageUtil.error(messageHandler, WeaverMessages.format(WeaverMessages.CANT_FIND_CORE_TYPE, tx.getName()));
  541. }
  542. return coreTy;
  543. }
  544. /**
  545. * Lookup a type by signature, if not found then build one and put it in the map.
  546. */
  547. public ReferenceType lookupOrCreateName(UnresolvedType ty) {
  548. String signature = ty.getSignature();
  549. ReferenceType ret = lookupBySignature(signature);
  550. if (ret == null) {
  551. ret = ReferenceType.fromTypeX(ty, this);
  552. typeMap.put(signature, ret);
  553. }
  554. return ret;
  555. }
  556. /**
  557. * Lookup a reference type in the world by its signature. Returns null if not found.
  558. */
  559. public ReferenceType lookupBySignature(String signature) {
  560. return (ReferenceType) typeMap.get(signature);
  561. }
  562. // ==========================================================================
  563. // ===
  564. // T Y P E R E S O L U T I O N -- E N D
  565. // ==========================================================================
  566. // ===
  567. /**
  568. * Member resolution is achieved by resolving the declaring type and then looking up the member in the resolved declaring type.
  569. */
  570. public ResolvedMember resolve(Member member) {
  571. ResolvedType declaring = member.getDeclaringType().resolve(this);
  572. if (declaring.isRawType()) {
  573. declaring = declaring.getGenericType();
  574. }
  575. ResolvedMember ret;
  576. if (member.getKind() == Member.FIELD) {
  577. ret = declaring.lookupField(member);
  578. } else {
  579. ret = declaring.lookupMethod(member);
  580. }
  581. if (ret != null) {
  582. return ret;
  583. }
  584. return declaring.lookupSyntheticMember(member);
  585. }
  586. private boolean allLintIgnored = false;
  587. public void setAllLintIgnored() {
  588. allLintIgnored = true;
  589. }
  590. public boolean areAllLintIgnored() {
  591. return allLintIgnored;
  592. }
  593. public abstract IWeavingSupport getWeavingSupport();
  594. /**
  595. * Create an advice shadow munger from the given advice attribute
  596. */
  597. // public abstract Advice createAdviceMunger(AjAttribute.AdviceAttribute
  598. // attribute, Pointcut pointcut, Member signature);
  599. /**
  600. * Create an advice shadow munger for the given advice kind
  601. */
  602. public final Advice createAdviceMunger(AdviceKind kind, Pointcut p, Member signature, int extraParameterFlags,
  603. IHasSourceLocation loc, ResolvedType declaringAspect) {
  604. AjAttribute.AdviceAttribute attribute = new AjAttribute.AdviceAttribute(kind, p, extraParameterFlags, loc.getStart(),
  605. loc.getEnd(), loc.getSourceContext());
  606. return getWeavingSupport().createAdviceMunger(attribute, p, signature, declaringAspect);
  607. }
  608. /**
  609. * Same signature as org.aspectj.util.PartialOrder.PartialComparable.compareTo
  610. */
  611. public int compareByPrecedence(ResolvedType aspect1, ResolvedType aspect2) {
  612. return precedenceCalculator.compareByPrecedence(aspect1, aspect2);
  613. }
  614. public Integer getPrecedenceIfAny(ResolvedType aspect1, ResolvedType aspect2) {
  615. return precedenceCalculator.getPrecedenceIfAny(aspect1, aspect2);
  616. }
  617. /**
  618. * compares by precedence with the additional rule that a super-aspect is sorted before its sub-aspects
  619. */
  620. public int compareByPrecedenceAndHierarchy(ResolvedType aspect1, ResolvedType aspect2) {
  621. return precedenceCalculator.compareByPrecedenceAndHierarchy(aspect1, aspect2);
  622. }
  623. // simple property getter and setters
  624. // ===========================================================
  625. /**
  626. * Nobody should hold onto a copy of this message handler, or setMessageHandler won't work right.
  627. */
  628. public IMessageHandler getMessageHandler() {
  629. return messageHandler;
  630. }
  631. public void setMessageHandler(IMessageHandler messageHandler) {
  632. if (this.isInPinpointMode()) {
  633. this.messageHandler = new PinpointingMessageHandler(messageHandler);
  634. } else {
  635. this.messageHandler = messageHandler;
  636. }
  637. }
  638. /**
  639. * convenenience method for creating and issuing messages via the message handler - if you supply two locations you will get two
  640. * messages.
  641. */
  642. public void showMessage(Kind kind, String message, ISourceLocation loc1, ISourceLocation loc2) {
  643. if (loc1 != null) {
  644. messageHandler.handleMessage(new Message(message, kind, null, loc1));
  645. if (loc2 != null) {
  646. messageHandler.handleMessage(new Message(message, kind, null, loc2));
  647. }
  648. } else {
  649. messageHandler.handleMessage(new Message(message, kind, null, loc2));
  650. }
  651. }
  652. public void setCrossReferenceHandler(ICrossReferenceHandler xrefHandler) {
  653. this.xrefHandler = xrefHandler;
  654. }
  655. /**
  656. * Get the cross-reference handler for the world, may be null.
  657. */
  658. public ICrossReferenceHandler getCrossReferenceHandler() {
  659. return xrefHandler;
  660. }
  661. public void setTypeVariableLookupScope(TypeVariableDeclaringElement scope) {
  662. typeVariableLookupScope = scope;
  663. }
  664. public TypeVariableDeclaringElement getTypeVariableLookupScope() {
  665. return typeVariableLookupScope;
  666. }
  667. public List<DeclareParents> getDeclareParents() {
  668. return crosscuttingMembersSet.getDeclareParents();
  669. }
  670. public List<DeclareAnnotation> getDeclareAnnotationOnTypes() {
  671. return crosscuttingMembersSet.getDeclareAnnotationOnTypes();
  672. }
  673. public List<DeclareAnnotation> getDeclareAnnotationOnFields() {
  674. return crosscuttingMembersSet.getDeclareAnnotationOnFields();
  675. }
  676. public List<DeclareAnnotation> getDeclareAnnotationOnMethods() {
  677. return crosscuttingMembersSet.getDeclareAnnotationOnMethods();
  678. }
  679. public List<DeclareTypeErrorOrWarning> getDeclareTypeEows() {
  680. return crosscuttingMembersSet.getDeclareTypeEows();
  681. }
  682. public List<DeclareSoft> getDeclareSoft() {
  683. return crosscuttingMembersSet.getDeclareSofts();
  684. }
  685. public CrosscuttingMembersSet getCrosscuttingMembersSet() {
  686. return crosscuttingMembersSet;
  687. }
  688. public IStructureModel getModel() {
  689. return model;
  690. }
  691. public void setModel(IStructureModel model) {
  692. this.model = model;
  693. }
  694. public Lint getLint() {
  695. return lint;
  696. }
  697. public void setLint(Lint lint) {
  698. this.lint = lint;
  699. }
  700. public boolean isXnoInline() {
  701. return XnoInline;
  702. }
  703. public void setXnoInline(boolean xnoInline) {
  704. XnoInline = xnoInline;
  705. }
  706. public boolean isXlazyTjp() {
  707. return XlazyTjp;
  708. }
  709. public void setXlazyTjp(boolean b) {
  710. XlazyTjp = b;
  711. }
  712. public boolean isHasMemberSupportEnabled() {
  713. return XhasMember;
  714. }
  715. public void setXHasMemberSupportEnabled(boolean b) {
  716. XhasMember = b;
  717. }
  718. public boolean isInPinpointMode() {
  719. return Xpinpoint;
  720. }
  721. public void setPinpointMode(boolean b) {
  722. Xpinpoint = b;
  723. }
  724. public boolean useFinal() {
  725. return useFinal;
  726. }
  727. public boolean isMinimalModel() {
  728. ensureAdvancedConfigurationProcessed();
  729. return minimalModel;
  730. }
  731. public boolean isTargettingRuntime1_6_10() {
  732. ensureAdvancedConfigurationProcessed();
  733. return targettingRuntime1_6_10;
  734. }
  735. public void setBehaveInJava5Way(boolean b) {
  736. behaveInJava5Way = b;
  737. }
  738. /**
  739. * Set the timing option (whether to collect timing info), this will also need INFO messages turned on for the message handler
  740. * being used. The reportPeriodically flag should be set to false under AJDT so numbers just come out at the end.
  741. */
  742. public void setTiming(boolean timersOn, boolean reportPeriodically) {
  743. timing = timersOn;
  744. timingPeriodically = reportPeriodically;
  745. }
  746. /**
  747. * Set the error and warning threashold which can be taken from CompilerOptions (see bug 129282)
  748. *
  749. * @param errorThreshold
  750. * @param warningThreshold
  751. */
  752. public void setErrorAndWarningThreshold(boolean errorThreshold, boolean warningThreshold) {
  753. this.errorThreshold = errorThreshold;
  754. this.warningThreshold = warningThreshold;
  755. }
  756. /**
  757. * @return true if ignoring the UnusedDeclaredThrownException and false if this compiler option is set to error or warning
  758. */
  759. public boolean isIgnoringUnusedDeclaredThrownException() {
  760. // the 0x800000 is CompilerOptions.UnusedDeclaredThrownException
  761. // which is ASTNode.bit24
  762. return errorThreshold||warningThreshold;
  763. // if ((errorThreshold & 0x800000) != 0 || (warningThreshold & 0x800000) != 0) {
  764. // return false;
  765. // }
  766. // return true;
  767. }
  768. public void performExtraConfiguration(String config) {
  769. if (config == null) {
  770. return;
  771. }
  772. // Bunch of name value pairs to split
  773. extraConfiguration = new Properties();
  774. int pos = -1;
  775. while ((pos = config.indexOf(",")) != -1) {
  776. String nvpair = config.substring(0, pos);
  777. int pos2 = nvpair.indexOf("=");
  778. if (pos2 != -1) {
  779. String n = nvpair.substring(0, pos2);
  780. String v = nvpair.substring(pos2 + 1);
  781. extraConfiguration.setProperty(n, v);
  782. }
  783. config = config.substring(pos + 1);
  784. }
  785. if (config.length() > 0) {
  786. int pos2 = config.indexOf("=");
  787. if (pos2 != -1) {
  788. String n = config.substring(0, pos2);
  789. String v = config.substring(pos2 + 1);
  790. extraConfiguration.setProperty(n, v);
  791. }
  792. }
  793. ensureAdvancedConfigurationProcessed();
  794. }
  795. public boolean areInfoMessagesEnabled() {
  796. if (infoMessagesEnabled == 0) {
  797. infoMessagesEnabled = (messageHandler.isIgnoring(IMessage.INFO) ? 1 : 2);
  798. }
  799. return infoMessagesEnabled == 2;
  800. }
  801. /**
  802. * may return null
  803. */
  804. public Properties getExtraConfiguration() {
  805. return extraConfiguration;
  806. }
  807. public final static String xsetAVOID_FINAL = "avoidFinal"; // default true
  808. public final static String xsetWEAVE_JAVA_PACKAGES = "weaveJavaPackages"; // default
  809. // false
  810. // -
  811. // controls
  812. // LTW
  813. public final static String xsetWEAVE_JAVAX_PACKAGES = "weaveJavaxPackages"; // default
  814. // false
  815. // -
  816. // controls
  817. // LTW
  818. public final static String xsetCAPTURE_ALL_CONTEXT = "captureAllContext"; // default
  819. // false
  820. public final static String xsetRUN_MINIMAL_MEMORY = "runMinimalMemory"; // default
  821. // true
  822. public final static String xsetDEBUG_STRUCTURAL_CHANGES_CODE = "debugStructuralChangesCode"; // default
  823. // false
  824. public final static String xsetDEBUG_BRIDGING = "debugBridging"; // default
  825. // false
  826. public final static String xsetTRANSIENT_TJP_FIELDS = "makeTjpFieldsTransient"; // default false
  827. public final static String xsetBCEL_REPOSITORY_CACHING = "bcelRepositoryCaching";
  828. public final static String xsetPIPELINE_COMPILATION = "pipelineCompilation";
  829. public final static String xsetGENERATE_STACKMAPS = "generateStackMaps";
  830. public final static String xsetPIPELINE_COMPILATION_DEFAULT = "true";
  831. public final static String xsetCOMPLETE_BINARY_TYPES = "completeBinaryTypes";
  832. public final static String xsetCOMPLETE_BINARY_TYPES_DEFAULT = "false";
  833. public final static String xsetTYPE_DEMOTION = "typeDemotion";
  834. public final static String xsetTYPE_DEMOTION_DEBUG = "typeDemotionDebug";
  835. public final static String xsetTYPE_REFS = "useWeakTypeRefs";
  836. public final static String xsetBCEL_REPOSITORY_CACHING_DEFAULT = "true";
  837. public final static String xsetFAST_PACK_METHODS = "fastPackMethods"; // default true
  838. public final static String xsetOVERWEAVING = "overWeaving";
  839. public final static String xsetOPTIMIZED_MATCHING = "optimizedMatching";
  840. public final static String xsetTIMERS_PER_JOINPOINT = "timersPerJoinpoint";
  841. public final static String xsetTIMERS_PER_FASTMATCH_CALL = "timersPerFastMatchCall";
  842. public final static String xsetITD_VERSION = "itdVersion";
  843. public final static String xsetITD_VERSION_ORIGINAL = "1";
  844. public final static String xsetITD_VERSION_2NDGEN = "2";
  845. public final static String xsetITD_VERSION_DEFAULT = xsetITD_VERSION_2NDGEN;
  846. public final static String xsetMINIMAL_MODEL = "minimalModel";
  847. public final static String xsetTARGETING_RUNTIME_1610 = "targetRuntime1_6_10";
  848. public boolean isInJava5Mode() {
  849. return behaveInJava5Way;
  850. }
  851. public boolean isTimingEnabled() {
  852. return timing;
  853. }
  854. public void setTargetAspectjRuntimeLevel(String s) {
  855. targetAspectjRuntimeLevel = s;
  856. }
  857. public void setOptionalJoinpoints(String jps) {
  858. if (jps == null) {
  859. return;
  860. }
  861. if (jps.indexOf("arrayconstruction") != -1) {
  862. optionalJoinpoint_ArrayConstruction = true;
  863. }
  864. if (jps.indexOf("synchronization") != -1) {
  865. optionalJoinpoint_Synchronization = true;
  866. }
  867. }
  868. public boolean isJoinpointArrayConstructionEnabled() {
  869. return optionalJoinpoint_ArrayConstruction;
  870. }
  871. public boolean isJoinpointSynchronizationEnabled() {
  872. return optionalJoinpoint_Synchronization;
  873. }
  874. public String getTargetAspectjRuntimeLevel() {
  875. return targetAspectjRuntimeLevel;
  876. }
  877. // OPTIMIZE are users falling foul of not supplying -1.5 and so targetting
  878. // the old runtime?
  879. public boolean isTargettingAspectJRuntime12() {
  880. boolean b = false; // pr116679
  881. if (!isInJava5Mode()) {
  882. b = true;
  883. } else {
  884. b = getTargetAspectjRuntimeLevel().equals(org.aspectj.weaver.Constants.RUNTIME_LEVEL_12);
  885. }
  886. // System.err.println("Asked if targetting runtime 1.2 , returning: "+b);
  887. return b;
  888. }
  889. /*
  890. * Map of types in the world, can have 'references' to expendable ones which can be garbage collected to recover memory. An
  891. * expendable type is a reference type that is not exposed to the weaver (ie just pulled in for type resolution purposes).
  892. */
  893. public static class TypeMap {
  894. // Strategy for entries in the expendable map
  895. public final static int DONT_USE_REFS = 0; // Hang around forever
  896. public final static int USE_WEAK_REFS = 1; // Collected asap
  897. public final static int USE_SOFT_REFS = 2; // Collected when short on memory
  898. public List<String> addedSinceLastDemote;
  899. public List<String> writtenClasses;
  900. private static boolean debug = false;
  901. public static boolean useExpendableMap = true; // configurable for reliable testing
  902. private boolean demotionSystemActive;
  903. private boolean debugDemotion = false;
  904. public int policy = USE_WEAK_REFS;
  905. // Map of types that never get thrown away
  906. final Map<String, ResolvedType> tMap = new HashMap<String, ResolvedType>();
  907. // Map of types that may be ejected from the cache if we need space
  908. final Map<String, Reference<ResolvedType>> expendableMap = Collections
  909. .synchronizedMap(new WeakHashMap<String, Reference<ResolvedType>>());
  910. private final World w;
  911. // profiling tools...
  912. private boolean memoryProfiling = false;
  913. private int maxExpendableMapSize = -1;
  914. private int collectedTypes = 0;
  915. private final ReferenceQueue<ResolvedType> rq = new ReferenceQueue<ResolvedType>();
  916. // private static Trace trace = TraceFactory.getTraceFactory().getTrace(World.TypeMap.class);
  917. TypeMap(World w) {
  918. // Demotion activated when switched on and loadtime weaving or in AJDT
  919. demotionSystemActive = w.isDemotionActive() && (w.isLoadtimeWeaving() || w.couldIncrementalCompileFollow());
  920. addedSinceLastDemote = new ArrayList<String>();
  921. writtenClasses = new ArrayList<String>();
  922. this.w = w;
  923. memoryProfiling = false;// !w.getMessageHandler().isIgnoring(Message.
  924. // INFO);
  925. }
  926. // For testing
  927. public Map<String, Reference<ResolvedType>> getExpendableMap() {
  928. return expendableMap;
  929. }
  930. // For testing
  931. public Map<String, ResolvedType> getMainMap() {
  932. return tMap;
  933. }
  934. public int demote() {
  935. return demote(false);
  936. }
  937. /**
  938. * Go through any types added during the previous file weave. If any are suitable for demotion, then put them in the
  939. * expendable map where GC can claim them at some point later. Demotion means: the type is not an aspect, the type is not
  940. * java.lang.Object, the type is not primitive and the type is not affected by type mungers in any way. Further refinements
  941. * of these conditions may allow for more demotions.
  942. *
  943. * @return number of types demoted
  944. */
  945. public int demote(boolean atEndOfCompile) {
  946. if (!demotionSystemActive) {
  947. return 0;
  948. }
  949. if (debugDemotion) {
  950. System.out.println("Demotion running " + addedSinceLastDemote);
  951. }
  952. boolean isLtw = w.isLoadtimeWeaving();
  953. int demotionCounter = 0;
  954. if (isLtw) {
  955. // Loadtime weaving demotion strategy
  956. for (String key : addedSinceLastDemote) {
  957. ResolvedType type = tMap.get(key);
  958. if (type != null && !type.isAspect() && !type.equals(UnresolvedType.OBJECT) && !type.isPrimitiveType()) {
  959. List<ConcreteTypeMunger> typeMungers = type.getInterTypeMungers();
  960. if (typeMungers == null || typeMungers.size() == 0) {
  961. tMap.remove(key);
  962. insertInExpendableMap(key, type);
  963. demotionCounter++;
  964. }
  965. }
  966. }
  967. addedSinceLastDemote.clear();
  968. } else {
  969. // Compile time demotion strategy
  970. List<String> forRemoval = new ArrayList<String>();
  971. for (String key : addedSinceLastDemote) {
  972. ResolvedType type = tMap.get(key);
  973. if (type == null) {
  974. // TODO not 100% sure why it is not there, where did it go?
  975. forRemoval.add(key);
  976. continue;
  977. }
  978. if (!writtenClasses.contains(type.getName())) { // COSTLY
  979. continue;
  980. }
  981. if (type != null && !type.isAspect() && !type.equals(UnresolvedType.OBJECT) && !type.isPrimitiveType()) {
  982. List<ConcreteTypeMunger> typeMungers = type.getInterTypeMungers();
  983. if (typeMungers == null || typeMungers.size() == 0) {
  984. /*
  985. * if (type.isNested()) { try { ReferenceType rt = (ReferenceType) w.resolve(type.getOutermostType());
  986. * if (!rt.isMissing()) { ReferenceTypeDelegate delegate = ((ReferenceType) type).getDelegate(); boolean
  987. * isWeavable = delegate == null ? false : delegate.isExposedToWeaver(); boolean hasBeenWoven = delegate
  988. * == null ? false : delegate.hasBeenWoven(); if (isWeavable && !hasBeenWoven) { // skip demotion of
  989. * this inner type for now continue; } } } catch (ClassCastException cce) { cce.printStackTrace();
  990. * System.out.println("outer of " + key + " is not a reftype? " + type.getOutermostType()); // throw new
  991. * IllegalStateException(cce); } }
  992. */
  993. ReferenceTypeDelegate delegate = ((ReferenceType) type).getDelegate();
  994. boolean isWeavable = delegate == null ? false : delegate.isExposedToWeaver();
  995. boolean hasBeenWoven = delegate == null ? false : delegate.hasBeenWoven();
  996. if (!isWeavable || hasBeenWoven) {
  997. if (debugDemotion) {
  998. System.out.println("Demoting " + key);
  999. }
  1000. forRemoval.add(key);
  1001. tMap.remove(key);
  1002. insertInExpendableMap(key, type);
  1003. demotionCounter++;
  1004. }
  1005. } else {
  1006. // no need to try this again, it will never be demoted
  1007. writtenClasses.remove(type.getName());
  1008. forRemoval.add(key);
  1009. }
  1010. } else {
  1011. writtenClasses.remove(type.getName());
  1012. // no need to try this again, it will never be demoted
  1013. forRemoval.add(key);
  1014. }
  1015. }
  1016. addedSinceLastDemote.removeAll(forRemoval);
  1017. }
  1018. if (debugDemotion) {
  1019. System.out.println("Demoted " + demotionCounter + " types. Types remaining in fixed set #" + tMap.keySet().size()
  1020. + ". addedSinceLastDemote size is " + addedSinceLastDemote.size());
  1021. System.out.println("writtenClasses.size() = " + writtenClasses.size() + ": " + writtenClasses);
  1022. }
  1023. if (atEndOfCompile) {
  1024. if (debugDemotion) {
  1025. System.out.println("Clearing writtenClasses");
  1026. }
  1027. writtenClasses.clear();
  1028. }
  1029. return demotionCounter;
  1030. }
  1031. private void insertInExpendableMap(String key, ResolvedType type) {
  1032. if (useExpendableMap) {
  1033. if (!expendableMap.containsKey(key)) {
  1034. if (policy == USE_SOFT_REFS) {
  1035. expendableMap.put(key, new SoftReference<ResolvedType>(type));
  1036. } else {
  1037. expendableMap.put(key, new WeakReference<ResolvedType>(type));
  1038. }
  1039. }
  1040. }
  1041. }
  1042. /**
  1043. * Add a new type into the map, the key is the type signature. Some types do *not* go in the map, these are ones involving
  1044. * *member* type variables. The reason is that when all you have is the signature which gives you a type variable name, you
  1045. * cannot guarantee you are using the type variable in the same way as someone previously working with a similarly named
  1046. * type variable. So, these do not go into the map: - TypeVariableReferenceType. - ParameterizedType where a member type
  1047. * variable is involved. - BoundedReferenceType when one of the bounds is a type variable.
  1048. *
  1049. * definition: "member type variables" - a tvar declared on a generic method/ctor as opposed to those you see declared on a
  1050. * generic type.
  1051. */
  1052. public ResolvedType put(String key, ResolvedType type) {
  1053. if (!type.isCacheable()) {
  1054. return type;
  1055. }
  1056. if (type.isParameterizedType() && type.isParameterizedWithTypeVariable()) {
  1057. if (debug) {
  1058. System.err
  1059. .println("Not putting a parameterized type that utilises member declared type variables into the typemap: key="
  1060. + key + " type=" + type);
  1061. }
  1062. return type;
  1063. }
  1064. if (type.isTypeVariableReference()) {
  1065. if (debug) {
  1066. System.err.println("Not putting a type variable reference type into the typemap: key=" + key + " type=" + type);
  1067. }
  1068. return type;
  1069. }
  1070. // this test should be improved - only avoid putting them in if one
  1071. // of the
  1072. // bounds is a member type variable
  1073. if (type instanceof BoundedReferenceType) {
  1074. if (debug) {
  1075. System.err.println("Not putting a bounded reference type into the typemap: key=" + key + " type=" + type);
  1076. }
  1077. return type;
  1078. }
  1079. if (type instanceof MissingResolvedTypeWithKnownSignature) {
  1080. if (debug) {
  1081. System.err.println("Not putting a missing type into the typemap: key=" + key + " type=" + type);
  1082. }
  1083. return type;
  1084. }
  1085. if ((type instanceof ReferenceType) && (((ReferenceType) type).getDelegate() == null) && w.isExpendable(type)) {
  1086. if (debug) {
  1087. System.err.println("Not putting expendable ref type with null delegate into typemap: key=" + key + " type="
  1088. + type);
  1089. }
  1090. return type;
  1091. }
  1092. // TODO should this be in as a permanent assertion?
  1093. /*
  1094. * if ((type instanceof ReferenceType) && type.getWorld().isInJava5Mode() && (((ReferenceType) type).getDelegate() !=
  1095. * null) && type.isGenericType()) { throw new BCException("Attempt to add generic type to typemap " + type.toString() +
  1096. * " (should be raw)"); }
  1097. */
  1098. if (w.isExpendable(type)) {
  1099. if (useExpendableMap) {
  1100. // Dont use reference queue for tracking if not profiling...
  1101. if (policy == USE_WEAK_REFS) {
  1102. if (memoryProfiling) {
  1103. expendableMap.put(key, new WeakReference<ResolvedType>(type, rq));
  1104. } else {
  1105. expendableMap.put(key, new WeakReference<ResolvedType>(type));
  1106. }
  1107. } else if (policy == USE_SOFT_REFS) {
  1108. if (memoryProfiling) {
  1109. expendableMap.put(key, new SoftReference<ResolvedType>(type, rq));
  1110. } else {
  1111. expendableMap.put(key, new SoftReference<ResolvedType>(type));
  1112. }
  1113. // } else {
  1114. // expendableMap.put(key, type);
  1115. }
  1116. }
  1117. if (memoryProfiling && expendableMap.size() > maxExpendableMapSize) {
  1118. maxExpendableMapSize = expendableMap.size();
  1119. }
  1120. return type;
  1121. } else {
  1122. if (demotionSystemActive) {
  1123. // System.out.println("Added since last demote " + key);
  1124. addedSinceLastDemote.add(key);
  1125. }
  1126. return tMap.put(key, type);
  1127. }
  1128. }
  1129. public void report() {
  1130. if (!memoryProfiling) {
  1131. return;
  1132. }
  1133. checkq();
  1134. w.getMessageHandler().handleMessage(
  1135. MessageUtil.info("MEMORY: world expendable type map reached maximum size of #" + maxExpendableMapSize
  1136. + " entries"));
  1137. w.getMessageHandler().handleMessage(
  1138. MessageUtil.info("MEMORY: types collected through garbage collection #" + collectedTypes + " entries"));
  1139. }
  1140. public void checkq() {
  1141. if (!memoryProfiling) {
  1142. return;
  1143. }
  1144. while (rq.poll() != null) {
  1145. collectedTypes++;
  1146. }
  1147. }
  1148. /**
  1149. * Lookup a type by its signature, always look in the real map before the expendable map
  1150. */
  1151. public ResolvedType get(String key) {
  1152. checkq();
  1153. ResolvedType ret = tMap.get(key);
  1154. if (ret == null) {
  1155. if (policy == USE_WEAK_REFS) {
  1156. WeakReference<ResolvedType> ref = (WeakReference<ResolvedType>) expendableMap.get(key);
  1157. if (ref != null) {
  1158. ret = ref.get();
  1159. }
  1160. } else if (policy == USE_SOFT_REFS) {
  1161. SoftReference<ResolvedType> ref = (SoftReference<ResolvedType>) expendableMap.get(key);
  1162. if (ref != null) {
  1163. ret = ref.get();
  1164. }
  1165. // } else {
  1166. // return (ResolvedType) expendableMap.get(key);
  1167. }
  1168. }
  1169. return ret;
  1170. }
  1171. /** Remove a type from the map */
  1172. public ResolvedType remove(String key) {
  1173. ResolvedType ret = tMap.remove(key);
  1174. if (ret == null) {
  1175. if (policy == USE_WEAK_REFS) {
  1176. WeakReference<ResolvedType> wref = (WeakReference<ResolvedType>) expendableMap.remove(key);
  1177. if (wref != null) {
  1178. ret = wref.get();
  1179. }
  1180. } else if (policy == USE_SOFT_REFS) {
  1181. SoftReference<ResolvedType> wref = (SoftReference<ResolvedType>) expendableMap.remove(key);
  1182. if (wref != null) {
  1183. ret = wref.get();
  1184. }
  1185. // } else {
  1186. // ret = (ResolvedType) expendableMap.remove(key);
  1187. }
  1188. }
  1189. return ret;
  1190. }
  1191. public void classWriteEvent(String classname) {
  1192. // that is a name com.Foo and not a signature Lcom/Foo; boooooooooo!
  1193. if (demotionSystemActive) {
  1194. writtenClasses.add(classname);
  1195. }
  1196. if (debugDemotion) {
  1197. System.out.println("Class write event for " + classname);
  1198. }
  1199. }
  1200. public void demote(ResolvedType type) {
  1201. String key = type.getSignature();
  1202. if (debugDemotion) {
  1203. addedSinceLastDemote.remove(key);
  1204. }
  1205. tMap.remove(key);
  1206. insertInExpendableMap(key, type);
  1207. }
  1208. // public ResolvedType[] getAllTypes() {
  1209. // List/* ResolvedType */results = new ArrayList();
  1210. //
  1211. // collectTypes(expendableMap, results);
  1212. // collectTypes(tMap, results);
  1213. // return (ResolvedType[]) results.toArray(new
  1214. // ResolvedType[results.size()]);
  1215. // }
  1216. //
  1217. // private void collectTypes(Map map, List/* ResolvedType */results) {
  1218. // for (Iterator iterator = map.keySet().iterator();
  1219. // iterator.hasNext();) {
  1220. // String key = (String) iterator.next();
  1221. // ResolvedType type = get(key);
  1222. // if (type != null)
  1223. // results.add(type);
  1224. // else
  1225. // System.err.println("null!:" + key);
  1226. // }
  1227. // }
  1228. }
  1229. /**
  1230. * This class is used to compute and store precedence relationships between aspects.
  1231. */
  1232. private static class AspectPrecedenceCalculator {
  1233. private final World world;
  1234. private final Map<PrecedenceCacheKey, Integer> cachedResults;
  1235. public AspectPrecedenceCalculator(World forSomeWorld) {
  1236. world = forSomeWorld;
  1237. cachedResults = new HashMap<PrecedenceCacheKey, Integer>();
  1238. }
  1239. /**
  1240. * Ask every declare precedence in the world to order the two aspects. If more than one declare precedence gives an
  1241. * ordering, and the orderings conflict, then that's an error.
  1242. */
  1243. public int compareByPrecedence(ResolvedType firstAspect, ResolvedType secondAspect) {
  1244. PrecedenceCacheKey key = new PrecedenceCacheKey(firstAspect, secondAspect);
  1245. if (cachedResults.containsKey(key)) {
  1246. return (cachedResults.get(key)).intValue();
  1247. } else {
  1248. int order = 0;
  1249. DeclarePrecedence orderer = null; // Records the declare
  1250. // precedence statement that
  1251. // gives the first ordering
  1252. for (Iterator<Declare> i = world.getCrosscuttingMembersSet().getDeclareDominates().iterator(); i.hasNext();) {
  1253. DeclarePrecedence d = (DeclarePrecedence) i.next();
  1254. int thisOrder = d.compare(firstAspect, secondAspect);
  1255. if (thisOrder != 0) {
  1256. if (orderer == null) {
  1257. orderer = d;
  1258. }
  1259. if (order != 0 && order != thisOrder) {
  1260. ISourceLocation[] isls = new ISourceLocation[2];
  1261. isls[0] = orderer.getSourceLocation();
  1262. isls[1] = d.getSourceLocation();
  1263. Message m = new Message("conflicting declare precedence orderings for aspects: "
  1264. + firstAspect.getName() + " and " + secondAspect.getName(), null, true, isls);
  1265. world.getMessageHandler().handleMessage(m);
  1266. } else {
  1267. order = thisOrder;
  1268. }
  1269. }
  1270. }
  1271. cachedResults.put(key, new Integer(order));
  1272. return order;
  1273. }
  1274. }
  1275. public Integer getPrecedenceIfAny(ResolvedType aspect1, ResolvedType aspect2) {
  1276. return cachedResults.get(new PrecedenceCacheKey(aspect1, aspect2));
  1277. }
  1278. public int compareByPrecedenceAndHierarchy(ResolvedType firstAspect, ResolvedType secondAspect) {
  1279. if (firstAspect.equals(secondAspect)) {
  1280. return 0;
  1281. }
  1282. int ret = compareByPrecedence(firstAspect, secondAspect);
  1283. if (ret != 0) {
  1284. return ret;
  1285. }
  1286. if (firstAspect.isAssignableFrom(secondAspect)) {
  1287. return -1;
  1288. } else if (secondAspect.isAssignableFrom(firstAspect)) {
  1289. return +1;
  1290. }
  1291. return 0;
  1292. }
  1293. private static class PrecedenceCacheKey {
  1294. public ResolvedType aspect1;
  1295. public ResolvedType aspect2;
  1296. public PrecedenceCacheKey(ResolvedType a1, ResolvedType a2) {
  1297. aspect1 = a1;
  1298. aspect2 = a2;
  1299. }
  1300. @Override
  1301. public boolean equals(Object obj) {
  1302. if (!(obj instanceof PrecedenceCacheKey)) {
  1303. return false;
  1304. }
  1305. PrecedenceCacheKey other = (PrecedenceCacheKey) obj;
  1306. return (aspect1 == other.aspect1 && aspect2 == other.aspect2);
  1307. }
  1308. @Override
  1309. public int hashCode() {
  1310. return aspect1.hashCode() + aspect2.hashCode();
  1311. }
  1312. }
  1313. }
  1314. public void validateType(UnresolvedType type) {
  1315. }
  1316. // --- with java5 we can get into a recursive mess if we aren't careful when
  1317. // resolving types (*cough* java.lang.Enum) ---
  1318. public boolean isDemotionActive() {
  1319. return true;
  1320. }
  1321. // --- this first map is for java15 delegates which may try and recursively
  1322. // access the same type variables.
  1323. // --- I would rather stash this against a reference type - but we don't
  1324. // guarantee referencetypes are unique for
  1325. // so we can't :(
  1326. private final Map<Class<?>, TypeVariable[]> workInProgress1 = new HashMap<Class<?>, TypeVariable[]>();
  1327. public TypeVariable[] getTypeVariablesCurrentlyBeingProcessed(Class<?> baseClass) {
  1328. return workInProgress1.get(baseClass);
  1329. }
  1330. public void recordTypeVariablesCurrentlyBeingProcessed(Class<?> baseClass, TypeVariable[] typeVariables) {
  1331. workInProgress1.put(baseClass, typeVariables);
  1332. }
  1333. public void forgetTypeVariablesCurrentlyBeingProcessed(Class<?> baseClass) {
  1334. workInProgress1.remove(baseClass);
  1335. }
  1336. public void setAddSerialVerUID(boolean b) {
  1337. addSerialVerUID = b;
  1338. }
  1339. public boolean isAddSerialVerUID() {
  1340. return addSerialVerUID;
  1341. }
  1342. /** be careful calling this - pr152257 */
  1343. public void flush() {
  1344. typeMap.expendableMap.clear();
  1345. }
  1346. public void ensureAdvancedConfigurationProcessed() {
  1347. // Check *once* whether the user has switched asm support off
  1348. if (!checkedAdvancedConfiguration) {
  1349. Properties p = getExtraConfiguration();
  1350. if (p != null) {
  1351. String s = p.getProperty(xsetBCEL_REPOSITORY_CACHING, xsetBCEL_REPOSITORY_CACHING_DEFAULT);
  1352. bcelRepositoryCaching = s.equalsIgnoreCase("true");
  1353. if (!bcelRepositoryCaching) {
  1354. getMessageHandler().handleMessage(
  1355. MessageUtil
  1356. .info("[bcelRepositoryCaching=false] AspectJ will not use a bcel cache for class information"));
  1357. }
  1358. // ITD Versions
  1359. // 1 is the first version in use up to AspectJ 1.6.8
  1360. // 2 is from 1.6.9 onwards
  1361. s = p.getProperty(xsetITD_VERSION, xsetITD_VERSION_DEFAULT);
  1362. if (s.equals(xsetITD_VERSION_ORIGINAL)) {
  1363. itdVersion = 1;
  1364. }
  1365. s = p.getProperty(xsetAVOID_FINAL, "false");
  1366. if (s.equalsIgnoreCase("true")) {
  1367. useFinal = false; // if avoidFinal=true, then set useFinal to false
  1368. }
  1369. s = p.getProperty(xsetMINIMAL_MODEL, "true");
  1370. if (s.equalsIgnoreCase("false")) {
  1371. minimalModel = false;
  1372. }
  1373. s = p.getProperty(xsetTARGETING_RUNTIME_1610, "false");
  1374. if (s.equalsIgnoreCase("true")) {
  1375. targettingRuntime1_6_10 = true;
  1376. }
  1377. s = p.getProperty(xsetFAST_PACK_METHODS, "true");
  1378. fastMethodPacking = s.equalsIgnoreCase("true");
  1379. s = p.getProperty(xsetPIPELINE_COMPILATION, xsetPIPELINE_COMPILATION_DEFAULT);
  1380. shouldPipelineCompilation = s.equalsIgnoreCase("true");
  1381. s = p.getProperty(xsetGENERATE_STACKMAPS, "false");
  1382. shouldGenerateStackMaps = s.equalsIgnoreCase("true");
  1383. s = p.getProperty(xsetCOMPLETE_BINARY_TYPES, xsetCOMPLETE_BINARY_TYPES_DEFAULT);
  1384. completeBinaryTypes = s.equalsIgnoreCase("true");
  1385. if (completeBinaryTypes) {
  1386. getMessageHandler().handleMessage(
  1387. MessageUtil.info("[completeBinaryTypes=true] Completion of binary types activated"));
  1388. }
  1389. s = p.getProperty(xsetTYPE_DEMOTION); // default is: ON
  1390. if (s != null) {
  1391. boolean b = typeMap.demotionSystemActive;
  1392. if (b && s.equalsIgnoreCase("false")) {
  1393. System.out.println("typeDemotion=false: type demotion switched OFF");
  1394. typeMap.demotionSystemActive = false;
  1395. } else if (!b && s.equalsIgnoreCase("true")) {
  1396. System.out.println("typeDemotion=true: type demotion switched ON");
  1397. typeMap.demotionSystemActive = true;
  1398. }
  1399. }
  1400. s = p.getProperty(xsetOVERWEAVING, "false");
  1401. if (s.equalsIgnoreCase("true")) {
  1402. overWeaving = true;
  1403. }
  1404. s = p.getProperty(xsetTYPE_DEMOTION_DEBUG, "false");
  1405. if (s.equalsIgnoreCase("true")) {
  1406. typeMap.debugDemotion = true;
  1407. }
  1408. s = p.getProperty(xsetTYPE_REFS, "true");
  1409. if (s.equalsIgnoreCase("false")) {
  1410. typeMap.policy = TypeMap.USE_SOFT_REFS;
  1411. }
  1412. runMinimalMemorySet = p.getProperty(xsetRUN_MINIMAL_MEMORY) != null;
  1413. s = p.getProperty(xsetRUN_MINIMAL_MEMORY, "false");
  1414. runMinimalMemory = s.equalsIgnoreCase("true");
  1415. // if (runMinimalMemory)
  1416. // getMessageHandler().handleMessage(MessageUtil.info(
  1417. // "[runMinimalMemory=true] Optimizing bcel processing (and cost of performance) to use less memory"
  1418. // ));
  1419. s = p.getProperty(xsetDEBUG_STRUCTURAL_CHANGES_CODE, "false");
  1420. forDEBUG_structuralChangesCode = s.equalsIgnoreCase("true");
  1421. s = p.getProperty(xsetTRANSIENT_TJP_FIELDS,"false");
  1422. transientTjpFields = s.equalsIgnoreCase("true");
  1423. s = p.getProperty(xsetDEBUG_BRIDGING, "false");
  1424. forDEBUG_bridgingCode = s.equalsIgnoreCase("true");
  1425. s = p.getProperty(xsetOPTIMIZED_MATCHING, "true");
  1426. optimizedMatching = s.equalsIgnoreCase("true");
  1427. if (!optimizedMatching) {
  1428. getMessageHandler().handleMessage(MessageUtil.info("[optimizedMatching=false] optimized matching turned off"));
  1429. }
  1430. s = p.getProperty(xsetTIMERS_PER_JOINPOINT, "25000");
  1431. try {
  1432. timersPerJoinpoint = Integer.parseInt(s);
  1433. } catch (Exception e) {
  1434. getMessageHandler().handleMessage(MessageUtil.error("unable to process timersPerJoinpoint value of " + s));
  1435. timersPerJoinpoint = 25000;
  1436. }
  1437. s = p.getProperty(xsetTIMERS_PER_FASTMATCH_CALL, "250");
  1438. try {
  1439. timersPerType = Integer.parseInt(s);
  1440. } catch (Exception e) {
  1441. getMessageHandler().handleMessage(MessageUtil.error("unable to process timersPerType value of " + s));
  1442. timersPerType = 250;
  1443. }
  1444. }
  1445. try {
  1446. if (systemPropertyOverWeaving) {
  1447. overWeaving = true;
  1448. }
  1449. String value = null;
  1450. value = System.getProperty("aspectj.typeDemotion", "false");
  1451. if (value.equalsIgnoreCase("true")) {
  1452. System.out.println("ASPECTJ: aspectj.typeDemotion=true: type demotion switched ON");
  1453. typeMap.demotionSystemActive = true;
  1454. }
  1455. value = System.getProperty("aspectj.minimalModel", "false");
  1456. if (value.equalsIgnoreCase("true")) {
  1457. System.out.println("ASPECTJ: aspectj.minimalModel=true: minimal model switched ON");
  1458. minimalModel = true;
  1459. }
  1460. } catch (Throwable t) {
  1461. System.err.println("ASPECTJ: Unable to read system properties");
  1462. t.printStackTrace();
  1463. }
  1464. checkedAdvancedConfiguration = true;
  1465. }
  1466. }
  1467. public boolean isRunMinimalMemory() {
  1468. ensureAdvancedConfigurationProcessed();
  1469. return runMinimalMemory;
  1470. }
  1471. public boolean isTransientTjpFields() {
  1472. ensureAdvancedConfigurationProcessed();
  1473. return transientTjpFields;
  1474. }
  1475. public boolean isRunMinimalMemorySet() {
  1476. ensureAdvancedConfigurationProcessed();
  1477. return runMinimalMemorySet;
  1478. }
  1479. public boolean shouldFastPackMethods() {
  1480. ensureAdvancedConfigurationProcessed();
  1481. return fastMethodPacking;
  1482. }
  1483. public boolean shouldPipelineCompilation() {
  1484. ensureAdvancedConfigurationProcessed();
  1485. return shouldPipelineCompilation;
  1486. }
  1487. public boolean shouldGenerateStackMaps() {
  1488. ensureAdvancedConfigurationProcessed();
  1489. return shouldGenerateStackMaps;
  1490. }
  1491. public void setIncrementalCompileCouldFollow(boolean b) {
  1492. incrementalCompileCouldFollow = b;
  1493. }
  1494. public boolean couldIncrementalCompileFollow() {
  1495. return incrementalCompileCouldFollow;
  1496. }
  1497. public void setSynchronizationPointcutsInUse() {
  1498. if (trace.isTraceEnabled()) {
  1499. trace.enter("setSynchronizationPointcutsInUse", this);
  1500. }
  1501. synchronizationPointcutsInUse = true;
  1502. if (trace.isTraceEnabled()) {
  1503. trace.exit("setSynchronizationPointcutsInUse");
  1504. }
  1505. }
  1506. public boolean areSynchronizationPointcutsInUse() {
  1507. return synchronizationPointcutsInUse;
  1508. }
  1509. /**
  1510. * Register a new pointcut designator handler with the world - this can be used by any pointcut parsers attached to the world.
  1511. *
  1512. * @param designatorHandler handler for the new pointcut
  1513. */
  1514. public void registerPointcutHandler(PointcutDesignatorHandler designatorHandler) {
  1515. if (pointcutDesignators == null) {
  1516. pointcutDesignators = new HashSet<PointcutDesignatorHandler>();
  1517. }
  1518. pointcutDesignators.add(designatorHandler);
  1519. }
  1520. public Set<PointcutDesignatorHandler> getRegisteredPointcutHandlers() {
  1521. if (pointcutDesignators == null) {
  1522. return Collections.emptySet();
  1523. }
  1524. return pointcutDesignators;
  1525. }
  1526. public void reportMatch(ShadowMunger munger, Shadow shadow) {
  1527. }
  1528. public boolean isOverWeaving() {
  1529. return overWeaving;
  1530. }
  1531. public void reportCheckerMatch(Checker checker, Shadow shadow) {
  1532. }
  1533. /**
  1534. * @return true if this world has the activation and scope of application of the aspects controlled via aop.xml files
  1535. */
  1536. public boolean isXmlConfigured() {
  1537. return false;
  1538. }
  1539. public boolean isAspectIncluded(ResolvedType aspectType) {
  1540. return true;
  1541. }
  1542. /**
  1543. * Determine if the named aspect requires a particular type around in order to be useful. The type is named in the aop.xml file
  1544. * against the aspect.
  1545. *
  1546. * @return true if there is a type missing that this aspect really needed around
  1547. */
  1548. public boolean hasUnsatisfiedDependency(ResolvedType aspectType) {
  1549. return false;
  1550. }
  1551. public TypePattern getAspectScope(ResolvedType declaringType) {
  1552. return null;
  1553. }
  1554. public Map<String, ResolvedType> getFixed() {
  1555. return typeMap.tMap;
  1556. }
  1557. public Map<String, Reference<ResolvedType>> getExpendable() {
  1558. return typeMap.expendableMap;
  1559. }
  1560. /**
  1561. * Ask the type map to demote any types it can - we don't want them anchored forever.
  1562. */
  1563. public void demote() {
  1564. typeMap.demote();
  1565. }
  1566. // protected boolean isExpendable(ResolvedType type) {
  1567. // if (type.equals(UnresolvedType.OBJECT))
  1568. // return false;
  1569. // if (type == null)
  1570. // return false;
  1571. // boolean isExposed = type.isExposedToWeaver();
  1572. // boolean nullDele = (type instanceof ReferenceType) ? ((ReferenceType) type).getDelegate() != null : true;
  1573. // if (isExposed || !isExposed && nullDele)
  1574. // return false;
  1575. // return !type.isPrimitiveType();
  1576. // }
  1577. /**
  1578. * Reference types we don't intend to weave may be ejected from the cache if we need the space.
  1579. */
  1580. protected boolean isExpendable(ResolvedType type) {
  1581. return !type.equals(UnresolvedType.OBJECT) && !type.isExposedToWeaver() && !type.isPrimitiveType()
  1582. && !type.isPrimitiveArray();
  1583. }
  1584. // map from aspect > excluded types
  1585. // memory issue here?
  1586. private Map<ResolvedType, Set<ResolvedType>> exclusionMap = new HashMap<ResolvedType, Set<ResolvedType>>();
  1587. public Map<ResolvedType, Set<ResolvedType>> getExclusionMap() {
  1588. return exclusionMap;
  1589. }
  1590. private TimeCollector timeCollector = null;
  1591. /**
  1592. * Record the time spent matching a pointcut - this will accumulate over the lifetime of this world/weaver and be reported every
  1593. * 25000 join points.
  1594. */
  1595. public void record(Pointcut pointcut, long timetaken) {
  1596. if (timeCollector == null) {
  1597. ensureAdvancedConfigurationProcessed();
  1598. timeCollector = new TimeCollector(this);
  1599. }
  1600. timeCollector.record(pointcut, timetaken);
  1601. }
  1602. /**
  1603. * Record the time spent fastmatching a pointcut - this will accumulate over the lifetime of this world/weaver and be reported
  1604. * every 250 types.
  1605. */
  1606. public void recordFastMatch(Pointcut pointcut, long timetaken) {
  1607. if (timeCollector == null) {
  1608. ensureAdvancedConfigurationProcessed();
  1609. timeCollector = new TimeCollector(this);
  1610. }
  1611. timeCollector.recordFastMatch(pointcut, timetaken);
  1612. }
  1613. public void reportTimers() {
  1614. if (timeCollector != null && !timingPeriodically) {
  1615. timeCollector.report();
  1616. timeCollector = new TimeCollector(this);
  1617. }
  1618. }
  1619. private static class TimeCollector {
  1620. private World world;
  1621. long joinpointCount;
  1622. long typeCount;
  1623. long perJoinpointCount;
  1624. long perTypes;
  1625. Map<String, Long> joinpointsPerPointcut = new HashMap<String, Long>();
  1626. Map<String, Long> timePerPointcut = new HashMap<String, Long>();
  1627. Map<String, Long> fastMatchTimesPerPointcut = new HashMap<String, Long>();
  1628. Map<String, Long> fastMatchTypesPerPointcut = new HashMap<String, Long>();
  1629. TimeCollector(World world) {
  1630. this.perJoinpointCount = world.timersPerJoinpoint;
  1631. this.perTypes = world.timersPerType;
  1632. this.world = world;
  1633. this.joinpointCount = 0;
  1634. this.typeCount = 0;
  1635. this.joinpointsPerPointcut = new HashMap<String, Long>();
  1636. this.timePerPointcut = new HashMap<String, Long>();
  1637. }
  1638. public void report() {
  1639. long totalTime = 0L;
  1640. for (String p : joinpointsPerPointcut.keySet()) {
  1641. totalTime += timePerPointcut.get(p);
  1642. }
  1643. world.getMessageHandler().handleMessage(
  1644. MessageUtil.info("Pointcut matching cost (total=" + (totalTime / 1000000) + "ms for " + joinpointCount
  1645. + " joinpoint match calls):"));
  1646. for (String p : joinpointsPerPointcut.keySet()) {
  1647. StringBuffer sb = new StringBuffer();
  1648. sb.append("Time:" + (timePerPointcut.get(p) / 1000000) + "ms (jps:#" + joinpointsPerPointcut.get(p)
  1649. + ") matching against " + p);
  1650. world.getMessageHandler().handleMessage(MessageUtil.info(sb.toString()));
  1651. }
  1652. world.getMessageHandler().handleMessage(MessageUtil.info("---"));
  1653. totalTime = 0L;
  1654. for (String p : fastMatchTimesPerPointcut.keySet()) {
  1655. totalTime += fastMatchTimesPerPointcut.get(p);
  1656. }
  1657. world.getMessageHandler().handleMessage(
  1658. MessageUtil.info("Pointcut fast matching cost (total=" + (totalTime / 1000000) + "ms for " + typeCount
  1659. + " fast match calls):"));
  1660. for (String p : fastMatchTimesPerPointcut.keySet()) {
  1661. StringBuffer sb = new StringBuffer();
  1662. sb.append("Time:" + (fastMatchTimesPerPointcut.get(p) / 1000000) + "ms (types:#" + fastMatchTypesPerPointcut.get(p)
  1663. + ") fast matching against " + p);
  1664. world.getMessageHandler().handleMessage(MessageUtil.info(sb.toString()));
  1665. }
  1666. world.getMessageHandler().handleMessage(MessageUtil.info("---"));
  1667. }
  1668. void record(Pointcut pointcut, long timetakenInNs) {
  1669. joinpointCount++;
  1670. String pointcutText = pointcut.toString();
  1671. Long jpcounter = joinpointsPerPointcut.get(pointcutText);
  1672. if (jpcounter == null) {
  1673. jpcounter = 1L;
  1674. } else {
  1675. jpcounter++;
  1676. }
  1677. joinpointsPerPointcut.put(pointcutText, jpcounter);
  1678. Long time = timePerPointcut.get(pointcutText);
  1679. if (time == null) {
  1680. time = timetakenInNs;
  1681. } else {
  1682. time += timetakenInNs;
  1683. }
  1684. timePerPointcut.put(pointcutText, time);
  1685. if (world.timingPeriodically) {
  1686. if ((joinpointCount % perJoinpointCount) == 0) {
  1687. long totalTime = 0L;
  1688. for (String p : joinpointsPerPointcut.keySet()) {
  1689. totalTime += timePerPointcut.get(p);
  1690. }
  1691. world.getMessageHandler().handleMessage(
  1692. MessageUtil.info("Pointcut matching cost (total=" + (totalTime / 1000000) + "ms for " + joinpointCount
  1693. + " joinpoint match calls):"));
  1694. for (String p : joinpointsPerPointcut.keySet()) {
  1695. StringBuffer sb = new StringBuffer();
  1696. sb.append("Time:" + (timePerPointcut.get(p) / 1000000) + "ms (jps:#" + joinpointsPerPointcut.get(p)
  1697. + ") matching against " + p);
  1698. world.getMessageHandler().handleMessage(MessageUtil.info(sb.toString()));
  1699. }
  1700. world.getMessageHandler().handleMessage(MessageUtil.info("---"));
  1701. }
  1702. }
  1703. }
  1704. void recordFastMatch(Pointcut pointcut, long timetakenInNs) {
  1705. typeCount++;
  1706. String pointcutText = pointcut.toString();
  1707. Long typecounter = fastMatchTypesPerPointcut.get(pointcutText);
  1708. if (typecounter == null) {
  1709. typecounter = 1L;
  1710. } else {
  1711. typecounter++;
  1712. }
  1713. fastMatchTypesPerPointcut.put(pointcutText, typecounter);
  1714. Long time = fastMatchTimesPerPointcut.get(pointcutText);
  1715. if (time == null) {
  1716. time = timetakenInNs;
  1717. } else {
  1718. time += timetakenInNs;
  1719. }
  1720. fastMatchTimesPerPointcut.put(pointcutText, time);
  1721. if (world.timingPeriodically) {
  1722. if ((typeCount % perTypes) == 0) {
  1723. long totalTime = 0L;
  1724. for (String p : fastMatchTimesPerPointcut.keySet()) {
  1725. totalTime += fastMatchTimesPerPointcut.get(p);
  1726. }
  1727. world.getMessageHandler().handleMessage(
  1728. MessageUtil.info("Pointcut fast matching cost (total=" + (totalTime / 1000000) + "ms for " + typeCount
  1729. + " fast match calls):"));
  1730. for (String p : fastMatchTimesPerPointcut.keySet()) {
  1731. StringBuffer sb = new StringBuffer();
  1732. sb.append("Time:" + (fastMatchTimesPerPointcut.get(p) / 1000000) + "ms (types:#"
  1733. + fastMatchTypesPerPointcut.get(p) + ") fast matching against " + p);
  1734. world.getMessageHandler().handleMessage(MessageUtil.info(sb.toString()));
  1735. }
  1736. world.getMessageHandler().handleMessage(MessageUtil.info("---"));
  1737. }
  1738. }
  1739. }
  1740. }
  1741. public TypeMap getTypeMap() {
  1742. return typeMap;
  1743. }
  1744. public static void reset() {
  1745. // ResolvedType.resetPrimitives();
  1746. }
  1747. /**
  1748. * Returns the version of ITD that this world wants to create. The default is the new style (2) but in some cases where there
  1749. * might be a clash, the old style can be used. It is set through the option -Xset:itdVersion=1
  1750. *
  1751. * @return the ITD version this world wants to create - 1=oldstyle 2=new, transparent style
  1752. */
  1753. public int getItdVersion() {
  1754. return itdVersion;
  1755. }
  1756. // if not loadtime weaving then we are compile time weaving or post-compile time weaving
  1757. public abstract boolean isLoadtimeWeaving();
  1758. public void classWriteEvent(char[][] compoundName) {
  1759. // override if interested in write events
  1760. }
  1761. }