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.

ConcreteAspectCodeGen.java 37KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  1. /*******************************************************************************
  2. * Copyright (c) 2005 Contributors.
  3. * All rights reserved.
  4. * This program and the accompanying materials are made available
  5. * under the terms of the Eclipse Public License v1.0
  6. * which accompanies this distribution and is available at
  7. * http://eclipse.org/legal/epl-v10.html
  8. *
  9. * Contributors:
  10. * Alexandre Vasseur initial implementation
  11. *******************************************************************************/
  12. package org.aspectj.weaver.loadtime;
  13. import java.lang.reflect.Modifier;
  14. import java.util.ArrayList;
  15. import java.util.Collection;
  16. import java.util.Collections;
  17. import java.util.HashMap;
  18. import java.util.Iterator;
  19. import java.util.List;
  20. import java.util.Map;
  21. import org.aspectj.apache.bcel.Constants;
  22. import org.aspectj.apache.bcel.classfile.ConstantPool;
  23. import org.aspectj.apache.bcel.classfile.JavaClass;
  24. import org.aspectj.apache.bcel.classfile.annotation.AnnotationGen;
  25. import org.aspectj.apache.bcel.classfile.annotation.ClassElementValue;
  26. import org.aspectj.apache.bcel.classfile.annotation.ElementValue;
  27. import org.aspectj.apache.bcel.classfile.annotation.NameValuePair;
  28. import org.aspectj.apache.bcel.classfile.annotation.SimpleElementValue;
  29. import org.aspectj.apache.bcel.generic.FieldGen;
  30. import org.aspectj.apache.bcel.generic.InstructionConstants;
  31. import org.aspectj.apache.bcel.generic.InstructionFactory;
  32. import org.aspectj.apache.bcel.generic.InstructionHandle;
  33. import org.aspectj.apache.bcel.generic.InstructionList;
  34. import org.aspectj.apache.bcel.generic.LocalVariableTag;
  35. import org.aspectj.apache.bcel.generic.ObjectType;
  36. import org.aspectj.apache.bcel.generic.Type;
  37. import org.aspectj.bridge.IMessage;
  38. import org.aspectj.bridge.Message;
  39. import org.aspectj.weaver.AjAttribute;
  40. import org.aspectj.weaver.AnnotationAJ;
  41. import org.aspectj.weaver.GeneratedReferenceTypeDelegate;
  42. import org.aspectj.weaver.ReferenceType;
  43. import org.aspectj.weaver.ResolvedMember;
  44. import org.aspectj.weaver.ResolvedType;
  45. import org.aspectj.weaver.UnresolvedType;
  46. import org.aspectj.weaver.World;
  47. import org.aspectj.weaver.bcel.BcelAnnotation;
  48. import org.aspectj.weaver.bcel.BcelPerClauseAspectAdder;
  49. import org.aspectj.weaver.bcel.BcelWorld;
  50. import org.aspectj.weaver.bcel.LazyClassGen;
  51. import org.aspectj.weaver.bcel.LazyMethodGen;
  52. import org.aspectj.weaver.loadtime.definition.Definition;
  53. import org.aspectj.weaver.loadtime.definition.Definition.AdviceKind;
  54. import org.aspectj.weaver.loadtime.definition.Definition.DeclareAnnotationKind;
  55. import org.aspectj.weaver.loadtime.definition.Definition.PointcutAndAdvice;
  56. import org.aspectj.weaver.patterns.BasicTokenSource;
  57. import org.aspectj.weaver.patterns.DeclareAnnotation;
  58. import org.aspectj.weaver.patterns.ISignaturePattern;
  59. import org.aspectj.weaver.patterns.ITokenSource;
  60. import org.aspectj.weaver.patterns.PatternParser;
  61. import org.aspectj.weaver.patterns.PerClause;
  62. import org.aspectj.weaver.patterns.TypePattern;
  63. /**
  64. * Generates bytecode for concrete-aspect.
  65. * <p>
  66. * The concrete aspect is generated annotation style aspect (so traditional Java constructs annotated with our AspectJ annotations).
  67. * As it is built during aop.xml definitions registration we perform the type munging for perclause, ie. aspectOf() artifact
  68. * directly, instead of waiting for it to go thru the weaver (that we are in the middle of configuring).
  69. *
  70. * @author Alexandre Vasseur
  71. * @author Andy Clement
  72. */
  73. public class ConcreteAspectCodeGen {
  74. private final static String[] EMPTY_STRINGS = new String[0];
  75. private final static Type[] EMPTY_TYPES = new Type[0];
  76. /**
  77. * Concrete aspect definition we build for
  78. */
  79. private final Definition.ConcreteAspect concreteAspect;
  80. /**
  81. * World for which we build for
  82. */
  83. private final World world;
  84. /**
  85. * Set to true when all is checks are verified
  86. */
  87. private boolean isValid = false;
  88. /**
  89. * The parent aspect, not concretized
  90. */
  91. private ResolvedType parent;
  92. /**
  93. * Aspect perClause, used for direct munging of aspectOf artifacts
  94. */
  95. private PerClause perclause;
  96. /**
  97. * Bytecode for the generated class
  98. */
  99. private byte[] bytes;
  100. /**
  101. * Create a new generator for a concrete aspect
  102. *
  103. * @param concreteAspect the aspect definition
  104. * @param world the related world (for type resolution, etc)
  105. */
  106. ConcreteAspectCodeGen(Definition.ConcreteAspect concreteAspect, World world) {
  107. this.concreteAspect = concreteAspect;
  108. this.world = world;
  109. }
  110. /**
  111. * Checks that concrete aspect is valid.
  112. *
  113. * @return true if ok, false otherwise
  114. */
  115. public boolean validate() {
  116. if (!(world instanceof BcelWorld)) {
  117. reportError("Internal error: world must be of type BcelWorld");
  118. return false;
  119. }
  120. // name must be undefined so far
  121. // TODO only convert the name to signature once, probably earlier than this
  122. ResolvedType current = world.lookupBySignature(UnresolvedType.forName(concreteAspect.name).getSignature());
  123. if (current != null && !current.isMissing()) {
  124. reportError("Attempt to concretize but chosen aspect name already defined: " + stringify());
  125. return false;
  126. }
  127. if (concreteAspect.pointcutsAndAdvice.size() != 0) {
  128. isValid = true;
  129. return true;
  130. }
  131. if (concreteAspect.declareAnnotations.size()!=0) {
  132. isValid = true;
  133. return true;
  134. }
  135. // it can happen that extends is null, for precedence only declaration
  136. if (concreteAspect.extend == null && concreteAspect.precedence != null) {
  137. if (concreteAspect.pointcuts.isEmpty()) {
  138. isValid = true;
  139. // m_perClause = new PerSingleton();
  140. parent = null;
  141. return true;// no need to checks more in that special case
  142. } else {
  143. reportError("Attempt to use nested pointcuts without extends clause: " + stringify());
  144. return false;
  145. }
  146. }
  147. String parentAspectName = concreteAspect.extend;
  148. if (parentAspectName.contains("<")) {
  149. // yikes, generic parent
  150. parent = world.resolve(UnresolvedType.forName(parentAspectName), true);
  151. if (parent.isMissing()) {
  152. reportError("Unable to resolve type reference: " + stringify());
  153. return false;
  154. }
  155. if (parent.isParameterizedType()) {
  156. UnresolvedType[] typeParameters = parent.getTypeParameters();
  157. for (UnresolvedType typeParameter : typeParameters) {
  158. if (typeParameter instanceof ResolvedType && ((ResolvedType) typeParameter).isMissing()) {
  159. reportError("Unablet to resolve type parameter '" + typeParameter.getName() + "' from " + stringify());
  160. return false;
  161. }
  162. }
  163. }
  164. } else {
  165. parent = world.resolve(concreteAspect.extend, true);
  166. }
  167. // handle inner classes
  168. if (parent.isMissing()) {
  169. // fallback on inner class lookup mechanism
  170. String fixedName = concreteAspect.extend;
  171. int hasDot = fixedName.lastIndexOf('.');
  172. while (hasDot > 0) {
  173. char[] fixedNameChars = fixedName.toCharArray();
  174. fixedNameChars[hasDot] = '$';
  175. fixedName = new String(fixedNameChars);
  176. hasDot = fixedName.lastIndexOf('.');
  177. parent = world.resolve(UnresolvedType.forName(fixedName), true);
  178. if (!parent.isMissing()) {
  179. break;
  180. }
  181. }
  182. }
  183. if (parent.isMissing()) {
  184. reportError("Cannot find parent aspect for: " + stringify());
  185. return false;
  186. }
  187. // extends must be abstract (allow for special case of Object where just using aspect for deows)
  188. if (!(parent.isAbstract() || parent.equals(ResolvedType.OBJECT))) {
  189. reportError("Attempt to concretize a non-abstract aspect: " + stringify());
  190. return false;
  191. }
  192. // m_parent must be aspect (allow for special case of Object where just using aspect for deows)
  193. if (!(parent.isAspect() || parent.equals(ResolvedType.OBJECT))) {
  194. reportError("Attempt to concretize a non aspect: " + stringify());
  195. return false;
  196. }
  197. // must have all abstractions defined
  198. List<String> elligibleAbstractions = new ArrayList<String>();
  199. Collection<ResolvedMember> abstractMethods = getOutstandingAbstractMethods(parent);
  200. for (ResolvedMember method : abstractMethods) {
  201. if ("()V".equals(method.getSignature())) {
  202. String n = method.getName();
  203. // Allow for the abstract pointcut being from a code style
  204. // aspect compiled with -1.5 (see test for 128744)
  205. if (n.startsWith("ajc$pointcut")) {
  206. n = n.substring(14);
  207. n = n.substring(0, n.indexOf("$"));
  208. elligibleAbstractions.add(n);
  209. } else if (hasPointcutAnnotation(method)) {
  210. elligibleAbstractions.add(method.getName());
  211. } else {
  212. // error, an outstanding abstract method that can't be
  213. // concretized in XML
  214. reportError("Abstract method '" + method.toString() + "' cannot be concretized in XML: " + stringify());
  215. return false;
  216. }
  217. } else {
  218. if (method.getName().startsWith("ajc$pointcut") || hasPointcutAnnotation(method)) {
  219. // it may be a pointcut but it doesn't meet the requirements for XML concretization
  220. reportError("Abstract method '"
  221. + method.toString()
  222. + "' cannot be concretized as a pointcut (illegal signature, must have no arguments, must return void): "
  223. + stringify());
  224. return false;
  225. } else {
  226. // error, an outstanding abstract method that can't be
  227. // concretized in XML
  228. reportError("Abstract method '" + method.toString() + "' cannot be concretized in XML: " + stringify());
  229. return false;
  230. }
  231. }
  232. }
  233. List<String> pointcutNames = new ArrayList<String>();
  234. for (Definition.Pointcut abstractPc : concreteAspect.pointcuts) {
  235. pointcutNames.add(abstractPc.name);
  236. }
  237. for (String elligiblePc : elligibleAbstractions) {
  238. if (!pointcutNames.contains(elligiblePc)) {
  239. reportError("Abstract pointcut '" + elligiblePc + "' not configured: " + stringify());
  240. return false;
  241. }
  242. }
  243. if (concreteAspect.perclause != null) {
  244. String perclauseString = concreteAspect.perclause;
  245. if (perclauseString.startsWith("persingleton")) {
  246. } else if (perclauseString.startsWith("percflow")) {
  247. } else if (perclauseString.startsWith("pertypewithin")) {
  248. } else if (perclauseString.startsWith("perthis")) {
  249. } else if (perclauseString.startsWith("pertarget")) {
  250. } else if (perclauseString.startsWith("percflowbelow")) {
  251. } else {
  252. reportError("Unrecognized per clause specified " + stringify());
  253. return false;
  254. }
  255. }
  256. isValid = true;
  257. return isValid;
  258. }
  259. private Collection<ResolvedMember> getOutstandingAbstractMethods(ResolvedType type) {
  260. Map<String, ResolvedMember> collector = new HashMap<String, ResolvedMember>();
  261. // let's get to the top of the hierarchy and then walk down ...
  262. // recording abstract methods then removing
  263. // them if they get defined further down the hierarchy
  264. getOutstandingAbstractMethodsHelper(type, collector);
  265. return collector.values();
  266. }
  267. // We are trying to determine abstract methods left over at the bottom of a
  268. // hierarchy that have not been concretized.
  269. private void getOutstandingAbstractMethodsHelper(ResolvedType type, Map<String, ResolvedMember> collector) {
  270. if (type == null) {
  271. return;
  272. }
  273. // Get to the top
  274. if (!type.equals(ResolvedType.OBJECT)) {
  275. if (type.getSuperclass() != null) {
  276. getOutstandingAbstractMethodsHelper(type.getSuperclass(), collector);
  277. }
  278. }
  279. ResolvedMember[] rms = type.getDeclaredMethods();
  280. if (rms != null) {
  281. for (ResolvedMember member : rms) {
  282. String key = member.getName() + member.getSignature();
  283. if (member.isAbstract()) {
  284. collector.put(key, member);
  285. } else {
  286. collector.remove(key);
  287. }
  288. }
  289. }
  290. }
  291. /**
  292. * Rebuild the XML snip that defines this concrete aspect, for log error purpose
  293. *
  294. * @return string repr.
  295. */
  296. private String stringify() {
  297. StringBuffer sb = new StringBuffer("<concrete-aspect name='");
  298. sb.append(concreteAspect.name);
  299. sb.append("' extends='");
  300. sb.append(concreteAspect.extend);
  301. sb.append("' perclause='");
  302. sb.append(concreteAspect.perclause);
  303. sb.append("'/> in aop.xml");
  304. // TODO needs the extra state from the definition (concretized pointcuts and advice definitions)
  305. return sb.toString();
  306. }
  307. private boolean hasPointcutAnnotation(ResolvedMember member) {
  308. AnnotationAJ[] as = member.getAnnotations();
  309. if (as == null || as.length == 0) {
  310. return false;
  311. }
  312. for (AnnotationAJ a : as) {
  313. if (a.getTypeSignature().equals("Lorg/aspectj/lang/annotation/Pointcut;")) {
  314. return true;
  315. }
  316. }
  317. return false;
  318. }
  319. public String getClassName() {
  320. return concreteAspect.name;
  321. }
  322. /**
  323. * @return the bytecode for the concrete aspect
  324. */
  325. public byte[] getBytes() {
  326. if (!isValid) {
  327. throw new RuntimeException("Must validate first");
  328. }
  329. if (bytes != null) {
  330. return bytes;
  331. }
  332. PerClause.Kind perclauseKind = PerClause.SINGLETON;
  333. PerClause parentPerClause = (parent != null ? parent.getPerClause() : null);
  334. if (parentPerClause != null) {
  335. perclauseKind = parentPerClause.getKind();
  336. }
  337. String perclauseString = null;
  338. if (concreteAspect.perclause != null) {
  339. perclauseString = concreteAspect.perclause;
  340. if (perclauseString.startsWith("persingleton")) {
  341. perclauseKind = PerClause.SINGLETON;
  342. } else if (perclauseString.startsWith("percflow")) {
  343. perclauseKind = PerClause.PERCFLOW;
  344. } else if (perclauseString.startsWith("pertypewithin")) {
  345. perclauseKind = PerClause.PERTYPEWITHIN;
  346. } else if (perclauseString.startsWith("perthis")) {
  347. perclauseKind = PerClause.PEROBJECT;
  348. } else if (perclauseString.startsWith("pertarget")) {
  349. perclauseKind = PerClause.PEROBJECT;
  350. } else if (perclauseString.startsWith("percflowbelow")) {
  351. perclauseKind = PerClause.PERCFLOW;
  352. }
  353. }
  354. // @Aspect //inherit clause from m_parent
  355. // @DeclarePrecedence("....") // if any
  356. // public class xxxName [extends xxxExtends] {
  357. // [@Pointcut(xxxExpression-n)
  358. // public void xxxName-n() {}]
  359. // }
  360. String parentName = "java/lang/Object";
  361. if (parent != null) {
  362. if (parent.isParameterizedType()) {
  363. parentName = parent.getGenericType().getName().replace('.', '/');
  364. } else {
  365. parentName = parent.getName().replace('.', '/');
  366. }
  367. }
  368. // @Aspect public class ...
  369. // TODO AV - we could point to the aop.xml that defines it and use JSR-45
  370. LazyClassGen cg = new LazyClassGen(concreteAspect.name.replace('.', '/'), parentName, null, Modifier.PUBLIC
  371. + Constants.ACC_SUPER, EMPTY_STRINGS, world);
  372. if (parent != null && parent.isParameterizedType()) {
  373. cg.setSuperClass(parent);
  374. }
  375. if (perclauseString == null) {
  376. AnnotationGen ag = new AnnotationGen(new ObjectType("org/aspectj/lang/annotation/Aspect"),
  377. Collections.<NameValuePair> emptyList(), true, cg.getConstantPool());
  378. cg.addAnnotation(ag);
  379. } else {
  380. // List elems = new ArrayList();
  381. List<NameValuePair> elems = new ArrayList<NameValuePair>();
  382. elems.add(new NameValuePair("value",
  383. new SimpleElementValue(ElementValue.STRING, cg.getConstantPool(), perclauseString), cg.getConstantPool()));
  384. AnnotationGen ag = new AnnotationGen(new ObjectType("org/aspectj/lang/annotation/Aspect"), elems, true,
  385. cg.getConstantPool());
  386. cg.addAnnotation(ag);
  387. }
  388. if (concreteAspect.precedence != null) {
  389. SimpleElementValue svg = new SimpleElementValue(ElementValue.STRING, cg.getConstantPool(), concreteAspect.precedence);
  390. List<NameValuePair> elems = new ArrayList<NameValuePair>();
  391. elems.add(new NameValuePair("value", svg, cg.getConstantPool()));
  392. AnnotationGen agprec = new AnnotationGen(new ObjectType("org/aspectj/lang/annotation/DeclarePrecedence"), elems, true,
  393. cg.getConstantPool());
  394. cg.addAnnotation(agprec);
  395. }
  396. // default constructor
  397. LazyMethodGen init = new LazyMethodGen(Modifier.PUBLIC, Type.VOID, "<init>", EMPTY_TYPES, EMPTY_STRINGS, cg);
  398. InstructionList cbody = init.getBody();
  399. cbody.append(InstructionConstants.ALOAD_0);
  400. cbody.append(cg.getFactory().createInvoke(parentName, "<init>", Type.VOID, EMPTY_TYPES, Constants.INVOKESPECIAL));
  401. cbody.append(InstructionConstants.RETURN);
  402. cg.addMethodGen(init);
  403. for (Definition.Pointcut abstractPc : concreteAspect.pointcuts) {
  404. // TODO AV - respect visibility instead of opening up as public?
  405. LazyMethodGen mg = new LazyMethodGen(Modifier.PUBLIC, Type.VOID, abstractPc.name, EMPTY_TYPES, EMPTY_STRINGS, cg);
  406. SimpleElementValue svg = new SimpleElementValue(ElementValue.STRING, cg.getConstantPool(), abstractPc.expression);
  407. List<NameValuePair> elems = new ArrayList<NameValuePair>();
  408. elems.add(new NameValuePair("value", svg, cg.getConstantPool()));
  409. AnnotationGen mag = new AnnotationGen(new ObjectType("org/aspectj/lang/annotation/Pointcut"), elems, true,
  410. cg.getConstantPool());
  411. AnnotationAJ max = new BcelAnnotation(mag, world);
  412. mg.addAnnotation(max);
  413. InstructionList body = mg.getBody();
  414. body.append(InstructionConstants.RETURN);
  415. cg.addMethodGen(mg);
  416. }
  417. // Construct any defined declare error/warnings
  418. if (concreteAspect.deows.size() > 0) {
  419. int counter = 1;
  420. for (Definition.DeclareErrorOrWarning deow : concreteAspect.deows) {
  421. // Building this:
  422. // @DeclareWarning("call(* javax.sql..*(..)) && !within(org.xyz.daos..*)")
  423. // static final String aMessage = "Only DAOs should be calling JDBC.";
  424. FieldGen field = new FieldGen(Modifier.FINAL, ObjectType.STRING, "rule" + (counter++), cg.getConstantPool());
  425. SimpleElementValue svg = new SimpleElementValue(ElementValue.STRING, cg.getConstantPool(), deow.pointcut);
  426. List<NameValuePair> elems = new ArrayList<NameValuePair>();
  427. elems.add(new NameValuePair("value", svg, cg.getConstantPool()));
  428. AnnotationGen mag = new AnnotationGen(new ObjectType("org/aspectj/lang/annotation/Declare"
  429. + (deow.isError ? "Error" : "Warning")), elems, true, cg.getConstantPool());
  430. field.addAnnotation(mag);
  431. field.setValue(deow.message);
  432. cg.addField(field, null);
  433. }
  434. }
  435. if (concreteAspect.pointcutsAndAdvice.size() > 0) {
  436. int adviceCounter = 1;
  437. for (PointcutAndAdvice paa : concreteAspect.pointcutsAndAdvice) {
  438. generateAdviceMethod(paa, adviceCounter, cg);
  439. adviceCounter++;
  440. }
  441. }
  442. if (concreteAspect.declareAnnotations.size()>0) {
  443. int decCounter = 1;
  444. for (Definition.DeclareAnnotation da: concreteAspect.declareAnnotations) {
  445. generateDeclareAnnotation(da,decCounter++,cg);
  446. }
  447. }
  448. // handle the perClause
  449. ReferenceType rt = new ReferenceType(ResolvedType.forName(concreteAspect.name).getSignature(), world);
  450. GeneratedReferenceTypeDelegate grtd = new GeneratedReferenceTypeDelegate(rt);
  451. grtd.setSuperclass(parent);
  452. rt.setDelegate(grtd);
  453. BcelPerClauseAspectAdder perClauseMunger = new BcelPerClauseAspectAdder(rt, perclauseKind);
  454. perClauseMunger.forceMunge(cg, false);
  455. // TODO AV - unsafe cast
  456. // register the fresh new class into the world repository as it does not
  457. // exist on the classpath anywhere
  458. JavaClass jc = cg.getJavaClass((BcelWorld) world);
  459. ((BcelWorld) world).addSourceObjectType(jc, true);
  460. bytes = jc.getBytes();
  461. return bytes;
  462. }
  463. /**
  464. * The DeclareAnnotation object encapsulates an method/field/type descriptor and an annotation. This uses a DeclareAnnotation object
  465. * captured from the XML (something like '<declare-annotation field="* field1(..)" annotation="@Annot(a='a',fred=false,'abc')"/>')
  466. * and builds the same construct that would have existed if the code style variant was used. This involves creating a member upon
  467. * which to hang the real annotation and then creating a classfile level attribute indicating a declare annotation is present
  468. * (that includes the signature pattern and a pointer to the real member holding the annotation).
  469. *
  470. */
  471. private void generateDeclareAnnotation(Definition.DeclareAnnotation da, int decCounter, LazyClassGen cg) {
  472. // Here is an example member from a code style declare annotation:
  473. //void ajc$declare_at_method_1();
  474. // RuntimeInvisibleAnnotations: length = 0x6
  475. // 00 01 00 1B 00 00
  476. // RuntimeVisibleAnnotations: length = 0x15
  477. // 00 01 00 1D 00 03 00 1E 73 00 1F 00 20 73 00 21
  478. // 00 22 73 00 23
  479. // org.aspectj.weaver.MethodDeclarationLineNumber: length = 0x8
  480. // 00 00 00 02 00 00 00 16
  481. // org.aspectj.weaver.AjSynthetic: length = 0x
  482. //
  483. // Code:
  484. // Stack=0, Locals=1, Args_size=1
  485. // 0: return
  486. // and at the class level a Declare attribute:
  487. // org.aspectj.weaver.Declare: length = 0x51
  488. // 05 00 00 00 03 01 00 05 40 41 6E 6E 6F 01 00 17
  489. // 61 6A 63 24 64 65 63 6C 61 72 65 5F 61 74 5F 6D
  490. // 65 74 68 6F 64 5F 31 01 01 00 00 00 00 05 05 00
  491. // 08 73 61 79 48 65 6C 6C 6F 00 01 04 00 00 00 00
  492. // 07 00 00 00 27 00 00 00 34 00 00 00 16 00 00 00
  493. // 3C
  494. AnnotationAJ constructedAnnotation = buildDeclareAnnotation_actualAnnotation(cg, da);
  495. if (constructedAnnotation==null) {
  496. return; // error occurred (and was reported), do not continue
  497. }
  498. String nameComponent = da.declareAnnotationKind.name().toLowerCase();
  499. String declareName = new StringBuilder("ajc$declare_at_").append(nameComponent).append("_").append(decCounter).toString();
  500. LazyMethodGen declareMethod = new LazyMethodGen(Modifier.PUBLIC, Type.VOID, declareName, Type.NO_ARGS, EMPTY_STRINGS, cg);
  501. InstructionList declareMethodBody = declareMethod.getBody();
  502. declareMethodBody.append(InstructionFactory.RETURN);
  503. declareMethod.addAnnotation(constructedAnnotation);
  504. DeclareAnnotation deca = null;
  505. ITokenSource tokenSource = BasicTokenSource.makeTokenSource(da.pattern,null);
  506. PatternParser pp = new PatternParser(tokenSource);
  507. if (da.declareAnnotationKind==DeclareAnnotationKind.Method || da.declareAnnotationKind==DeclareAnnotationKind.Field) {
  508. ISignaturePattern isp = (da.declareAnnotationKind==DeclareAnnotationKind.Method?pp.parseCompoundMethodOrConstructorSignaturePattern(true):pp.parseCompoundFieldSignaturePattern());
  509. deca = new DeclareAnnotation(da.declareAnnotationKind==DeclareAnnotationKind.Method?DeclareAnnotation.AT_METHOD:DeclareAnnotation.AT_FIELD, isp);
  510. } else if (da.declareAnnotationKind==DeclareAnnotationKind.Type) {
  511. TypePattern tp = pp.parseTypePattern();
  512. deca = new DeclareAnnotation(DeclareAnnotation.AT_TYPE,tp);
  513. }
  514. deca.setAnnotationMethod(declareName);
  515. deca.setAnnotationString(da.annotation);
  516. AjAttribute attribute = new AjAttribute.DeclareAttribute(deca);
  517. cg.addAttribute(attribute);
  518. cg.addMethodGen(declareMethod);
  519. }
  520. /**
  521. * Construct the annotation that the declare wants to add to the target.
  522. */
  523. private AnnotationAJ buildDeclareAnnotation_actualAnnotation(LazyClassGen cg, Definition.DeclareAnnotation da) {
  524. AnnotationGen anno = buildAnnotationFromString(cg.getConstantPool(),cg.getWorld(),da.annotation);
  525. if (anno==null) {
  526. return null;
  527. } else {
  528. AnnotationAJ bcelAnnotation = new BcelAnnotation(anno, world);
  529. return bcelAnnotation;
  530. }
  531. }
  532. // TODO support array values
  533. // TODO support annotation values
  534. /**
  535. * Build an AnnotationGen object based on a string, for example "@Foo(35,message='string')". Notice single quotes are fine for
  536. * strings as they don't need special handling in the XML.
  537. */
  538. private AnnotationGen buildAnnotationFromString(ConstantPool cp, World w, String annotationString) {
  539. int paren = annotationString.indexOf('(');
  540. if (paren==-1) {
  541. // the easy case, no values
  542. AnnotationGen aaj = buildBaseAnnotationType(cp,world,annotationString);
  543. return aaj;
  544. } else {
  545. // Discover the name and name/value pairs
  546. String name = annotationString.substring(0,paren);
  547. // break the rest into pieces based on the commas
  548. List<String> values = new ArrayList<String>();
  549. int pos = paren+1;
  550. int depth = 0;
  551. int len = annotationString.length();
  552. int start = pos;
  553. while (pos<len) {
  554. char ch = annotationString.charAt(pos);
  555. if (ch==')' && depth==0) {
  556. break; // reached the end
  557. }
  558. if (ch=='(' || ch=='[') {
  559. depth++;
  560. } else if (ch==')' || ch==']') {
  561. depth--;
  562. }
  563. if (ch==',' && depth==0) {
  564. // found a comma at the right level to end a name/value pair
  565. values.add(annotationString.substring(start,pos).trim());
  566. start=pos+1;
  567. }
  568. pos++;
  569. }
  570. if (start != pos) {
  571. // there is a last bit to add
  572. values.add(annotationString.substring(start,pos).trim());
  573. }
  574. AnnotationGen aaj = buildBaseAnnotationType(cp,world,name);
  575. if (aaj==null) {
  576. return null; // a check failed
  577. }
  578. String typename = aaj.getTypeName();
  579. ResolvedType type = UnresolvedType.forName(typename).resolve(world); // shame it isn't retrievable from the anno
  580. ResolvedMember[] rms = type.getDeclaredMethods();
  581. // Add the values
  582. for (String value: values) {
  583. int equalsIndex = value.indexOf("=");
  584. String key = "value";
  585. if (value.charAt(0)!='\"' && equalsIndex!=-1) {
  586. key = value.substring(0,equalsIndex).trim();
  587. value = value.substring(equalsIndex+1).trim();
  588. }
  589. boolean keyIsOk = false;
  590. for (ResolvedMember rm : rms) {
  591. NameValuePair nvp = null;
  592. if (rm.getName().equals(key)) {
  593. // found it!
  594. keyIsOk = true;
  595. UnresolvedType rt = rm.getReturnType();
  596. if (rt.isPrimitiveType()) {
  597. switch (rt.getSignature().charAt(0)) {
  598. case 'J': // long
  599. try {
  600. long longValue = Long.parseLong(value);
  601. nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.PRIMITIVE_LONG, cp, longValue), cp);
  602. } catch (NumberFormatException nfe) {
  603. reportError("unable to interpret annotation value '" + value + "' as a long");
  604. return null;
  605. }
  606. break;
  607. case 'S': // short
  608. try {
  609. short shortValue = Short.parseShort(value);
  610. nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.PRIMITIVE_SHORT, cp, shortValue), cp);
  611. } catch (NumberFormatException nfe) {
  612. reportError("unable to interpret annotation value '" + value + "' as a short");
  613. return null;
  614. }
  615. break;
  616. case 'F': // float
  617. try {
  618. float floatValue = Float.parseFloat(value);
  619. nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.PRIMITIVE_FLOAT, cp, floatValue), cp);
  620. } catch (NumberFormatException nfe) {
  621. reportError("unable to interpret annotation value '" + value + "' as a float");
  622. return null;
  623. }
  624. break;
  625. case 'D': // double
  626. try {
  627. double doubleValue = Double.parseDouble(value);
  628. nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.PRIMITIVE_DOUBLE, cp, doubleValue), cp);
  629. } catch (NumberFormatException nfe) {
  630. reportError("unable to interpret annotation value '" + value + "' as a double");
  631. return null;
  632. }
  633. break;
  634. case 'I': // integer
  635. try {
  636. int intValue = Integer.parseInt(value);
  637. nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.PRIMITIVE_INT, cp, intValue), cp);
  638. } catch (NumberFormatException nfe) {
  639. reportError("unable to interpret annotation value '" + value + "' as an integer");
  640. return null;
  641. }
  642. break;
  643. case 'B': // byte
  644. try {
  645. byte byteValue = Byte.parseByte(value);
  646. nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.PRIMITIVE_BYTE, cp, byteValue), cp);
  647. } catch (NumberFormatException nfe) {
  648. reportError("unable to interpret annotation value '" + value + "' as a byte");
  649. return null;
  650. }
  651. break;
  652. case 'C': // char
  653. if (value.length() < 2) {
  654. reportError("unable to interpret annotation value '" + value + "' as a char");
  655. return null;
  656. }
  657. nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.PRIMITIVE_CHAR, cp, value.charAt(1)), cp);
  658. break;
  659. case 'Z': // boolean
  660. try {
  661. boolean booleanValue = Boolean.parseBoolean(value);
  662. nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.PRIMITIVE_BOOLEAN, cp, booleanValue), cp);
  663. } catch (NumberFormatException nfe) {
  664. reportError("unable to interpret annotation value '" + value + "' as a boolean");
  665. return null;
  666. }
  667. break;
  668. default:
  669. reportError("not yet supporting XML setting of annotation values of type " + rt.getName());
  670. return null;
  671. }
  672. } else if (UnresolvedType.JL_STRING.equals(rt)) {
  673. if (value.length() < 2) {
  674. reportError("Invalid string value specified in annotation string: " + annotationString);
  675. return null;
  676. }
  677. value = value.substring(1, value.length() - 1); // trim the quotes off
  678. nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.STRING, cp, value), cp);
  679. } else if (UnresolvedType.JL_CLASS.equals(rt)) {
  680. // format of class string:
  681. // Foo.class
  682. // java.lang.Foo.class
  683. if (value.length() < 6) {
  684. reportError("Not a well formed class value for an annotation '" + value + "'");
  685. return null;
  686. }
  687. String clazz = value.substring(0, value.length() - 6);
  688. boolean qualified = clazz.contains(".");
  689. if (!qualified) {
  690. // if not qualified, have to assume java.lang
  691. clazz = "java.lang." + clazz;
  692. }
  693. nvp = new NameValuePair(key, new ClassElementValue(new ObjectType(clazz), cp), cp);
  694. }
  695. }
  696. if (nvp != null) {
  697. aaj.addElementNameValuePair(nvp);
  698. }
  699. }
  700. if (!keyIsOk) {
  701. reportError("annotation @"+typename+" does not have a value named "+key);
  702. return null;
  703. }
  704. }
  705. return aaj;
  706. }
  707. }
  708. private AnnotationGen buildBaseAnnotationType(ConstantPool cp,World world, String typename) {
  709. String annoname = typename;
  710. if (annoname.startsWith("@")) {
  711. annoname= annoname.substring(1);
  712. }
  713. ResolvedType annotationType = UnresolvedType.forName(annoname).resolve(world);
  714. if (!annotationType.isAnnotation()) {
  715. reportError("declare is not specifying an annotation type :"+typename);
  716. return null;
  717. }
  718. if (!annotationType.isAnnotationWithRuntimeRetention()) {
  719. reportError("declare is using an annotation type that does not have runtime retention: "+typename);
  720. return null;
  721. }
  722. List<NameValuePair> elems = new ArrayList<NameValuePair>();
  723. return new AnnotationGen(new ObjectType(annoname), elems, true, cp);
  724. }
  725. /**
  726. * Construct the annotation that indicates this is a declare
  727. */
  728. /**
  729. * The PointcutAndAdvice object encapsulates an advice kind, a pointcut and names a Java method in a particular class. Generate
  730. * an annotation style advice that has that pointcut whose implementation delegates to the Java method.
  731. */
  732. private void generateAdviceMethod(PointcutAndAdvice paa, int adviceCounter, LazyClassGen cg) {
  733. // Check: Verify the class to be called does exist:
  734. ResolvedType delegateClass = world.resolve(UnresolvedType.forName(paa.adviceClass));
  735. if (delegateClass.isMissing()) {
  736. reportError("Class to invoke cannot be found: '" + paa.adviceClass + "'");
  737. return;
  738. }
  739. // Generate a name for this advice, includes advice kind plus a counter
  740. String adviceName = new StringBuilder("generated$").append(paa.adviceKind.toString().toLowerCase()).append("$advice$")
  741. .append(adviceCounter).toString();
  742. // Build the annotation that encapsulates the pointcut
  743. AnnotationAJ aaj = buildAdviceAnnotation(cg, paa);
  744. // Chop up the supplied advice method string into its pieces.
  745. // Example: foo(JoinPoint jp, java.lang.String string)
  746. // JoinPoint and friends are recognized (so dont need fq package)
  747. String method = paa.adviceMethod;
  748. int paren = method.indexOf("(");
  749. String methodName = method.substring(0, paren);
  750. String signature = method.substring(paren);
  751. // Check: signature looks ok
  752. if (signature.charAt(0) != '(' || !signature.endsWith(")")) {
  753. reportError("Badly formatted parameter signature: '" + method + "'");
  754. return;
  755. }
  756. // Extract parameter types and names
  757. List<Type> paramTypes = new ArrayList<Type>();
  758. List<String> paramNames = new ArrayList<String>();
  759. if (signature.charAt(1) != ')') {
  760. // there are parameters to convert into a signature
  761. StringBuilder convertedSignature = new StringBuilder("(");
  762. boolean paramsBroken = false;
  763. int pos = 1;
  764. while (pos < signature.length() && signature.charAt(pos) != ')' && !paramsBroken) {
  765. int nextChunkEndPos = signature.indexOf(',', pos);
  766. if (nextChunkEndPos == -1) {
  767. nextChunkEndPos = signature.indexOf(')', pos);
  768. }
  769. // chunk will be a type plus a space plus a name
  770. String nextChunk = signature.substring(pos, nextChunkEndPos).trim();
  771. int space = nextChunk.indexOf(" ");
  772. ResolvedType resolvedParamType = null;
  773. if (space == -1) {
  774. // There is no parameter name, hopefully not needed!
  775. if (nextChunk.equals("JoinPoint")) {
  776. nextChunk = "org.aspectj.lang.JoinPoint";
  777. } else if (nextChunk.equals("JoinPoint.StaticPart")) {
  778. nextChunk = "org.aspectj.lang.JoinPoint$StaticPart";
  779. } else if (nextChunk.equals("ProceedingJoinPoint")) {
  780. nextChunk = "org.aspectj.lang.ProceedingJoinPoint";
  781. }
  782. UnresolvedType unresolvedParamType = UnresolvedType.forName(nextChunk);
  783. resolvedParamType = world.resolve(unresolvedParamType);
  784. } else {
  785. String typename = nextChunk.substring(0, space);
  786. if (typename.equals("JoinPoint")) {
  787. typename = "org.aspectj.lang.JoinPoint";
  788. } else if (typename.equals("JoinPoint.StaticPart")) {
  789. typename = "org.aspectj.lang.JoinPoint$StaticPart";
  790. } else if (typename.equals("ProceedingJoinPoint")) {
  791. typename = "org.aspectj.lang.ProceedingJoinPoint";
  792. }
  793. UnresolvedType unresolvedParamType = UnresolvedType.forName(typename);
  794. resolvedParamType = world.resolve(unresolvedParamType);
  795. String paramname = nextChunk.substring(space).trim();
  796. paramNames.add(paramname);
  797. }
  798. if (resolvedParamType.isMissing()) {
  799. reportError("Cannot find type specified as parameter: '" + nextChunk + "' from signature '" + signature + "'");
  800. paramsBroken = true;
  801. }
  802. paramTypes.add(Type.getType(resolvedParamType.getSignature()));
  803. convertedSignature.append(resolvedParamType.getSignature());
  804. pos = nextChunkEndPos + 1;
  805. }
  806. convertedSignature.append(")");
  807. signature = convertedSignature.toString();
  808. if (paramsBroken) {
  809. return;
  810. }
  811. }
  812. Type returnType = Type.VOID;
  813. // If around advice we must find the actual delegate method and use its return type
  814. if (paa.adviceKind == AdviceKind.Around) {
  815. ResolvedMember[] methods = delegateClass.getDeclaredMethods();
  816. ResolvedMember found = null;
  817. for (ResolvedMember candidate : methods) {
  818. if (candidate.getName().equals(methodName)) {
  819. UnresolvedType[] cparms = candidate.getParameterTypes();
  820. if (cparms.length == paramTypes.size()) {
  821. boolean paramsMatch = true;
  822. for (int i = 0; i < cparms.length; i++) {
  823. if (!cparms[i].getSignature().equals(paramTypes.get(i).getSignature())) {
  824. paramsMatch = false;
  825. break;
  826. }
  827. }
  828. if (paramsMatch) {
  829. found = candidate;
  830. break;
  831. }
  832. }
  833. }
  834. }
  835. if (found != null) {
  836. returnType = Type.getType(found.getReturnType().getSignature());
  837. } else {
  838. reportError("Unable to find method to invoke. In class: " + delegateClass.getName() + " cant find "
  839. + paa.adviceMethod);
  840. return;
  841. }
  842. }
  843. // Time to construct the method itself:
  844. LazyMethodGen advice = new LazyMethodGen(Modifier.PUBLIC, returnType, adviceName, paramTypes.toArray(new Type[paramTypes
  845. .size()]), EMPTY_STRINGS, cg);
  846. InstructionList adviceBody = advice.getBody();
  847. // Generate code to load the parameters
  848. int pos = 1; // first slot after 'this'
  849. for (Type paramType : paramTypes) {
  850. adviceBody.append(InstructionFactory.createLoad(paramType, pos));
  851. pos += paramType.getSize();
  852. }
  853. // Generate the delegate call
  854. adviceBody.append(cg.getFactory().createInvoke(paa.adviceClass, methodName, signature + returnType.getSignature(),
  855. Constants.INVOKESTATIC));
  856. // Generate the right return
  857. if (returnType == Type.VOID) {
  858. adviceBody.append(InstructionConstants.RETURN);
  859. } else {
  860. if (returnType.getSignature().length() < 2) {
  861. String sig = returnType.getSignature();
  862. if (sig.equals("F")) {
  863. adviceBody.append(InstructionConstants.FRETURN);
  864. } else if (sig.equals("D")) {
  865. adviceBody.append(InstructionConstants.DRETURN);
  866. } else if (sig.equals("J")) {
  867. adviceBody.append(InstructionConstants.LRETURN);
  868. } else {
  869. adviceBody.append(InstructionConstants.IRETURN);
  870. }
  871. } else {
  872. adviceBody.append(InstructionConstants.ARETURN);
  873. }
  874. }
  875. // Add the annotation
  876. advice.addAnnotation(aaj);
  877. InstructionHandle start = adviceBody.getStart();
  878. // Setup the local variable targeters so that the binding will work
  879. String sig = concreteAspect.name.replace('.', '/');
  880. start.addTargeter(new LocalVariableTag("L" + sig + ";", "this", 0, start.getPosition()));
  881. if (paramNames.size() > 0) {
  882. for (int i = 0; i < paramNames.size(); i++) {
  883. start.addTargeter(new LocalVariableTag(paramTypes.get(i).getSignature(), paramNames.get(i), i + 1, start
  884. .getPosition()));
  885. }
  886. }
  887. // Record the new method in the class
  888. cg.addMethodGen(advice);
  889. }
  890. /**
  891. * For the given PointcutAndAdvice build the correct advice annotation.
  892. */
  893. private AnnotationAJ buildAdviceAnnotation(LazyClassGen cg, PointcutAndAdvice paa) {
  894. SimpleElementValue svg = new SimpleElementValue(ElementValue.STRING, cg.getConstantPool(), paa.pointcut);
  895. List<NameValuePair> elems = new ArrayList<NameValuePair>();
  896. elems.add(new NameValuePair("value", svg, cg.getConstantPool()));
  897. AnnotationGen mag = new AnnotationGen(new ObjectType("org/aspectj/lang/annotation/" + paa.adviceKind.toString()), elems,
  898. true, cg.getConstantPool());
  899. AnnotationAJ aaj = new BcelAnnotation(mag, world);
  900. return aaj;
  901. }
  902. /**
  903. * Error reporting
  904. *
  905. * @param message
  906. */
  907. private void reportError(String message) {
  908. world.getMessageHandler().handleMessage(new Message(message, IMessage.ERROR, null, null));
  909. }
  910. }