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.

InterTypeMethodDeclaration.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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 org.aspectj.ajdt.internal.compiler.lookup.EclipseFactory;
  15. import org.aspectj.ajdt.internal.compiler.lookup.EclipseTypeMunger;
  16. import org.aspectj.ajdt.internal.compiler.problem.AjProblemReporter;
  17. import org.aspectj.org.eclipse.jdt.internal.compiler.ClassFile;
  18. import org.aspectj.org.eclipse.jdt.internal.compiler.CompilationResult;
  19. import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument;
  20. import org.aspectj.org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
  21. import org.aspectj.org.eclipse.jdt.internal.compiler.ast.LocalDeclaration;
  22. import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeParameter;
  23. import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference;
  24. import org.aspectj.org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
  25. import org.aspectj.org.eclipse.jdt.internal.compiler.codegen.CodeStream;
  26. import org.aspectj.org.eclipse.jdt.internal.compiler.codegen.Opcodes;
  27. import org.aspectj.org.eclipse.jdt.internal.compiler.flow.FlowContext;
  28. import org.aspectj.org.eclipse.jdt.internal.compiler.flow.FlowInfo;
  29. import org.aspectj.org.eclipse.jdt.internal.compiler.flow.InitializationFlowContext;
  30. import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope;
  31. import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ExtraCompilerModifiers;
  32. import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LocalVariableBinding;
  33. import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
  34. import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
  35. import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
  36. import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TagBits;
  37. import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
  38. import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding;
  39. import org.aspectj.org.eclipse.jdt.internal.compiler.parser.Parser;
  40. import org.aspectj.org.eclipse.jdt.internal.compiler.problem.AbortCompilationUnit;
  41. import org.aspectj.weaver.AjAttribute;
  42. import org.aspectj.weaver.AjcMemberMaker;
  43. import org.aspectj.weaver.Constants;
  44. import org.aspectj.weaver.NameMangler;
  45. import org.aspectj.weaver.NewMethodTypeMunger;
  46. import org.aspectj.weaver.ResolvedMember;
  47. import org.aspectj.weaver.ResolvedMemberImpl;
  48. import org.aspectj.weaver.ResolvedType;
  49. import org.aspectj.weaver.Shadow;
  50. import org.aspectj.weaver.UnresolvedType;
  51. /**
  52. * An inter-type method declaration.
  53. *
  54. * @author Jim Hugunin
  55. */
  56. public class InterTypeMethodDeclaration extends InterTypeDeclaration {
  57. public InterTypeMethodDeclaration(CompilationResult result, TypeReference onType) {
  58. super(result, onType);
  59. }
  60. public void parseStatements(Parser parser, CompilationUnitDeclaration unit) {
  61. if (ignoreFurtherInvestigation)
  62. return;
  63. if (!Modifier.isAbstract(declaredModifiers)) {
  64. parser.parse(this, unit);
  65. }
  66. }
  67. protected char[] getPrefix() {
  68. return (NameMangler.ITD_PREFIX + "interMethod$").toCharArray();
  69. }
  70. public boolean isFinal() {
  71. return (declaredModifiers & ClassFileConstants.AccFinal) != 0;
  72. }
  73. // public boolean isAbstract() {
  74. // boolean b = (declaredModifiers & ClassFileConstants.AccAbstract) != 0;
  75. // return b;//super.isAbstract();
  76. // }
  77. @Override
  78. public void analyseCode(ClassScope classScope, FlowContext flowContext, FlowInfo flowInfo) {
  79. if (Modifier.isAbstract(declaredModifiers))
  80. return;
  81. super.analyseCode(classScope, flowContext, flowInfo);
  82. }
  83. public void resolve(ClassScope upperScope) {
  84. if (munger == null)
  85. ignoreFurtherInvestigation = true;
  86. if (binding == null)
  87. ignoreFurtherInvestigation = true;
  88. if (ignoreFurtherInvestigation)
  89. return;
  90. if (!Modifier.isStatic(declaredModifiers)) {
  91. this.arguments = AstUtil.insert(AstUtil.makeFinalArgument("ajc$this_".toCharArray(), onTypeBinding), this.arguments);
  92. binding.parameters = AstUtil.insert(onTypeBinding, binding.parameters);
  93. // If the inserted argument is a generic type, we should include the associated type variables to ensure
  94. // the generated signature is correct (it will be checked by eclipse when this type is consumed in binary form).
  95. TypeVariableBinding onTypeTVBs[] = onTypeBinding.typeVariables();
  96. if (onTypeTVBs!=null && onTypeTVBs.length!=0) {
  97. // The type parameters don't seem to need to be correct
  98. // TypeParameter tp = new TypeParameter();
  99. // tp.binding = tvb[0];
  100. // tp.name = tvb[0].sourceName;
  101. // this.typeParameters = AstUtil.insert(tp,this.typeParameters);
  102. binding.typeVariables = AstUtil.insert(onTypeBinding.typeVariables(), binding.typeVariables);
  103. }
  104. }
  105. super.resolve(upperScope);
  106. }
  107. public void resolveStatements() {
  108. checkAndSetModifiersForMethod();
  109. if ((modifiers & ExtraCompilerModifiers.AccSemicolonBody) != 0) {
  110. if ((declaredModifiers & ClassFileConstants.AccAbstract) == 0)
  111. scope.problemReporter().methodNeedBody(this);
  112. } else {
  113. // the method HAS a body --> abstract native modifiers are forbiden
  114. if (((declaredModifiers & ClassFileConstants.AccAbstract) != 0))
  115. scope.problemReporter().methodNeedingNoBody(this);
  116. }
  117. // XXX AMC we need to do this, but I'm not 100% comfortable as I don't
  118. // know why the return type is wrong in this case. Also, we don't seem to need
  119. // to do it for args...
  120. if (munger.getSignature().getReturnType().isRawType()) {
  121. if (!binding.returnType.isRawType()) {
  122. EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope);
  123. binding.returnType = world.makeTypeBinding(munger.getSignature().getReturnType());
  124. }
  125. }
  126. // check @Override annotation - based on MethodDeclaration.resolveStatements() @Override processing
  127. checkOverride: {
  128. if (this.binding == null)
  129. break checkOverride;
  130. if (this.scope.compilerOptions().sourceLevel < ClassFileConstants.JDK1_5)
  131. break checkOverride;
  132. boolean hasOverrideAnnotation = (this.binding.tagBits & TagBits.AnnotationOverride) != 0;
  133. // Need to verify
  134. if (hasOverrideAnnotation) {
  135. // Work out the real method binding that we can use for comparison
  136. EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(scope);
  137. MethodBinding realthing = world.makeMethodBinding(munger.getSignature(), munger.getTypeVariableAliases());
  138. boolean reportError = true;
  139. // Go up the hierarchy, looking for something we override
  140. ReferenceBinding supertype = onTypeBinding.superclass();
  141. while (supertype != null && reportError) {
  142. MethodBinding[] possibles = supertype.getMethods(declaredSelector);
  143. for (int i = 0; i < possibles.length; i++) {
  144. MethodBinding mb = possibles[i];
  145. boolean couldBeMatch = true;
  146. if (mb.parameters.length != realthing.parameters.length)
  147. couldBeMatch = false;
  148. else {
  149. for (int j = 0; j < mb.parameters.length && couldBeMatch; j++) {
  150. if (!mb.parameters[j].equals(realthing.parameters[j]))
  151. couldBeMatch = false;
  152. }
  153. }
  154. // return types compatible? (allow for covariance)
  155. if (couldBeMatch && !returnType.resolvedType.isCompatibleWith(mb.returnType))
  156. couldBeMatch = false;
  157. if (couldBeMatch)
  158. reportError = false;
  159. }
  160. supertype = supertype.superclass(); // superclass of object is null
  161. }
  162. // If we couldn't find something we override, report the error
  163. if (reportError)
  164. ((AjProblemReporter) this.scope.problemReporter()).itdMethodMustOverride(this, realthing);
  165. }
  166. }
  167. if (!Modifier.isAbstract(declaredModifiers))
  168. super.resolveStatements();
  169. if (Modifier.isStatic(declaredModifiers)) {
  170. // Check the target for ITD is not an interface
  171. if (onTypeBinding.isInterface()) {
  172. scope.problemReporter().signalError(sourceStart, sourceEnd, "methods in interfaces cannot be declared static");
  173. }
  174. }
  175. }
  176. public EclipseTypeMunger build(ClassScope classScope) {
  177. EclipseFactory factory = EclipseFactory.fromScopeLookupEnvironment(classScope);
  178. resolveOnType(classScope);
  179. if (ignoreFurtherInvestigation)
  180. return null;
  181. binding = classScope.referenceContext.binding.resolveTypesFor(binding);
  182. if (binding == null) {
  183. // if binding is null, we failed to find a type used in the method params, this error
  184. // has already been reported.
  185. this.ignoreFurtherInvestigation = true;
  186. // return null;
  187. throw new AbortCompilationUnit(compilationResult, null);
  188. }
  189. if (isTargetAnnotation(classScope, "method"))
  190. return null; // Error message output in isTargetAnnotation
  191. if (isTargetEnum(classScope, "method"))
  192. return null; // Error message output in isTargetEnum
  193. if (interTypeScope == null)
  194. return null; // We encountered a problem building the scope, don't continue - error already reported
  195. // This signature represents what we want consumers of the targetted type to 'see'
  196. // must use the factory method to build it since there may be typevariables from the binding
  197. // referred to in the parameters/returntype
  198. ResolvedMemberImpl sig = factory.makeResolvedMemberForITD(binding, onTypeBinding, interTypeScope.getRecoveryAliases());
  199. sig.resetName(new String(declaredSelector));
  200. int resetModifiers = declaredModifiers;
  201. if (binding.isVarargs())
  202. resetModifiers = resetModifiers | Constants.ACC_VARARGS;
  203. sig.resetModifiers(resetModifiers);
  204. NewMethodTypeMunger myMunger = new NewMethodTypeMunger(sig, null, typeVariableAliases);
  205. setMunger(myMunger);
  206. ResolvedType aspectType = factory.fromEclipse(classScope.referenceContext.binding);
  207. ResolvedMember me = myMunger.getInterMethodBody(aspectType);
  208. this.selector = binding.selector = me.getName().toCharArray();
  209. return new EclipseTypeMunger(factory, myMunger, aspectType, this);
  210. }
  211. private AjAttribute makeAttribute() {
  212. return new AjAttribute.TypeMunger(munger);
  213. }
  214. public void generateCode(ClassScope classScope, ClassFile classFile) {
  215. if (ignoreFurtherInvestigation) {
  216. // System.err.println("no code for " + this);
  217. return;
  218. }
  219. classFile.extraAttributes.add(new EclipseAttributeAdapter(makeAttribute()));
  220. if (!Modifier.isAbstract(declaredModifiers)) {
  221. super.generateCode(classScope, classFile); // this makes the interMethodBody
  222. }
  223. // annotations on the ITD declaration get put on this method
  224. generateDispatchMethod(classScope, classFile);
  225. }
  226. public void generateDispatchMethod(ClassScope classScope, ClassFile classFile) {
  227. EclipseFactory world = EclipseFactory.fromScopeLookupEnvironment(classScope);
  228. UnresolvedType aspectType = world.fromBinding(classScope.referenceContext.binding);
  229. ResolvedMember signature = munger.getSignature();
  230. ResolvedMember dispatchMember = AjcMemberMaker.interMethodDispatcher(signature, aspectType);
  231. MethodBinding dispatchBinding = world.makeMethodBinding(dispatchMember, munger.getTypeVariableAliases(), munger
  232. .getSignature().getDeclaringType());
  233. MethodBinding introducedMethod = world.makeMethodBinding(AjcMemberMaker.interMethod(signature, aspectType, onTypeBinding
  234. .isInterface()), munger.getTypeVariableAliases());
  235. classFile.generateMethodInfoHeader(dispatchBinding);
  236. int methodAttributeOffset = classFile.contentsOffset;
  237. // Watch out! We are passing in 'binding' here (instead of dispatchBinding) so that
  238. // the dispatch binding attributes will include the annotations from the 'binding'.
  239. // There is a chance that something else on the binding (e.g. throws clause) might
  240. // damage the attributes generated for the dispatch binding.
  241. int attributeNumber = classFile.generateMethodInfoAttributes(binding, makeEffectiveSignatureAttribute(signature,
  242. Shadow.MethodCall, false));
  243. int codeAttributeOffset = classFile.contentsOffset;
  244. classFile.generateCodeAttributeHeader();
  245. CodeStream codeStream = classFile.codeStream;
  246. codeStream.reset(this, classFile);
  247. codeStream.initializeMaxLocals(dispatchBinding);
  248. Argument[] itdArgs = this.arguments;
  249. if (itdArgs != null) {
  250. for (int a = 0; a < itdArgs.length; a++) {
  251. LocalVariableBinding lvb = itdArgs[a].binding;
  252. LocalVariableBinding lvbCopy = new LocalVariableBinding(lvb.name, lvb.type, lvb.modifiers, true);
  253. // e37: have to create a declaration so that the check in ClassFile (line 2538) won't skip it
  254. lvbCopy.declaration = new LocalDeclaration(itdArgs[a].name,0,0);
  255. codeStream.record(lvbCopy);
  256. lvbCopy.recordInitializationStartPC(0);
  257. lvbCopy.resolvedPosition = lvb.resolvedPosition;
  258. }
  259. }
  260. MethodBinding methodBinding = introducedMethod;
  261. TypeBinding[] parameters = methodBinding.parameters;
  262. int length = parameters.length;
  263. int resolvedPosition;
  264. if (methodBinding.isStatic())
  265. resolvedPosition = 0;
  266. else {
  267. codeStream.aload_0();
  268. resolvedPosition = 1;
  269. }
  270. for (int i = 0; i < length; i++) {
  271. codeStream.load(parameters[i], resolvedPosition);
  272. if ((parameters[i] == TypeBinding.DOUBLE) || (parameters[i] == TypeBinding.LONG))
  273. resolvedPosition += 2;
  274. else
  275. resolvedPosition++;
  276. }
  277. // TypeBinding type;
  278. if (methodBinding.isStatic())
  279. codeStream.invoke(Opcodes.OPC_invokestatic,methodBinding,null);
  280. else {
  281. if (methodBinding.declaringClass.isInterface()) {
  282. codeStream.invoke(Opcodes.OPC_invokeinterface, methodBinding, null);
  283. } else {
  284. codeStream.invoke(Opcodes.OPC_invokevirtual, methodBinding, null);
  285. }
  286. }
  287. AstUtil.generateReturn(dispatchBinding.returnType, codeStream);
  288. // tag the local variables as used throughout the method
  289. if (itdArgs != null && codeStream.locals != null) {
  290. for (int a = 0; a < itdArgs.length; a++) {
  291. if (codeStream.locals[a] != null) {
  292. codeStream.locals[a].recordInitializationEndPC(codeStream.position);
  293. }
  294. }
  295. }
  296. classFile.completeCodeAttribute(codeAttributeOffset);
  297. attributeNumber++;
  298. classFile.completeMethodInfo(binding,methodAttributeOffset, attributeNumber);
  299. }
  300. protected Shadow.Kind getShadowKindForBody() {
  301. return Shadow.MethodExecution;
  302. }
  303. // XXX this code is copied from MethodScope, with a few adjustments for ITDs...
  304. private void checkAndSetModifiersForMethod() {
  305. // for reported problems, we want the user to see the declared selector
  306. char[] realSelector = this.selector;
  307. this.selector = declaredSelector;
  308. final ReferenceBinding declaringClass = this.binding.declaringClass;
  309. if ((declaredModifiers & ExtraCompilerModifiers.AccAlternateModifierProblem) != 0)
  310. scope.problemReporter().duplicateModifierForMethod(onTypeBinding, this);
  311. // after this point, tests on the 16 bits reserved.
  312. int realModifiers = declaredModifiers & ExtraCompilerModifiers.AccJustFlag;
  313. // check for abnormal modifiers
  314. int unexpectedModifiers = ~(ClassFileConstants.AccPublic | ClassFileConstants.AccPrivate | ClassFileConstants.AccProtected
  315. | ClassFileConstants.AccAbstract | ClassFileConstants.AccStatic | ClassFileConstants.AccFinal
  316. | ClassFileConstants.AccSynchronized | ClassFileConstants.AccNative | ClassFileConstants.AccStrictfp);
  317. if ((realModifiers & unexpectedModifiers) != 0) {
  318. scope.problemReporter().illegalModifierForMethod(this);
  319. declaredModifiers &= ~ExtraCompilerModifiers.AccJustFlag | ~unexpectedModifiers;
  320. }
  321. // check for incompatible modifiers in the visibility bits, isolate the visibility bits
  322. int accessorBits = realModifiers
  323. & (ClassFileConstants.AccPublic | ClassFileConstants.AccProtected | ClassFileConstants.AccPrivate);
  324. if ((accessorBits & (accessorBits - 1)) != 0) {
  325. scope.problemReporter().illegalVisibilityModifierCombinationForMethod(onTypeBinding, this);
  326. // need to keep the less restrictive so disable Protected/Private as necessary
  327. if ((accessorBits & ClassFileConstants.AccPublic) != 0) {
  328. if ((accessorBits & ClassFileConstants.AccProtected) != 0)
  329. declaredModifiers &= ~ClassFileConstants.AccProtected;
  330. if ((accessorBits & ClassFileConstants.AccPrivate) != 0)
  331. declaredModifiers &= ~ClassFileConstants.AccPrivate;
  332. } else if ((accessorBits & ClassFileConstants.AccProtected) != 0 && (accessorBits & ClassFileConstants.AccPrivate) != 0) {
  333. declaredModifiers &= ~ClassFileConstants.AccPrivate;
  334. }
  335. }
  336. // check for modifiers incompatible with abstract modifier
  337. if ((declaredModifiers & ClassFileConstants.AccAbstract) != 0) {
  338. int incompatibleWithAbstract = ClassFileConstants.AccStatic | ClassFileConstants.AccFinal
  339. | ClassFileConstants.AccSynchronized | ClassFileConstants.AccNative | ClassFileConstants.AccStrictfp;
  340. if ((declaredModifiers & incompatibleWithAbstract) != 0)
  341. scope.problemReporter().illegalAbstractModifierCombinationForMethod(onTypeBinding, this);
  342. if (!onTypeBinding.isAbstract())
  343. scope.problemReporter().abstractMethodInAbstractClass((SourceTypeBinding) onTypeBinding, this);
  344. }
  345. /*
  346. * DISABLED for backward compatibility with javac (if enabled should also mark private methods as final) // methods from a
  347. * final class are final : 8.4.3.3 if (methodBinding.declaringClass.isFinal()) modifiers |= AccFinal;
  348. */
  349. // native methods cannot also be tagged as strictfp
  350. if ((declaredModifiers & ClassFileConstants.AccNative) != 0 && (declaredModifiers & ClassFileConstants.AccStrictfp) != 0)
  351. scope.problemReporter().nativeMethodsCannotBeStrictfp(onTypeBinding, this);
  352. // static members are only authorized in a static member or top level type
  353. if (((realModifiers & ClassFileConstants.AccStatic) != 0) && declaringClass.isNestedType() && !declaringClass.isStatic())
  354. scope.problemReporter().unexpectedStaticModifierForMethod(onTypeBinding, this);
  355. // restore the true selector now that any problems have been reported
  356. this.selector = realSelector;
  357. }
  358. }