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.

AtAjAttributes.java 76KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026
  1. /*******************************************************************************
  2. * Copyright (c) 2005 Contributors.
  3. * All rights reserved.
  4. * This program and the accompanying materials are made available
  5. * under the terms of the Eclipse Public License v1.0
  6. * which accompanies this distribution and is available at
  7. * http://eclipse.org/legal/epl-v10.html
  8. *
  9. * Contributors:
  10. * initial implementation Alexandre Vasseur
  11. *******************************************************************************/
  12. package org.aspectj.weaver.bcel;
  13. import java.io.ByteArrayInputStream;
  14. import java.io.IOException;
  15. import java.lang.reflect.Modifier;
  16. import java.util.ArrayList;
  17. import java.util.Arrays;
  18. import java.util.Collections;
  19. import java.util.Comparator;
  20. import java.util.Iterator;
  21. import java.util.List;
  22. import java.util.StringTokenizer;
  23. import org.aspectj.apache.bcel.Constants;
  24. import org.aspectj.apache.bcel.classfile.Attribute;
  25. import org.aspectj.apache.bcel.classfile.Constant;
  26. import org.aspectj.apache.bcel.classfile.ConstantUtf8;
  27. import org.aspectj.apache.bcel.classfile.Field;
  28. import org.aspectj.apache.bcel.classfile.JavaClass;
  29. import org.aspectj.apache.bcel.classfile.LocalVariable;
  30. import org.aspectj.apache.bcel.classfile.LocalVariableTable;
  31. import org.aspectj.apache.bcel.classfile.Method;
  32. import org.aspectj.apache.bcel.classfile.Unknown;
  33. import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen;
  34. import org.aspectj.apache.bcel.classfile.annotation.ArrayElementValue;
  35. import org.aspectj.apache.bcel.classfile.annotation.ClassElementValue;
  36. import org.aspectj.apache.bcel.classfile.annotation.ElementValue;
  37. import org.aspectj.apache.bcel.classfile.annotation.NameValuePair;
  38. import org.aspectj.apache.bcel.classfile.annotation.RuntimeAnnos;
  39. import org.aspectj.apache.bcel.classfile.annotation.RuntimeVisAnnos;
  40. import org.aspectj.apache.bcel.generic.Type;
  41. import org.aspectj.asm.AsmManager;
  42. import org.aspectj.asm.IHierarchy;
  43. import org.aspectj.asm.IProgramElement;
  44. import org.aspectj.bridge.IMessage;
  45. import org.aspectj.bridge.IMessageHandler;
  46. import org.aspectj.bridge.ISourceLocation;
  47. import org.aspectj.bridge.Message;
  48. import org.aspectj.bridge.MessageUtil;
  49. import org.aspectj.weaver.Advice;
  50. import org.aspectj.weaver.AdviceKind;
  51. import org.aspectj.weaver.AjAttribute;
  52. import org.aspectj.weaver.AjAttribute.WeaverVersionInfo;
  53. import org.aspectj.weaver.AjcMemberMaker;
  54. import org.aspectj.weaver.BindingScope;
  55. import org.aspectj.weaver.ISourceContext;
  56. import org.aspectj.weaver.MethodDelegateTypeMunger;
  57. import org.aspectj.weaver.NameMangler;
  58. import org.aspectj.weaver.ReferenceType;
  59. import org.aspectj.weaver.ReferenceTypeDelegate;
  60. import org.aspectj.weaver.ResolvedMember;
  61. import org.aspectj.weaver.ResolvedPointcutDefinition;
  62. import org.aspectj.weaver.ResolvedType;
  63. import org.aspectj.weaver.UnresolvedType;
  64. import org.aspectj.weaver.VersionedDataInputStream;
  65. import org.aspectj.weaver.WeaverMessages;
  66. import org.aspectj.weaver.World;
  67. import org.aspectj.weaver.patterns.DeclareErrorOrWarning;
  68. import org.aspectj.weaver.patterns.DeclareParents;
  69. import org.aspectj.weaver.patterns.DeclareParentsMixin;
  70. import org.aspectj.weaver.patterns.DeclarePrecedence;
  71. import org.aspectj.weaver.patterns.FormalBinding;
  72. import org.aspectj.weaver.patterns.IScope;
  73. import org.aspectj.weaver.patterns.ParserException;
  74. import org.aspectj.weaver.patterns.PatternParser;
  75. import org.aspectj.weaver.patterns.PerCflow;
  76. import org.aspectj.weaver.patterns.PerClause;
  77. import org.aspectj.weaver.patterns.PerFromSuper;
  78. import org.aspectj.weaver.patterns.PerObject;
  79. import org.aspectj.weaver.patterns.PerSingleton;
  80. import org.aspectj.weaver.patterns.PerTypeWithin;
  81. import org.aspectj.weaver.patterns.Pointcut;
  82. import org.aspectj.weaver.patterns.TypePattern;
  83. /**
  84. * Annotation defined aspect reader. Reads the Java 5 annotations and turns them into AjAttributes
  85. *
  86. * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
  87. */
  88. public class AtAjAttributes {
  89. private final static List<AjAttribute> NO_ATTRIBUTES = Collections.emptyList();
  90. private final static String[] EMPTY_STRINGS = new String[0];
  91. private final static String VALUE = "value";
  92. private final static String ARGNAMES = "argNames";
  93. private final static String POINTCUT = "pointcut";
  94. private final static String THROWING = "throwing";
  95. private final static String RETURNING = "returning";
  96. private final static String STRING_DESC = "Ljava/lang/String;";
  97. private final static String ASPECTJ_ANNOTATION_PACKAGE = "org.aspectj.lang.annotation";
  98. private final static char PACKAGE_INITIAL_CHAR = ASPECTJ_ANNOTATION_PACKAGE.charAt(0);
  99. /**
  100. * A struct that allows to add extra arguments without always breaking the API
  101. */
  102. private static class AjAttributeStruct {
  103. /**
  104. * The list of AjAttribute.XXX that we are populating from the @AJ read
  105. */
  106. List<AjAttribute> ajAttributes = new ArrayList<AjAttribute>();
  107. /**
  108. * The resolved type (class) for which we are reading @AJ for (be it class, method, field annotations)
  109. */
  110. final ResolvedType enclosingType;
  111. final ISourceContext context;
  112. final IMessageHandler handler;
  113. public AjAttributeStruct(ResolvedType type, ISourceContext sourceContext, IMessageHandler messageHandler) {
  114. enclosingType = type;
  115. context = sourceContext;
  116. handler = messageHandler;
  117. }
  118. }
  119. /**
  120. * A struct when we read @AJ on method
  121. *
  122. * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
  123. */
  124. private static class AjAttributeMethodStruct extends AjAttributeStruct {
  125. // argument names used for formal binding
  126. private String[] m_argumentNamesLazy = null;
  127. public String unparsedArgumentNames = null; // Set only if discovered as
  128. // argNames attribute of
  129. // annotation
  130. final Method method;
  131. final BcelMethod bMethod;
  132. public AjAttributeMethodStruct(Method method, BcelMethod bMethod, ResolvedType type, ISourceContext sourceContext,
  133. IMessageHandler messageHandler) {
  134. super(type, sourceContext, messageHandler);
  135. this.method = method;
  136. this.bMethod = bMethod;
  137. }
  138. public String[] getArgumentNames() {
  139. if (m_argumentNamesLazy == null) {
  140. m_argumentNamesLazy = getMethodArgumentNames(method, unparsedArgumentNames, this);
  141. }
  142. return m_argumentNamesLazy;
  143. }
  144. }
  145. /**
  146. * A struct when we read @AJ on field
  147. */
  148. private static class AjAttributeFieldStruct extends AjAttributeStruct {
  149. final Field field;
  150. // final BcelField bField;
  151. public AjAttributeFieldStruct(Field field, BcelField bField, ResolvedType type, ISourceContext sourceContext,
  152. IMessageHandler messageHandler) {
  153. super(type, sourceContext, messageHandler);
  154. this.field = field;
  155. // this.bField = bField;
  156. }
  157. }
  158. /**
  159. * Annotations are RuntimeVisible only. This allow us to not visit RuntimeInvisible ones.
  160. *
  161. * @param attribute
  162. * @return true if runtime visible annotation
  163. */
  164. public static boolean acceptAttribute(Attribute attribute) {
  165. return (attribute instanceof RuntimeVisAnnos);
  166. }
  167. /**
  168. * Extract class level annotations and turn them into AjAttributes.
  169. *
  170. * @param javaClass
  171. * @param type
  172. * @param context
  173. * @param msgHandler
  174. * @return list of AjAttributes
  175. */
  176. public static List<AjAttribute> readAj5ClassAttributes(AsmManager model, JavaClass javaClass, ReferenceType type,
  177. ISourceContext context, IMessageHandler msgHandler, boolean isCodeStyleAspect) {
  178. boolean ignoreThisClass = javaClass.getClassName().charAt(0) == PACKAGE_INITIAL_CHAR
  179. && javaClass.getClassName().startsWith(ASPECTJ_ANNOTATION_PACKAGE);
  180. if (ignoreThisClass) {
  181. return NO_ATTRIBUTES;
  182. }
  183. boolean containsPointcut = false;
  184. boolean containsAnnotationClassReference = false;
  185. Constant[] cpool = javaClass.getConstantPool().getConstantPool();
  186. for (Constant constant : cpool) {
  187. if (constant != null && constant.getTag() == Constants.CONSTANT_Utf8) {
  188. String constantValue = ((ConstantUtf8) constant).getValue();
  189. if (constantValue.length() > 28 && constantValue.charAt(1) == PACKAGE_INITIAL_CHAR) {
  190. if (constantValue.startsWith("Lorg/aspectj/lang/annotation")) {
  191. containsAnnotationClassReference = true;
  192. if ("Lorg/aspectj/lang/annotation/DeclareAnnotation;".equals(constantValue)) {
  193. msgHandler.handleMessage(new Message(
  194. "Found @DeclareAnnotation while current release does not support it (see '" + type.getName()
  195. + "')", IMessage.WARNING, null, type.getSourceLocation()));
  196. }
  197. if ("Lorg/aspectj/lang/annotation/Pointcut;".equals(constantValue)) {
  198. containsPointcut = true;
  199. }
  200. }
  201. }
  202. }
  203. }
  204. if (!containsAnnotationClassReference) {
  205. return NO_ATTRIBUTES;
  206. }
  207. AjAttributeStruct struct = new AjAttributeStruct(type, context, msgHandler);
  208. Attribute[] attributes = javaClass.getAttributes();
  209. boolean hasAtAspectAnnotation = false;
  210. boolean hasAtPrecedenceAnnotation = false;
  211. WeaverVersionInfo wvinfo = null;
  212. for (Attribute attribute : attributes) {
  213. if (acceptAttribute(attribute)) {
  214. RuntimeAnnos rvs = (RuntimeAnnos) attribute;
  215. // we don't need to look for several attribute occurrences since
  216. // it cannot happen as per JSR175
  217. if (!isCodeStyleAspect && !javaClass.isInterface()) {
  218. hasAtAspectAnnotation = handleAspectAnnotation(rvs, struct);
  219. // TODO AV - if put outside the if isCodeStyleAspect then we
  220. // would enable mix style
  221. hasAtPrecedenceAnnotation = handlePrecedenceAnnotation(rvs, struct);
  222. }
  223. // there can only be one RuntimeVisible bytecode attribute
  224. break;
  225. }
  226. }
  227. for (int i = attributes.length - 1; i >= 0; i--) {
  228. Attribute attribute = attributes[i];
  229. if (attribute.getName().equals(WeaverVersionInfo.AttributeName)) {
  230. try {
  231. VersionedDataInputStream s = new VersionedDataInputStream(new ByteArrayInputStream(
  232. ((Unknown) attribute).getBytes()), null);
  233. wvinfo = WeaverVersionInfo.read(s);
  234. struct.ajAttributes.add(0, wvinfo);
  235. } catch (IOException ioe) {
  236. ioe.printStackTrace();
  237. }
  238. }
  239. }
  240. if (wvinfo == null) {
  241. // If we are in here due to a resetState() call (presumably because of reweavable state processing), the
  242. // original type delegate will have been set with a version but that version will be missing from
  243. // the new set of attributes (looks like a bug where the version attribute was not included in the
  244. // data compressed into the attribute). So rather than 'defaulting' to current, we should use one
  245. // if it set on the delegate for the type.
  246. ReferenceTypeDelegate delegate = type.getDelegate();
  247. if (delegate instanceof BcelObjectType) {
  248. wvinfo = ((BcelObjectType) delegate).getWeaverVersionAttribute();
  249. if (wvinfo != null) {
  250. if (wvinfo.getMajorVersion() != WeaverVersionInfo.WEAVER_VERSION_MAJOR_UNKNOWN) {
  251. // use this one
  252. struct.ajAttributes.add(0, wvinfo);
  253. } else {
  254. wvinfo = null;
  255. }
  256. }
  257. }
  258. if (wvinfo == null) {
  259. struct.ajAttributes.add(0, wvinfo = new AjAttribute.WeaverVersionInfo());
  260. }
  261. }
  262. // basic semantic check
  263. if (hasAtPrecedenceAnnotation && !hasAtAspectAnnotation) {
  264. msgHandler.handleMessage(new Message("Found @DeclarePrecedence on a non @Aspect type '" + type.getName() + "'",
  265. IMessage.WARNING, null, type.getSourceLocation()));
  266. // bypass what we have read
  267. return NO_ATTRIBUTES;
  268. }
  269. // the following block will not detect @Pointcut in non @Aspect types
  270. // for optimization purpose
  271. if (!(hasAtAspectAnnotation || isCodeStyleAspect) && !containsPointcut) {
  272. return NO_ATTRIBUTES;
  273. }
  274. // FIXME AV - turn on when ajcMightHaveAspect
  275. // if (hasAtAspectAnnotation && type.isInterface()) {
  276. // msgHandler.handleMessage(
  277. // new Message(
  278. // "Found @Aspect on an interface type '" + type.getName() + "'",
  279. // IMessage.WARNING,
  280. // null,
  281. // type.getSourceLocation()
  282. // )
  283. // );
  284. // // bypass what we have read
  285. // return EMPTY_LIST;
  286. // }
  287. // semantic check: @Aspect must be public
  288. // FIXME AV - do we really want to enforce that?
  289. // if (hasAtAspectAnnotation && !javaClass.isPublic()) {
  290. // msgHandler.handleMessage(
  291. // new Message(
  292. // "Found @Aspect annotation on a non public class '" +
  293. // javaClass.getClassName() + "'",
  294. // IMessage.ERROR,
  295. // null,
  296. // type.getSourceLocation()
  297. // )
  298. // );
  299. // return EMPTY_LIST;
  300. // }
  301. // code style pointcuts are class attributes
  302. // we need to gather the @AJ pointcut right now and not at method level
  303. // annotation extraction time
  304. // in order to be able to resolve the pointcut references later on
  305. // we don't need to look in super class, the pointcut reference in the
  306. // grammar will do it
  307. for (int i = 0; i < javaClass.getMethods().length; i++) {
  308. Method method = javaClass.getMethods()[i];
  309. if (method.getName().startsWith(NameMangler.PREFIX)) {
  310. continue; // already dealt with by ajc...
  311. }
  312. // FIXME alex optimize, this method struct will gets recreated for
  313. // advice extraction
  314. AjAttributeMethodStruct mstruct = null;
  315. boolean processedPointcut = false;
  316. Attribute[] mattributes = method.getAttributes();
  317. for (Attribute mattribute : mattributes) {
  318. if (acceptAttribute(mattribute)) {
  319. // TODO speed all this nonsense up rather than looking
  320. // through all the annotations every time
  321. // same for fields
  322. mstruct = new AjAttributeMethodStruct(method, null, type, context, msgHandler);
  323. processedPointcut = handlePointcutAnnotation((RuntimeAnnos) mattribute, mstruct);
  324. if (!processedPointcut) {
  325. processedPointcut = handleDeclareMixinAnnotation((RuntimeAnnos) mattribute, mstruct);
  326. }
  327. // there can only be one RuntimeVisible bytecode attribute
  328. break;
  329. }
  330. }
  331. if (processedPointcut) {
  332. struct.ajAttributes.addAll(mstruct.ajAttributes);
  333. }
  334. }
  335. // code style declare error / warning / implements / parents are field
  336. // attributes
  337. Field[] fs = javaClass.getFields();
  338. for (Field field : fs) {
  339. if (field.getName().startsWith(NameMangler.PREFIX)) {
  340. continue; // already dealt with by ajc...
  341. }
  342. // FIXME alex optimize, this method struct will gets recreated for
  343. // advice extraction
  344. AjAttributeFieldStruct fstruct = new AjAttributeFieldStruct(field, null, type, context, msgHandler);
  345. Attribute[] fattributes = field.getAttributes();
  346. for (Attribute fattribute : fattributes) {
  347. if (acceptAttribute(fattribute)) {
  348. RuntimeAnnos frvs = (RuntimeAnnos) fattribute;
  349. if (handleDeclareErrorOrWarningAnnotation(model, frvs, fstruct)
  350. || handleDeclareParentsAnnotation(frvs, fstruct)) {
  351. // semantic check - must be in an @Aspect [remove if
  352. // previous block bypassed in advance]
  353. if (!type.isAnnotationStyleAspect() && !isCodeStyleAspect) {
  354. msgHandler.handleMessage(new Message("Found @AspectJ annotations in a non @Aspect type '"
  355. + type.getName() + "'", IMessage.WARNING, null, type.getSourceLocation()));
  356. // go ahead
  357. }
  358. }
  359. // there can only be one RuntimeVisible bytecode attribute
  360. break;
  361. }
  362. }
  363. struct.ajAttributes.addAll(fstruct.ajAttributes);
  364. }
  365. return struct.ajAttributes;
  366. }
  367. /**
  368. * Extract method level annotations and turn them into AjAttributes.
  369. *
  370. * @param method
  371. * @param type
  372. * @param context
  373. * @param msgHandler
  374. * @return list of AjAttributes
  375. */
  376. public static List<AjAttribute> readAj5MethodAttributes(Method method, BcelMethod bMethod, ResolvedType type,
  377. ResolvedPointcutDefinition preResolvedPointcut, ISourceContext context, IMessageHandler msgHandler) {
  378. if (method.getName().startsWith(NameMangler.PREFIX)) {
  379. return Collections.emptyList(); // already dealt with by ajc...
  380. }
  381. AjAttributeMethodStruct struct = new AjAttributeMethodStruct(method, bMethod, type, context, msgHandler);
  382. Attribute[] attributes = method.getAttributes();
  383. // we remember if we found one @AJ annotation for minimal semantic error
  384. // reporting
  385. // the real reporting beeing done thru AJDT and the compiler mapping @AJ
  386. // to AjAtttribute
  387. // or thru APT
  388. //
  389. // Note: we could actually skip the whole thing if type is not itself an
  390. // @Aspect
  391. // but then we would not see any warning. We do bypass for pointcut but
  392. // not for advice since it would
  393. // be too silent.
  394. boolean hasAtAspectJAnnotation = false;
  395. boolean hasAtAspectJAnnotationMustReturnVoid = false;
  396. for (Attribute attribute : attributes) {
  397. try {
  398. if (acceptAttribute(attribute)) {
  399. RuntimeAnnos rvs = (RuntimeAnnos) attribute;
  400. hasAtAspectJAnnotationMustReturnVoid = hasAtAspectJAnnotationMustReturnVoid
  401. || handleBeforeAnnotation(rvs, struct, preResolvedPointcut);
  402. hasAtAspectJAnnotationMustReturnVoid = hasAtAspectJAnnotationMustReturnVoid
  403. || handleAfterAnnotation(rvs, struct, preResolvedPointcut);
  404. hasAtAspectJAnnotationMustReturnVoid = hasAtAspectJAnnotationMustReturnVoid
  405. || handleAfterReturningAnnotation(rvs, struct, preResolvedPointcut, bMethod);
  406. hasAtAspectJAnnotationMustReturnVoid = hasAtAspectJAnnotationMustReturnVoid
  407. || handleAfterThrowingAnnotation(rvs, struct, preResolvedPointcut, bMethod);
  408. hasAtAspectJAnnotation = hasAtAspectJAnnotation || handleAroundAnnotation(rvs, struct, preResolvedPointcut);
  409. // there can only be one RuntimeVisible bytecode attribute
  410. break;
  411. }
  412. } catch (ReturningFormalNotDeclaredInAdviceSignatureException e) {
  413. msgHandler.handleMessage(new Message(WeaverMessages.format(WeaverMessages.RETURNING_FORMAL_NOT_DECLARED_IN_ADVICE,
  414. e.getFormalName()), IMessage.ERROR, null, bMethod.getSourceLocation()));
  415. } catch (ThrownFormalNotDeclaredInAdviceSignatureException e) {
  416. msgHandler.handleMessage(new Message(WeaverMessages.format(WeaverMessages.THROWN_FORMAL_NOT_DECLARED_IN_ADVICE,
  417. e.getFormalName()), IMessage.ERROR, null, bMethod.getSourceLocation()));
  418. }
  419. }
  420. hasAtAspectJAnnotation = hasAtAspectJAnnotation || hasAtAspectJAnnotationMustReturnVoid;
  421. // semantic check - must be in an @Aspect [remove if previous block
  422. // bypassed in advance]
  423. if (hasAtAspectJAnnotation && !type.isAspect()) { // isAnnotationStyleAspect())
  424. // {
  425. msgHandler.handleMessage(new Message("Found @AspectJ annotations in a non @Aspect type '" + type.getName() + "'",
  426. IMessage.WARNING, null, type.getSourceLocation()));
  427. // go ahead
  428. }
  429. // semantic check - advice must be public
  430. if (hasAtAspectJAnnotation && !struct.method.isPublic()) {
  431. msgHandler.handleMessage(new Message("Found @AspectJ annotation on a non public advice '"
  432. + methodToString(struct.method) + "'", IMessage.ERROR, null, type.getSourceLocation()));
  433. // go ahead
  434. }
  435. // semantic check - advice must not be static
  436. if (hasAtAspectJAnnotation && struct.method.isStatic()) {
  437. msgHandler.handleMessage(MessageUtil.error("Advice cannot be declared static '" + methodToString(struct.method) + "'",
  438. type.getSourceLocation()));
  439. // new Message(
  440. // "Advice cannot be declared static '" +
  441. // methodToString(struct.method) + "'",
  442. // IMessage.ERROR,
  443. // null,
  444. // type.getSourceLocation()
  445. // )
  446. // );
  447. // go ahead
  448. }
  449. // semantic check for non around advice must return void
  450. if (hasAtAspectJAnnotationMustReturnVoid && !Type.VOID.equals(struct.method.getReturnType())) {
  451. msgHandler.handleMessage(new Message("Found @AspectJ annotation on a non around advice not returning void '"
  452. + methodToString(struct.method) + "'", IMessage.ERROR, null, type.getSourceLocation()));
  453. // go ahead
  454. }
  455. return struct.ajAttributes;
  456. }
  457. /**
  458. * Extract field level annotations and turn them into AjAttributes.
  459. *
  460. * @param field
  461. * @param type
  462. * @param context
  463. * @param msgHandler
  464. * @return list of AjAttributes, always empty for now
  465. */
  466. public static List<AjAttribute> readAj5FieldAttributes(Field field, BcelField bField, ResolvedType type,
  467. ISourceContext context, IMessageHandler msgHandler) {
  468. // Note: field annotation are for ITD and DEOW - processed at class
  469. // level directly
  470. return Collections.emptyList();
  471. }
  472. /**
  473. * Read @Aspect
  474. *
  475. * @param runtimeAnnotations
  476. * @param struct
  477. * @return true if found
  478. */
  479. private static boolean handleAspectAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeStruct struct) {
  480. AnnotationGen aspect = getAnnotation(runtimeAnnotations, AjcMemberMaker.ASPECT_ANNOTATION);
  481. if (aspect != null) {
  482. // semantic check for inheritance (only one level up)
  483. boolean extendsAspect = false;
  484. if (!"java.lang.Object".equals(struct.enclosingType.getSuperclass().getName())) {
  485. if (!struct.enclosingType.getSuperclass().isAbstract() && struct.enclosingType.getSuperclass().isAspect()) {
  486. reportError("cannot extend a concrete aspect", struct);
  487. return false;
  488. }
  489. extendsAspect = struct.enclosingType.getSuperclass().isAspect();
  490. }
  491. NameValuePair aspectPerClause = getAnnotationElement(aspect, VALUE);
  492. final PerClause perClause;
  493. if (aspectPerClause == null) {
  494. // empty value means singleton unless inherited
  495. if (!extendsAspect) {
  496. perClause = new PerSingleton();
  497. } else {
  498. perClause = new PerFromSuper(struct.enclosingType.getSuperclass().getPerClause().getKind());
  499. }
  500. } else {
  501. String perX = aspectPerClause.getValue().stringifyValue();
  502. if (perX == null || perX.length() <= 0) {
  503. perClause = new PerSingleton();
  504. } else {
  505. perClause = parsePerClausePointcut(perX, struct);
  506. }
  507. }
  508. if (perClause == null) {
  509. // could not parse it, ignore the aspect
  510. return false;
  511. } else {
  512. perClause.setLocation(struct.context, -1, -1);// struct.context.getOffset(),
  513. // struct.context.getOffset()+1);//FIXME
  514. // AVASM
  515. // Not setting version here
  516. // struct.ajAttributes.add(new AjAttribute.WeaverVersionInfo());
  517. AjAttribute.Aspect aspectAttribute = new AjAttribute.Aspect(perClause);
  518. struct.ajAttributes.add(aspectAttribute);
  519. FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0];
  520. final IScope binding;
  521. binding = new BindingScope(struct.enclosingType, struct.context, bindings);
  522. // // we can't resolve here since the perclause typically refers
  523. // to pointcuts
  524. // // defined in the aspect that we haven't told the
  525. // BcelObjectType about yet.
  526. //
  527. // perClause.resolve(binding);
  528. // so we prepare to do it later...
  529. aspectAttribute.setResolutionScope(binding);
  530. return true;
  531. }
  532. }
  533. return false;
  534. }
  535. /**
  536. * Read a perClause, returns null on failure and issue messages
  537. *
  538. * @param perClauseString like "pertarget(.....)"
  539. * @param struct for which we are parsing the per clause
  540. * @return a PerClause instance
  541. */
  542. private static PerClause parsePerClausePointcut(String perClauseString, AjAttributeStruct struct) {
  543. final String pointcutString;
  544. Pointcut pointcut = null;
  545. TypePattern typePattern = null;
  546. final PerClause perClause;
  547. if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERCFLOW.getName())) {
  548. pointcutString = PerClause.KindAnnotationPrefix.PERCFLOW.extractPointcut(perClauseString);
  549. pointcut = parsePointcut(pointcutString, struct, false);
  550. perClause = new PerCflow(pointcut, false);
  551. } else if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERCFLOWBELOW.getName())) {
  552. pointcutString = PerClause.KindAnnotationPrefix.PERCFLOWBELOW.extractPointcut(perClauseString);
  553. pointcut = parsePointcut(pointcutString, struct, false);
  554. perClause = new PerCflow(pointcut, true);
  555. } else if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERTARGET.getName())) {
  556. pointcutString = PerClause.KindAnnotationPrefix.PERTARGET.extractPointcut(perClauseString);
  557. pointcut = parsePointcut(pointcutString, struct, false);
  558. perClause = new PerObject(pointcut, false);
  559. } else if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERTHIS.getName())) {
  560. pointcutString = PerClause.KindAnnotationPrefix.PERTHIS.extractPointcut(perClauseString);
  561. pointcut = parsePointcut(pointcutString, struct, false);
  562. perClause = new PerObject(pointcut, true);
  563. } else if (perClauseString.startsWith(PerClause.KindAnnotationPrefix.PERTYPEWITHIN.getName())) {
  564. pointcutString = PerClause.KindAnnotationPrefix.PERTYPEWITHIN.extractPointcut(perClauseString);
  565. typePattern = parseTypePattern(pointcutString, struct);
  566. perClause = new PerTypeWithin(typePattern);
  567. } else if (perClauseString.equalsIgnoreCase(PerClause.SINGLETON.getName() + "()")) {
  568. perClause = new PerSingleton();
  569. } else {
  570. // could not parse the @AJ perclause - fallback to singleton and
  571. // issue an error
  572. reportError("@Aspect per clause cannot be read '" + perClauseString + "'", struct);
  573. return null;
  574. }
  575. if (!PerClause.SINGLETON.equals(perClause.getKind()) && !PerClause.PERTYPEWITHIN.equals(perClause.getKind())
  576. && pointcut == null) {
  577. // we could not parse the pointcut
  578. return null;
  579. }
  580. if (PerClause.PERTYPEWITHIN.equals(perClause.getKind()) && typePattern == null) {
  581. // we could not parse the type pattern
  582. return null;
  583. }
  584. return perClause;
  585. }
  586. /**
  587. * Read @DeclarePrecedence
  588. *
  589. * @param runtimeAnnotations
  590. * @param struct
  591. * @return true if found
  592. */
  593. private static boolean handlePrecedenceAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeStruct struct) {
  594. AnnotationGen aspect = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREPRECEDENCE_ANNOTATION);
  595. if (aspect != null) {
  596. NameValuePair precedence = getAnnotationElement(aspect, VALUE);
  597. if (precedence != null) {
  598. String precedencePattern = precedence.getValue().stringifyValue();
  599. PatternParser parser = new PatternParser(precedencePattern);
  600. DeclarePrecedence ajPrecedence = parser.parseDominates();
  601. struct.ajAttributes.add(new AjAttribute.DeclareAttribute(ajPrecedence));
  602. return true;
  603. }
  604. }
  605. return false;
  606. }
  607. // /**
  608. // * Read @DeclareImplements
  609. // *
  610. // * @param runtimeAnnotations
  611. // * @param struct
  612. // * @return true if found
  613. // */
  614. // private static boolean
  615. // handleDeclareImplementsAnnotation(RuntimeAnnotations runtimeAnnotations,
  616. // AjAttributeFieldStruct
  617. // struct) {//, ResolvedPointcutDefinition preResolvedPointcut) {
  618. // Annotation deci = getAnnotation(runtimeAnnotations,
  619. // AjcMemberMaker.DECLAREIMPLEMENTS_ANNOTATION);
  620. // if (deci != null) {
  621. // ElementNameValuePairGen deciPatternNVP = getAnnotationElement(deci,
  622. // VALUE);
  623. // String deciPattern = deciPatternNVP.getValue().stringifyValue();
  624. // if (deciPattern != null) {
  625. // TypePattern typePattern = parseTypePattern(deciPattern, struct);
  626. // ResolvedType fieldType =
  627. // UnresolvedType.forSignature(struct.field.getSignature()).resolve(struct.enclosingType.getWorld());
  628. // if (fieldType.isPrimitiveType()) {
  629. // return false;
  630. // } else if (fieldType.isInterface()) {
  631. // TypePattern parent = new
  632. // ExactTypePattern(UnresolvedType.forSignature(struct.field.getSignature()),
  633. // false, false);
  634. // parent.resolve(struct.enclosingType.getWorld());
  635. // List parents = new ArrayList(1);
  636. // parents.add(parent);
  637. // //TODO kick ISourceLocation sl = struct.bField.getSourceLocation(); ??
  638. // struct.ajAttributes.add(
  639. // new AjAttribute.DeclareAttribute(
  640. // new DeclareParents(
  641. // typePattern,
  642. // parents,
  643. // false
  644. // )
  645. // )
  646. // );
  647. // return true;
  648. // } else {
  649. // reportError("@DeclareImplements: can only be used on field whose type is an interface",
  650. // struct);
  651. // return false;
  652. // }
  653. // }
  654. // }
  655. // return false;
  656. // }
  657. private static boolean handleDeclareParentsAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeFieldStruct struct) {
  658. AnnotationGen decpAnno = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREPARENTS_ANNOTATION);
  659. if (decpAnno != null) {
  660. NameValuePair decpPatternNameValuePair = getAnnotationElement(decpAnno, VALUE);
  661. String decpPattern = decpPatternNameValuePair.getValue().stringifyValue();
  662. System.out.println("decpPatterNVP = "+decpPattern);
  663. if (decpPattern != null) {
  664. TypePattern typePattern = parseTypePattern(decpPattern, struct);
  665. ResolvedType fieldType = UnresolvedType.forSignature(struct.field.getSignature()).resolve(
  666. struct.enclosingType.getWorld());
  667. if (fieldType.isParameterizedOrRawType()) {
  668. fieldType = fieldType.getGenericType();
  669. }
  670. if (fieldType.isInterface()) {
  671. TypePattern parent = parseTypePattern(fieldType.getName(), struct);
  672. FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0];
  673. IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings);
  674. // first add the declare implements like
  675. List<TypePattern> parents = new ArrayList<TypePattern>(1);
  676. parents.add(parent);
  677. DeclareParents dp = new DeclareParents(typePattern, parents, false);
  678. dp.resolve(binding); // resolves the parent and child parts of the decp
  679. // resolve this so that we can use it for the
  680. // MethodDelegateMungers below.
  681. // eg. '@Coloured *' will change from a WildTypePattern to
  682. // an 'AnyWithAnnotationTypePattern' after this resolution
  683. typePattern = dp.getChild(); // this retrieves the resolved version
  684. // TODO kick ISourceLocation sl =
  685. // struct.bField.getSourceLocation(); ??
  686. // dp.setLocation(dp.getDeclaringType().getSourceContext(),
  687. // dp.getDeclaringType().getSourceLocation().getOffset(),
  688. // dp.getDeclaringType().getSourceLocation().getOffset());
  689. dp.setLocation(struct.context, -1, -1); // not ideal...
  690. struct.ajAttributes.add(new AjAttribute.DeclareAttribute(dp));
  691. // do we have a defaultImpl=xxx.class (ie implementation)
  692. String defaultImplClassName = null;
  693. NameValuePair defaultImplNVP = getAnnotationElement(decpAnno, "defaultImpl");
  694. if (defaultImplNVP != null) {
  695. ClassElementValue defaultImpl = (ClassElementValue) defaultImplNVP.getValue();
  696. defaultImplClassName = UnresolvedType.forSignature(defaultImpl.getClassString()).getName();
  697. if (defaultImplClassName.equals("org.aspectj.lang.annotation.DeclareParents")) {
  698. defaultImplClassName = null;
  699. } else {
  700. // check public no arg ctor
  701. ResolvedType impl = struct.enclosingType.getWorld().resolve(defaultImplClassName, false);
  702. ResolvedMember[] mm = impl.getDeclaredMethods();
  703. int implModifiers = impl.getModifiers();
  704. boolean defaultVisibilityImpl = !(Modifier.isPrivate(implModifiers)
  705. || Modifier.isProtected(implModifiers) || Modifier.isPublic(implModifiers));
  706. boolean hasNoCtorOrANoArgOne = true;
  707. ResolvedMember foundOneOfIncorrectVisibility = null;
  708. for (ResolvedMember resolvedMember : mm) {
  709. if (resolvedMember.getName().equals("<init>")) {
  710. hasNoCtorOrANoArgOne = false;
  711. if (resolvedMember.getParameterTypes().length == 0) {
  712. if (defaultVisibilityImpl) { // default visibility implementation
  713. if (resolvedMember.isPublic() || resolvedMember.isDefault()) {
  714. hasNoCtorOrANoArgOne = true;
  715. } else {
  716. foundOneOfIncorrectVisibility = resolvedMember;
  717. }
  718. } else if (Modifier.isPublic(implModifiers)) { // public
  719. // implementation
  720. if (resolvedMember.isPublic()) {
  721. hasNoCtorOrANoArgOne = true;
  722. } else {
  723. foundOneOfIncorrectVisibility = resolvedMember;
  724. }
  725. }
  726. }
  727. }
  728. if (hasNoCtorOrANoArgOne) {
  729. break;
  730. }
  731. }
  732. if (!hasNoCtorOrANoArgOne) {
  733. if (foundOneOfIncorrectVisibility != null) {
  734. reportError(
  735. "@DeclareParents: defaultImpl=\""
  736. + defaultImplClassName
  737. + "\" has a no argument constructor, but it is of incorrect visibility. It must be at least as visible as the type.",
  738. struct);
  739. } else {
  740. reportError("@DeclareParents: defaultImpl=\"" + defaultImplClassName
  741. + "\" has no public no-arg constructor", struct);
  742. }
  743. }
  744. if (!fieldType.isAssignableFrom(impl)) {
  745. reportError("@DeclareParents: defaultImpl=\"" + defaultImplClassName
  746. + "\" does not implement the interface '" + fieldType.toString() + "'", struct);
  747. }
  748. }
  749. }
  750. boolean hasAtLeastOneMethod = false;
  751. // then iterate on field interface hierarchy (not object)
  752. Iterator<ResolvedMember> methodIterator = fieldType.getMethodsIncludingIntertypeDeclarations(false, true);
  753. while (methodIterator.hasNext()) {
  754. ResolvedMember method = methodIterator.next();
  755. if (method.isAbstract()) {
  756. // moved to be detected at weave time if the target
  757. // doesnt implement the methods
  758. // if (defaultImplClassName == null) {
  759. // // non marker interface with no default impl
  760. // provided
  761. // reportError("@DeclareParents: used with a non marker interface and no defaultImpl=\"...\" provided",
  762. // struct);
  763. // return false;
  764. // }
  765. hasAtLeastOneMethod = true;
  766. // What we are saying here:
  767. // We have this method 'method' and we want to put a
  768. // forwarding method into a type that matches
  769. // typePattern that should delegate to the version
  770. // of the method in 'defaultImplClassName'
  771. // Now the method may be from a supertype but the
  772. // declaring type of the method we pass into the
  773. // type
  774. // munger is what is used to determine the type of
  775. // the field that hosts the delegate instance.
  776. // So here we create a modified method with an
  777. // alternative declaring type so that we lookup
  778. // the right field. See pr164016.
  779. MethodDelegateTypeMunger mdtm = new MethodDelegateTypeMunger(method, struct.enclosingType, defaultImplClassName, typePattern);
  780. mdtm.setFieldType(fieldType);
  781. mdtm.setSourceLocation(struct.enclosingType.getSourceLocation());
  782. struct.ajAttributes.add(new AjAttribute.TypeMunger(mdtm));
  783. }
  784. }
  785. // successful so far, we thus need a bcel type munger to have
  786. // a field hosting the mixin in the target type
  787. if (hasAtLeastOneMethod && defaultImplClassName != null) {
  788. ResolvedMember fieldHost = AjcMemberMaker.itdAtDeclareParentsField(null, fieldType, struct.enclosingType);
  789. struct.ajAttributes.add(new AjAttribute.TypeMunger(new MethodDelegateTypeMunger.FieldHostTypeMunger(
  790. fieldHost, struct.enclosingType, typePattern)));
  791. }
  792. return true;
  793. } else {
  794. reportError("@DeclareParents: can only be used on a field whose type is an interface", struct);
  795. return false;
  796. }
  797. }
  798. }
  799. return false;
  800. }
  801. /**
  802. * Return a nicely formatted method string, for example: int X.foo(java.lang.String)
  803. */
  804. public static String getMethodForMessage(AjAttributeMethodStruct methodstructure) {
  805. StringBuffer sb = new StringBuffer();
  806. sb.append("Method '");
  807. sb.append(methodstructure.method.getReturnType().toString());
  808. sb.append(" ").append(methodstructure.enclosingType).append(".").append(methodstructure.method.getName());
  809. sb.append("(");
  810. Type[] args = methodstructure.method.getArgumentTypes();
  811. if (args != null) {
  812. for (int t = 0; t < args.length; t++) {
  813. if (t > 0) {
  814. sb.append(",");
  815. }
  816. sb.append(args[t].toString());
  817. }
  818. }
  819. sb.append(")'");
  820. return sb.toString();
  821. }
  822. /**
  823. * Process any @DeclareMixin annotation.
  824. *
  825. * Example Declaration <br>
  826. *
  827. * @DeclareMixin("Foo+") public I createImpl(Object o) { return new Impl(o); }
  828. *
  829. * <br>
  830. * @param runtimeAnnotations
  831. * @param struct
  832. * @return true if found
  833. */
  834. private static boolean handleDeclareMixinAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeMethodStruct struct) {
  835. AnnotationGen declareMixinAnnotation = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREMIXIN_ANNOTATION);
  836. if (declareMixinAnnotation == null) {
  837. // No annotation found
  838. return false;
  839. }
  840. Method annotatedMethod = struct.method;
  841. World world = struct.enclosingType.getWorld();
  842. NameValuePair declareMixinPatternNameValuePair = getAnnotationElement(declareMixinAnnotation, VALUE);
  843. // declareMixinPattern could be of the form "Bar*" or "A || B" or "Foo+"
  844. String declareMixinPattern = declareMixinPatternNameValuePair.getValue().stringifyValue();
  845. TypePattern targetTypePattern = parseTypePattern(declareMixinPattern, struct);
  846. // Return value of the annotated method is the interface or class that the mixin delegate should have
  847. ResolvedType methodReturnType = UnresolvedType.forSignature(annotatedMethod.getReturnType().getSignature()).resolve(world);
  848. if (methodReturnType.isParameterizedOrRawType()) {
  849. methodReturnType = methodReturnType.getGenericType();
  850. }
  851. if (methodReturnType.isPrimitiveType()) {
  852. reportError(getMethodForMessage(struct) + ": factory methods for a mixin cannot return void or a primitive type",
  853. struct);
  854. return false;
  855. }
  856. if (annotatedMethod.getArgumentTypes().length > 1) {
  857. reportError(getMethodForMessage(struct) + ": factory methods for a mixin can take a maximum of one parameter", struct);
  858. return false;
  859. }
  860. // The set of interfaces to be mixed in is either:
  861. // supplied as a list in the 'Class[] interfaces' value in the annotation value
  862. // supplied as just the interface return value of the annotated method
  863. // supplied as just the class return value of the annotated method
  864. NameValuePair interfaceListSpecified = getAnnotationElement(declareMixinAnnotation, "interfaces");
  865. List<TypePattern> newParents = new ArrayList<TypePattern>(1);
  866. List<ResolvedType> newInterfaceTypes = new ArrayList<ResolvedType>(1);
  867. if (interfaceListSpecified != null) {
  868. ArrayElementValue arrayOfInterfaceTypes = (ArrayElementValue) interfaceListSpecified.getValue();
  869. int numberOfTypes = arrayOfInterfaceTypes.getElementValuesArraySize();
  870. ElementValue[] theTypes = arrayOfInterfaceTypes.getElementValuesArray();
  871. for (int i = 0; i < numberOfTypes; i++) {
  872. ClassElementValue interfaceType = (ClassElementValue) theTypes[i];
  873. // Check: needs to be resolvable
  874. // TODO crappy replace required
  875. ResolvedType ajInterfaceType = UnresolvedType.forSignature(interfaceType.getClassString().replace("/", "."))
  876. .resolve(world);
  877. if (ajInterfaceType.isMissing() || !ajInterfaceType.isInterface()) {
  878. reportError(
  879. "Types listed in the 'interfaces' DeclareMixin annotation value must be valid interfaces. This is invalid: "
  880. + ajInterfaceType.getName(), struct); // TODO better error location, use the method position
  881. return false;
  882. }
  883. if (!ajInterfaceType.isAssignableFrom(methodReturnType)) {
  884. reportError(getMethodForMessage(struct) + ": factory method does not return something that implements '"
  885. + ajInterfaceType.getName() + "'", struct);
  886. return false;
  887. }
  888. newInterfaceTypes.add(ajInterfaceType);
  889. // Checking that it is a superinterface of the methods return value is done at weave time
  890. TypePattern newParent = parseTypePattern(ajInterfaceType.getName(), struct);
  891. newParents.add(newParent);
  892. }
  893. } else {
  894. if (methodReturnType.isClass()) {
  895. reportError(
  896. getMethodForMessage(struct)
  897. + ": factory methods for a mixin must either return an interface type or specify interfaces in the annotation and return a class",
  898. struct);
  899. return false;
  900. }
  901. // Use the method return type: this might be a class or an interface
  902. TypePattern newParent = parseTypePattern(methodReturnType.getName(), struct);
  903. newInterfaceTypes.add(methodReturnType);
  904. newParents.add(newParent);
  905. }
  906. if (newParents.size() == 0) {
  907. // Warning: did they foolishly put @DeclareMixin(value="Bar+",interfaces={})
  908. // TODO output warning
  909. return false;
  910. }
  911. // Create the declare parents that will add the interfaces to matching targets
  912. FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0];
  913. IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings);
  914. // how do we mark this as a decp due to decmixin?
  915. DeclareParents dp = new DeclareParentsMixin(targetTypePattern, newParents);
  916. dp.resolve(binding);
  917. targetTypePattern = dp.getChild();
  918. dp.setLocation(struct.context, -1, -1); // not ideal...
  919. struct.ajAttributes.add(new AjAttribute.DeclareAttribute(dp));
  920. // The factory method for building the implementation is the
  921. // one attached to the annotation:
  922. // Method implementationFactory = struct.method;
  923. boolean hasAtLeastOneMethod = false;
  924. for (ResolvedType typeForDelegation : newInterfaceTypes) {
  925. // TODO check for overlapping interfaces. Eg. A implements I, I extends J - if they specify interfaces={I,J} we dont
  926. // want to do any methods twice
  927. ResolvedMember[] methods = typeForDelegation.getMethodsWithoutIterator(true, false, false).toArray(
  928. new ResolvedMember[0]);
  929. for (ResolvedMember resolvedMember : methods) {
  930. ResolvedMember method = resolvedMember;
  931. if (method.isAbstract()) {
  932. hasAtLeastOneMethod = true;
  933. if (method.hasBackingGenericMember()) {
  934. method = method.getBackingGenericMember();
  935. }
  936. MethodDelegateTypeMunger mdtm = new MethodDelegateTypeMunger(method, struct.enclosingType, "",
  937. targetTypePattern, struct.method.getName(), struct.method.getSignature());
  938. mdtm.setFieldType(methodReturnType);
  939. mdtm.setSourceLocation(struct.enclosingType.getSourceLocation());
  940. struct.ajAttributes.add(new AjAttribute.TypeMunger(mdtm));
  941. }
  942. }
  943. }
  944. // if any method delegate was created then a field to hold the delegate instance must also be added
  945. if (hasAtLeastOneMethod) {
  946. ResolvedMember fieldHost = AjcMemberMaker.itdAtDeclareParentsField(null, methodReturnType, struct.enclosingType);
  947. struct.ajAttributes.add(new AjAttribute.TypeMunger(new MethodDelegateTypeMunger.FieldHostTypeMunger(fieldHost,
  948. struct.enclosingType, targetTypePattern)));
  949. }
  950. return true;
  951. }
  952. /**
  953. * Read @Before
  954. *
  955. * @param runtimeAnnotations
  956. * @param struct
  957. * @return true if found
  958. */
  959. private static boolean handleBeforeAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeMethodStruct struct,
  960. ResolvedPointcutDefinition preResolvedPointcut) {
  961. AnnotationGen before = getAnnotation(runtimeAnnotations, AjcMemberMaker.BEFORE_ANNOTATION);
  962. if (before != null) {
  963. NameValuePair beforeAdvice = getAnnotationElement(before, VALUE);
  964. if (beforeAdvice != null) {
  965. // this/target/args binding
  966. String argumentNames = getArgNamesValue(before);
  967. if (argumentNames != null) {
  968. struct.unparsedArgumentNames = argumentNames;
  969. }
  970. FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0];
  971. try {
  972. bindings = extractBindings(struct);
  973. } catch (UnreadableDebugInfoException unreadableDebugInfoException) {
  974. return false;
  975. }
  976. IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings);
  977. // joinpoint, staticJoinpoint binding
  978. int extraArgument = extractExtraArgument(struct.method);
  979. Pointcut pc = null;
  980. if (preResolvedPointcut != null) {
  981. pc = preResolvedPointcut.getPointcut();
  982. // pc.resolve(binding);
  983. } else {
  984. pc = parsePointcut(beforeAdvice.getValue().stringifyValue(), struct, false);
  985. if (pc == null) {
  986. return false;// parse error
  987. }
  988. pc = pc.resolve(binding);
  989. }
  990. setIgnoreUnboundBindingNames(pc, bindings);
  991. ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(),
  992. struct.bMethod.getDeclarationOffset());
  993. struct.ajAttributes.add(new AjAttribute.AdviceAttribute(AdviceKind.Before, pc, extraArgument, sl.getOffset(), sl
  994. .getOffset() + 1,// FIXME AVASM
  995. struct.context));
  996. return true;
  997. }
  998. }
  999. return false;
  1000. }
  1001. /**
  1002. * Read @After
  1003. *
  1004. * @param runtimeAnnotations
  1005. * @param struct
  1006. * @return true if found
  1007. */
  1008. private static boolean handleAfterAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeMethodStruct struct,
  1009. ResolvedPointcutDefinition preResolvedPointcut) {
  1010. AnnotationGen after = getAnnotation(runtimeAnnotations, AjcMemberMaker.AFTER_ANNOTATION);
  1011. if (after != null) {
  1012. NameValuePair afterAdvice = getAnnotationElement(after, VALUE);
  1013. if (afterAdvice != null) {
  1014. // this/target/args binding
  1015. FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0];
  1016. String argumentNames = getArgNamesValue(after);
  1017. if (argumentNames != null) {
  1018. struct.unparsedArgumentNames = argumentNames;
  1019. }
  1020. try {
  1021. bindings = extractBindings(struct);
  1022. } catch (UnreadableDebugInfoException unreadableDebugInfoException) {
  1023. return false;
  1024. }
  1025. IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings);
  1026. // joinpoint, staticJoinpoint binding
  1027. int extraArgument = extractExtraArgument(struct.method);
  1028. Pointcut pc = null;
  1029. if (preResolvedPointcut != null) {
  1030. pc = preResolvedPointcut.getPointcut();
  1031. } else {
  1032. pc = parsePointcut(afterAdvice.getValue().stringifyValue(), struct, false);
  1033. if (pc == null) {
  1034. return false;// parse error
  1035. }
  1036. pc.resolve(binding);
  1037. }
  1038. setIgnoreUnboundBindingNames(pc, bindings);
  1039. ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(),
  1040. struct.bMethod.getDeclarationOffset());
  1041. struct.ajAttributes.add(new AjAttribute.AdviceAttribute(AdviceKind.After, pc, extraArgument, sl.getOffset(), sl
  1042. .getOffset() + 1,// FIXME AVASM
  1043. struct.context));
  1044. return true;
  1045. }
  1046. }
  1047. return false;
  1048. }
  1049. /**
  1050. * Read @AfterReturning
  1051. *
  1052. * @param runtimeAnnotations
  1053. * @param struct
  1054. * @return true if found
  1055. */
  1056. private static boolean handleAfterReturningAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeMethodStruct struct,
  1057. ResolvedPointcutDefinition preResolvedPointcut, BcelMethod owningMethod)
  1058. throws ReturningFormalNotDeclaredInAdviceSignatureException {
  1059. AnnotationGen after = getAnnotation(runtimeAnnotations, AjcMemberMaker.AFTERRETURNING_ANNOTATION);
  1060. if (after != null) {
  1061. NameValuePair annValue = getAnnotationElement(after, VALUE);
  1062. NameValuePair annPointcut = getAnnotationElement(after, POINTCUT);
  1063. NameValuePair annReturned = getAnnotationElement(after, RETURNING);
  1064. // extract the pointcut and returned type/binding - do some checks
  1065. String pointcut = null;
  1066. String returned = null;
  1067. if ((annValue != null && annPointcut != null) || (annValue == null && annPointcut == null)) {
  1068. reportError("@AfterReturning: either 'value' or 'poincut' must be provided, not both", struct);
  1069. return false;
  1070. }
  1071. if (annValue != null) {
  1072. pointcut = annValue.getValue().stringifyValue();
  1073. } else {
  1074. pointcut = annPointcut.getValue().stringifyValue();
  1075. }
  1076. if (isNullOrEmpty(pointcut)) {
  1077. reportError("@AfterReturning: either 'value' or 'poincut' must be provided, not both", struct);
  1078. return false;
  1079. }
  1080. if (annReturned != null) {
  1081. returned = annReturned.getValue().stringifyValue();
  1082. if (isNullOrEmpty(returned)) {
  1083. returned = null;
  1084. } else {
  1085. // check that thrownFormal exists as the last parameter in
  1086. // the advice
  1087. String[] pNames = owningMethod.getParameterNames();
  1088. if (pNames == null || pNames.length == 0 || !Arrays.asList(pNames).contains(returned)) {
  1089. throw new ReturningFormalNotDeclaredInAdviceSignatureException(returned);
  1090. }
  1091. }
  1092. }
  1093. String argumentNames = getArgNamesValue(after);
  1094. if (argumentNames != null) {
  1095. struct.unparsedArgumentNames = argumentNames;
  1096. }
  1097. // this/target/args binding
  1098. // exclude the return binding from the pointcut binding since it is
  1099. // an extraArg binding
  1100. FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0];
  1101. try {
  1102. bindings = (returned == null ? extractBindings(struct) : extractBindings(struct, returned));
  1103. } catch (UnreadableDebugInfoException unreadableDebugInfoException) {
  1104. return false;
  1105. }
  1106. IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings);
  1107. // joinpoint, staticJoinpoint binding
  1108. int extraArgument = extractExtraArgument(struct.method);
  1109. // return binding
  1110. if (returned != null) {
  1111. extraArgument |= Advice.ExtraArgument;
  1112. }
  1113. Pointcut pc = null;
  1114. if (preResolvedPointcut != null) {
  1115. pc = preResolvedPointcut.getPointcut();
  1116. } else {
  1117. pc = parsePointcut(pointcut, struct, false);
  1118. if (pc == null) {
  1119. return false;// parse error
  1120. }
  1121. pc.resolve(binding);
  1122. }
  1123. setIgnoreUnboundBindingNames(pc, bindings);
  1124. ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(),
  1125. struct.bMethod.getDeclarationOffset());
  1126. struct.ajAttributes.add(new AjAttribute.AdviceAttribute(AdviceKind.AfterReturning, pc, extraArgument, sl.getOffset(),
  1127. sl.getOffset() + 1,// FIXME AVASM
  1128. struct.context));
  1129. return true;
  1130. }
  1131. return false;
  1132. }
  1133. /**
  1134. * Read @AfterThrowing
  1135. *
  1136. * @param runtimeAnnotations
  1137. * @param struct
  1138. * @return true if found
  1139. */
  1140. private static boolean handleAfterThrowingAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeMethodStruct struct,
  1141. ResolvedPointcutDefinition preResolvedPointcut, BcelMethod owningMethod)
  1142. throws ThrownFormalNotDeclaredInAdviceSignatureException {
  1143. AnnotationGen after = getAnnotation(runtimeAnnotations, AjcMemberMaker.AFTERTHROWING_ANNOTATION);
  1144. if (after != null) {
  1145. NameValuePair annValue = getAnnotationElement(after, VALUE);
  1146. NameValuePair annPointcut = getAnnotationElement(after, POINTCUT);
  1147. NameValuePair annThrown = getAnnotationElement(after, THROWING);
  1148. // extract the pointcut and throwned type/binding - do some checks
  1149. String pointcut = null;
  1150. String thrownFormal = null;
  1151. if ((annValue != null && annPointcut != null) || (annValue == null && annPointcut == null)) {
  1152. reportError("@AfterThrowing: either 'value' or 'poincut' must be provided, not both", struct);
  1153. return false;
  1154. }
  1155. if (annValue != null) {
  1156. pointcut = annValue.getValue().stringifyValue();
  1157. } else {
  1158. pointcut = annPointcut.getValue().stringifyValue();
  1159. }
  1160. if (isNullOrEmpty(pointcut)) {
  1161. reportError("@AfterThrowing: either 'value' or 'poincut' must be provided, not both", struct);
  1162. return false;
  1163. }
  1164. if (annThrown != null) {
  1165. thrownFormal = annThrown.getValue().stringifyValue();
  1166. if (isNullOrEmpty(thrownFormal)) {
  1167. thrownFormal = null;
  1168. } else {
  1169. // check that thrownFormal exists as the last parameter in
  1170. // the advice
  1171. String[] pNames = owningMethod.getParameterNames();
  1172. if (pNames == null || pNames.length == 0 || !Arrays.asList(pNames).contains(thrownFormal)) {
  1173. throw new ThrownFormalNotDeclaredInAdviceSignatureException(thrownFormal);
  1174. }
  1175. }
  1176. }
  1177. String argumentNames = getArgNamesValue(after);
  1178. if (argumentNames != null) {
  1179. struct.unparsedArgumentNames = argumentNames;
  1180. }
  1181. // this/target/args binding
  1182. // exclude the throwned binding from the pointcut binding since it
  1183. // is an extraArg binding
  1184. FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0];
  1185. try {
  1186. bindings = (thrownFormal == null ? extractBindings(struct) : extractBindings(struct, thrownFormal));
  1187. } catch (UnreadableDebugInfoException unreadableDebugInfoException) {
  1188. return false;
  1189. }
  1190. IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings);
  1191. // joinpoint, staticJoinpoint binding
  1192. int extraArgument = extractExtraArgument(struct.method);
  1193. // return binding
  1194. if (thrownFormal != null) {
  1195. extraArgument |= Advice.ExtraArgument;
  1196. }
  1197. Pointcut pc = null;
  1198. if (preResolvedPointcut != null) {
  1199. pc = preResolvedPointcut.getPointcut();
  1200. } else {
  1201. pc = parsePointcut(pointcut, struct, false);
  1202. if (pc == null) {
  1203. return false;// parse error
  1204. }
  1205. pc.resolve(binding);
  1206. }
  1207. setIgnoreUnboundBindingNames(pc, bindings);
  1208. ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(),
  1209. struct.bMethod.getDeclarationOffset());
  1210. struct.ajAttributes.add(new AjAttribute.AdviceAttribute(AdviceKind.AfterThrowing, pc, extraArgument, sl.getOffset(), sl
  1211. .getOffset() + 1, struct.context));
  1212. return true;
  1213. }
  1214. return false;
  1215. }
  1216. /**
  1217. * Read @Around
  1218. *
  1219. * @param runtimeAnnotations
  1220. * @param struct
  1221. * @return true if found
  1222. */
  1223. private static boolean handleAroundAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeMethodStruct struct,
  1224. ResolvedPointcutDefinition preResolvedPointcut) {
  1225. AnnotationGen around = getAnnotation(runtimeAnnotations, AjcMemberMaker.AROUND_ANNOTATION);
  1226. if (around != null) {
  1227. NameValuePair aroundAdvice = getAnnotationElement(around, VALUE);
  1228. if (aroundAdvice != null) {
  1229. // this/target/args binding
  1230. String argumentNames = getArgNamesValue(around);
  1231. if (argumentNames != null) {
  1232. struct.unparsedArgumentNames = argumentNames;
  1233. }
  1234. FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0];
  1235. try {
  1236. bindings = extractBindings(struct);
  1237. } catch (UnreadableDebugInfoException unreadableDebugInfoException) {
  1238. return false;
  1239. }
  1240. IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings);
  1241. // joinpoint, staticJoinpoint binding
  1242. int extraArgument = extractExtraArgument(struct.method);
  1243. Pointcut pc = null;
  1244. if (preResolvedPointcut != null) {
  1245. pc = preResolvedPointcut.getPointcut();
  1246. } else {
  1247. pc = parsePointcut(aroundAdvice.getValue().stringifyValue(), struct, false);
  1248. if (pc == null) {
  1249. return false;// parse error
  1250. }
  1251. pc.resolve(binding);
  1252. }
  1253. setIgnoreUnboundBindingNames(pc, bindings);
  1254. ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(),
  1255. struct.bMethod.getDeclarationOffset());
  1256. struct.ajAttributes.add(new AjAttribute.AdviceAttribute(AdviceKind.Around, pc, extraArgument, sl.getOffset(), sl
  1257. .getOffset() + 1,// FIXME AVASM
  1258. struct.context));
  1259. return true;
  1260. }
  1261. }
  1262. return false;
  1263. }
  1264. /**
  1265. * Read @Pointcut and handle the resolving in a lazy way to deal with pointcut references
  1266. *
  1267. * @param runtimeAnnotations
  1268. * @param struct
  1269. * @return true if a pointcut was handled
  1270. */
  1271. private static boolean handlePointcutAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeMethodStruct struct) {
  1272. AnnotationGen pointcut = getAnnotation(runtimeAnnotations, AjcMemberMaker.POINTCUT_ANNOTATION);
  1273. if (pointcut == null) {
  1274. return false;
  1275. }
  1276. NameValuePair pointcutExpr = getAnnotationElement(pointcut, VALUE);
  1277. // semantic check: the method must return void, or be
  1278. // "public static boolean" for if() support
  1279. if (!(Type.VOID.equals(struct.method.getReturnType()) || (Type.BOOLEAN.equals(struct.method.getReturnType())
  1280. && struct.method.isStatic() && struct.method.isPublic()))) {
  1281. reportWarning("Found @Pointcut on a method not returning 'void' or not 'public static boolean'", struct);
  1282. // no need to stop
  1283. }
  1284. // semantic check: the method must not throw anything
  1285. if (struct.method.getExceptionTable() != null) {
  1286. reportWarning("Found @Pointcut on a method throwing exception", struct);
  1287. // no need to stop
  1288. }
  1289. String argumentNames = getArgNamesValue(pointcut);
  1290. if (argumentNames != null) {
  1291. struct.unparsedArgumentNames = argumentNames;
  1292. }
  1293. // this/target/args binding
  1294. final IScope binding;
  1295. try {
  1296. if (struct.method.isAbstract()) {
  1297. binding = null;
  1298. } else {
  1299. binding = new BindingScope(struct.enclosingType, struct.context, extractBindings(struct));
  1300. }
  1301. } catch (UnreadableDebugInfoException e) {
  1302. return false;
  1303. }
  1304. UnresolvedType[] argumentTypes = new UnresolvedType[struct.method.getArgumentTypes().length];
  1305. for (int i = 0; i < argumentTypes.length; i++) {
  1306. argumentTypes[i] = UnresolvedType.forSignature(struct.method.getArgumentTypes()[i].getSignature());
  1307. }
  1308. Pointcut pc = null;
  1309. if (struct.method.isAbstract()) {
  1310. if ((pointcutExpr != null && isNullOrEmpty(pointcutExpr.getValue().stringifyValue())) || pointcutExpr == null) {
  1311. // abstract pointcut
  1312. // leave pc = null
  1313. } else {
  1314. reportError("Found defined @Pointcut on an abstract method", struct);
  1315. return false;// stop
  1316. }
  1317. } else {
  1318. if (pointcutExpr == null || isNullOrEmpty(pointcutExpr.getValue().stringifyValue())) {
  1319. // the matches nothing pointcut (125475/125480) - perhaps not as
  1320. // cleanly supported as it could be.
  1321. } else {
  1322. // if (pointcutExpr != null) {
  1323. // use a LazyResolvedPointcutDefinition so that the pointcut is
  1324. // resolved lazily
  1325. // since for it to be resolved, we will need other pointcuts to
  1326. // be registered as well
  1327. pc = parsePointcut(pointcutExpr.getValue().stringifyValue(), struct, true);
  1328. if (pc == null) {
  1329. return false;// parse error
  1330. }
  1331. pc.setLocation(struct.context, -1, -1);// FIXME AVASM !! bMethod
  1332. // is null here..
  1333. // } else {
  1334. // reportError("Found undefined @Pointcut on a non-abstract method",
  1335. // struct);
  1336. // return false;
  1337. // }
  1338. }
  1339. }
  1340. // do not resolve binding now but lazily
  1341. struct.ajAttributes.add(new AjAttribute.PointcutDeclarationAttribute(new LazyResolvedPointcutDefinition(
  1342. struct.enclosingType, struct.method.getModifiers(), struct.method.getName(), argumentTypes, UnresolvedType
  1343. .forSignature(struct.method.getReturnType().getSignature()), pc,// can
  1344. // be
  1345. // null
  1346. // for
  1347. // abstract
  1348. // pointcut
  1349. binding // can be null for abstract pointcut
  1350. )));
  1351. return true;
  1352. }
  1353. /**
  1354. * Read @DeclareError, @DeclareWarning
  1355. *
  1356. * @param runtimeAnnotations
  1357. * @param struct
  1358. * @return true if found
  1359. */
  1360. private static boolean handleDeclareErrorOrWarningAnnotation(AsmManager model, RuntimeAnnos runtimeAnnotations,
  1361. AjAttributeFieldStruct struct) {
  1362. AnnotationGen error = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREERROR_ANNOTATION);
  1363. boolean hasError = false;
  1364. if (error != null) {
  1365. NameValuePair declareError = getAnnotationElement(error, VALUE);
  1366. if (declareError != null) {
  1367. if (!STRING_DESC.equals(struct.field.getSignature()) || struct.field.getConstantValue() == null) {
  1368. reportError("@DeclareError used on a non String constant field", struct);
  1369. return false;
  1370. }
  1371. Pointcut pc = parsePointcut(declareError.getValue().stringifyValue(), struct, false);
  1372. if (pc == null) {
  1373. hasError = false;// cannot parse pointcut
  1374. } else {
  1375. DeclareErrorOrWarning deow = new DeclareErrorOrWarning(true, pc, struct.field.getConstantValue().toString());
  1376. setDeclareErrorOrWarningLocation(model, deow, struct);
  1377. struct.ajAttributes.add(new AjAttribute.DeclareAttribute(deow));
  1378. hasError = true;
  1379. }
  1380. }
  1381. }
  1382. AnnotationGen warning = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREWARNING_ANNOTATION);
  1383. boolean hasWarning = false;
  1384. if (warning != null) {
  1385. NameValuePair declareWarning = getAnnotationElement(warning, VALUE);
  1386. if (declareWarning != null) {
  1387. if (!STRING_DESC.equals(struct.field.getSignature()) || struct.field.getConstantValue() == null) {
  1388. reportError("@DeclareWarning used on a non String constant field", struct);
  1389. return false;
  1390. }
  1391. Pointcut pc = parsePointcut(declareWarning.getValue().stringifyValue(), struct, false);
  1392. if (pc == null) {
  1393. hasWarning = false;// cannot parse pointcut
  1394. } else {
  1395. DeclareErrorOrWarning deow = new DeclareErrorOrWarning(false, pc, struct.field.getConstantValue().toString());
  1396. setDeclareErrorOrWarningLocation(model, deow, struct);
  1397. struct.ajAttributes.add(new AjAttribute.DeclareAttribute(deow));
  1398. return hasWarning = true;
  1399. }
  1400. }
  1401. }
  1402. return hasError || hasWarning;
  1403. }
  1404. /**
  1405. * Sets the location for the declare error / warning using the corresponding IProgramElement in the structure model. This will
  1406. * only fix bug 120356 if compiled with -emacssym, however, it does mean that the cross references view in AJDT will show the
  1407. * correct information.
  1408. *
  1409. * Other possibilities for fix: 1. using the information in ajcDeclareSoft (if this is set correctly) which will fix the problem
  1410. * if compiled with ajc but not if compiled with javac. 2. creating an AjAttribute called FieldDeclarationLineNumberAttribute
  1411. * (much like MethodDeclarationLineNumberAttribute) which we can ask for the offset. This will again only fix bug 120356 when
  1412. * compiled with ajc.
  1413. *
  1414. * @param deow
  1415. * @param struct
  1416. */
  1417. private static void setDeclareErrorOrWarningLocation(AsmManager model, DeclareErrorOrWarning deow, AjAttributeFieldStruct struct) {
  1418. IHierarchy top = (model == null ? null : model.getHierarchy());
  1419. if (top != null && top.getRoot() != null) {
  1420. IProgramElement ipe = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.FIELD, struct.field.getName());
  1421. if (ipe != null && ipe.getSourceLocation() != null) {
  1422. ISourceLocation sourceLocation = ipe.getSourceLocation();
  1423. int start = sourceLocation.getOffset();
  1424. int end = start + struct.field.getName().length();
  1425. deow.setLocation(struct.context, start, end);
  1426. return;
  1427. }
  1428. }
  1429. deow.setLocation(struct.context, -1, -1);
  1430. }
  1431. /**
  1432. * Returns a readable representation of a method. Method.toString() is not suitable.
  1433. *
  1434. * @param method
  1435. * @return a readable representation of a method
  1436. */
  1437. private static String methodToString(Method method) {
  1438. StringBuffer sb = new StringBuffer();
  1439. sb.append(method.getName());
  1440. sb.append(method.getSignature());
  1441. return sb.toString();
  1442. }
  1443. /**
  1444. * Build the bindings for a given method (pointcut / advice)
  1445. *
  1446. * @param struct
  1447. * @return null if no debug info is available
  1448. */
  1449. private static FormalBinding[] extractBindings(AjAttributeMethodStruct struct) throws UnreadableDebugInfoException {
  1450. Method method = struct.method;
  1451. String[] argumentNames = struct.getArgumentNames();
  1452. // assert debug info was here
  1453. if (argumentNames.length != method.getArgumentTypes().length) {
  1454. reportError(
  1455. "Cannot read debug info for @Aspect to handle formal binding in pointcuts (please compile with 'javac -g' or '<javac debug='true'.../>' in Ant)",
  1456. struct);
  1457. throw new UnreadableDebugInfoException();
  1458. }
  1459. List<FormalBinding> bindings = new ArrayList<FormalBinding>();
  1460. for (int i = 0; i < argumentNames.length; i++) {
  1461. String argumentName = argumentNames[i];
  1462. UnresolvedType argumentType = UnresolvedType.forSignature(method.getArgumentTypes()[i].getSignature());
  1463. // do not bind JoinPoint / StaticJoinPoint /
  1464. // EnclosingStaticJoinPoint
  1465. // TODO solve me : this means that the JP/SJP/ESJP cannot appear as
  1466. // binding
  1467. // f.e. when applying advice on advice etc
  1468. if ((AjcMemberMaker.TYPEX_JOINPOINT.equals(argumentType)
  1469. || AjcMemberMaker.TYPEX_PROCEEDINGJOINPOINT.equals(argumentType)
  1470. || AjcMemberMaker.TYPEX_STATICJOINPOINT.equals(argumentType)
  1471. || AjcMemberMaker.TYPEX_ENCLOSINGSTATICJOINPOINT.equals(argumentType) || AjcMemberMaker.AROUND_CLOSURE_TYPE
  1472. .equals(argumentType))) {
  1473. // continue;// skip
  1474. bindings.add(new FormalBinding.ImplicitFormalBinding(argumentType, argumentName, i));
  1475. } else {
  1476. bindings.add(new FormalBinding(argumentType, argumentName, i));
  1477. }
  1478. }
  1479. return bindings.toArray(new FormalBinding[] {});
  1480. }
  1481. // FIXME alex deal with exclude index
  1482. private static FormalBinding[] extractBindings(AjAttributeMethodStruct struct, String excludeFormal)
  1483. throws UnreadableDebugInfoException {
  1484. FormalBinding[] bindings = extractBindings(struct);
  1485. // int excludeIndex = -1;
  1486. for (int i = 0; i < bindings.length; i++) {
  1487. FormalBinding binding = bindings[i];
  1488. if (binding.getName().equals(excludeFormal)) {
  1489. // excludeIndex = i;
  1490. bindings[i] = new FormalBinding.ImplicitFormalBinding(binding.getType(), binding.getName(), binding.getIndex());
  1491. break;
  1492. }
  1493. }
  1494. return bindings;
  1495. //
  1496. // if (excludeIndex >= 0) {
  1497. // FormalBinding[] bindingsFiltered = new
  1498. // FormalBinding[bindings.length-1];
  1499. // int k = 0;
  1500. // for (int i = 0; i < bindings.length; i++) {
  1501. // if (i == excludeIndex) {
  1502. // ;
  1503. // } else {
  1504. // bindingsFiltered[k] = new FormalBinding(bindings[i].getType(),
  1505. // bindings[i].getName(), k);
  1506. // k++;
  1507. // }
  1508. // }
  1509. // return bindingsFiltered;
  1510. // } else {
  1511. // return bindings;
  1512. // }
  1513. }
  1514. /**
  1515. * Compute the flag for the xxxJoinPoint extra argument
  1516. *
  1517. * @param method
  1518. * @return extra arg flag
  1519. */
  1520. private static int extractExtraArgument(Method method) {
  1521. Type[] methodArgs = method.getArgumentTypes();
  1522. String[] sigs = new String[methodArgs.length];
  1523. for (int i = 0; i < methodArgs.length; i++) {
  1524. sigs[i] = methodArgs[i].getSignature();
  1525. }
  1526. return extractExtraArgument(sigs);
  1527. }
  1528. /**
  1529. * Compute the flag for the xxxJoinPoint extra argument
  1530. *
  1531. * @param argumentSignatures
  1532. * @return extra arg flag
  1533. */
  1534. public static int extractExtraArgument(String[] argumentSignatures) {
  1535. int extraArgument = 0;
  1536. for (String argumentSignature : argumentSignatures) {
  1537. if (AjcMemberMaker.TYPEX_JOINPOINT.getSignature().equals(argumentSignature)) {
  1538. extraArgument |= Advice.ThisJoinPoint;
  1539. } else if (AjcMemberMaker.TYPEX_PROCEEDINGJOINPOINT.getSignature().equals(argumentSignature)) {
  1540. extraArgument |= Advice.ThisJoinPoint;
  1541. } else if (AjcMemberMaker.TYPEX_STATICJOINPOINT.getSignature().equals(argumentSignature)) {
  1542. extraArgument |= Advice.ThisJoinPointStaticPart;
  1543. } else if (AjcMemberMaker.TYPEX_ENCLOSINGSTATICJOINPOINT.getSignature().equals(argumentSignature)) {
  1544. extraArgument |= Advice.ThisEnclosingJoinPointStaticPart;
  1545. }
  1546. }
  1547. return extraArgument;
  1548. }
  1549. /**
  1550. * Returns the runtime (RV/RIV) annotation of type annotationType or null if no such annotation
  1551. *
  1552. * @param rvs
  1553. * @param annotationType
  1554. * @return annotation
  1555. */
  1556. private static AnnotationGen getAnnotation(RuntimeAnnos rvs, UnresolvedType annotationType) {
  1557. final String annotationTypeName = annotationType.getName();
  1558. for (AnnotationGen rv : rvs.getAnnotations()) {
  1559. if (annotationTypeName.equals(rv.getTypeName())) {
  1560. return rv;
  1561. }
  1562. }
  1563. return null;
  1564. }
  1565. /**
  1566. * Returns the value of a given element of an annotation or null if not found Caution: Does not handles default value.
  1567. *
  1568. * @param annotation
  1569. * @param elementName
  1570. * @return annotation NVP
  1571. */
  1572. private static NameValuePair getAnnotationElement(AnnotationGen annotation, String elementName) {
  1573. for (NameValuePair element : annotation.getValues()) {
  1574. if (elementName.equals(element.getNameString())) {
  1575. return element;
  1576. }
  1577. }
  1578. return null;
  1579. }
  1580. /**
  1581. * Return the argNames set for an annotation or null if it is not specified.
  1582. */
  1583. private static String getArgNamesValue(AnnotationGen anno) {
  1584. List<NameValuePair> elements = anno.getValues();
  1585. for (NameValuePair element : elements) {
  1586. if (ARGNAMES.equals(element.getNameString())) {
  1587. return element.getValue().stringifyValue();
  1588. }
  1589. }
  1590. return null;
  1591. }
  1592. private static String lastbit(String fqname) {
  1593. int i = fqname.lastIndexOf(".");
  1594. if (i == -1) {
  1595. return fqname;
  1596. } else {
  1597. return fqname.substring(i + 1);
  1598. }
  1599. }
  1600. /**
  1601. * Extract the method argument names. First we try the debug info attached to the method (the LocalVariableTable) - if we cannot
  1602. * find that we look to use the argNames value that may have been supplied on the associated annotation. If that fails we just
  1603. * don't know and return an empty string.
  1604. *
  1605. * @param method
  1606. * @param argNamesFromAnnotation
  1607. * @param methodStruct
  1608. * @return method argument names
  1609. */
  1610. private static String[] getMethodArgumentNames(Method method, String argNamesFromAnnotation,
  1611. AjAttributeMethodStruct methodStruct) {
  1612. if (method.getArgumentTypes().length == 0) {
  1613. return EMPTY_STRINGS;
  1614. }
  1615. final int startAtStackIndex = method.isStatic() ? 0 : 1;
  1616. final List<MethodArgument> arguments = new ArrayList<MethodArgument>();
  1617. LocalVariableTable lt = method.getLocalVariableTable();
  1618. if (lt != null) {
  1619. LocalVariable[] lvt = lt.getLocalVariableTable();
  1620. for (LocalVariable localVariable : lvt) {
  1621. if (localVariable != null) { // pr348488
  1622. if (localVariable.getStartPC() == 0) {
  1623. if (localVariable.getIndex() >= startAtStackIndex) {
  1624. arguments.add(new MethodArgument(localVariable.getName(), localVariable.getIndex()));
  1625. }
  1626. }
  1627. } else {
  1628. String typename = (methodStruct.enclosingType != null ? methodStruct.enclosingType.getName() : "");
  1629. System.err.println("AspectJ: 348488 debug: unusual local variable table for method " + typename + "."
  1630. + method.getName());
  1631. }
  1632. }
  1633. if (arguments.size() == 0) {
  1634. // The local variable table is causing us trouble, try the annotation value
  1635. // See 539121 for a jacoco variant of the cobertura issue below
  1636. if (argNamesFromAnnotation != null) {
  1637. String[] argNames = extractArgNamesFromAnnotationValue(method, argNamesFromAnnotation, methodStruct);
  1638. if (argNames.length != 0) {
  1639. return argNames;
  1640. }
  1641. }
  1642. // could be cobertura code where some extra bytecode has been stuffed in at the start of the method
  1643. // but the local variable table hasn't been repaired - for example:
  1644. // LocalVariable(start_pc = 6, length = 40, index = 0:com.example.ExampleAspect this)
  1645. // LocalVariable(start_pc = 6, length = 40, index = 1:org.aspectj.lang.ProceedingJoinPoint pjp)
  1646. // LocalVariable(start_pc = 6, length = 40, index = 2:int __cobertura__line__number__)
  1647. // LocalVariable(start_pc = 6, length = 40, index = 3:int __cobertura__branch__number__)
  1648. LocalVariable localVariable = lvt[0];
  1649. if (localVariable != null) { // pr348488
  1650. if (localVariable.getStartPC() != 0) {
  1651. // looks suspicious so let's use this information
  1652. for (int j = 0; j < lvt.length && arguments.size() < method.getArgumentTypes().length; j++) {
  1653. localVariable = lvt[j];
  1654. if (localVariable.getIndex() >= startAtStackIndex) {
  1655. arguments.add(new MethodArgument(localVariable.getName(), localVariable.getIndex()));
  1656. }
  1657. }
  1658. }
  1659. }
  1660. }
  1661. } else {
  1662. if (argNamesFromAnnotation != null) {
  1663. String[] argNames = extractArgNamesFromAnnotationValue(method, argNamesFromAnnotation, methodStruct);
  1664. if (argNames != null) {
  1665. return argNames;
  1666. }
  1667. }
  1668. }
  1669. if (arguments.size() != method.getArgumentTypes().length) {
  1670. return EMPTY_STRINGS;
  1671. }
  1672. // sort by index
  1673. Collections.sort(arguments, new Comparator<MethodArgument>() {
  1674. public int compare(MethodArgument mo, MethodArgument mo1) {
  1675. if (mo.indexOnStack == mo1.indexOnStack) {
  1676. return 0;
  1677. } else if (mo.indexOnStack > mo1.indexOnStack) {
  1678. return 1;
  1679. } else {
  1680. return -1;
  1681. }
  1682. }
  1683. });
  1684. String[] argumentNames = new String[arguments.size()];
  1685. int i = 0;
  1686. for (MethodArgument methodArgument : arguments) {
  1687. argumentNames[i++] = methodArgument.name;
  1688. }
  1689. return argumentNames;
  1690. }
  1691. private static String[] extractArgNamesFromAnnotationValue(Method method, String argNamesFromAnnotation,
  1692. AjAttributeMethodStruct methodStruct) {
  1693. StringTokenizer st = new StringTokenizer(argNamesFromAnnotation, " ,");
  1694. List<String> args = new ArrayList<String>();
  1695. while (st.hasMoreTokens()) {
  1696. args.add(st.nextToken());
  1697. }
  1698. if (args.size() != method.getArgumentTypes().length) {
  1699. StringBuffer shortString = new StringBuffer().append(lastbit(method.getReturnType().toString())).append(" ")
  1700. .append(method.getName());
  1701. if (method.getArgumentTypes().length > 0) {
  1702. shortString.append("(");
  1703. for (int i = 0; i < method.getArgumentTypes().length; i++) {
  1704. shortString.append(lastbit(method.getArgumentTypes()[i].toString()));
  1705. if ((i + 1) < method.getArgumentTypes().length) {
  1706. shortString.append(",");
  1707. }
  1708. }
  1709. shortString.append(")");
  1710. }
  1711. reportError("argNames annotation value does not specify the right number of argument names for the method '"
  1712. + shortString.toString() + "'", methodStruct);
  1713. return EMPTY_STRINGS;
  1714. }
  1715. return args.toArray(new String[] {});
  1716. }
  1717. /**
  1718. * A method argument, used for sorting by indexOnStack (ie order in signature)
  1719. *
  1720. * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
  1721. */
  1722. private static class MethodArgument {
  1723. String name;
  1724. int indexOnStack;
  1725. public MethodArgument(String name, int indexOnStack) {
  1726. this.name = name;
  1727. this.indexOnStack = indexOnStack;
  1728. }
  1729. }
  1730. /**
  1731. * LazyResolvedPointcutDefinition lazyly resolve the pointcut so that we have time to register all pointcut referenced before
  1732. * pointcut resolution happens
  1733. *
  1734. * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
  1735. */
  1736. public static class LazyResolvedPointcutDefinition extends ResolvedPointcutDefinition {
  1737. private final Pointcut m_pointcutUnresolved; // null for abstract
  1738. // pointcut
  1739. private final IScope m_binding;
  1740. private Pointcut m_lazyPointcut = null;
  1741. public LazyResolvedPointcutDefinition(UnresolvedType declaringType, int modifiers, String name,
  1742. UnresolvedType[] parameterTypes, UnresolvedType returnType, Pointcut pointcut, IScope binding) {
  1743. super(declaringType, modifiers, name, parameterTypes, returnType, Pointcut.makeMatchesNothing(Pointcut.RESOLVED));
  1744. m_pointcutUnresolved = pointcut;
  1745. m_binding = binding;
  1746. }
  1747. @Override
  1748. public Pointcut getPointcut() {
  1749. if (m_lazyPointcut == null && m_pointcutUnresolved == null) {
  1750. m_lazyPointcut = Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
  1751. }
  1752. if (m_lazyPointcut == null && m_pointcutUnresolved != null) {
  1753. m_lazyPointcut = m_pointcutUnresolved.resolve(m_binding);
  1754. m_lazyPointcut.copyLocationFrom(m_pointcutUnresolved);
  1755. }
  1756. return m_lazyPointcut;
  1757. }
  1758. }
  1759. /**
  1760. * Helper to test empty strings
  1761. *
  1762. * @param s
  1763. * @return true if empty or null
  1764. */
  1765. private static boolean isNullOrEmpty(String s) {
  1766. return (s == null || s.length() <= 0);
  1767. }
  1768. /**
  1769. * Set the pointcut bindings for which to ignore unbound issues, so that we can implicitly bind xxxJoinPoint for @AJ advices
  1770. *
  1771. * @param pointcut
  1772. * @param bindings
  1773. */
  1774. private static void setIgnoreUnboundBindingNames(Pointcut pointcut, FormalBinding[] bindings) {
  1775. // register ImplicitBindings as to be ignored since unbound
  1776. // TODO is it likely to fail in a bad way if f.e. this(jp) etc ?
  1777. List<String> ignores = new ArrayList<String>();
  1778. for (FormalBinding formalBinding : bindings) {
  1779. if (formalBinding instanceof FormalBinding.ImplicitFormalBinding) {
  1780. ignores.add(formalBinding.getName());
  1781. }
  1782. }
  1783. pointcut.m_ignoreUnboundBindingForNames = ignores.toArray(new String[ignores.size()]);
  1784. }
  1785. /**
  1786. * A check exception when we cannot read debug info (needed for formal binding)
  1787. */
  1788. private static class UnreadableDebugInfoException extends Exception {
  1789. }
  1790. /**
  1791. * Report an error
  1792. *
  1793. * @param message
  1794. * @param location
  1795. */
  1796. private static void reportError(String message, AjAttributeStruct location) {
  1797. if (!location.handler.isIgnoring(IMessage.ERROR)) {
  1798. location.handler.handleMessage(new Message(message, location.enclosingType.getSourceLocation(), true));
  1799. }
  1800. }
  1801. // private static void reportError(String message, IMessageHandler handler, ISourceLocation sourceLocation) {
  1802. // if (!handler.isIgnoring(IMessage.ERROR)) {
  1803. // handler.handleMessage(new Message(message, sourceLocation, true));
  1804. // }
  1805. // }
  1806. /**
  1807. * Report a warning
  1808. *
  1809. * @param message
  1810. * @param location
  1811. */
  1812. private static void reportWarning(String message, AjAttributeStruct location) {
  1813. if (!location.handler.isIgnoring(IMessage.WARNING)) {
  1814. location.handler.handleMessage(new Message(message, location.enclosingType.getSourceLocation(), false));
  1815. }
  1816. }
  1817. /**
  1818. * Parse the given pointcut, return null on failure and issue an error
  1819. *
  1820. * @param pointcutString
  1821. * @param struct
  1822. * @param allowIf
  1823. * @return pointcut, unresolved
  1824. */
  1825. private static Pointcut parsePointcut(String pointcutString, AjAttributeStruct struct, boolean allowIf) {
  1826. try {
  1827. PatternParser parser = new PatternParser(pointcutString, struct.context);
  1828. Pointcut pointcut = parser.parsePointcut();
  1829. parser.checkEof();
  1830. pointcut.check(null, struct.enclosingType.getWorld());
  1831. if (!allowIf && pointcutString.contains("if()") && hasIf(pointcut)) {
  1832. reportError("if() pointcut is not allowed at this pointcut location '" + pointcutString + "'", struct);
  1833. return null;
  1834. }
  1835. pointcut.setLocation(struct.context, -1, -1);// FIXME -1,-1 is not
  1836. // good enough
  1837. return pointcut;
  1838. } catch (ParserException e) {
  1839. reportError("Invalid pointcut '" + pointcutString + "': " + e.toString()
  1840. + (e.getLocation() == null ? "" : " at position " + e.getLocation().getStart()), struct);
  1841. return null;
  1842. }
  1843. }
  1844. private static boolean hasIf(Pointcut pointcut) {
  1845. IfFinder visitor = new IfFinder();
  1846. pointcut.accept(visitor, null);
  1847. return visitor.hasIf;
  1848. }
  1849. /**
  1850. * Parse the given type pattern, return null on failure and issue an error
  1851. *
  1852. * @param patternString
  1853. * @param location
  1854. * @return type pattern
  1855. */
  1856. private static TypePattern parseTypePattern(String patternString, AjAttributeStruct location) {
  1857. try {
  1858. TypePattern typePattern = new PatternParser(patternString).parseTypePattern();
  1859. typePattern.setLocation(location.context, -1, -1);// FIXME -1,-1 is
  1860. // not good
  1861. // enough
  1862. return typePattern;
  1863. } catch (ParserException e) {
  1864. reportError("Invalid type pattern'" + patternString + "' : " + e.getLocation(), location);
  1865. return null;
  1866. }
  1867. }
  1868. static class ThrownFormalNotDeclaredInAdviceSignatureException extends Exception {
  1869. private final String formalName;
  1870. public ThrownFormalNotDeclaredInAdviceSignatureException(String formalName) {
  1871. this.formalName = formalName;
  1872. }
  1873. public String getFormalName() {
  1874. return formalName;
  1875. }
  1876. }
  1877. static class ReturningFormalNotDeclaredInAdviceSignatureException extends Exception {
  1878. private final String formalName;
  1879. public ReturningFormalNotDeclaredInAdviceSignatureException(String formalName) {
  1880. this.formalName = formalName;
  1881. }
  1882. public String getFormalName() {
  1883. return formalName;
  1884. }
  1885. }
  1886. }