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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025
  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 v 2.0
  6. * which accompanies this distribution and is available at
  7. * https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.txt
  8. *
  9. * Contributors:
  10. * 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 Alexandre Vasseur (alex AT gnilux DOT com)
  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<>();
  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 = FormalBinding.NONE;
  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. if (decpPattern != null) {
  663. TypePattern typePattern = parseTypePattern(decpPattern, struct);
  664. ResolvedType fieldType = UnresolvedType.forSignature(struct.field.getSignature()).resolve(
  665. struct.enclosingType.getWorld());
  666. if (fieldType.isParameterizedOrRawType()) {
  667. fieldType = fieldType.getGenericType();
  668. }
  669. if (fieldType.isInterface()) {
  670. TypePattern parent = parseTypePattern(fieldType.getName(), struct);
  671. FormalBinding[] bindings = FormalBinding.NONE;
  672. IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings);
  673. // first add the declare implements like
  674. List<TypePattern> parents = new ArrayList<>(1);
  675. parents.add(parent);
  676. DeclareParents dp = new DeclareParents(typePattern, parents, false);
  677. dp.resolve(binding); // resolves the parent and child parts of the decp
  678. // resolve this so that we can use it for the
  679. // MethodDelegateMungers below.
  680. // eg. '@Coloured *' will change from a WildTypePattern to
  681. // an 'AnyWithAnnotationTypePattern' after this resolution
  682. typePattern = dp.getChild(); // this retrieves the resolved version
  683. // TODO kick ISourceLocation sl =
  684. // struct.bField.getSourceLocation(); ??
  685. // dp.setLocation(dp.getDeclaringType().getSourceContext(),
  686. // dp.getDeclaringType().getSourceLocation().getOffset(),
  687. // dp.getDeclaringType().getSourceLocation().getOffset());
  688. dp.setLocation(struct.context, -1, -1); // not ideal...
  689. struct.ajAttributes.add(new AjAttribute.DeclareAttribute(dp));
  690. // do we have a defaultImpl=xxx.class (ie implementation)
  691. String defaultImplClassName = null;
  692. NameValuePair defaultImplNVP = getAnnotationElement(decpAnno, "defaultImpl");
  693. if (defaultImplNVP != null) {
  694. ClassElementValue defaultImpl = (ClassElementValue) defaultImplNVP.getValue();
  695. defaultImplClassName = UnresolvedType.forSignature(defaultImpl.getClassString()).getName();
  696. if (defaultImplClassName.equals("org.aspectj.lang.annotation.DeclareParents")) {
  697. defaultImplClassName = null;
  698. } else {
  699. // check public no arg ctor
  700. ResolvedType impl = struct.enclosingType.getWorld().resolve(defaultImplClassName, false);
  701. ResolvedMember[] mm = impl.getDeclaredMethods();
  702. int implModifiers = impl.getModifiers();
  703. boolean defaultVisibilityImpl = !(Modifier.isPrivate(implModifiers)
  704. || Modifier.isProtected(implModifiers) || Modifier.isPublic(implModifiers));
  705. boolean hasNoCtorOrANoArgOne = true;
  706. ResolvedMember foundOneOfIncorrectVisibility = null;
  707. for (ResolvedMember resolvedMember : mm) {
  708. if (resolvedMember.getName().equals("<init>")) {
  709. hasNoCtorOrANoArgOne = false;
  710. if (resolvedMember.getParameterTypes().length == 0) {
  711. if (defaultVisibilityImpl) { // default visibility implementation
  712. if (resolvedMember.isPublic() || resolvedMember.isDefault()) {
  713. hasNoCtorOrANoArgOne = true;
  714. } else {
  715. foundOneOfIncorrectVisibility = resolvedMember;
  716. }
  717. } else if (Modifier.isPublic(implModifiers)) { // public
  718. // implementation
  719. if (resolvedMember.isPublic()) {
  720. hasNoCtorOrANoArgOne = true;
  721. } else {
  722. foundOneOfIncorrectVisibility = resolvedMember;
  723. }
  724. }
  725. }
  726. }
  727. if (hasNoCtorOrANoArgOne) {
  728. break;
  729. }
  730. }
  731. if (!hasNoCtorOrANoArgOne) {
  732. if (foundOneOfIncorrectVisibility != null) {
  733. reportError(
  734. "@DeclareParents: defaultImpl=\""
  735. + defaultImplClassName
  736. + "\" has a no argument constructor, but it is of incorrect visibility. It must be at least as visible as the type.",
  737. struct);
  738. } else {
  739. reportError("@DeclareParents: defaultImpl=\"" + defaultImplClassName
  740. + "\" has no public no-arg constructor", struct);
  741. }
  742. }
  743. if (!fieldType.isAssignableFrom(impl)) {
  744. reportError("@DeclareParents: defaultImpl=\"" + defaultImplClassName
  745. + "\" does not implement the interface '" + fieldType.toString() + "'", struct);
  746. }
  747. }
  748. }
  749. boolean hasAtLeastOneMethod = false;
  750. // then iterate on field interface hierarchy (not object)
  751. Iterator<ResolvedMember> methodIterator = fieldType.getMethodsIncludingIntertypeDeclarations(false, true);
  752. while (methodIterator.hasNext()) {
  753. ResolvedMember method = methodIterator.next();
  754. if (method.isAbstract()) {
  755. // moved to be detected at weave time if the target
  756. // doesnt implement the methods
  757. // if (defaultImplClassName == null) {
  758. // // non marker interface with no default impl
  759. // provided
  760. // reportError("@DeclareParents: used with a non marker interface and no defaultImpl=\"...\" provided",
  761. // struct);
  762. // return false;
  763. // }
  764. hasAtLeastOneMethod = true;
  765. // What we are saying here:
  766. // We have this method 'method' and we want to put a
  767. // forwarding method into a type that matches
  768. // typePattern that should delegate to the version
  769. // of the method in 'defaultImplClassName'
  770. // Now the method may be from a supertype but the
  771. // declaring type of the method we pass into the
  772. // type
  773. // munger is what is used to determine the type of
  774. // the field that hosts the delegate instance.
  775. // So here we create a modified method with an
  776. // alternative declaring type so that we lookup
  777. // the right field. See pr164016.
  778. MethodDelegateTypeMunger mdtm = new MethodDelegateTypeMunger(method, struct.enclosingType, defaultImplClassName, typePattern);
  779. mdtm.setFieldType(fieldType);
  780. mdtm.setSourceLocation(struct.enclosingType.getSourceLocation());
  781. struct.ajAttributes.add(new AjAttribute.TypeMunger(mdtm));
  782. }
  783. }
  784. // successful so far, we thus need a bcel type munger to have
  785. // a field hosting the mixin in the target type
  786. if (hasAtLeastOneMethod && defaultImplClassName != null) {
  787. ResolvedMember fieldHost = AjcMemberMaker.itdAtDeclareParentsField(null, fieldType, struct.enclosingType);
  788. struct.ajAttributes.add(new AjAttribute.TypeMunger(new MethodDelegateTypeMunger.FieldHostTypeMunger(
  789. fieldHost, struct.enclosingType, typePattern)));
  790. }
  791. return true;
  792. } else {
  793. reportError("@DeclareParents: can only be used on a field whose type is an interface", struct);
  794. return false;
  795. }
  796. }
  797. }
  798. return false;
  799. }
  800. /**
  801. * @return a nicely formatted method string, for example: int X.foo(java.lang.String)
  802. */
  803. public static String getMethodForMessage(AjAttributeMethodStruct methodstructure) {
  804. StringBuilder sb = new StringBuilder();
  805. sb.append("Method '");
  806. sb.append(methodstructure.method.getReturnType().toString());
  807. sb.append(" ").append(methodstructure.enclosingType).append(".").append(methodstructure.method.getName());
  808. sb.append("(");
  809. Type[] args = methodstructure.method.getArgumentTypes();
  810. if (args != null) {
  811. for (int t = 0; t < args.length; t++) {
  812. if (t > 0) {
  813. sb.append(",");
  814. }
  815. sb.append(args[t].toString());
  816. }
  817. }
  818. sb.append(")'");
  819. return sb.toString();
  820. }
  821. /**
  822. * Process any @DeclareMixin annotation.
  823. *
  824. * Example Declaration <br>
  825. *
  826. * @DeclareMixin("Foo+") public I createImpl(Object o) { return new Impl(o); }
  827. *
  828. * <br>
  829. * @param runtimeAnnotations
  830. * @param struct
  831. * @return true if found
  832. */
  833. private static boolean handleDeclareMixinAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeMethodStruct struct) {
  834. AnnotationGen declareMixinAnnotation = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREMIXIN_ANNOTATION);
  835. if (declareMixinAnnotation == null) {
  836. // No annotation found
  837. return false;
  838. }
  839. Method annotatedMethod = struct.method;
  840. World world = struct.enclosingType.getWorld();
  841. NameValuePair declareMixinPatternNameValuePair = getAnnotationElement(declareMixinAnnotation, VALUE);
  842. // declareMixinPattern could be of the form "Bar*" or "A || B" or "Foo+"
  843. String declareMixinPattern = declareMixinPatternNameValuePair.getValue().stringifyValue();
  844. TypePattern targetTypePattern = parseTypePattern(declareMixinPattern, struct);
  845. // Return value of the annotated method is the interface or class that the mixin delegate should have
  846. ResolvedType methodReturnType = UnresolvedType.forSignature(annotatedMethod.getReturnType().getSignature()).resolve(world);
  847. if (methodReturnType.isParameterizedOrRawType()) {
  848. methodReturnType = methodReturnType.getGenericType();
  849. }
  850. if (methodReturnType.isPrimitiveType()) {
  851. reportError(getMethodForMessage(struct) + ": factory methods for a mixin cannot return void or a primitive type",
  852. struct);
  853. return false;
  854. }
  855. if (annotatedMethod.getArgumentTypes().length > 1) {
  856. reportError(getMethodForMessage(struct) + ": factory methods for a mixin can take a maximum of one parameter", struct);
  857. return false;
  858. }
  859. // The set of interfaces to be mixed in is either:
  860. // supplied as a list in the 'Class[] interfaces' value in the annotation value
  861. // supplied as just the interface return value of the annotated method
  862. // supplied as just the class return value of the annotated method
  863. NameValuePair interfaceListSpecified = getAnnotationElement(declareMixinAnnotation, "interfaces");
  864. List<TypePattern> newParents = new ArrayList<>(1);
  865. List<ResolvedType> newInterfaceTypes = new ArrayList<>(1);
  866. if (interfaceListSpecified != null) {
  867. ArrayElementValue arrayOfInterfaceTypes = (ArrayElementValue) interfaceListSpecified.getValue();
  868. int numberOfTypes = arrayOfInterfaceTypes.getElementValuesArraySize();
  869. ElementValue[] theTypes = arrayOfInterfaceTypes.getElementValuesArray();
  870. for (int i = 0; i < numberOfTypes; i++) {
  871. ClassElementValue interfaceType = (ClassElementValue) theTypes[i];
  872. // Check: needs to be resolvable
  873. // TODO crappy replace required
  874. ResolvedType ajInterfaceType = UnresolvedType.forSignature(interfaceType.getClassString().replace("/", "."))
  875. .resolve(world);
  876. if (ajInterfaceType.isMissing() || !ajInterfaceType.isInterface()) {
  877. reportError(
  878. "Types listed in the 'interfaces' DeclareMixin annotation value must be valid interfaces. This is invalid: "
  879. + ajInterfaceType.getName(), struct); // TODO better error location, use the method position
  880. return false;
  881. }
  882. if (!ajInterfaceType.isAssignableFrom(methodReturnType)) {
  883. reportError(getMethodForMessage(struct) + ": factory method does not return something that implements '"
  884. + ajInterfaceType.getName() + "'", struct);
  885. return false;
  886. }
  887. newInterfaceTypes.add(ajInterfaceType);
  888. // Checking that it is a superinterface of the methods return value is done at weave time
  889. TypePattern newParent = parseTypePattern(ajInterfaceType.getName(), struct);
  890. newParents.add(newParent);
  891. }
  892. } else {
  893. if (methodReturnType.isClass()) {
  894. reportError(
  895. getMethodForMessage(struct)
  896. + ": factory methods for a mixin must either return an interface type or specify interfaces in the annotation and return a class",
  897. struct);
  898. return false;
  899. }
  900. // Use the method return type: this might be a class or an interface
  901. TypePattern newParent = parseTypePattern(methodReturnType.getName(), struct);
  902. newInterfaceTypes.add(methodReturnType);
  903. newParents.add(newParent);
  904. }
  905. if (newParents.size() == 0) {
  906. // Warning: did they foolishly put @DeclareMixin(value="Bar+",interfaces={})
  907. // TODO output warning
  908. return false;
  909. }
  910. // Create the declare parents that will add the interfaces to matching targets
  911. FormalBinding[] bindings = FormalBinding.NONE;
  912. IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings);
  913. // how do we mark this as a decp due to decmixin?
  914. DeclareParents dp = new DeclareParentsMixin(targetTypePattern, newParents);
  915. dp.resolve(binding);
  916. targetTypePattern = dp.getChild();
  917. dp.setLocation(struct.context, -1, -1); // not ideal...
  918. struct.ajAttributes.add(new AjAttribute.DeclareAttribute(dp));
  919. // The factory method for building the implementation is the
  920. // one attached to the annotation:
  921. // Method implementationFactory = struct.method;
  922. boolean hasAtLeastOneMethod = false;
  923. for (ResolvedType typeForDelegation : newInterfaceTypes) {
  924. // TODO check for overlapping interfaces. Eg. A implements I, I extends J - if they specify interfaces={I,J} we dont
  925. // want to do any methods twice
  926. ResolvedMember[] methods = typeForDelegation.getMethodsWithoutIterator(true, false, false).toArray(
  927. ResolvedMember.NONE);
  928. for (ResolvedMember resolvedMember : methods) {
  929. ResolvedMember method = resolvedMember;
  930. if (method.isAbstract()) {
  931. hasAtLeastOneMethod = true;
  932. if (method.hasBackingGenericMember()) {
  933. method = method.getBackingGenericMember();
  934. }
  935. MethodDelegateTypeMunger mdtm = new MethodDelegateTypeMunger(method, struct.enclosingType, "",
  936. targetTypePattern, struct.method.getName(), struct.method.getSignature());
  937. mdtm.setFieldType(methodReturnType);
  938. mdtm.setSourceLocation(struct.enclosingType.getSourceLocation());
  939. struct.ajAttributes.add(new AjAttribute.TypeMunger(mdtm));
  940. }
  941. }
  942. }
  943. // if any method delegate was created then a field to hold the delegate instance must also be added
  944. if (hasAtLeastOneMethod) {
  945. ResolvedMember fieldHost = AjcMemberMaker.itdAtDeclareParentsField(null, methodReturnType, struct.enclosingType);
  946. struct.ajAttributes.add(new AjAttribute.TypeMunger(new MethodDelegateTypeMunger.FieldHostTypeMunger(fieldHost,
  947. struct.enclosingType, targetTypePattern)));
  948. }
  949. return true;
  950. }
  951. /**
  952. * Read @Before
  953. *
  954. * @param runtimeAnnotations
  955. * @param struct
  956. * @return true if found
  957. */
  958. private static boolean handleBeforeAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeMethodStruct struct,
  959. ResolvedPointcutDefinition preResolvedPointcut) {
  960. AnnotationGen before = getAnnotation(runtimeAnnotations, AjcMemberMaker.BEFORE_ANNOTATION);
  961. if (before != null) {
  962. NameValuePair beforeAdvice = getAnnotationElement(before, VALUE);
  963. if (beforeAdvice != null) {
  964. // this/target/args binding
  965. String argumentNames = getArgNamesValue(before);
  966. if (argumentNames != null) {
  967. struct.unparsedArgumentNames = argumentNames;
  968. }
  969. FormalBinding[] bindings = FormalBinding.NONE;
  970. try {
  971. bindings = extractBindings(struct);
  972. } catch (UnreadableDebugInfoException unreadableDebugInfoException) {
  973. return false;
  974. }
  975. IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings);
  976. // joinpoint, staticJoinpoint binding
  977. int extraArgument = extractExtraArgument(struct.method);
  978. Pointcut pc = null;
  979. if (preResolvedPointcut != null) {
  980. pc = preResolvedPointcut.getPointcut();
  981. // pc.resolve(binding);
  982. } else {
  983. pc = parsePointcut(beforeAdvice.getValue().stringifyValue(), struct, false);
  984. if (pc == null) {
  985. return false;// parse error
  986. }
  987. pc = pc.resolve(binding);
  988. }
  989. setIgnoreUnboundBindingNames(pc, bindings);
  990. ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(),
  991. struct.bMethod.getDeclarationOffset());
  992. struct.ajAttributes.add(new AjAttribute.AdviceAttribute(AdviceKind.Before, pc, extraArgument, sl.getOffset(), sl
  993. .getOffset() + 1,// FIXME AVASM
  994. struct.context));
  995. return true;
  996. }
  997. }
  998. return false;
  999. }
  1000. /**
  1001. * Read @After
  1002. *
  1003. * @param runtimeAnnotations
  1004. * @param struct
  1005. * @return true if found
  1006. */
  1007. private static boolean handleAfterAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeMethodStruct struct,
  1008. ResolvedPointcutDefinition preResolvedPointcut) {
  1009. AnnotationGen after = getAnnotation(runtimeAnnotations, AjcMemberMaker.AFTER_ANNOTATION);
  1010. if (after != null) {
  1011. NameValuePair afterAdvice = getAnnotationElement(after, VALUE);
  1012. if (afterAdvice != null) {
  1013. // this/target/args binding
  1014. FormalBinding[] bindings = FormalBinding.NONE;
  1015. String argumentNames = getArgNamesValue(after);
  1016. if (argumentNames != null) {
  1017. struct.unparsedArgumentNames = argumentNames;
  1018. }
  1019. try {
  1020. bindings = extractBindings(struct);
  1021. } catch (UnreadableDebugInfoException unreadableDebugInfoException) {
  1022. return false;
  1023. }
  1024. IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings);
  1025. // joinpoint, staticJoinpoint binding
  1026. int extraArgument = extractExtraArgument(struct.method);
  1027. Pointcut pc = null;
  1028. if (preResolvedPointcut != null) {
  1029. pc = preResolvedPointcut.getPointcut();
  1030. } else {
  1031. pc = parsePointcut(afterAdvice.getValue().stringifyValue(), struct, false);
  1032. if (pc == null) {
  1033. return false;// parse error
  1034. }
  1035. pc.resolve(binding);
  1036. }
  1037. setIgnoreUnboundBindingNames(pc, bindings);
  1038. ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(),
  1039. struct.bMethod.getDeclarationOffset());
  1040. struct.ajAttributes.add(new AjAttribute.AdviceAttribute(AdviceKind.After, pc, extraArgument, sl.getOffset(), sl
  1041. .getOffset() + 1,// FIXME AVASM
  1042. struct.context));
  1043. return true;
  1044. }
  1045. }
  1046. return false;
  1047. }
  1048. /**
  1049. * Read @AfterReturning
  1050. *
  1051. * @param runtimeAnnotations
  1052. * @param struct
  1053. * @return true if found
  1054. */
  1055. private static boolean handleAfterReturningAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeMethodStruct struct,
  1056. ResolvedPointcutDefinition preResolvedPointcut, BcelMethod owningMethod)
  1057. throws ReturningFormalNotDeclaredInAdviceSignatureException {
  1058. AnnotationGen after = getAnnotation(runtimeAnnotations, AjcMemberMaker.AFTERRETURNING_ANNOTATION);
  1059. if (after != null) {
  1060. NameValuePair annValue = getAnnotationElement(after, VALUE);
  1061. NameValuePair annPointcut = getAnnotationElement(after, POINTCUT);
  1062. NameValuePair annReturned = getAnnotationElement(after, RETURNING);
  1063. // extract the pointcut and returned type/binding - do some checks
  1064. String pointcut = null;
  1065. String returned = null;
  1066. if ((annValue != null && annPointcut != null) || (annValue == null && annPointcut == null)) {
  1067. reportError("@AfterReturning: either 'value' or 'poincut' must be provided, not both", struct);
  1068. return false;
  1069. }
  1070. if (annValue != null) {
  1071. pointcut = annValue.getValue().stringifyValue();
  1072. } else {
  1073. pointcut = annPointcut.getValue().stringifyValue();
  1074. }
  1075. if (isNullOrEmpty(pointcut)) {
  1076. reportError("@AfterReturning: either 'value' or 'poincut' must be provided, not both", struct);
  1077. return false;
  1078. }
  1079. if (annReturned != null) {
  1080. returned = annReturned.getValue().stringifyValue();
  1081. if (isNullOrEmpty(returned)) {
  1082. returned = null;
  1083. } else {
  1084. // check that thrownFormal exists as the last parameter in
  1085. // the advice
  1086. String[] pNames = owningMethod.getParameterNames();
  1087. if (pNames == null || pNames.length == 0 || !Arrays.asList(pNames).contains(returned)) {
  1088. throw new ReturningFormalNotDeclaredInAdviceSignatureException(returned);
  1089. }
  1090. }
  1091. }
  1092. String argumentNames = getArgNamesValue(after);
  1093. if (argumentNames != null) {
  1094. struct.unparsedArgumentNames = argumentNames;
  1095. }
  1096. // this/target/args binding
  1097. // exclude the return binding from the pointcut binding since it is
  1098. // an extraArg binding
  1099. FormalBinding[] bindings = FormalBinding.NONE;
  1100. try {
  1101. bindings = (returned == null ? extractBindings(struct) : extractBindings(struct, returned));
  1102. } catch (UnreadableDebugInfoException unreadableDebugInfoException) {
  1103. return false;
  1104. }
  1105. IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings);
  1106. // joinpoint, staticJoinpoint binding
  1107. int extraArgument = extractExtraArgument(struct.method);
  1108. // return binding
  1109. if (returned != null) {
  1110. extraArgument |= Advice.ExtraArgument;
  1111. }
  1112. Pointcut pc = null;
  1113. if (preResolvedPointcut != null) {
  1114. pc = preResolvedPointcut.getPointcut();
  1115. } else {
  1116. pc = parsePointcut(pointcut, struct, false);
  1117. if (pc == null) {
  1118. return false;// parse error
  1119. }
  1120. pc.resolve(binding);
  1121. }
  1122. setIgnoreUnboundBindingNames(pc, bindings);
  1123. ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(),
  1124. struct.bMethod.getDeclarationOffset());
  1125. struct.ajAttributes.add(new AjAttribute.AdviceAttribute(AdviceKind.AfterReturning, pc, extraArgument, sl.getOffset(),
  1126. sl.getOffset() + 1,// FIXME AVASM
  1127. struct.context));
  1128. return true;
  1129. }
  1130. return false;
  1131. }
  1132. /**
  1133. * Read @AfterThrowing
  1134. *
  1135. * @param runtimeAnnotations
  1136. * @param struct
  1137. * @return true if found
  1138. */
  1139. private static boolean handleAfterThrowingAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeMethodStruct struct,
  1140. ResolvedPointcutDefinition preResolvedPointcut, BcelMethod owningMethod)
  1141. throws ThrownFormalNotDeclaredInAdviceSignatureException {
  1142. AnnotationGen after = getAnnotation(runtimeAnnotations, AjcMemberMaker.AFTERTHROWING_ANNOTATION);
  1143. if (after != null) {
  1144. NameValuePair annValue = getAnnotationElement(after, VALUE);
  1145. NameValuePair annPointcut = getAnnotationElement(after, POINTCUT);
  1146. NameValuePair annThrown = getAnnotationElement(after, THROWING);
  1147. // extract the pointcut and throwned type/binding - do some checks
  1148. String pointcut = null;
  1149. String thrownFormal = null;
  1150. if ((annValue != null && annPointcut != null) || (annValue == null && annPointcut == null)) {
  1151. reportError("@AfterThrowing: either 'value' or 'poincut' must be provided, not both", struct);
  1152. return false;
  1153. }
  1154. if (annValue != null) {
  1155. pointcut = annValue.getValue().stringifyValue();
  1156. } else {
  1157. pointcut = annPointcut.getValue().stringifyValue();
  1158. }
  1159. if (isNullOrEmpty(pointcut)) {
  1160. reportError("@AfterThrowing: either 'value' or 'poincut' must be provided, not both", struct);
  1161. return false;
  1162. }
  1163. if (annThrown != null) {
  1164. thrownFormal = annThrown.getValue().stringifyValue();
  1165. if (isNullOrEmpty(thrownFormal)) {
  1166. thrownFormal = null;
  1167. } else {
  1168. // check that thrownFormal exists as the last parameter in
  1169. // the advice
  1170. String[] pNames = owningMethod.getParameterNames();
  1171. if (pNames == null || pNames.length == 0 || !Arrays.asList(pNames).contains(thrownFormal)) {
  1172. throw new ThrownFormalNotDeclaredInAdviceSignatureException(thrownFormal);
  1173. }
  1174. }
  1175. }
  1176. String argumentNames = getArgNamesValue(after);
  1177. if (argumentNames != null) {
  1178. struct.unparsedArgumentNames = argumentNames;
  1179. }
  1180. // this/target/args binding
  1181. // exclude the throwned binding from the pointcut binding since it
  1182. // is an extraArg binding
  1183. FormalBinding[] bindings = FormalBinding.NONE;
  1184. try {
  1185. bindings = (thrownFormal == null ? extractBindings(struct) : extractBindings(struct, thrownFormal));
  1186. } catch (UnreadableDebugInfoException unreadableDebugInfoException) {
  1187. return false;
  1188. }
  1189. IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings);
  1190. // joinpoint, staticJoinpoint binding
  1191. int extraArgument = extractExtraArgument(struct.method);
  1192. // return binding
  1193. if (thrownFormal != null) {
  1194. extraArgument |= Advice.ExtraArgument;
  1195. }
  1196. Pointcut pc = null;
  1197. if (preResolvedPointcut != null) {
  1198. pc = preResolvedPointcut.getPointcut();
  1199. } else {
  1200. pc = parsePointcut(pointcut, struct, false);
  1201. if (pc == null) {
  1202. return false;// parse error
  1203. }
  1204. pc.resolve(binding);
  1205. }
  1206. setIgnoreUnboundBindingNames(pc, bindings);
  1207. ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(),
  1208. struct.bMethod.getDeclarationOffset());
  1209. struct.ajAttributes.add(new AjAttribute.AdviceAttribute(AdviceKind.AfterThrowing, pc, extraArgument, sl.getOffset(), sl
  1210. .getOffset() + 1, struct.context));
  1211. return true;
  1212. }
  1213. return false;
  1214. }
  1215. /**
  1216. * Read @Around
  1217. *
  1218. * @param runtimeAnnotations
  1219. * @param struct
  1220. * @return true if found
  1221. */
  1222. private static boolean handleAroundAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeMethodStruct struct,
  1223. ResolvedPointcutDefinition preResolvedPointcut) {
  1224. AnnotationGen around = getAnnotation(runtimeAnnotations, AjcMemberMaker.AROUND_ANNOTATION);
  1225. if (around != null) {
  1226. NameValuePair aroundAdvice = getAnnotationElement(around, VALUE);
  1227. if (aroundAdvice != null) {
  1228. // this/target/args binding
  1229. String argumentNames = getArgNamesValue(around);
  1230. if (argumentNames != null) {
  1231. struct.unparsedArgumentNames = argumentNames;
  1232. }
  1233. FormalBinding[] bindings = FormalBinding.NONE;
  1234. try {
  1235. bindings = extractBindings(struct);
  1236. } catch (UnreadableDebugInfoException unreadableDebugInfoException) {
  1237. return false;
  1238. }
  1239. IScope binding = new BindingScope(struct.enclosingType, struct.context, bindings);
  1240. // joinpoint, staticJoinpoint binding
  1241. int extraArgument = extractExtraArgument(struct.method);
  1242. Pointcut pc = null;
  1243. if (preResolvedPointcut != null) {
  1244. pc = preResolvedPointcut.getPointcut();
  1245. } else {
  1246. pc = parsePointcut(aroundAdvice.getValue().stringifyValue(), struct, false);
  1247. if (pc == null) {
  1248. return false;// parse error
  1249. }
  1250. pc.resolve(binding);
  1251. }
  1252. setIgnoreUnboundBindingNames(pc, bindings);
  1253. ISourceLocation sl = struct.context.makeSourceLocation(struct.bMethod.getDeclarationLineNumber(),
  1254. struct.bMethod.getDeclarationOffset());
  1255. struct.ajAttributes.add(new AjAttribute.AdviceAttribute(AdviceKind.Around, pc, extraArgument, sl.getOffset(), sl
  1256. .getOffset() + 1,// FIXME AVASM
  1257. struct.context));
  1258. return true;
  1259. }
  1260. }
  1261. return false;
  1262. }
  1263. /**
  1264. * Read @Pointcut and handle the resolving in a lazy way to deal with pointcut references
  1265. *
  1266. * @param runtimeAnnotations
  1267. * @param struct
  1268. * @return true if a pointcut was handled
  1269. */
  1270. private static boolean handlePointcutAnnotation(RuntimeAnnos runtimeAnnotations, AjAttributeMethodStruct struct) {
  1271. AnnotationGen pointcut = getAnnotation(runtimeAnnotations, AjcMemberMaker.POINTCUT_ANNOTATION);
  1272. if (pointcut == null) {
  1273. return false;
  1274. }
  1275. NameValuePair pointcutExpr = getAnnotationElement(pointcut, VALUE);
  1276. // semantic check: the method must return void, or be
  1277. // "public static boolean" for if() support
  1278. if (!(Type.VOID.equals(struct.method.getReturnType()) || (Type.BOOLEAN.equals(struct.method.getReturnType())
  1279. && struct.method.isStatic() && struct.method.isPublic()))) {
  1280. reportWarning("Found @Pointcut on a method not returning 'void' or not 'public static boolean'", struct);
  1281. // no need to stop
  1282. }
  1283. // semantic check: the method must not throw anything
  1284. if (struct.method.getExceptionTable() != null) {
  1285. reportWarning("Found @Pointcut on a method throwing exception", struct);
  1286. // no need to stop
  1287. }
  1288. String argumentNames = getArgNamesValue(pointcut);
  1289. if (argumentNames != null) {
  1290. struct.unparsedArgumentNames = argumentNames;
  1291. }
  1292. // this/target/args binding
  1293. final IScope binding;
  1294. try {
  1295. if (struct.method.isAbstract()) {
  1296. binding = null;
  1297. } else {
  1298. binding = new BindingScope(struct.enclosingType, struct.context, extractBindings(struct));
  1299. }
  1300. } catch (UnreadableDebugInfoException e) {
  1301. return false;
  1302. }
  1303. UnresolvedType[] argumentTypes = new UnresolvedType[struct.method.getArgumentTypes().length];
  1304. for (int i = 0; i < argumentTypes.length; i++) {
  1305. argumentTypes[i] = UnresolvedType.forSignature(struct.method.getArgumentTypes()[i].getSignature());
  1306. }
  1307. Pointcut pc = null;
  1308. if (struct.method.isAbstract()) {
  1309. if ((pointcutExpr != null && isNullOrEmpty(pointcutExpr.getValue().stringifyValue())) || pointcutExpr == null) {
  1310. // abstract pointcut
  1311. // leave pc = null
  1312. } else {
  1313. reportError("Found defined @Pointcut on an abstract method", struct);
  1314. return false;// stop
  1315. }
  1316. } else {
  1317. if (pointcutExpr == null || isNullOrEmpty(pointcutExpr.getValue().stringifyValue())) {
  1318. // the matches nothing pointcut (125475/125480) - perhaps not as
  1319. // cleanly supported as it could be.
  1320. } else {
  1321. // if (pointcutExpr != null) {
  1322. // use a LazyResolvedPointcutDefinition so that the pointcut is
  1323. // resolved lazily
  1324. // since for it to be resolved, we will need other pointcuts to
  1325. // be registered as well
  1326. pc = parsePointcut(pointcutExpr.getValue().stringifyValue(), struct, true);
  1327. if (pc == null) {
  1328. return false;// parse error
  1329. }
  1330. pc.setLocation(struct.context, -1, -1);// FIXME AVASM !! bMethod
  1331. // is null here..
  1332. // } else {
  1333. // reportError("Found undefined @Pointcut on a non-abstract method",
  1334. // struct);
  1335. // return false;
  1336. // }
  1337. }
  1338. }
  1339. // do not resolve binding now but lazily
  1340. struct.ajAttributes.add(new AjAttribute.PointcutDeclarationAttribute(new LazyResolvedPointcutDefinition(
  1341. struct.enclosingType, struct.method.getModifiers(), struct.method.getName(), argumentTypes, UnresolvedType
  1342. .forSignature(struct.method.getReturnType().getSignature()), pc,// can
  1343. // be
  1344. // null
  1345. // for
  1346. // abstract
  1347. // pointcut
  1348. binding // can be null for abstract pointcut
  1349. )));
  1350. return true;
  1351. }
  1352. /**
  1353. * Read @DeclareError, @DeclareWarning
  1354. *
  1355. * @param runtimeAnnotations
  1356. * @param struct
  1357. * @return true if found
  1358. */
  1359. private static boolean handleDeclareErrorOrWarningAnnotation(AsmManager model, RuntimeAnnos runtimeAnnotations,
  1360. AjAttributeFieldStruct struct) {
  1361. AnnotationGen error = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREERROR_ANNOTATION);
  1362. boolean hasError = false;
  1363. if (error != null) {
  1364. NameValuePair declareError = getAnnotationElement(error, VALUE);
  1365. if (declareError != null) {
  1366. if (!STRING_DESC.equals(struct.field.getSignature()) || struct.field.getConstantValue() == null) {
  1367. reportError("@DeclareError used on a non String constant field", struct);
  1368. return false;
  1369. }
  1370. Pointcut pc = parsePointcut(declareError.getValue().stringifyValue(), struct, false);
  1371. if (pc == null) {
  1372. hasError = false;// cannot parse pointcut
  1373. } else {
  1374. DeclareErrorOrWarning deow = new DeclareErrorOrWarning(true, pc, struct.field.getConstantValue().toString());
  1375. setDeclareErrorOrWarningLocation(model, deow, struct);
  1376. struct.ajAttributes.add(new AjAttribute.DeclareAttribute(deow));
  1377. hasError = true;
  1378. }
  1379. }
  1380. }
  1381. AnnotationGen warning = getAnnotation(runtimeAnnotations, AjcMemberMaker.DECLAREWARNING_ANNOTATION);
  1382. boolean hasWarning = false;
  1383. if (warning != null) {
  1384. NameValuePair declareWarning = getAnnotationElement(warning, VALUE);
  1385. if (declareWarning != null) {
  1386. if (!STRING_DESC.equals(struct.field.getSignature()) || struct.field.getConstantValue() == null) {
  1387. reportError("@DeclareWarning used on a non String constant field", struct);
  1388. return false;
  1389. }
  1390. Pointcut pc = parsePointcut(declareWarning.getValue().stringifyValue(), struct, false);
  1391. if (pc == null) {
  1392. hasWarning = false;// cannot parse pointcut
  1393. } else {
  1394. DeclareErrorOrWarning deow = new DeclareErrorOrWarning(false, pc, struct.field.getConstantValue().toString());
  1395. setDeclareErrorOrWarningLocation(model, deow, struct);
  1396. struct.ajAttributes.add(new AjAttribute.DeclareAttribute(deow));
  1397. return hasWarning = true;
  1398. }
  1399. }
  1400. }
  1401. return hasError || hasWarning;
  1402. }
  1403. /**
  1404. * Sets the location for the declare error / warning using the corresponding IProgramElement in the structure model. This will
  1405. * only fix bug 120356 if compiled with -emacssym, however, it does mean that the cross references view in AJDT will show the
  1406. * correct information.
  1407. *
  1408. * Other possibilities for fix: 1. using the information in ajcDeclareSoft (if this is set correctly) which will fix the problem
  1409. * if compiled with ajc but not if compiled with javac. 2. creating an AjAttribute called FieldDeclarationLineNumberAttribute
  1410. * (much like MethodDeclarationLineNumberAttribute) which we can ask for the offset. This will again only fix bug 120356 when
  1411. * compiled with ajc.
  1412. *
  1413. * @param deow
  1414. * @param struct
  1415. */
  1416. private static void setDeclareErrorOrWarningLocation(AsmManager model, DeclareErrorOrWarning deow, AjAttributeFieldStruct struct) {
  1417. IHierarchy top = (model == null ? null : model.getHierarchy());
  1418. if (top != null && top.getRoot() != null) {
  1419. IProgramElement ipe = top.findElementForLabel(top.getRoot(), IProgramElement.Kind.FIELD, struct.field.getName());
  1420. if (ipe != null && ipe.getSourceLocation() != null) {
  1421. ISourceLocation sourceLocation = ipe.getSourceLocation();
  1422. int start = sourceLocation.getOffset();
  1423. int end = start + struct.field.getName().length();
  1424. deow.setLocation(struct.context, start, end);
  1425. return;
  1426. }
  1427. }
  1428. deow.setLocation(struct.context, -1, -1);
  1429. }
  1430. /**
  1431. * Returns a readable representation of a method. Method.toString() is not suitable.
  1432. *
  1433. * @param method
  1434. * @return a readable representation of a method
  1435. */
  1436. private static String methodToString(Method method) {
  1437. StringBuilder sb = new StringBuilder();
  1438. sb.append(method.getName());
  1439. sb.append(method.getSignature());
  1440. return sb.toString();
  1441. }
  1442. /**
  1443. * Build the bindings for a given method (pointcut / advice)
  1444. *
  1445. * @param struct
  1446. * @return null if no debug info is available
  1447. */
  1448. private static FormalBinding[] extractBindings(AjAttributeMethodStruct struct) throws UnreadableDebugInfoException {
  1449. Method method = struct.method;
  1450. String[] argumentNames = struct.getArgumentNames();
  1451. // assert debug info was here
  1452. if (argumentNames.length != method.getArgumentTypes().length) {
  1453. reportError(
  1454. "Cannot read debug info for @Aspect to handle formal binding in pointcuts (please compile with 'javac -g' or '<javac debug='true'.../>' in Ant)",
  1455. struct);
  1456. throw new UnreadableDebugInfoException();
  1457. }
  1458. List<FormalBinding> bindings = new ArrayList<>();
  1459. for (int i = 0; i < argumentNames.length; i++) {
  1460. String argumentName = argumentNames[i];
  1461. UnresolvedType argumentType = UnresolvedType.forSignature(method.getArgumentTypes()[i].getSignature());
  1462. // do not bind JoinPoint / StaticJoinPoint /
  1463. // EnclosingStaticJoinPoint
  1464. // TODO solve me : this means that the JP/SJP/ESJP cannot appear as
  1465. // binding
  1466. // f.e. when applying advice on advice etc
  1467. if ((AjcMemberMaker.TYPEX_JOINPOINT.equals(argumentType)
  1468. || AjcMemberMaker.TYPEX_PROCEEDINGJOINPOINT.equals(argumentType)
  1469. || AjcMemberMaker.TYPEX_STATICJOINPOINT.equals(argumentType)
  1470. || AjcMemberMaker.TYPEX_ENCLOSINGSTATICJOINPOINT.equals(argumentType) || AjcMemberMaker.AROUND_CLOSURE_TYPE
  1471. .equals(argumentType))) {
  1472. // continue;// skip
  1473. bindings.add(new FormalBinding.ImplicitFormalBinding(argumentType, argumentName, i));
  1474. } else {
  1475. bindings.add(new FormalBinding(argumentType, argumentName, i));
  1476. }
  1477. }
  1478. return bindings.toArray(FormalBinding.NONE);
  1479. }
  1480. // FIXME alex deal with exclude index
  1481. private static FormalBinding[] extractBindings(AjAttributeMethodStruct struct, String excludeFormal)
  1482. throws UnreadableDebugInfoException {
  1483. FormalBinding[] bindings = extractBindings(struct);
  1484. // int excludeIndex = -1;
  1485. for (int i = 0; i < bindings.length; i++) {
  1486. FormalBinding binding = bindings[i];
  1487. if (binding.getName().equals(excludeFormal)) {
  1488. // excludeIndex = i;
  1489. bindings[i] = new FormalBinding.ImplicitFormalBinding(binding.getType(), binding.getName(), binding.getIndex());
  1490. break;
  1491. }
  1492. }
  1493. return bindings;
  1494. //
  1495. // if (excludeIndex >= 0) {
  1496. // FormalBinding[] bindingsFiltered = new
  1497. // FormalBinding[bindings.length-1];
  1498. // int k = 0;
  1499. // for (int i = 0; i < bindings.length; i++) {
  1500. // if (i == excludeIndex) {
  1501. // ;
  1502. // } else {
  1503. // bindingsFiltered[k] = new FormalBinding(bindings[i].getType(),
  1504. // bindings[i].getName(), k);
  1505. // k++;
  1506. // }
  1507. // }
  1508. // return bindingsFiltered;
  1509. // } else {
  1510. // return bindings;
  1511. // }
  1512. }
  1513. /**
  1514. * Compute the flag for the xxxJoinPoint extra argument
  1515. *
  1516. * @param method
  1517. * @return extra arg flag
  1518. */
  1519. private static int extractExtraArgument(Method method) {
  1520. Type[] methodArgs = method.getArgumentTypes();
  1521. String[] sigs = new String[methodArgs.length];
  1522. for (int i = 0; i < methodArgs.length; i++) {
  1523. sigs[i] = methodArgs[i].getSignature();
  1524. }
  1525. return extractExtraArgument(sigs);
  1526. }
  1527. /**
  1528. * Compute the flag for the xxxJoinPoint extra argument
  1529. *
  1530. * @param argumentSignatures
  1531. * @return extra arg flag
  1532. */
  1533. public static int extractExtraArgument(String[] argumentSignatures) {
  1534. int extraArgument = 0;
  1535. for (String argumentSignature : argumentSignatures) {
  1536. if (AjcMemberMaker.TYPEX_JOINPOINT.getSignature().equals(argumentSignature)) {
  1537. extraArgument |= Advice.ThisJoinPoint;
  1538. } else if (AjcMemberMaker.TYPEX_PROCEEDINGJOINPOINT.getSignature().equals(argumentSignature)) {
  1539. extraArgument |= Advice.ThisJoinPoint;
  1540. } else if (AjcMemberMaker.TYPEX_STATICJOINPOINT.getSignature().equals(argumentSignature)) {
  1541. extraArgument |= Advice.ThisJoinPointStaticPart;
  1542. } else if (AjcMemberMaker.TYPEX_ENCLOSINGSTATICJOINPOINT.getSignature().equals(argumentSignature)) {
  1543. extraArgument |= Advice.ThisEnclosingJoinPointStaticPart;
  1544. }
  1545. }
  1546. return extraArgument;
  1547. }
  1548. /**
  1549. * Returns the runtime (RV/RIV) annotation of type annotationType or null if no such annotation
  1550. *
  1551. * @param rvs
  1552. * @param annotationType
  1553. * @return annotation
  1554. */
  1555. private static AnnotationGen getAnnotation(RuntimeAnnos rvs, UnresolvedType annotationType) {
  1556. final String annotationTypeName = annotationType.getName();
  1557. for (AnnotationGen rv : rvs.getAnnotations()) {
  1558. if (annotationTypeName.equals(rv.getTypeName())) {
  1559. return rv;
  1560. }
  1561. }
  1562. return null;
  1563. }
  1564. /**
  1565. * Returns the value of a given element of an annotation or null if not found Caution: Does not handles default value.
  1566. *
  1567. * @param annotation
  1568. * @param elementName
  1569. * @return annotation NVP
  1570. */
  1571. private static NameValuePair getAnnotationElement(AnnotationGen annotation, String elementName) {
  1572. for (NameValuePair element : annotation.getValues()) {
  1573. if (elementName.equals(element.getNameString())) {
  1574. return element;
  1575. }
  1576. }
  1577. return null;
  1578. }
  1579. /**
  1580. * Return the argNames set for an annotation or null if it is not specified.
  1581. */
  1582. private static String getArgNamesValue(AnnotationGen anno) {
  1583. List<NameValuePair> elements = anno.getValues();
  1584. for (NameValuePair element : elements) {
  1585. if (ARGNAMES.equals(element.getNameString())) {
  1586. return element.getValue().stringifyValue();
  1587. }
  1588. }
  1589. return null;
  1590. }
  1591. private static String lastbit(String fqname) {
  1592. int i = fqname.lastIndexOf(".");
  1593. if (i == -1) {
  1594. return fqname;
  1595. } else {
  1596. return fqname.substring(i + 1);
  1597. }
  1598. }
  1599. /**
  1600. * Extract the method argument names. First we try the debug info attached to the method (the LocalVariableTable) - if we cannot
  1601. * find that we look to use the argNames value that may have been supplied on the associated annotation. If that fails we just
  1602. * don't know and return an empty string.
  1603. *
  1604. * @param method
  1605. * @param argNamesFromAnnotation
  1606. * @param methodStruct
  1607. * @return method argument names
  1608. */
  1609. private static String[] getMethodArgumentNames(Method method, String argNamesFromAnnotation,
  1610. AjAttributeMethodStruct methodStruct) {
  1611. if (method.getArgumentTypes().length == 0) {
  1612. return EMPTY_STRINGS;
  1613. }
  1614. final int startAtStackIndex = method.isStatic() ? 0 : 1;
  1615. final List<MethodArgument> arguments = new ArrayList<>();
  1616. LocalVariableTable lt = method.getLocalVariableTable();
  1617. if (lt != null) {
  1618. LocalVariable[] lvt = lt.getLocalVariableTable();
  1619. for (LocalVariable localVariable : lvt) {
  1620. if (localVariable != null) { // pr348488
  1621. if (localVariable.getStartPC() == 0) {
  1622. if (localVariable.getIndex() >= startAtStackIndex) {
  1623. arguments.add(new MethodArgument(localVariable.getName(), localVariable.getIndex()));
  1624. }
  1625. }
  1626. } else {
  1627. String typename = (methodStruct.enclosingType != null ? methodStruct.enclosingType.getName() : "");
  1628. System.err.println("AspectJ: 348488 debug: unusual local variable table for method " + typename + "."
  1629. + method.getName());
  1630. }
  1631. }
  1632. if (arguments.size() == 0) {
  1633. // The local variable table is causing us trouble, try the annotation value
  1634. // See 539121 for a jacoco variant of the cobertura issue below
  1635. if (argNamesFromAnnotation != null) {
  1636. String[] argNames = extractArgNamesFromAnnotationValue(method, argNamesFromAnnotation, methodStruct);
  1637. if (argNames.length != 0) {
  1638. return argNames;
  1639. }
  1640. }
  1641. // could be cobertura code where some extra bytecode has been stuffed in at the start of the method
  1642. // but the local variable table hasn't been repaired - for example:
  1643. // LocalVariable(start_pc = 6, length = 40, index = 0:com.example.ExampleAspect this)
  1644. // LocalVariable(start_pc = 6, length = 40, index = 1:org.aspectj.lang.ProceedingJoinPoint pjp)
  1645. // LocalVariable(start_pc = 6, length = 40, index = 2:int __cobertura__line__number__)
  1646. // LocalVariable(start_pc = 6, length = 40, index = 3:int __cobertura__branch__number__)
  1647. LocalVariable localVariable = lvt[0];
  1648. if (localVariable != null) { // pr348488
  1649. if (localVariable.getStartPC() != 0) {
  1650. // looks suspicious so let's use this information
  1651. for (int j = 0; j < lvt.length && arguments.size() < method.getArgumentTypes().length; j++) {
  1652. localVariable = lvt[j];
  1653. if (localVariable.getIndex() >= startAtStackIndex) {
  1654. arguments.add(new MethodArgument(localVariable.getName(), localVariable.getIndex()));
  1655. }
  1656. }
  1657. }
  1658. }
  1659. }
  1660. } else {
  1661. if (argNamesFromAnnotation != null) {
  1662. String[] argNames = extractArgNamesFromAnnotationValue(method, argNamesFromAnnotation, methodStruct);
  1663. if (argNames != null) {
  1664. return argNames;
  1665. }
  1666. }
  1667. }
  1668. if (arguments.size() != method.getArgumentTypes().length) {
  1669. return EMPTY_STRINGS;
  1670. }
  1671. // sort by index
  1672. arguments.sort(new Comparator<MethodArgument>() {
  1673. public int compare(MethodArgument mo, MethodArgument mo1) {
  1674. if (mo.indexOnStack == mo1.indexOnStack) {
  1675. return 0;
  1676. } else if (mo.indexOnStack > mo1.indexOnStack) {
  1677. return 1;
  1678. } else {
  1679. return -1;
  1680. }
  1681. }
  1682. });
  1683. String[] argumentNames = new String[arguments.size()];
  1684. int i = 0;
  1685. for (MethodArgument methodArgument : arguments) {
  1686. argumentNames[i++] = methodArgument.name;
  1687. }
  1688. return argumentNames;
  1689. }
  1690. private static String[] extractArgNamesFromAnnotationValue(Method method, String argNamesFromAnnotation,
  1691. AjAttributeMethodStruct methodStruct) {
  1692. StringTokenizer st = new StringTokenizer(argNamesFromAnnotation, " ,");
  1693. List<String> args = new ArrayList<>();
  1694. while (st.hasMoreTokens()) {
  1695. args.add(st.nextToken());
  1696. }
  1697. if (args.size() != method.getArgumentTypes().length) {
  1698. StringBuilder shortString = new StringBuilder().append(lastbit(method.getReturnType().toString())).append(" ")
  1699. .append(method.getName());
  1700. if (method.getArgumentTypes().length > 0) {
  1701. shortString.append("(");
  1702. for (int i = 0; i < method.getArgumentTypes().length; i++) {
  1703. shortString.append(lastbit(method.getArgumentTypes()[i].toString()));
  1704. if ((i + 1) < method.getArgumentTypes().length) {
  1705. shortString.append(",");
  1706. }
  1707. }
  1708. shortString.append(")");
  1709. }
  1710. reportError("argNames annotation value does not specify the right number of argument names for the method '"
  1711. + shortString.toString() + "'", methodStruct);
  1712. return EMPTY_STRINGS;
  1713. }
  1714. return args.toArray(new String[] {});
  1715. }
  1716. /**
  1717. * A method argument, used for sorting by indexOnStack (ie order in signature)
  1718. *
  1719. * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a>
  1720. */
  1721. private static class MethodArgument {
  1722. String name;
  1723. int indexOnStack;
  1724. public MethodArgument(String name, int indexOnStack) {
  1725. this.name = name;
  1726. this.indexOnStack = indexOnStack;
  1727. }
  1728. }
  1729. /**
  1730. * LazyResolvedPointcutDefinition lazyly resolve the pointcut so that we have time to register all pointcut referenced before
  1731. * pointcut resolution happens
  1732. *
  1733. * @author Alexandre Vasseur (alex AT gnilux DOT com)
  1734. */
  1735. public static class LazyResolvedPointcutDefinition extends ResolvedPointcutDefinition {
  1736. private final Pointcut m_pointcutUnresolved; // null for abstract
  1737. // pointcut
  1738. private final IScope m_binding;
  1739. private Pointcut m_lazyPointcut = null;
  1740. public LazyResolvedPointcutDefinition(UnresolvedType declaringType, int modifiers, String name,
  1741. UnresolvedType[] parameterTypes, UnresolvedType returnType, Pointcut pointcut, IScope binding) {
  1742. super(declaringType, modifiers, name, parameterTypes, returnType, Pointcut.makeMatchesNothing(Pointcut.RESOLVED));
  1743. m_pointcutUnresolved = pointcut;
  1744. m_binding = binding;
  1745. }
  1746. @Override
  1747. public Pointcut getPointcut() {
  1748. if (m_lazyPointcut == null && m_pointcutUnresolved == null) {
  1749. m_lazyPointcut = Pointcut.makeMatchesNothing(Pointcut.CONCRETE);
  1750. }
  1751. if (m_lazyPointcut == null && m_pointcutUnresolved != null) {
  1752. m_lazyPointcut = m_pointcutUnresolved.resolve(m_binding);
  1753. m_lazyPointcut.copyLocationFrom(m_pointcutUnresolved);
  1754. }
  1755. return m_lazyPointcut;
  1756. }
  1757. }
  1758. /**
  1759. * Helper to test empty strings
  1760. *
  1761. * @param s
  1762. * @return true if empty or null
  1763. */
  1764. private static boolean isNullOrEmpty(String s) {
  1765. return (s == null || s.length() <= 0);
  1766. }
  1767. /**
  1768. * Set the pointcut bindings for which to ignore unbound issues, so that we can implicitly bind xxxJoinPoint for @AJ advices
  1769. *
  1770. * @param pointcut
  1771. * @param bindings
  1772. */
  1773. private static void setIgnoreUnboundBindingNames(Pointcut pointcut, FormalBinding[] bindings) {
  1774. // register ImplicitBindings as to be ignored since unbound
  1775. // TODO is it likely to fail in a bad way if f.e. this(jp) etc ?
  1776. List<String> ignores = new ArrayList<>();
  1777. for (FormalBinding formalBinding : bindings) {
  1778. if (formalBinding instanceof FormalBinding.ImplicitFormalBinding) {
  1779. ignores.add(formalBinding.getName());
  1780. }
  1781. }
  1782. pointcut.m_ignoreUnboundBindingForNames = ignores.toArray(new String[0]);
  1783. }
  1784. /**
  1785. * A check exception when we cannot read debug info (needed for formal binding)
  1786. */
  1787. private static class UnreadableDebugInfoException extends Exception {
  1788. }
  1789. /**
  1790. * Report an error
  1791. *
  1792. * @param message
  1793. * @param location
  1794. */
  1795. private static void reportError(String message, AjAttributeStruct location) {
  1796. if (!location.handler.isIgnoring(IMessage.ERROR)) {
  1797. location.handler.handleMessage(new Message(message, location.enclosingType.getSourceLocation(), true));
  1798. }
  1799. }
  1800. // private static void reportError(String message, IMessageHandler handler, ISourceLocation sourceLocation) {
  1801. // if (!handler.isIgnoring(IMessage.ERROR)) {
  1802. // handler.handleMessage(new Message(message, sourceLocation, true));
  1803. // }
  1804. // }
  1805. /**
  1806. * Report a warning
  1807. *
  1808. * @param message
  1809. * @param location
  1810. */
  1811. private static void reportWarning(String message, AjAttributeStruct location) {
  1812. if (!location.handler.isIgnoring(IMessage.WARNING)) {
  1813. location.handler.handleMessage(new Message(message, location.enclosingType.getSourceLocation(), false));
  1814. }
  1815. }
  1816. /**
  1817. * Parse the given pointcut, return null on failure and issue an error
  1818. *
  1819. * @param pointcutString
  1820. * @param struct
  1821. * @param allowIf
  1822. * @return pointcut, unresolved
  1823. */
  1824. private static Pointcut parsePointcut(String pointcutString, AjAttributeStruct struct, boolean allowIf) {
  1825. try {
  1826. PatternParser parser = new PatternParser(pointcutString, struct.context);
  1827. Pointcut pointcut = parser.parsePointcut();
  1828. parser.checkEof();
  1829. pointcut.check(null, struct.enclosingType.getWorld());
  1830. if (!allowIf && pointcutString.contains("if()") && hasIf(pointcut)) {
  1831. reportError("if() pointcut is not allowed at this pointcut location '" + pointcutString + "'", struct);
  1832. return null;
  1833. }
  1834. pointcut.setLocation(struct.context, -1, -1);// FIXME -1,-1 is not
  1835. // good enough
  1836. return pointcut;
  1837. } catch (ParserException e) {
  1838. reportError("Invalid pointcut '" + pointcutString + "': " + e.toString()
  1839. + (e.getLocation() == null ? "" : " at position " + e.getLocation().getStart()), struct);
  1840. return null;
  1841. }
  1842. }
  1843. private static boolean hasIf(Pointcut pointcut) {
  1844. IfFinder visitor = new IfFinder();
  1845. pointcut.accept(visitor, null);
  1846. return visitor.hasIf;
  1847. }
  1848. /**
  1849. * Parse the given type pattern, return null on failure and issue an error
  1850. *
  1851. * @param patternString
  1852. * @param location
  1853. * @return type pattern
  1854. */
  1855. private static TypePattern parseTypePattern(String patternString, AjAttributeStruct location) {
  1856. try {
  1857. TypePattern typePattern = new PatternParser(patternString).parseTypePattern();
  1858. typePattern.setLocation(location.context, -1, -1);// FIXME -1,-1 is
  1859. // not good
  1860. // enough
  1861. return typePattern;
  1862. } catch (ParserException e) {
  1863. reportError("Invalid type pattern'" + patternString + "' : " + e.getLocation(), location);
  1864. return null;
  1865. }
  1866. }
  1867. static class ThrownFormalNotDeclaredInAdviceSignatureException extends Exception {
  1868. private final String formalName;
  1869. public ThrownFormalNotDeclaredInAdviceSignatureException(String formalName) {
  1870. this.formalName = formalName;
  1871. }
  1872. public String getFormalName() {
  1873. return formalName;
  1874. }
  1875. }
  1876. static class ReturningFormalNotDeclaredInAdviceSignatureException extends Exception {
  1877. private final String formalName;
  1878. public ReturningFormalNotDeclaredInAdviceSignatureException(String formalName) {
  1879. this.formalName = formalName;
  1880. }
  1881. public String getFormalName() {
  1882. return formalName;
  1883. }
  1884. }
  1885. }