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.

AdviceDeclaration.java 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. /* *******************************************************************
  2. * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
  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://www.eclipse.org/legal/epl-v10.html
  8. *
  9. * Contributors:
  10. * PARC initial implementation
  11. * ******************************************************************/
  12. package org.aspectj.ajdt.internal.compiler.ast;
  13. import java.lang.reflect.Modifier;
  14. import java.util.ArrayList;
  15. import java.util.List;
  16. import org.aspectj.ajdt.internal.compiler.lookup.AjTypeConstants;
  17. import org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
  18. import org.aspectj.ajdt.internal.compiler.lookup.PrivilegedHandler;
  19. import org.aspectj.bridge.context.CompilationAndWeavingContext;
  20. import org.aspectj.bridge.context.ContextToken;
  21. import org.aspectj.org.eclipse.jdt.core.Flags;
  22. import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
  23. import org.aspectj.org.eclipse.jdt.internal.compiler.ClassFile;
  24. import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult;
  25. import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation;
  26. import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument;
  27. import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference;
  28. import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleTypeReference;
  29. import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
  30. import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference;
  31. import org.aspectj.org.eclipse.jdt.internal.compiler.codegen.CodeStream;
  32. import org.aspectj.org.eclipse.jdt.internal.compiler.codegen.Opcodes;
  33. import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ArrayBinding;
  34. import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope;
  35. import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ExtraCompilerModifiers;
  36. import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
  37. import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
  38. import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
  39. import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeConstants;
  40. import org.aspectj.weaver.Advice;
  41. import org.aspectj.weaver.AdviceKind;
  42. import org.aspectj.weaver.AjAttribute;
  43. import org.aspectj.weaver.NameMangler;
  44. import org.aspectj.weaver.ResolvedMember;
  45. import org.aspectj.weaver.UnresolvedType;
  46. /**
  47. * Represents before, after and around advice in an aspect. Will generate a method corresponding to the body of the advice with an
  48. * attribute including additional information.
  49. *
  50. * @author Jim Hugunin
  51. */
  52. public class AdviceDeclaration extends AjMethodDeclaration {
  53. public PointcutDesignator pointcutDesignator; // set during parsing
  54. int baseArgumentCount; // referenced by IfPseudoToken.makeArguments
  55. public Argument extraArgument; // set during parsing, referenced by Proceed
  56. public AdviceKind kind; // set during parsing, referenced by Proceed and AsmElementFormatter
  57. private int extraArgumentFlags = 0;
  58. public MethodBinding proceedMethodBinding; // set during this.resolveStaments, referenced by Proceed
  59. public List proceedCalls = new ArrayList(2); // populated during Proceed.findEnclosingAround
  60. private boolean proceedInInners;
  61. private ResolvedMember[] proceedCallSignatures;
  62. private boolean[] formalsUnchangedToProceed;
  63. private UnresolvedType[] declaredExceptions;
  64. public AdviceDeclaration(CompilationResult result, AdviceKind kind) {
  65. super(result);
  66. this.returnType = TypeReference.baseTypeReference(T_void, 0);
  67. this.kind = kind;
  68. }
  69. // override
  70. protected int generateInfoAttributes(ClassFile classFile) {
  71. List l = new ArrayList(1);
  72. l.add(new EclipseAttributeAdapter(makeAttribute()));
  73. addDeclarationStartLineAttribute(l, classFile);
  74. return classFile.generateMethodInfoAttributes(binding, l);
  75. }
  76. private AjAttribute makeAttribute() {
  77. if (kind == AdviceKind.Around) {
  78. return new AjAttribute.AdviceAttribute(kind, pointcutDesignator.getPointcut(), extraArgumentFlags, sourceStart,
  79. sourceEnd, null, proceedInInners, proceedCallSignatures, formalsUnchangedToProceed, declaredExceptions);
  80. } else {
  81. return new AjAttribute.AdviceAttribute(kind, pointcutDesignator.getPointcut(), extraArgumentFlags, sourceStart,
  82. sourceEnd, null);
  83. }
  84. }
  85. // override
  86. public void resolveStatements() {
  87. if (binding == null || ignoreFurtherInvestigation)
  88. return;
  89. ClassScope upperScope = (ClassScope) scope.parent; // !!! safety
  90. modifiers = checkAndSetModifiers(modifiers, upperScope);
  91. int bindingModifiers = (modifiers | (binding.modifiers & ExtraCompilerModifiers.AccGenericSignature));
  92. binding.modifiers = bindingModifiers;
  93. if (kind == AdviceKind.AfterThrowing && extraArgument != null) {
  94. TypeBinding argTb = extraArgument.binding.type;
  95. TypeBinding expectedTb = upperScope.getJavaLangThrowable();
  96. if (!argTb.isCompatibleWith(expectedTb)) {
  97. scope.problemReporter().typeMismatchError(argTb, expectedTb, extraArgument,null);
  98. ignoreFurtherInvestigation = true;
  99. return;
  100. }
  101. }
  102. pointcutDesignator.finishResolveTypes(this, this.binding, baseArgumentCount, upperScope.referenceContext.binding);
  103. if (binding == null || ignoreFurtherInvestigation)
  104. return;
  105. if (kind == AdviceKind.Around) {
  106. ReferenceBinding[] exceptions = new ReferenceBinding[] { upperScope.getJavaLangThrowable() };
  107. proceedMethodBinding = new MethodBinding(Modifier.STATIC | Flags.AccSynthetic, "proceed".toCharArray(),
  108. binding.returnType, resize(baseArgumentCount + 1, binding.parameters), exceptions, binding.declaringClass);
  109. proceedMethodBinding.selector = CharOperation.concat(selector, proceedMethodBinding.selector);
  110. }
  111. super.resolveStatements(); // upperScope);
  112. if (binding != null)
  113. determineExtraArgumentFlags();
  114. if (kind == AdviceKind.Around) {
  115. int n = proceedCalls.size();
  116. // EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(upperScope);
  117. // System.err.println("access to: " + Arrays.asList(handler.getMembers()));
  118. // XXX set these correctly
  119. formalsUnchangedToProceed = new boolean[baseArgumentCount];
  120. proceedCallSignatures = new ResolvedMember[0];
  121. proceedInInners = false;
  122. declaredExceptions = new UnresolvedType[0];
  123. for (int i = 0; i < n; i++) {
  124. Proceed call = (Proceed) proceedCalls.get(i);
  125. if (call.inInner) {
  126. // System.err.println("proceed in inner: " + call);
  127. proceedInInners = true;
  128. // XXX wrong
  129. // proceedCallSignatures[i] = world.makeResolvedMember(call.binding);
  130. }
  131. }
  132. // ??? should reorganize into AspectDeclaration
  133. // if we have proceed in inners we won't ever be inlined so the code below is unneeded
  134. if (!proceedInInners) {
  135. PrivilegedHandler handler = (PrivilegedHandler) upperScope.referenceContext.binding.privilegedHandler;
  136. if (handler == null) {
  137. handler = new PrivilegedHandler((AspectDeclaration) upperScope.referenceContext);
  138. // upperScope.referenceContext.binding.privilegedHandler = handler;
  139. }
  140. this.traverse(new MakeDeclsPublicVisitor(), (ClassScope) null);
  141. AccessForInlineVisitor v = new AccessForInlineVisitor((AspectDeclaration) upperScope.referenceContext, handler);
  142. ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.ACCESS_FOR_INLINE,
  143. selector);
  144. this.traverse(v, (ClassScope) null);
  145. CompilationAndWeavingContext.leavingPhase(tok);
  146. // ??? if we found a construct that we can't inline, set
  147. // proceedInInners so that we won't try to inline this body
  148. if (!v.isInlinable)
  149. proceedInInners = true;
  150. }
  151. }
  152. }
  153. // called by Proceed.resolveType
  154. public int getDeclaredParameterCount() {
  155. // this only works before code generation
  156. return this.arguments.length - 3 - ((extraArgument == null) ? 0 : 1);
  157. // Advice.countOnes(extraArgumentFlags);
  158. }
  159. private void generateProceedMethod(ClassScope classScope, ClassFile classFile) {
  160. MethodBinding binding = proceedMethodBinding;
  161. classFile.generateMethodInfoHeader(binding);
  162. int methodAttributeOffset = classFile.contentsOffset;
  163. int attributeNumber = classFile.generateMethodInfoAttributes(binding, AstUtil.getAjSyntheticAttribute());
  164. int codeAttributeOffset = classFile.contentsOffset;
  165. classFile.generateCodeAttributeHeader();
  166. CodeStream codeStream = classFile.codeStream;
  167. codeStream.reset(this, classFile);
  168. // push the closure
  169. int nargs = binding.parameters.length;
  170. int closureIndex = 0;
  171. for (int i = 0; i < nargs - 1; i++) {
  172. closureIndex += AstUtil.slotsNeeded(binding.parameters[i]);
  173. }
  174. codeStream.aload(closureIndex);
  175. // build the Object[]
  176. codeStream.generateInlinedValue(nargs - 1);
  177. codeStream.newArray(new ArrayBinding(classScope.getType(TypeConstants.JAVA_LANG_OBJECT,
  178. TypeConstants.JAVA_LANG_OBJECT.length), 1, classScope.environment()));
  179. int index = 0;
  180. for (int i = 0; i < nargs - 1; i++) {
  181. TypeBinding type = binding.parameters[i];
  182. codeStream.dup();
  183. codeStream.generateInlinedValue(i);
  184. codeStream.load(type, index);
  185. index += AstUtil.slotsNeeded(type);
  186. if (type.isBaseType()) {
  187. codeStream.invoke(Opcodes.OPC_invokestatic, AjTypeConstants.getConversionMethodToObject(classScope, type), null);
  188. }
  189. codeStream.aastore();
  190. }
  191. // call run
  192. ReferenceBinding closureType = (ReferenceBinding) binding.parameters[nargs - 1];
  193. MethodBinding runMethod = closureType.getMethods("run".toCharArray())[0];
  194. codeStream.invoke(Opcodes.OPC_invokevirtual, runMethod, null);
  195. TypeBinding returnType = binding.returnType;
  196. if (returnType.isBaseType()) {
  197. codeStream.invoke(Opcodes.OPC_invokestatic, AjTypeConstants.getConversionMethodFromObject(classScope, returnType), null);
  198. } else {
  199. codeStream.checkcast(returnType);
  200. }
  201. AstUtil.generateReturn(returnType, codeStream);
  202. codeStream.recordPositionsFrom(0, 1);
  203. classFile.completeCodeAttribute(codeAttributeOffset);
  204. attributeNumber++;
  205. classFile.completeMethodInfo(binding,methodAttributeOffset, attributeNumber);
  206. }
  207. // override
  208. public void generateCode(ClassScope classScope, ClassFile classFile) {
  209. if (ignoreFurtherInvestigation)
  210. return;
  211. super.generateCode(classScope, classFile);
  212. if (proceedMethodBinding != null) {
  213. generateProceedMethod(classScope, classFile);
  214. }
  215. }
  216. private void determineExtraArgumentFlags() {
  217. if (extraArgument != null)
  218. extraArgumentFlags |= Advice.ExtraArgument;
  219. ThisJoinPointVisitor tjp = new ThisJoinPointVisitor(this);
  220. extraArgumentFlags |= tjp.removeUnusedExtraArguments();
  221. }
  222. private static TypeBinding[] resize(int newSize, TypeBinding[] bindings) {
  223. int len = bindings.length;
  224. TypeBinding[] ret = new TypeBinding[newSize];
  225. System.arraycopy(bindings, 0, ret, 0, Math.min(newSize, len));
  226. return ret;
  227. }
  228. /**
  229. * Add either the @Before, @After, @Around, @AfterReturning or @AfterThrowing annotation
  230. */
  231. public void addAtAspectJAnnotations() {
  232. Annotation adviceAnnotation = null;
  233. String pointcutExpression = pointcutDesignator.getPointcut().toString();
  234. String extraArgumentName = "";
  235. if (extraArgument != null) {
  236. extraArgumentName = new String(extraArgument.name);
  237. }
  238. String argNames = buildArgNameRepresentation();
  239. if (kind == AdviceKind.Before) {
  240. adviceAnnotation = AtAspectJAnnotationFactory.createBeforeAnnotation(pointcutExpression, argNames,
  241. declarationSourceStart);
  242. } else if (kind == AdviceKind.After) {
  243. adviceAnnotation = AtAspectJAnnotationFactory.createAfterAnnotation(pointcutExpression, argNames,
  244. declarationSourceStart);
  245. } else if (kind == AdviceKind.AfterReturning) {
  246. adviceAnnotation = AtAspectJAnnotationFactory.createAfterReturningAnnotation(pointcutExpression, argNames,
  247. extraArgumentName, declarationSourceStart);
  248. } else if (kind == AdviceKind.AfterThrowing) {
  249. adviceAnnotation = AtAspectJAnnotationFactory.createAfterThrowingAnnotation(pointcutExpression, argNames,
  250. extraArgumentName, declarationSourceStart);
  251. } else if (kind == AdviceKind.Around) {
  252. adviceAnnotation = AtAspectJAnnotationFactory.createAroundAnnotation(pointcutExpression, argNames,
  253. declarationSourceStart);
  254. }
  255. AtAspectJAnnotationFactory.addAnnotation(this, adviceAnnotation, this.scope);
  256. }
  257. private String buildArgNameRepresentation() {
  258. StringBuffer args = new StringBuffer();
  259. int numArgsWeCareAbout = getDeclaredParameterCount();
  260. if (this.arguments != null) {
  261. for (int i = 0; i < numArgsWeCareAbout; i++) {
  262. if (i != 0)
  263. args.append(",");
  264. args.append(new String(this.arguments[i].name));
  265. }
  266. }
  267. if (extraArgument != null) {
  268. if (numArgsWeCareAbout > 0) {
  269. args.append(",");
  270. }
  271. args.append(new String(extraArgument.name));
  272. }
  273. return args.toString();
  274. }
  275. // override, Called by ClassScope.postParse
  276. public void postParse(TypeDeclaration typeDec) {
  277. AspectDeclaration aspectDecl = (AspectDeclaration) typeDec;
  278. int adviceSequenceNumberInType = aspectDecl.adviceCounter++;
  279. StringBuffer stringifiedPointcut = new StringBuffer(30);
  280. pointcutDesignator.print(0, stringifiedPointcut);
  281. this.selector = NameMangler.adviceName(EclipseFactory.getName(typeDec.binding).replace('.', '_'), kind,
  282. adviceSequenceNumberInType, stringifiedPointcut.toString().hashCode()).toCharArray();
  283. if (arguments != null) {
  284. baseArgumentCount = arguments.length;
  285. }
  286. if (kind == AdviceKind.Around) {
  287. extraArgument = makeFinalArgument("ajc$aroundClosure", AjTypeConstants.getAroundClosureType());
  288. }
  289. int addedArguments = 3;
  290. if (extraArgument != null) {
  291. addedArguments += 1;
  292. }
  293. arguments = extendArgumentsLength(arguments, addedArguments);
  294. int index = baseArgumentCount;
  295. if (extraArgument != null) {
  296. arguments[index++] = extraArgument;
  297. }
  298. arguments[index++] = makeFinalArgument("thisJoinPointStaticPart", AjTypeConstants.getJoinPointStaticPartType());
  299. arguments[index++] = makeFinalArgument("thisJoinPoint", AjTypeConstants.getJoinPointType());
  300. arguments[index++] = makeFinalArgument("thisEnclosingJoinPointStaticPart", AjTypeConstants.getJoinPointStaticPartType());
  301. if (pointcutDesignator.isError()) {
  302. this.ignoreFurtherInvestigation = true;
  303. }
  304. pointcutDesignator.postParse(typeDec, this);
  305. }
  306. private int checkAndSetModifiers(int modifiers, ClassScope scope) {
  307. if (modifiers == 0)
  308. return Modifier.PUBLIC;
  309. else if (modifiers == Modifier.STRICT)
  310. return Modifier.PUBLIC | Modifier.STRICT;
  311. else {
  312. tagAsHavingErrors();
  313. scope.problemReporter().signalError(declarationSourceStart, sourceStart - 1,
  314. "illegal modifier on advice, only strictfp is allowed");
  315. return Modifier.PUBLIC;
  316. }
  317. }
  318. // called by IfPseudoToken
  319. public static Argument[] addTjpArguments(Argument[] arguments, TypeDeclaration containingTypeDec) {
  320. int index = arguments.length;
  321. arguments = extendArgumentsLength(arguments, 4);
  322. arguments[index++] = makeFinalArgument("thisJoinPointStaticPart", AjTypeConstants.getJoinPointStaticPartType());
  323. arguments[index++] = makeFinalArgument("thisJoinPoint", AjTypeConstants.getJoinPointType());
  324. arguments[index++] = makeFinalArgument("thisEnclosingJoinPointStaticPart", AjTypeConstants.getJoinPointStaticPartType());
  325. arguments[index++] = makeFinalArgument("thisAspectInstance", toReference(containingTypeDec.name));
  326. return arguments;
  327. }
  328. private static TypeReference toReference(char[] typename) {
  329. if (CharOperation.contains('.', typename)) {
  330. char[][] compoundName = CharOperation.splitOn('.', typename);
  331. return new QualifiedTypeReference(compoundName, new long[compoundName.length]);
  332. } else {
  333. return new SingleTypeReference(typename, 0);
  334. }
  335. }
  336. private static Argument makeFinalArgument(String name, TypeReference typeRef) {
  337. long pos = 0; // XXX encode start and end location
  338. return new Argument(name.toCharArray(), pos, typeRef, Modifier.FINAL);
  339. }
  340. private static Argument[] extendArgumentsLength(Argument[] args, int addedArguments) {
  341. if (args == null) {
  342. return new Argument[addedArguments];
  343. }
  344. int len = args.length;
  345. Argument[] ret = new Argument[len + addedArguments];
  346. System.arraycopy(args, 0, ret, 0, len);
  347. return ret;
  348. }
  349. // public String toString(int tab) {
  350. // String s = tabString(tab);
  351. // if (modifiers != AccDefault) {
  352. // s += modifiersString(modifiers);
  353. // }
  354. //
  355. // if (kind == AdviceKind.Around) {
  356. // s += returnTypeToString(0);
  357. // }
  358. //
  359. // s += new String(selector) + "("; //$NON-NLS-1$
  360. // if (arguments != null) {
  361. // for (int i = 0; i < arguments.length; i++) {
  362. // s += arguments[i].toString(0);
  363. // if (i != (arguments.length - 1))
  364. // s = s + ", "; //$NON-NLS-1$
  365. // };
  366. // };
  367. // s += ")"; //$NON-NLS-1$
  368. //
  369. // if (extraArgument != null) {
  370. // s += "(" + extraArgument.toString(0) + ")";
  371. // }
  372. //
  373. //
  374. //
  375. // if (thrownExceptions != null) {
  376. // s += " throws "; //$NON-NLS-1$
  377. // for (int i = 0; i < thrownExceptions.length; i++) {
  378. // s += thrownExceptions[i].toString(0);
  379. // if (i != (thrownExceptions.length - 1))
  380. // s = s + ", "; //$NON-NLS-1$
  381. // };
  382. // };
  383. //
  384. // s += ": ";
  385. // if (pointcutDesignator != null) {
  386. // s += pointcutDesignator.toString(0);
  387. // }
  388. //
  389. // s += toStringStatements(tab + 1);
  390. // return s;
  391. // }
  392. public StringBuffer printBody(int indent, StringBuffer output) {
  393. output.append(": ");
  394. if (pointcutDesignator != null) {
  395. output.append(pointcutDesignator.toString());
  396. }
  397. return super.printBody(indent, output);
  398. }
  399. public StringBuffer printReturnType(int indent, StringBuffer output) {
  400. if (this.kind == AdviceKind.Around) {
  401. return super.printReturnType(indent, output);
  402. }
  403. return output;
  404. }
  405. }