diff options
author | Andy Clement <aclement@pivotal.io> | 2019-01-23 18:53:51 -0800 |
---|---|---|
committer | Andy Clement <aclement@pivotal.io> | 2019-01-23 18:53:51 -0800 |
commit | afaa961b294eca20fa9d54359c53a1de2d3c41fd (patch) | |
tree | 4b756f0f0dc4764cfcaeb200756de79cd4cdf56a /org.aspectj.matcher/src/test | |
parent | 74dcae875f1c89b7e3fa2ffa6b524a3c187a597e (diff) | |
download | aspectj-afaa961b294eca20fa9d54359c53a1de2d3c41fd.tar.gz aspectj-afaa961b294eca20fa9d54359c53a1de2d3c41fd.zip |
mavenized org.aspectj.matcher module - wip
Diffstat (limited to 'org.aspectj.matcher/src/test')
38 files changed, 6638 insertions, 0 deletions
diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/matcher/tools/CommonAdvancedPointcutExpressionTests.java b/org.aspectj.matcher/src/test/java/org/aspectj/matcher/tools/CommonAdvancedPointcutExpressionTests.java new file mode 100644 index 000000000..532588363 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/matcher/tools/CommonAdvancedPointcutExpressionTests.java @@ -0,0 +1,689 @@ +/******************************************************************************* + * Copyright (c) 2008 Contributors + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Andy Clement + *******************************************************************************/ +package org.aspectj.matcher.tools; + +import junit.framework.TestCase; + +import org.aspectj.weaver.ResolvedMember; +import org.aspectj.weaver.ResolvedType; +import org.aspectj.weaver.World; +import org.aspectj.weaver.tools.StandardPointcutExpression; +import org.aspectj.weaver.tools.StandardPointcutParser; + +/** + * Test the use of the pointcut parser and matching infrastructure. The org.aspectj.matcher.tools infrastructure used should not be + * aware of what kind of World it is working with and only operate in terms of the type abstraction expressed in the + * org.aspectj.matcher project (so Members, etc). These tests require some testdata types. + * + * This is based on the Reflection oriented PointcutExpressionTest in the weaver project. + * + * @author Andy Clement + */ +public abstract class CommonAdvancedPointcutExpressionTests extends TestCase { + + private World world; + private StandardPointcutParser pointcutParser; + + protected abstract World getWorld(); + + protected void setUp() throws Exception { + super.setUp(); + world = getWorld(); + pointcutParser = StandardPointcutParser.getPointcutParserSupportingAllPrimitives(world); + } + + public void testResolvingOneType() { + assertFalse(world.resolve("testdata.SomeAnnotation").isMissing()); + assertFalse(world.resolve("testdata.MethodLevelAnnotation").isMissing()); + assertFalse(world.resolve("testdata.AnnotatedClass").isMissing()); + } + + public void testTypeLevelAnnotationMatchingWithStaticInitialization01() { + StandardPointcutExpression ex = pointcutParser.parsePointcutExpression("staticinitialization(@testdata.SomeAnnotation *)"); + ResolvedType jlString = world.resolve("java.lang.String"); + ResolvedType tAnnotatedClass = world.resolve("testdata.AnnotatedClass"); + + assertTrue(ex.matchesStaticInitialization(tAnnotatedClass).alwaysMatches()); + assertTrue(ex.matchesStaticInitialization(jlString).neverMatches()); + } + + public void testTypeLevelAnnotationMatchingWithExecution01() { + StandardPointcutExpression ex = pointcutParser.parsePointcutExpression("execution(* (@testdata.SomeAnnotation *).*(..))"); + ResolvedType jlString = world.resolve("java.lang.String"); + ResolvedType tAnnotatedClass = world.resolve("testdata.AnnotatedClass"); + assertTrue(ex.matchesMethodExecution(getMethod(tAnnotatedClass, "annotatedMethod", "()V")).alwaysMatches()); + assertTrue(ex.matchesMethodExecution(getMethod(jlString, "valueOf", "(Z)Ljava/lang/String;")).neverMatches()); + } + + public void testMethodLevelAnnotationMatchingWithExecution01() { + StandardPointcutExpression ex = pointcutParser + .parsePointcutExpression("execution(@testdata.MethodLevelAnnotation * *(..))"); + ResolvedType jlString = world.resolve("java.lang.String"); + ResolvedType tAnnotatedClass = world.resolve("testdata.AnnotatedClass"); + assertTrue(ex.matchesMethodExecution(getMethod(tAnnotatedClass, "annotatedMethod", "()V")).alwaysMatches()); + assertTrue(ex.matchesMethodExecution(getMethod(tAnnotatedClass, "nonAnnotatedMethod", "()V")).neverMatches()); + assertTrue(ex.matchesMethodExecution(getMethod(jlString, "valueOf", "(Z)Ljava/lang/String;")).neverMatches()); + } + + // + // ResolvedMember stringSplitMethod = getMethod(jlString, "split", "(Ljava/lang/String;I)[Ljava/lang/String;"); + // ResolvedMember stringValueOfIntMethod = getMethod(jlString, "valueOf", "(I)Ljava/lang/String;"); + // ResolvedMember listAddMethod = getMethod(juList, "add", "(Ljava/lang/Object;)Z"); + + // public void testResolveTypeAndRetrieveMethod() { + // ResolvedType type = world.resolve("java.lang.String"); + // assertNotNull(type); + // ResolvedMember method = getMethod(type, "valueOf", "(Z)Ljava/lang/String;"); // grab the method 'String valueOf()' + // assertNotNull(method); + // } + // + // public void testMethodExecutionMatching01() { + // checkAlwaysMatches("execution(String valueOf(boolean))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); + // } + // + // public void testMethodExecutionMatching02() { + // checkAlwaysMatches("execution(* *val*(..))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); + // checkAlwaysMatches("execution(String *(..))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); + // checkAlwaysMatches("execution(* *(boolean))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); + // checkAlwaysMatches("execution(* j*..*.valueOf(..))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); + // checkAlwaysMatches("execution(* *(*))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); + // + // checkNeverMatches("execution(* vulueOf(..))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); + // checkNeverMatches("execution(int *(..))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); + // checkNeverMatches("execution(* valueOf(String))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); + // checkNeverMatches("execution(private * valueOf(..))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); + // } + // + // public void testMethodExecutionMatching03() { + // checkAlwaysMatches("execution(* *())", "java.util.List", "toArray", "()[Ljava/lang/Object;"); + // checkAlwaysMatches("execution(*[] *())", "java.util.List", "toArray", "()[Ljava/lang/Object;"); + // checkAlwaysMatches("execution(*b*[] *())", "java.util.List", "toArray", "()[Ljava/lang/Object;"); + // } + // + // public void testMethodMatchesStaticInitialization() { + // StandardPointcutExpression ex = pointcutParser.parsePointcutExpression("staticinitialization(java.lang.String)"); + // assertNotNull(ex); + // + // ResolvedType jlString = world.resolve("java.lang.String"); + // + // boolean b = ex.matchesStaticInitialization(jlString).alwaysMatches(); + // assertTrue(b); + // } + + // public void testMethodExecutionMatching04() { + // was execution((* *..A.aa(..)) + // assertTrue("Should match execution of A.aa", ex.matchesMethodExecution(aa).alwaysMatches()); + // assertTrue("Should match execution of B.aa", ex.matchesMethodExecution(bsaa).alwaysMatches()); + // assertTrue("Should not match execution of A.a", ex.matchesMethodExecution(a).neverMatches()); + // ex = p.parsePointcutExpression("call(* *..A.a*(int))"); + // assertTrue("Should not match execution of A.a", ex.matchesMethodExecution(a).neverMatches()); + // + // // test this + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); + // assertTrue("Should match A", ex.matchesMethodExecution(a).alwaysMatches()); + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("Maybe matches B", ex.matchesMethodExecution(a).maybeMatches()); + // assertFalse("Maybe matches B", ex.matchesMethodExecution(a).alwaysMatches()); + // + // // test target + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); + // assertTrue("Should match A", ex.matchesMethodExecution(a).alwaysMatches()); + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("Maybe matches B", ex.matchesMethodExecution(a).maybeMatches()); + // assertFalse("Maybe matches B", ex.matchesMethodExecution(a).alwaysMatches()); + // + // // test args + // ex = p.parsePointcutExpression("args(..,int)"); + // assertTrue("Should match A.aa", ex.matchesMethodExecution(aa).alwaysMatches()); + // assertTrue("Should match A.aaa", ex.matchesMethodExecution(aaa).alwaysMatches()); + // assertTrue("Should not match A.a", ex.matchesMethodExecution(a).neverMatches()); + // + // // within + // ex = p.parsePointcutExpression("within(*..A)"); + // assertTrue("Matches in class A", ex.matchesMethodExecution(a).alwaysMatches()); + // assertTrue("Does not match in class B", ex.matchesMethodExecution(bsaa).neverMatches()); + // + // // withincode + // ex = p.parsePointcutExpression("withincode(* a*(..))"); + // assertTrue("Should not match", ex.matchesMethodExecution(a).neverMatches()); + + // public void testMatchesMethodCall() { + // PointcutExpression ex = p.parsePointcutExpression("call(* *..A.a*(..))"); + // assertTrue("Should match call to A.a()", ex.matchesMethodCall(a, a).alwaysMatches()); + // assertTrue("Should match call to A.aaa()", ex.matchesMethodCall(aaa, a).alwaysMatches()); + // assertTrue("Should match call to B.aa()", ex.matchesMethodCall(bsaa, a).alwaysMatches()); + // assertTrue("Should not match call to B.b()", ex.matchesMethodCall(b, a).neverMatches()); + // ex = p.parsePointcutExpression("call(* *..A.a*(int))"); + // assertTrue("Should match call to A.aa()", ex.matchesMethodCall(aa, a).alwaysMatches()); + // assertTrue("Should not match call to A.a()", ex.matchesMethodCall(a, a).neverMatches()); + // ex = p.parsePointcutExpression("call(void aaa(..)) && this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); + // assertTrue("Should match call to A.aaa() from Client", ex.matchesMethodCall(aaa, foo).alwaysMatches()); + // ex = p.parsePointcutExpression("call(void aaa(..)) && this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("Should match call to A.aaa() from B", ex.matchesMethodCall(aaa, b).alwaysMatches()); + // assertTrue("May match call to A.aaa() from A", ex.matchesMethodCall(aaa, a).maybeMatches()); + // assertFalse("May match call to A.aaa() from A", ex.matchesMethodCall(aaa, a).alwaysMatches()); + // ex = p.parsePointcutExpression("execution(* *.*(..))"); + // assertTrue("Should not match call to A.aa", ex.matchesMethodCall(aa, a).neverMatches()); + // // this + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); + // assertTrue("Should match Client", ex.matchesMethodCall(a, foo).alwaysMatches()); + // assertTrue("Should not match A", ex.matchesMethodCall(a, a).neverMatches()); + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("Should maybe match B", ex.matchesMethodCall(bsaa, a).maybeMatches()); + // assertFalse("Should maybe match B", ex.matchesMethodCall(bsaa, a).alwaysMatches()); + // // target + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); + // assertTrue("Should not match Client", ex.matchesMethodCall(a, a).neverMatches()); + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); + // assertTrue("Should match A", ex.matchesMethodCall(a, a).alwaysMatches()); + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("Should maybe match A", ex.matchesMethodCall(aa, a).maybeMatches()); + // assertFalse("Should maybe match A", ex.matchesMethodCall(aa, a).alwaysMatches()); + // // test args + // ex = p.parsePointcutExpression("args(..,int)"); + // assertTrue("Should match A.aa", ex.matchesMethodCall(aa, a).alwaysMatches()); + // assertTrue("Should match A.aaa", ex.matchesMethodCall(aaa, a).alwaysMatches()); + // assertTrue("Should not match A.a", ex.matchesMethodCall(a, a).neverMatches()); + // // within + // ex = p.parsePointcutExpression("within(*..A)"); + // assertTrue("Matches in class A", ex.matchesMethodCall(a, a).alwaysMatches()); + // assertTrue("Does not match in class B", ex.matchesMethodCall(a, b).neverMatches()); + // assertTrue("Matches in class A", ex.matchesMethodCall(a, A.class).alwaysMatches()); + // assertTrue("Does not match in class B", ex.matchesMethodCall(a, B.class).neverMatches()); + // // withincode + // ex = p.parsePointcutExpression("withincode(* a*(..))"); + // assertTrue("Should match", ex.matchesMethodCall(b, bsaa).alwaysMatches()); + // assertTrue("Should not match", ex.matchesMethodCall(b, b).neverMatches()); + // } + // public void testMatchesConstructorCall() { + // PointcutExpression ex = p.parsePointcutExpression("call(new(String))"); + // assertTrue("Should match A(String)", ex.matchesConstructorCall(asCons, b).alwaysMatches()); + // assertTrue("Should match B(String)", ex.matchesConstructorCall(bsStringCons, b).alwaysMatches()); + // assertTrue("Should not match B()", ex.matchesConstructorCall(bsCons, foo).neverMatches()); + // ex = p.parsePointcutExpression("call(*..A.new(String))"); + // assertTrue("Should match A(String)", ex.matchesConstructorCall(asCons, b).alwaysMatches()); + // assertTrue("Should not match B(String)", ex.matchesConstructorCall(bsStringCons, foo).neverMatches()); + // // this + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); + // assertTrue("Should match Client", ex.matchesConstructorCall(asCons, foo).alwaysMatches()); + // assertTrue("Should not match A", ex.matchesConstructorCall(asCons, a).neverMatches()); + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("Should maybe match B", ex.matchesConstructorCall(asCons, a).maybeMatches()); + // assertFalse("Should maybe match B", ex.matchesConstructorCall(asCons, a).alwaysMatches()); + // // target + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); + // assertTrue("Should not match Client", ex.matchesConstructorCall(asCons, foo).neverMatches()); + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); + // assertTrue("Should not match A (no target)", ex.matchesConstructorCall(asCons, a).neverMatches()); + // // args + // ex = p.parsePointcutExpression("args(String)"); + // assertTrue("Should match A(String)", ex.matchesConstructorCall(asCons, b).alwaysMatches()); + // assertTrue("Should match B(String)", ex.matchesConstructorCall(bsStringCons, foo).alwaysMatches()); + // assertTrue("Should not match B()", ex.matchesConstructorCall(bsCons, foo).neverMatches()); + // // within + // ex = p.parsePointcutExpression("within(*..A)"); + // assertTrue("Matches in class A", ex.matchesConstructorCall(asCons, a).alwaysMatches()); + // assertTrue("Does not match in class B", ex.matchesConstructorCall(asCons, b).neverMatches()); + // // withincode + // ex = p.parsePointcutExpression("withincode(* a*(..))"); + // assertTrue("Should match", ex.matchesConstructorCall(bsCons, aa).alwaysMatches()); + // assertTrue("Should not match", ex.matchesConstructorCall(bsCons, b).neverMatches()); + // } + // + // public void testMatchesConstructorExecution() { + // PointcutExpression ex = p.parsePointcutExpression("execution(new(String))"); + // assertTrue("Should match A(String)", ex.matchesConstructorExecution(asCons).alwaysMatches()); + // assertTrue("Should match B(String)", ex.matchesConstructorExecution(bsStringCons).alwaysMatches()); + // assertTrue("Should not match B()", ex.matchesConstructorExecution(bsCons).neverMatches()); + // ex = p.parsePointcutExpression("execution(*..A.new(String))"); + // assertTrue("Should match A(String)", ex.matchesConstructorExecution(asCons).alwaysMatches()); + // assertTrue("Should not match B(String)", ex.matchesConstructorExecution(bsStringCons).neverMatches()); + // + // // test this + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); + // assertTrue("Should match A", ex.matchesConstructorExecution(asCons).alwaysMatches()); + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("Maybe matches B", ex.matchesConstructorExecution(asCons).maybeMatches()); + // assertFalse("Maybe matches B", ex.matchesConstructorExecution(asCons).alwaysMatches()); + // assertTrue("Should match B", ex.matchesConstructorExecution(bsCons).alwaysMatches()); + // assertTrue("Does not match client", ex.matchesConstructorExecution(clientCons).neverMatches()); + // + // // test target + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); + // assertTrue("Should match A", ex.matchesConstructorExecution(asCons).alwaysMatches()); + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("Maybe matches B", ex.matchesConstructorExecution(asCons).maybeMatches()); + // assertFalse("Maybe matches B", ex.matchesConstructorExecution(asCons).alwaysMatches()); + // assertTrue("Should match B", ex.matchesConstructorExecution(bsCons).alwaysMatches()); + // assertTrue("Does not match client", ex.matchesConstructorExecution(clientCons).neverMatches()); + // + // // within + // ex = p.parsePointcutExpression("within(*..A)"); + // assertTrue("Matches in class A", ex.matchesConstructorExecution(asCons).alwaysMatches()); + // assertTrue("Does not match in class B", ex.matchesConstructorExecution(bsCons).neverMatches()); + // + // // withincode + // ex = p.parsePointcutExpression("withincode(* a*(..))"); + // assertTrue("Does not match", ex.matchesConstructorExecution(bsCons).neverMatches()); + // + // // args + // ex = p.parsePointcutExpression("args(String)"); + // assertTrue("Should match A(String)", ex.matchesConstructorExecution(asCons).alwaysMatches()); + // assertTrue("Should match B(String)", ex.matchesConstructorExecution(bsStringCons).alwaysMatches()); + // assertTrue("Should not match B()", ex.matchesConstructorExecution(bsCons).neverMatches()); + // } + // + // public void testMatchesAdviceExecution() { + // PointcutExpression ex = p.parsePointcutExpression("adviceexecution()"); + // assertTrue("Should match (advice) A.a", ex.matchesAdviceExecution(a).alwaysMatches()); + // // test this + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); + // assertTrue("Should match Client", ex.matchesAdviceExecution(foo).alwaysMatches()); + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("Maybe matches B", ex.matchesAdviceExecution(a).maybeMatches()); + // assertFalse("Maybe matches B", ex.matchesAdviceExecution(a).alwaysMatches()); + // assertTrue("Does not match client", ex.matchesAdviceExecution(foo).neverMatches()); + // + // // test target + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); + // assertTrue("Should match Client", ex.matchesAdviceExecution(foo).alwaysMatches()); + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("Maybe matches B", ex.matchesAdviceExecution(a).maybeMatches()); + // assertFalse("Maybe matches B", ex.matchesAdviceExecution(a).alwaysMatches()); + // assertTrue("Does not match client", ex.matchesAdviceExecution(foo).neverMatches()); + // + // // test within + // ex = p.parsePointcutExpression("within(*..A)"); + // assertTrue("Matches in class A", ex.matchesAdviceExecution(a).alwaysMatches()); + // assertTrue("Does not match in class B", ex.matchesAdviceExecution(b).neverMatches()); + // + // // withincode + // ex = p.parsePointcutExpression("withincode(* a*(..))"); + // assertTrue("Does not match", ex.matchesAdviceExecution(a).neverMatches()); + // + // // test args + // ex = p.parsePointcutExpression("args(..,int)"); + // assertTrue("Should match A.aa", ex.matchesAdviceExecution(aa).alwaysMatches()); + // assertTrue("Should match A.aaa", ex.matchesAdviceExecution(aaa).alwaysMatches()); + // assertTrue("Should not match A.a", ex.matchesAdviceExecution(a).neverMatches()); + // } + // + // public void testMatchesHandler() { + // PointcutExpression ex = p.parsePointcutExpression("handler(Exception)"); + // assertTrue("Should match catch(Exception)", ex.matchesHandler(Exception.class, Client.class).alwaysMatches()); + // assertTrue("Should not match catch(Throwable)", ex.matchesHandler(Throwable.class, Client.class).neverMatches()); + // // test this + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); + // assertTrue("Should match Client", ex.matchesHandler(Exception.class, foo).alwaysMatches()); + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("Maybe matches B", ex.matchesHandler(Exception.class, a).maybeMatches()); + // assertFalse("Maybe matches B", ex.matchesHandler(Exception.class, a).alwaysMatches()); + // assertTrue("Does not match client", ex.matchesHandler(Exception.class, foo).neverMatches()); + // // target - no target for exception handlers + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); + // assertTrue("Should match Client", ex.matchesHandler(Exception.class, foo).neverMatches()); + // // args + // ex = p.parsePointcutExpression("args(Exception)"); + // assertTrue("Should match Exception", ex.matchesHandler(Exception.class, foo).alwaysMatches()); + // assertTrue("Should match RuntimeException", ex.matchesHandler(RuntimeException.class, foo).alwaysMatches()); + // assertTrue("Should not match String", ex.matchesHandler(String.class, foo).neverMatches()); + // assertTrue("Maybe matches Throwable", ex.matchesHandler(Throwable.class, foo).maybeMatches()); + // assertFalse("Maybe matches Throwable", ex.matchesHandler(Throwable.class, foo).alwaysMatches()); + // // within + // ex = p.parsePointcutExpression("within(*..Client)"); + // assertTrue("Matches in class Client", ex.matchesHandler(Exception.class, foo).alwaysMatches()); + // assertTrue("Does not match in class B", ex.matchesHandler(Exception.class, b).neverMatches()); + // // withincode + // ex = p.parsePointcutExpression("withincode(* a*(..))"); + // assertTrue("Matches within aa", ex.matchesHandler(Exception.class, aa).alwaysMatches()); + // assertTrue("Does not match within b", ex.matchesHandler(Exception.class, b).neverMatches()); + // } + // + // public void testMatchesInitialization() { + // PointcutExpression ex = p.parsePointcutExpression("initialization(new(String))"); + // assertTrue("Should match A(String)", ex.matchesInitialization(asCons).alwaysMatches()); + // assertTrue("Should match B(String)", ex.matchesInitialization(bsStringCons).alwaysMatches()); + // assertTrue("Should not match B()", ex.matchesInitialization(bsCons).neverMatches()); + // ex = p.parsePointcutExpression("initialization(*..A.new(String))"); + // assertTrue("Should match A(String)", ex.matchesInitialization(asCons).alwaysMatches()); + // assertTrue("Should not match B(String)", ex.matchesInitialization(bsStringCons).neverMatches()); + // // test this + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); + // assertTrue("Should match A", ex.matchesInitialization(asCons).alwaysMatches()); + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("Maybe matches B", ex.matchesInitialization(asCons).maybeMatches()); + // assertFalse("Maybe matches B", ex.matchesInitialization(asCons).alwaysMatches()); + // + // // test target + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); + // assertTrue("Should match A", ex.matchesInitialization(asCons).alwaysMatches()); + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("Maybe matches B", ex.matchesInitialization(asCons).maybeMatches()); + // assertFalse("Maybe matches B", ex.matchesInitialization(asCons).alwaysMatches()); + // // within + // ex = p.parsePointcutExpression("within(*..A)"); + // assertTrue("Matches in class A", ex.matchesInitialization(asCons).alwaysMatches()); + // assertTrue("Does not match in class B", ex.matchesInitialization(bsCons).neverMatches()); + // // withincode + // ex = p.parsePointcutExpression("withincode(* a*(..))"); + // assertTrue("Does not match", ex.matchesInitialization(bsCons).neverMatches()); + // // args + // ex = p.parsePointcutExpression("args(String)"); + // assertTrue("Should match A(String)", ex.matchesInitialization(asCons).alwaysMatches()); + // assertTrue("Should match B(String)", ex.matchesInitialization(bsStringCons).alwaysMatches()); + // assertTrue("Should not match B()", ex.matchesInitialization(bsCons).neverMatches()); + // } + // + // public void testMatchesPreInitialization() { + // PointcutExpression ex = p.parsePointcutExpression("preinitialization(new(String))"); + // assertTrue("Should match A(String)", ex.matchesPreInitialization(asCons).alwaysMatches()); + // assertTrue("Should match B(String)", ex.matchesPreInitialization(bsStringCons).alwaysMatches()); + // assertTrue("Should not match B()", ex.matchesPreInitialization(bsCons).neverMatches()); + // ex = p.parsePointcutExpression("preinitialization(*..A.new(String))"); + // assertTrue("Should match A(String)", ex.matchesPreInitialization(asCons).alwaysMatches()); + // assertTrue("Should not match B(String)", ex.matchesPreInitialization(bsStringCons).neverMatches()); + // // test this + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); + // assertTrue("No match, no this at preinit", ex.matchesPreInitialization(asCons).neverMatches()); + // + // // test target + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); + // assertTrue("No match, no target at preinit", ex.matchesPreInitialization(asCons).neverMatches()); + // + // // within + // ex = p.parsePointcutExpression("within(*..A)"); + // assertTrue("Matches in class A", ex.matchesPreInitialization(asCons).alwaysMatches()); + // assertTrue("Does not match in class B", ex.matchesPreInitialization(bsCons).neverMatches()); + // // withincode + // ex = p.parsePointcutExpression("withincode(* a*(..))"); + // assertTrue("Does not match", ex.matchesPreInitialization(bsCons).neverMatches()); + // // args + // ex = p.parsePointcutExpression("args(String)"); + // assertTrue("Should match A(String)", ex.matchesPreInitialization(asCons).alwaysMatches()); + // assertTrue("Should match B(String)", ex.matchesPreInitialization(bsStringCons).alwaysMatches()); + // assertTrue("Should not match B()", ex.matchesPreInitialization(bsCons).neverMatches()); + // } + // + // public void testMatchesStaticInitialization() { + // // staticinit + // PointcutExpression ex = p.parsePointcutExpression("staticinitialization(*..A+)"); + // assertTrue("Matches A", ex.matchesStaticInitialization(A.class).alwaysMatches()); + // assertTrue("Matches B", ex.matchesStaticInitialization(B.class).alwaysMatches()); + // assertTrue("Doesn't match Client", ex.matchesStaticInitialization(Client.class).neverMatches()); + // // this + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); + // assertTrue("No this", ex.matchesStaticInitialization(A.class).neverMatches()); + // // target + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); + // assertTrue("No target", ex.matchesStaticInitialization(A.class).neverMatches()); + // + // // args + // ex = p.parsePointcutExpression("args()"); + // assertTrue("No args", ex.matchesStaticInitialization(A.class).alwaysMatches()); + // ex = p.parsePointcutExpression("args(String)"); + // assertTrue("No args", ex.matchesStaticInitialization(A.class).neverMatches()); + // + // // within + // ex = p.parsePointcutExpression("within(*..A)"); + // assertTrue("Matches in class A", ex.matchesStaticInitialization(A.class).alwaysMatches()); + // assertTrue("Does not match in class B", ex.matchesStaticInitialization(B.class).neverMatches()); + // + // // withincode + // ex = p.parsePointcutExpression("withincode(* a*(..))"); + // assertTrue("Does not match", ex.matchesStaticInitialization(A.class).neverMatches()); + // } + // + // public void testMatchesFieldSet() { + // PointcutExpression ex = p.parsePointcutExpression("set(* *..A+.*)"); + // assertTrue("matches x", ex.matchesFieldSet(x, a).alwaysMatches()); + // assertTrue("matches y", ex.matchesFieldSet(y, foo).alwaysMatches()); + // assertTrue("does not match n", ex.matchesFieldSet(n, foo).neverMatches()); + // // this + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); + // assertTrue("matches Client", ex.matchesFieldSet(x, foo).alwaysMatches()); + // assertTrue("does not match A", ex.matchesFieldSet(n, a).neverMatches()); + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("maybe matches A", ex.matchesFieldSet(x, a).maybeMatches()); + // assertFalse("maybe matches A", ex.matchesFieldSet(x, a).alwaysMatches()); + // // target + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("matches B", ex.matchesFieldSet(y, foo).alwaysMatches()); + // assertTrue("maybe matches A", ex.matchesFieldSet(x, foo).maybeMatches()); + // assertFalse("maybe matches A", ex.matchesFieldSet(x, foo).alwaysMatches()); + // // args + // ex = p.parsePointcutExpression("args(int)"); + // assertTrue("matches x", ex.matchesFieldSet(x, a).alwaysMatches()); + // assertTrue("matches y", ex.matchesFieldSet(y, a).alwaysMatches()); + // assertTrue("does not match n", ex.matchesFieldSet(n, a).neverMatches()); + // // within + // ex = p.parsePointcutExpression("within(*..A)"); + // assertTrue("Matches in class A", ex.matchesFieldSet(x, a).alwaysMatches()); + // assertTrue("Does not match in class B", ex.matchesFieldSet(x, b).neverMatches()); + // // withincode + // ex = p.parsePointcutExpression("withincode(* a*(..))"); + // assertTrue("Should match", ex.matchesFieldSet(x, aa).alwaysMatches()); + // assertTrue("Should not match", ex.matchesFieldSet(x, b).neverMatches()); + // } + // + // public void testMatchesFieldGet() { + // PointcutExpression ex = p.parsePointcutExpression("get(* *..A+.*)"); + // assertTrue("matches x", ex.matchesFieldGet(x, a).alwaysMatches()); + // assertTrue("matches y", ex.matchesFieldGet(y, foo).alwaysMatches()); + // assertTrue("does not match n", ex.matchesFieldGet(n, foo).neverMatches()); + // // this + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); + // assertTrue("matches Client", ex.matchesFieldGet(x, foo).alwaysMatches()); + // assertTrue("does not match A", ex.matchesFieldGet(n, a).neverMatches()); + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("maybe matches A", ex.matchesFieldGet(x, a).maybeMatches()); + // assertFalse("maybe matches A", ex.matchesFieldGet(x, a).alwaysMatches()); + // // target + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("matches B", ex.matchesFieldGet(y, foo).alwaysMatches()); + // assertTrue("maybe matches A", ex.matchesFieldGet(x, foo).maybeMatches()); + // assertFalse("maybe matches A", ex.matchesFieldGet(x, foo).alwaysMatches()); + // // args - no args at get join point + // ex = p.parsePointcutExpression("args(int)"); + // assertTrue("matches x", ex.matchesFieldGet(x, a).neverMatches()); + // // within + // ex = p.parsePointcutExpression("within(*..A)"); + // assertTrue("Matches in class A", ex.matchesFieldGet(x, a).alwaysMatches()); + // assertTrue("Does not match in class B", ex.matchesFieldGet(x, b).neverMatches()); + // // withincode + // ex = p.parsePointcutExpression("withincode(* a*(..))"); + // assertTrue("Should match", ex.matchesFieldGet(x, aa).alwaysMatches()); + // assertTrue("Should not match", ex.matchesFieldGet(x, b).neverMatches()); + // } + // + // public void testArgsMatching() { + // // too few args + // PointcutExpression ex = p.parsePointcutExpression("args(*,*,*,*)"); + // assertTrue("Too few args", ex.matchesMethodExecution(foo).neverMatches()); + // assertTrue("Matching #args", ex.matchesMethodExecution(bar).alwaysMatches()); + // // one too few + ellipsis + // ex = p.parsePointcutExpression("args(*,*,*,..)"); + // assertTrue("Matches with ellipsis", ex.matchesMethodExecution(foo).alwaysMatches()); + // // exact number + ellipsis + // assertTrue("Matches with ellipsis", ex.matchesMethodExecution(bar).alwaysMatches()); + // assertTrue("Does not match with ellipsis", ex.matchesMethodExecution(a).neverMatches()); + // // too many + ellipsis + // ex = p.parsePointcutExpression("args(*,..,*)"); + // assertTrue("Matches with ellipsis", ex.matchesMethodExecution(bar).alwaysMatches()); + // assertTrue("Does not match with ellipsis", ex.matchesMethodExecution(a).neverMatches()); + // assertTrue("Matches with ellipsis", ex.matchesMethodExecution(aaa).alwaysMatches()); + // // exact match + // ex = p.parsePointcutExpression("args(String,int,Number)"); + // assertTrue("Matches exactly", ex.matchesMethodExecution(foo).alwaysMatches()); + // // maybe match + // ex = p.parsePointcutExpression("args(String,int,Double)"); + // assertTrue("Matches maybe", ex.matchesMethodExecution(foo).maybeMatches()); + // assertFalse("Matches maybe", ex.matchesMethodExecution(foo).alwaysMatches()); + // // never match + // ex = p.parsePointcutExpression("args(String,Integer,Number)"); + // if (LangUtil.is15VMOrGreater()) { + // assertTrue("matches", ex.matchesMethodExecution(foo).alwaysMatches()); + // } else { + // assertTrue("Does not match", ex.matchesMethodExecution(foo).neverMatches()); + // } + // } + // + // // public void testMatchesDynamically() { + // // // everything other than this,target,args should just return true + // // PointcutExpression ex = p.parsePointcutExpression("call(* *.*(..)) && execution(* *.*(..)) &&" + + // // "get(* *) && set(* *) && initialization(new(..)) && preinitialization(new(..)) &&" + + // // "staticinitialization(X) && adviceexecution() && within(Y) && withincode(* *.*(..)))"); + // // assertTrue("Matches dynamically",ex.matchesDynamically(a,b,new Object[0])); + // // // this + // // ex = p.parsePointcutExpression("this(String)"); + // // assertTrue("String matches",ex.matchesDynamically("",this,new Object[0])); + // // assertFalse("Object doesn't match",ex.matchesDynamically(new Object(),this,new Object[0])); + // // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); + // // assertTrue("A matches",ex.matchesDynamically(new A(""),this,new Object[0])); + // // assertTrue("B matches",ex.matchesDynamically(new B(""),this,new Object[0])); + // // // target + // // ex = p.parsePointcutExpression("target(String)"); + // // assertTrue("String matches",ex.matchesDynamically(this,"",new Object[0])); + // // assertFalse("Object doesn't match",ex.matchesDynamically(this,new Object(),new Object[0])); + // // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); + // // assertTrue("A matches",ex.matchesDynamically(this,new A(""),new Object[0])); + // // assertTrue("B matches",ex.matchesDynamically(this,new B(""),new Object[0])); + // // // args + // // ex = p.parsePointcutExpression("args(*,*,*,*)"); + // // assertFalse("Too few args",ex.matchesDynamically(null,null,new Object[]{a,b})); + // // assertTrue("Matching #args",ex.matchesDynamically(null,null,new Object[]{a,b,aa,aaa})); + // // // one too few + ellipsis + // // ex = p.parsePointcutExpression("args(*,*,*,..)"); + // // assertTrue("Matches with ellipsis",ex.matchesDynamically(null,null,new Object[]{a,b,aa,aaa})); + // // // exact number + ellipsis + // // assertTrue("Matches with ellipsis",ex.matchesDynamically(null,null,new Object[]{a,b,aa})); + // // assertFalse("Does not match with ellipsis",ex.matchesDynamically(null,null,new Object[]{a,b})); + // // // too many + ellipsis + // // ex = p.parsePointcutExpression("args(*,..,*)"); + // // assertTrue("Matches with ellipsis",ex.matchesDynamically(null,null,new Object[]{a,b,aa,aaa})); + // // assertFalse("Does not match with ellipsis",ex.matchesDynamically(null,null,new Object[]{a})); + // // assertTrue("Matches with ellipsis",ex.matchesDynamically(null,null,new Object[]{a,b})); + // // // exact match + // // ex = p.parsePointcutExpression("args(String,int,Number)"); + // // assertTrue("Matches exactly",ex.matchesDynamically(null,null,new Object[]{"",new Integer(5),new Double(5.0)})); + // // ex = p.parsePointcutExpression("args(String,Integer,Number)"); + // // assertTrue("Matches exactly",ex.matchesDynamically(null,null,new Object[]{"",new Integer(5),new Double(5.0)})); + // // // never match + // // ex = p.parsePointcutExpression("args(String,Integer,Number)"); + // // assertFalse("Does not match",ex.matchesDynamically(null,null,new Object[]{a,b,aa})); + // // } + // + // public void testGetPointcutExpression() { + // PointcutExpression ex = p.parsePointcutExpression("staticinitialization(*..A+)"); + // assertEquals("staticinitialization(*..A+)", ex.getPointcutExpression()); + // } + // + // public void testCouldMatchJoinPointsInType() { + // PointcutExpression ex = p.parsePointcutExpression("execution(* org.aspectj.weaver.tools.PointcutExpressionTest.B.*(..))"); + // assertTrue("Could maybe match String (as best we know at this point)", ex.couldMatchJoinPointsInType(String.class)); + // assertTrue("Will always match B", ex.couldMatchJoinPointsInType(B.class)); + // ex = p.parsePointcutExpression("within(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertFalse("Will never match String", ex.couldMatchJoinPointsInType(String.class)); + // assertTrue("Will always match B", ex.couldMatchJoinPointsInType(B.class)); + // } + // + // public void testMayNeedDynamicTest() { + // PointcutExpression ex = p.parsePointcutExpression("execution(* org.aspectj.weaver.tools.PointcutExpressionTest.B.*(..))"); + // assertFalse("No dynamic test needed", ex.mayNeedDynamicTest()); + // ex = p + // .parsePointcutExpression("execution(* org.aspectj.weaver.tools.PointcutExpressionTest.B.*(..)) && args(org.aspectj.weaver.tools.PointcutExpressionTest.X)"); + // assertTrue("Dynamic test needed", ex.mayNeedDynamicTest()); + // } + + // static class A { + // public A(String s) { + // } + // + // public void a() { + // } + // + // public void aa(int i) { + // } + // + // public void aaa(String s, int i) { + // } + // + // int x; + // } + // + // static class B extends A { + // public B() { + // super(""); + // } + // + // public B(String s) { + // super(s); + // } + // + // public String b() { + // return null; + // } + // + // public void aa(int i) { + // } + // + // int y; + // } + // + // static class Client { + // public Client() { + // } + // + // Number n; + // + // public void foo(String s, int i, Number n) { + // } + // + // public void bar(String s, int i, Integer i2, Number n) { + // } + // } + // + // static class X { + // } + + private ResolvedMember getMethod(ResolvedType type, String methodName, String methodSignature) { + ResolvedMember[] methods = type.getDeclaredMethods(); + for (int i = 0; i < methods.length; i++) { + if (methods[i].getName().equals(methodName) + && (methodSignature == null || methodSignature.equals(methods[i].getSignature()))) { + return methods[i]; + } + } + return null; + } + + @SuppressWarnings("unused") + private void checkAlwaysMatches(String pointcutExpression, String type, String methodName, String methodSignature) { + StandardPointcutExpression ex = pointcutParser.parsePointcutExpression(pointcutExpression); + assertNotNull(ex); + ResolvedType resolvedType = world.resolve(type); + ResolvedMember method = getMethod(resolvedType, methodName, methodSignature); + assertNotNull(method); + boolean b = ex.matchesMethodExecution(method).alwaysMatches(); + assertTrue(b); + } + + @SuppressWarnings("unused") + private void checkNeverMatches(String pointcutExpression, String type, String methodName, String methodSignature) { + StandardPointcutExpression ex = pointcutParser.parsePointcutExpression(pointcutExpression); + assertNotNull(ex); + ResolvedType resolvedType = world.resolve(type); + ResolvedMember method = getMethod(resolvedType, methodName, methodSignature); + assertNotNull(method); + boolean b = ex.matchesMethodExecution(method).neverMatches(); + assertTrue(b); + } + +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/matcher/tools/CommonPointcutExpressionTests.java b/org.aspectj.matcher/src/test/java/org/aspectj/matcher/tools/CommonPointcutExpressionTests.java new file mode 100644 index 000000000..8fccfbf99 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/matcher/tools/CommonPointcutExpressionTests.java @@ -0,0 +1,770 @@ +/******************************************************************************* + * Copyright (c) 2008 Contributors + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Andy Clement + *******************************************************************************/ +package org.aspectj.matcher.tools; + +import junit.framework.TestCase; + +import org.aspectj.weaver.ResolvedMember; +import org.aspectj.weaver.ResolvedType; +import org.aspectj.weaver.UnresolvedType; +import org.aspectj.weaver.World; +import org.aspectj.weaver.tools.ShadowMatch; +import org.aspectj.weaver.tools.StandardPointcutExpression; +import org.aspectj.weaver.tools.StandardPointcutParser; + +/** + * Test the use of the pointcut parser and matching infrastructure. The org.aspectj.matcher.tools infrastructure used should not be + * aware of what kind of World it is working with and only operate in terms of the type abstraction expressed in the + * org.aspectj.matcher project (so Members, etc). These tests only use base java types, there is no other testdata. + * + * This is based on the Reflection oriented PointcutExpressionTest in the weaver project. + * + * @author Andy Clement + */ +public abstract class CommonPointcutExpressionTests extends TestCase { + + private World world; + private StandardPointcutParser pointcutParser; + + protected abstract World getWorld(); + + protected void setUp() throws Exception { + super.setUp(); + world = getWorld(); + pointcutParser = StandardPointcutParser.getPointcutParserSupportingAllPrimitives(world); + } + + // -- some very basic stuff, if these don't pass it isn't worth continuing + + public void testResolvingOneType() { + // do it via name + ResolvedType type = world.resolve("java.lang.String"); + assertNotNull(type); + // do it via signature + type = world.resolve(UnresolvedType.forSignature("Ljava/lang/String;")); + assertNotNull(type); + } + + public void testResolveTypeAndRetrieveMethod() { + ResolvedType type = world.resolve("java.lang.String"); + assertNotNull(type); + ResolvedMember method = getMethod(type, "valueOf", "(Z)Ljava/lang/String;"); // grab the method 'String valueOf()' + assertNotNull(method); + } + + // -- next few tests relate to matching different pointcut expressions against a method-execution join point + + public void testMethodExecutionMatching01() { + checkAlwaysMatches("execution(String valueOf(boolean))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); + } + + public void testMethodExecutionMatching02() { + checkAlwaysMatches("execution(* *val*(..))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); + checkAlwaysMatches("execution(String *(..))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); + checkAlwaysMatches("execution(* *(boolean))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); + checkAlwaysMatches("execution(* j*..*.valueOf(..))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); + checkAlwaysMatches("execution(* *(*))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); + + checkNeverMatches("execution(* vulueOf(..))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); + checkNeverMatches("execution(int *(..))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); + checkNeverMatches("execution(* valueOf(String))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); + checkNeverMatches("execution(private * valueOf(..))", "java.lang.String", "valueOf", "(Z)Ljava/lang/String;"); + } + + public void testMethodExecutionMatching03() { + checkAlwaysMatches("execution(* *())", "java.util.List", "toArray", "()[Ljava/lang/Object;"); + checkAlwaysMatches("execution(*[] *())", "java.util.List", "toArray", "()[Ljava/lang/Object;"); + checkAlwaysMatches("execution(*b*[] *())", "java.util.List", "toArray", "()[Ljava/lang/Object;"); + } + + public void testConstructorExecutionMatching01() { + checkAlwaysMatches("execution(new())", "java.lang.String", "<init>", "()V"); + } + + public void testConstructorExecutionMatching02() { + checkAlwaysMatches("execution(new(char[]))", "java.lang.String", "<init>", "([C)V"); + checkAlwaysMatches("execution(new(..))", "java.lang.String", "<init>", "()V"); + checkAlwaysMatches("execution(new(..))", "java.lang.String", "<init>", "(Ljava/lang/String;)V"); + checkAlwaysMatches("execution(new(*))", "java.lang.String", "<init>", "(Ljava/lang/String;)V"); + checkNeverMatches("execution(new(*))", "java.lang.String", "<init>", "()V"); + checkAlwaysMatches("execution(new(*,*,*))", "java.lang.String", "<init>", "([CII)V"); + checkAlwaysMatches("execution(new(*,int,*))", "java.lang.String", "<init>", "([III)V"); + checkNeverMatches("execution(new(..,int[]))", "java.lang.String", "<init>", "([III)V"); + } + + public void testConstructorExecutionMatching03() { + + ResolvedType jlArrayList = world.resolve("java.util.ArrayList"); + ResolvedType juList = world.resolve("java.util.List"); + + StandardPointcutExpression ex = pointcutParser.parsePointcutExpression("execution(java.util.ArrayList.new(..))"); + assertNotNull(ex); + + // simple constructor + ShadowMatch shadowMatch = ex.matchesMethodExecution(getMethod(jlArrayList, "<init>", "()V")); + assertTrue(shadowMatch.alwaysMatches()); + + ex = pointcutParser.parsePointcutExpression("execution(ArrayList.new(..))"); + shadowMatch = ex.matchesMethodExecution(getMethod(jlArrayList, "<init>", "()V")); + assertTrue(shadowMatch.alwaysMatches()); + + ex = pointcutParser.parsePointcutExpression("execution(*Arr*.new(..))"); + shadowMatch = ex.matchesMethodExecution(getMethod(jlArrayList, "<init>", "()V")); + assertTrue(shadowMatch.alwaysMatches()); + + ex = pointcutParser.parsePointcutExpression("execution(java.util.*.new(..))"); + shadowMatch = ex.matchesMethodExecution(getMethod(jlArrayList, "<init>", "()V")); + assertTrue(shadowMatch.alwaysMatches()); + + ex = pointcutParser.parsePointcutExpression("execution(java.*.new(..))"); + shadowMatch = ex.matchesMethodExecution(getMethod(jlArrayList, "<init>", "()V")); + assertTrue(shadowMatch.neverMatches()); + + ex = pointcutParser.parsePointcutExpression("execution(java..*.new(..))"); + shadowMatch = ex.matchesMethodExecution(getMethod(jlArrayList, "<init>", "()V")); + assertTrue(shadowMatch.alwaysMatches()); + + ex = pointcutParser.parsePointcutExpression("execution(*..ArrayList.new(..))"); + shadowMatch = ex.matchesMethodExecution(getMethod(jlArrayList, "<init>", "()V")); + assertTrue(shadowMatch.alwaysMatches()); + } + + public void testMatchingThis01() { + StandardPointcutExpression ex = pointcutParser.parsePointcutExpression("this(java.lang.String)"); + ResolvedType jlString = world.resolve("java.lang.String"); + ResolvedType juList = world.resolve("java.util.List"); + + // regular method + ShadowMatch shadowMatch = ex.matchesMethodExecution(getMethod(jlString, "toLowerCase", "()Ljava/lang/String;")); + assertTrue(shadowMatch.alwaysMatches()); + + // static method + shadowMatch = ex.matchesMethodExecution(getMethod(jlString, "valueOf", "(Z)Ljava/lang/String;")); + assertTrue(shadowMatch.neverMatches()); + + // maybe match: this could be an ArrayList when clear() is called + ex = pointcutParser.parsePointcutExpression("this(java.util.ArrayList)"); + shadowMatch = ex.matchesMethodExecution(getMethod(juList, "clear", "()V")); + assertTrue(shadowMatch.maybeMatches()); + assertFalse(shadowMatch.neverMatches()); + assertFalse(shadowMatch.alwaysMatches()); + } + + public void testMatchingTarget01() { + StandardPointcutExpression ex = pointcutParser.parsePointcutExpression("target(java.lang.String)"); + ResolvedType jlString = world.resolve("java.lang.String"); + ResolvedType juList = world.resolve("java.util.List"); + + // regular method + ShadowMatch shadowMatch = ex.matchesMethodExecution(getMethod(jlString, "toLowerCase", "()Ljava/lang/String;")); + assertTrue(shadowMatch.alwaysMatches()); + + // static method + shadowMatch = ex.matchesMethodExecution(getMethod(jlString, "valueOf", "(Z)Ljava/lang/String;")); + assertTrue(shadowMatch.neverMatches()); + + // maybe match: target could be an ArrayList when clear() is called + ex = pointcutParser.parsePointcutExpression("target(java.util.ArrayList)"); + shadowMatch = ex.matchesMethodExecution(getMethod(juList, "clear", "()V")); + assertTrue(shadowMatch.maybeMatches()); + assertFalse(shadowMatch.neverMatches()); + assertFalse(shadowMatch.alwaysMatches()); + } + + public void testMatchingArgs01() { + StandardPointcutExpression ex = pointcutParser.parsePointcutExpression("args(..,int)"); + ResolvedType jlString = world.resolve("java.lang.String"); + ResolvedType juList = world.resolve("java.util.List"); + + ResolvedMember stringSplitMethod = getMethod(jlString, "split", "(Ljava/lang/String;I)[Ljava/lang/String;"); + ResolvedMember stringValueOfIntMethod = getMethod(jlString, "valueOf", "(I)Ljava/lang/String;"); + ResolvedMember stringValueOfLongMethod = getMethod(jlString, "valueOf", "(J)Ljava/lang/String;"); + + ShadowMatch shadowMatch = ex.matchesMethodExecution(stringSplitMethod); + assertTrue(shadowMatch.alwaysMatches()); + + shadowMatch = ex.matchesMethodExecution(stringValueOfIntMethod); + assertTrue(shadowMatch.alwaysMatches()); + + shadowMatch = ex.matchesMethodExecution(stringValueOfLongMethod); + assertTrue(shadowMatch.neverMatches()); + + // at List.add(Object) the Object might be a String + ex = pointcutParser.parsePointcutExpression("args(java.lang.String)"); + shadowMatch = ex.matchesMethodExecution(getMethod(juList, "add", "(Ljava/lang/Object;)Z")); + assertTrue(shadowMatch.maybeMatches()); + } + + public void testMatchingWithin01() { + StandardPointcutExpression ex = pointcutParser.parsePointcutExpression("within(java.lang.String)"); + ResolvedType jlString = world.resolve("java.lang.String"); + ResolvedType juList = world.resolve("java.util.List"); + + ResolvedMember stringSplitMethod = getMethod(jlString, "split", "(Ljava/lang/String;I)[Ljava/lang/String;"); + ResolvedMember stringValueOfIntMethod = getMethod(jlString, "valueOf", "(I)Ljava/lang/String;"); + ResolvedMember listAddMethod = getMethod(juList, "add", "(Ljava/lang/Object;)Z"); + + assertTrue(ex.matchesMethodExecution(stringSplitMethod).alwaysMatches()); + assertTrue(ex.matchesMethodExecution(stringValueOfIntMethod).alwaysMatches()); + assertTrue(ex.matchesMethodExecution(listAddMethod).neverMatches()); + } + + public void testMatchingWithinCode01() { + StandardPointcutExpression ex = pointcutParser.parsePointcutExpression("withincode(* *..String.*(..))"); + ResolvedType jlString = world.resolve("java.lang.String"); + ResolvedType juList = world.resolve("java.util.List"); + + ResolvedMember stringSplitMethod = getMethod(jlString, "split", "(Ljava/lang/String;I)[Ljava/lang/String;"); + ResolvedMember stringValueOfIntMethod = getMethod(jlString, "valueOf", "(I)Ljava/lang/String;"); + ResolvedMember listAddMethod = getMethod(juList, "add", "(Ljava/lang/Object;)Z"); + + assertTrue(ex.matchesMethodExecution(stringSplitMethod).neverMatches()); + assertTrue(ex.matchesMethodExecution(stringValueOfIntMethod).neverMatches()); + assertTrue(ex.matchesMethodExecution(listAddMethod).neverMatches()); + } + + // -- next few tests relate to matching different pointcut expressions against a method-call join point + + public void testCallMatchesMethodCall() { + StandardPointcutExpression ex = pointcutParser.parsePointcutExpression("call(* *..String.*(..))"); + ResolvedType jlString = world.resolve("java.lang.String"); + ResolvedType juList = world.resolve("java.util.List"); + + ResolvedMember stringSplitMethod = getMethod(jlString, "split", "(Ljava/lang/String;I)[Ljava/lang/String;"); + ResolvedMember stringValueOfIntMethod = getMethod(jlString, "valueOf", "(I)Ljava/lang/String;"); + ResolvedMember listAddMethod = getMethod(juList, "add", "(Ljava/lang/Object;)Z"); + + // call from list to string, should be OK + assertTrue(ex.matchesMethodCall(stringSplitMethod, listAddMethod).alwaysMatches()); + assertTrue(ex.matchesMethodCall(stringValueOfIntMethod, listAddMethod).alwaysMatches()); + assertTrue(ex.matchesMethodCall(listAddMethod, stringSplitMethod).neverMatches()); + + ex = pointcutParser.parsePointcutExpression("call(* *..ArrayList.*(..))"); + assertTrue(ex.matchesMethodCall(listAddMethod, stringSplitMethod).neverMatches()); + } + + public void testCall() { + StandardPointcutExpression ex = pointcutParser.parsePointcutExpression("call(* *..A.a*(..))"); + // assertTrue("Should match call to A.a()", ex.matchesMethodCall(a, a).alwaysMatches()); + // assertTrue("Should match call to A.aaa()", ex.matchesMethodCall(aaa, a).alwaysMatches()); + // assertTrue("Should match call to B.aa()", ex.matchesMethodCall(bsaa, a).alwaysMatches()); + // assertTrue("Should not match call to B.b()", ex.matchesMethodCall(b, a).neverMatches()); + // ex = p.parsePointcutExpression("call(* *..A.a*(int))"); + // assertTrue("Should match call to A.aa()", ex.matchesMethodCall(aa, a).alwaysMatches()); + // assertTrue("Should not match call to A.a()", ex.matchesMethodCall(a, a).neverMatches()); + // ex = p.parsePointcutExpression("call(void aaa(..)) && this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); + // assertTrue("Should match call to A.aaa() from Client", ex.matchesMethodCall(aaa, foo).alwaysMatches()); + // ex = p.parsePointcutExpression("call(void aaa(..)) && this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("Should match call to A.aaa() from B", ex.matchesMethodCall(aaa, b).alwaysMatches()); + // assertTrue("May match call to A.aaa() from A", ex.matchesMethodCall(aaa, a).maybeMatches()); + // assertFalse("May match call to A.aaa() from A", ex.matchesMethodCall(aaa, a).alwaysMatches()); + // ex = p.parsePointcutExpression("execution(* *.*(..))"); + // assertTrue("Should not match call to A.aa", ex.matchesMethodCall(aa, a).neverMatches()); + } + + public void testCallAndThisMatchesMethodCall() { + StandardPointcutExpression ex = pointcutParser.parsePointcutExpression("call(* *(..)) && this(java.util.ArrayList)"); + ResolvedType jlString = world.resolve("java.lang.String"); + ResolvedType juList = world.resolve("java.util.List"); + + ResolvedMember stringSplitMethod = getMethod(jlString, "split", "(Ljava/lang/String;I)[Ljava/lang/String;"); + ResolvedMember stringValueOfIntMethod = getMethod(jlString, "valueOf", "(I)Ljava/lang/String;"); + ResolvedMember listAddMethod = getMethod(juList, "add", "(Ljava/lang/Object;)Z"); + + // Calling from list.add() to string split, the callee *might* be an ArrayList, so possible match + assertTrue(ex.matchesMethodCall(stringSplitMethod, listAddMethod).maybeMatches()); + } + + // // this + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); + // assertTrue("Should match Client", ex.matchesMethodCall(a, foo).alwaysMatches()); + // assertTrue("Should not match A", ex.matchesMethodCall(a, a).neverMatches()); + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("Should maybe match B", ex.matchesMethodCall(bsaa, a).maybeMatches()); + // assertFalse("Should maybe match B", ex.matchesMethodCall(bsaa, a).alwaysMatches()); + // // target + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); + // assertTrue("Should not match Client", ex.matchesMethodCall(a, a).neverMatches()); + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); + // assertTrue("Should match A", ex.matchesMethodCall(a, a).alwaysMatches()); + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("Should maybe match A", ex.matchesMethodCall(aa, a).maybeMatches()); + // assertFalse("Should maybe match A", ex.matchesMethodCall(aa, a).alwaysMatches()); + // // test args + // ex = p.parsePointcutExpression("args(..,int)"); + // assertTrue("Should match A.aa", ex.matchesMethodCall(aa, a).alwaysMatches()); + // assertTrue("Should match A.aaa", ex.matchesMethodCall(aaa, a).alwaysMatches()); + // assertTrue("Should not match A.a", ex.matchesMethodCall(a, a).neverMatches()); + // // within + // ex = p.parsePointcutExpression("within(*..A)"); + // assertTrue("Matches in class A", ex.matchesMethodCall(a, a).alwaysMatches()); + // assertTrue("Does not match in class B", ex.matchesMethodCall(a, b).neverMatches()); + // assertTrue("Matches in class A", ex.matchesMethodCall(a, A.class).alwaysMatches()); + // assertTrue("Does not match in class B", ex.matchesMethodCall(a, B.class).neverMatches()); + // // withincode + // ex = p.parsePointcutExpression("withincode(* a*(..))"); + // assertTrue("Should match", ex.matchesMethodCall(b, bsaa).alwaysMatches()); + // assertTrue("Should not match", ex.matchesMethodCall(b, b).neverMatches()); + // } + // public void testMatchesConstructorCall() { + // PointcutExpression ex = p.parsePointcutExpression("call(new(String))"); + // assertTrue("Should match A(String)", ex.matchesConstructorCall(asCons, b).alwaysMatches()); + // assertTrue("Should match B(String)", ex.matchesConstructorCall(bsStringCons, b).alwaysMatches()); + // assertTrue("Should not match B()", ex.matchesConstructorCall(bsCons, foo).neverMatches()); + // ex = p.parsePointcutExpression("call(*..A.new(String))"); + // assertTrue("Should match A(String)", ex.matchesConstructorCall(asCons, b).alwaysMatches()); + // assertTrue("Should not match B(String)", ex.matchesConstructorCall(bsStringCons, foo).neverMatches()); + // // this + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); + // assertTrue("Should match Client", ex.matchesConstructorCall(asCons, foo).alwaysMatches()); + // assertTrue("Should not match A", ex.matchesConstructorCall(asCons, a).neverMatches()); + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("Should maybe match B", ex.matchesConstructorCall(asCons, a).maybeMatches()); + // assertFalse("Should maybe match B", ex.matchesConstructorCall(asCons, a).alwaysMatches()); + // // target + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); + // assertTrue("Should not match Client", ex.matchesConstructorCall(asCons, foo).neverMatches()); + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); + // assertTrue("Should not match A (no target)", ex.matchesConstructorCall(asCons, a).neverMatches()); + // // args + // ex = p.parsePointcutExpression("args(String)"); + // assertTrue("Should match A(String)", ex.matchesConstructorCall(asCons, b).alwaysMatches()); + // assertTrue("Should match B(String)", ex.matchesConstructorCall(bsStringCons, foo).alwaysMatches()); + // assertTrue("Should not match B()", ex.matchesConstructorCall(bsCons, foo).neverMatches()); + // // within + // ex = p.parsePointcutExpression("within(*..A)"); + // assertTrue("Matches in class A", ex.matchesConstructorCall(asCons, a).alwaysMatches()); + // assertTrue("Does not match in class B", ex.matchesConstructorCall(asCons, b).neverMatches()); + // // withincode + // ex = p.parsePointcutExpression("withincode(* a*(..))"); + // assertTrue("Should match", ex.matchesConstructorCall(bsCons, aa).alwaysMatches()); + // assertTrue("Should not match", ex.matchesConstructorCall(bsCons, b).neverMatches()); + // } + // + // + // // test this + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); + // assertTrue("Should match A", ex.matchesConstructorExecution(asCons).alwaysMatches()); + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("Maybe matches B", ex.matchesConstructorExecution(asCons).maybeMatches()); + // assertFalse("Maybe matches B", ex.matchesConstructorExecution(asCons).alwaysMatches()); + // assertTrue("Should match B", ex.matchesConstructorExecution(bsCons).alwaysMatches()); + // assertTrue("Does not match client", ex.matchesConstructorExecution(clientCons).neverMatches()); + // + // // test target + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); + // assertTrue("Should match A", ex.matchesConstructorExecution(asCons).alwaysMatches()); + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("Maybe matches B", ex.matchesConstructorExecution(asCons).maybeMatches()); + // assertFalse("Maybe matches B", ex.matchesConstructorExecution(asCons).alwaysMatches()); + // assertTrue("Should match B", ex.matchesConstructorExecution(bsCons).alwaysMatches()); + // assertTrue("Does not match client", ex.matchesConstructorExecution(clientCons).neverMatches()); + // + // // within + // ex = p.parsePointcutExpression("within(*..A)"); + // assertTrue("Matches in class A", ex.matchesConstructorExecution(asCons).alwaysMatches()); + // assertTrue("Does not match in class B", ex.matchesConstructorExecution(bsCons).neverMatches()); + // + // // withincode + // ex = p.parsePointcutExpression("withincode(* a*(..))"); + // assertTrue("Does not match", ex.matchesConstructorExecution(bsCons).neverMatches()); + // + // // args + // ex = p.parsePointcutExpression("args(String)"); + // assertTrue("Should match A(String)", ex.matchesConstructorExecution(asCons).alwaysMatches()); + // assertTrue("Should match B(String)", ex.matchesConstructorExecution(bsStringCons).alwaysMatches()); + // assertTrue("Should not match B()", ex.matchesConstructorExecution(bsCons).neverMatches()); + // } + // + // public void testMatchesAdviceExecution() { + // PointcutExpression ex = p.parsePointcutExpression("adviceexecution()"); + // assertTrue("Should match (advice) A.a", ex.matchesAdviceExecution(a).alwaysMatches()); + // // test this + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); + // assertTrue("Should match Client", ex.matchesAdviceExecution(foo).alwaysMatches()); + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("Maybe matches B", ex.matchesAdviceExecution(a).maybeMatches()); + // assertFalse("Maybe matches B", ex.matchesAdviceExecution(a).alwaysMatches()); + // assertTrue("Does not match client", ex.matchesAdviceExecution(foo).neverMatches()); + // + // // test target + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); + // assertTrue("Should match Client", ex.matchesAdviceExecution(foo).alwaysMatches()); + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("Maybe matches B", ex.matchesAdviceExecution(a).maybeMatches()); + // assertFalse("Maybe matches B", ex.matchesAdviceExecution(a).alwaysMatches()); + // assertTrue("Does not match client", ex.matchesAdviceExecution(foo).neverMatches()); + // + // // test within + // ex = p.parsePointcutExpression("within(*..A)"); + // assertTrue("Matches in class A", ex.matchesAdviceExecution(a).alwaysMatches()); + // assertTrue("Does not match in class B", ex.matchesAdviceExecution(b).neverMatches()); + // + // // withincode + // ex = p.parsePointcutExpression("withincode(* a*(..))"); + // assertTrue("Does not match", ex.matchesAdviceExecution(a).neverMatches()); + // + // // test args + // ex = p.parsePointcutExpression("args(..,int)"); + // assertTrue("Should match A.aa", ex.matchesAdviceExecution(aa).alwaysMatches()); + // assertTrue("Should match A.aaa", ex.matchesAdviceExecution(aaa).alwaysMatches()); + // assertTrue("Should not match A.a", ex.matchesAdviceExecution(a).neverMatches()); + // } + // + // public void testMatchesHandler() { + // PointcutExpression ex = p.parsePointcutExpression("handler(Exception)"); + // assertTrue("Should match catch(Exception)", ex.matchesHandler(Exception.class, Client.class).alwaysMatches()); + // assertTrue("Should not match catch(Throwable)", ex.matchesHandler(Throwable.class, Client.class).neverMatches()); + // // test this + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); + // assertTrue("Should match Client", ex.matchesHandler(Exception.class, foo).alwaysMatches()); + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("Maybe matches B", ex.matchesHandler(Exception.class, a).maybeMatches()); + // assertFalse("Maybe matches B", ex.matchesHandler(Exception.class, a).alwaysMatches()); + // assertTrue("Does not match client", ex.matchesHandler(Exception.class, foo).neverMatches()); + // // target - no target for exception handlers + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); + // assertTrue("Should match Client", ex.matchesHandler(Exception.class, foo).neverMatches()); + // // args + // ex = p.parsePointcutExpression("args(Exception)"); + // assertTrue("Should match Exception", ex.matchesHandler(Exception.class, foo).alwaysMatches()); + // assertTrue("Should match RuntimeException", ex.matchesHandler(RuntimeException.class, foo).alwaysMatches()); + // assertTrue("Should not match String", ex.matchesHandler(String.class, foo).neverMatches()); + // assertTrue("Maybe matches Throwable", ex.matchesHandler(Throwable.class, foo).maybeMatches()); + // assertFalse("Maybe matches Throwable", ex.matchesHandler(Throwable.class, foo).alwaysMatches()); + // // within + // ex = p.parsePointcutExpression("within(*..Client)"); + // assertTrue("Matches in class Client", ex.matchesHandler(Exception.class, foo).alwaysMatches()); + // assertTrue("Does not match in class B", ex.matchesHandler(Exception.class, b).neverMatches()); + // // withincode + // ex = p.parsePointcutExpression("withincode(* a*(..))"); + // assertTrue("Matches within aa", ex.matchesHandler(Exception.class, aa).alwaysMatches()); + // assertTrue("Does not match within b", ex.matchesHandler(Exception.class, b).neverMatches()); + // } + // -- next few tests relate to matching different pointcut expressions against a staticinitialization join point + + public void testMethodMatchesStaticInitialization01() { + StandardPointcutExpression ex = pointcutParser.parsePointcutExpression("staticinitialization(java.lang.String)"); + assertNotNull(ex); + + ResolvedType jlString = world.resolve("java.lang.String"); + + boolean b = ex.matchesStaticInitialization(jlString).alwaysMatches(); + assertTrue(b); + } + + public void testMethodMatchesStaticInitialization02() { + ResolvedType jlString = world.resolve("java.lang.String"); + StandardPointcutExpression ex = pointcutParser.parsePointcutExpression("staticinitialization(java..*)"); + assertTrue(ex.matchesStaticInitialization(jlString).alwaysMatches()); + ex = pointcutParser.parsePointcutExpression("staticinitialization(java..*)"); + assertTrue(ex.matchesStaticInitialization(jlString).alwaysMatches()); + ex = pointcutParser.parsePointcutExpression("staticinitialization(java.*)"); + assertTrue(ex.matchesStaticInitialization(jlString).neverMatches()); + } + + public void testMethodMatchesStaticInitialization03() { + ResolvedType juArrayList = world.resolve("java.util.ArrayList"); + StandardPointcutExpression ex = pointcutParser.parsePointcutExpression("staticinitialization(java..*)"); + assertTrue(ex.matchesStaticInitialization(juArrayList).alwaysMatches()); + ex = pointcutParser.parsePointcutExpression("staticinitialization(java.util.ArrayList)"); + assertTrue(ex.matchesStaticInitialization(juArrayList).alwaysMatches()); + ex = pointcutParser.parsePointcutExpression("staticinitialization(java.util.List+)"); + assertTrue(ex.matchesStaticInitialization(juArrayList).alwaysMatches()); + ex = pointcutParser.parsePointcutExpression("staticinitialization(List)"); + assertTrue(ex.matchesStaticInitialization(juArrayList).neverMatches()); + } + + // + // public void testMatchesInitialization() { + // PointcutExpression ex = p.parsePointcutExpression("initialization(new(String))"); + // assertTrue("Should match A(String)", ex.matchesInitialization(asCons).alwaysMatches()); + // assertTrue("Should match B(String)", ex.matchesInitialization(bsStringCons).alwaysMatches()); + // assertTrue("Should not match B()", ex.matchesInitialization(bsCons).neverMatches()); + // ex = p.parsePointcutExpression("initialization(*..A.new(String))"); + // assertTrue("Should match A(String)", ex.matchesInitialization(asCons).alwaysMatches()); + // assertTrue("Should not match B(String)", ex.matchesInitialization(bsStringCons).neverMatches()); + // // test this + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); + // assertTrue("Should match A", ex.matchesInitialization(asCons).alwaysMatches()); + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("Maybe matches B", ex.matchesInitialization(asCons).maybeMatches()); + // assertFalse("Maybe matches B", ex.matchesInitialization(asCons).alwaysMatches()); + // + // // test target + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); + // assertTrue("Should match A", ex.matchesInitialization(asCons).alwaysMatches()); + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("Maybe matches B", ex.matchesInitialization(asCons).maybeMatches()); + // assertFalse("Maybe matches B", ex.matchesInitialization(asCons).alwaysMatches()); + // // within + // ex = p.parsePointcutExpression("within(*..A)"); + // assertTrue("Matches in class A", ex.matchesInitialization(asCons).alwaysMatches()); + // assertTrue("Does not match in class B", ex.matchesInitialization(bsCons).neverMatches()); + // // withincode + // ex = p.parsePointcutExpression("withincode(* a*(..))"); + // assertTrue("Does not match", ex.matchesInitialization(bsCons).neverMatches()); + // // args + // ex = p.parsePointcutExpression("args(String)"); + // assertTrue("Should match A(String)", ex.matchesInitialization(asCons).alwaysMatches()); + // assertTrue("Should match B(String)", ex.matchesInitialization(bsStringCons).alwaysMatches()); + // assertTrue("Should not match B()", ex.matchesInitialization(bsCons).neverMatches()); + // } + // + // public void testMatchesPreInitialization() { + // PointcutExpression ex = p.parsePointcutExpression("preinitialization(new(String))"); + // assertTrue("Should match A(String)", ex.matchesPreInitialization(asCons).alwaysMatches()); + // assertTrue("Should match B(String)", ex.matchesPreInitialization(bsStringCons).alwaysMatches()); + // assertTrue("Should not match B()", ex.matchesPreInitialization(bsCons).neverMatches()); + // ex = p.parsePointcutExpression("preinitialization(*..A.new(String))"); + // assertTrue("Should match A(String)", ex.matchesPreInitialization(asCons).alwaysMatches()); + // assertTrue("Should not match B(String)", ex.matchesPreInitialization(bsStringCons).neverMatches()); + // // test this + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); + // assertTrue("No match, no this at preinit", ex.matchesPreInitialization(asCons).neverMatches()); + // + // // test target + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); + // assertTrue("No match, no target at preinit", ex.matchesPreInitialization(asCons).neverMatches()); + // + // // within + // ex = p.parsePointcutExpression("within(*..A)"); + // assertTrue("Matches in class A", ex.matchesPreInitialization(asCons).alwaysMatches()); + // assertTrue("Does not match in class B", ex.matchesPreInitialization(bsCons).neverMatches()); + // // withincode + // ex = p.parsePointcutExpression("withincode(* a*(..))"); + // assertTrue("Does not match", ex.matchesPreInitialization(bsCons).neverMatches()); + // // args + // ex = p.parsePointcutExpression("args(String)"); + // assertTrue("Should match A(String)", ex.matchesPreInitialization(asCons).alwaysMatches()); + // assertTrue("Should match B(String)", ex.matchesPreInitialization(bsStringCons).alwaysMatches()); + // assertTrue("Should not match B()", ex.matchesPreInitialization(bsCons).neverMatches()); + // } + // + // public void testMatchesStaticInitialization() { + // // this + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); + // assertTrue("No this", ex.matchesStaticInitialization(A.class).neverMatches()); + // // target + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); + // assertTrue("No target", ex.matchesStaticInitialization(A.class).neverMatches()); + // + // // args + // ex = p.parsePointcutExpression("args()"); + // assertTrue("No args", ex.matchesStaticInitialization(A.class).alwaysMatches()); + // ex = p.parsePointcutExpression("args(String)"); + // assertTrue("No args", ex.matchesStaticInitialization(A.class).neverMatches()); + // + // // within + // ex = p.parsePointcutExpression("within(*..A)"); + // assertTrue("Matches in class A", ex.matchesStaticInitialization(A.class).alwaysMatches()); + // assertTrue("Does not match in class B", ex.matchesStaticInitialization(B.class).neverMatches()); + // + // // withincode + // ex = p.parsePointcutExpression("withincode(* a*(..))"); + // assertTrue("Does not match", ex.matchesStaticInitialization(A.class).neverMatches()); + // } + // + // public void testMatchesFieldSet() { + // PointcutExpression ex = p.parsePointcutExpression("set(* *..A+.*)"); + // assertTrue("matches x", ex.matchesFieldSet(x, a).alwaysMatches()); + // assertTrue("matches y", ex.matchesFieldSet(y, foo).alwaysMatches()); + // assertTrue("does not match n", ex.matchesFieldSet(n, foo).neverMatches()); + // // this + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); + // assertTrue("matches Client", ex.matchesFieldSet(x, foo).alwaysMatches()); + // assertTrue("does not match A", ex.matchesFieldSet(n, a).neverMatches()); + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("maybe matches A", ex.matchesFieldSet(x, a).maybeMatches()); + // assertFalse("maybe matches A", ex.matchesFieldSet(x, a).alwaysMatches()); + // // target + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("matches B", ex.matchesFieldSet(y, foo).alwaysMatches()); + // assertTrue("maybe matches A", ex.matchesFieldSet(x, foo).maybeMatches()); + // assertFalse("maybe matches A", ex.matchesFieldSet(x, foo).alwaysMatches()); + // // args + // ex = p.parsePointcutExpression("args(int)"); + // assertTrue("matches x", ex.matchesFieldSet(x, a).alwaysMatches()); + // assertTrue("matches y", ex.matchesFieldSet(y, a).alwaysMatches()); + // assertTrue("does not match n", ex.matchesFieldSet(n, a).neverMatches()); + // // within + // ex = p.parsePointcutExpression("within(*..A)"); + // assertTrue("Matches in class A", ex.matchesFieldSet(x, a).alwaysMatches()); + // assertTrue("Does not match in class B", ex.matchesFieldSet(x, b).neverMatches()); + // // withincode + // ex = p.parsePointcutExpression("withincode(* a*(..))"); + // assertTrue("Should match", ex.matchesFieldSet(x, aa).alwaysMatches()); + // assertTrue("Should not match", ex.matchesFieldSet(x, b).neverMatches()); + // } + // + // public void testMatchesFieldGet() { + // PointcutExpression ex = p.parsePointcutExpression("get(* *..A+.*)"); + // assertTrue("matches x", ex.matchesFieldGet(x, a).alwaysMatches()); + // assertTrue("matches y", ex.matchesFieldGet(y, foo).alwaysMatches()); + // assertTrue("does not match n", ex.matchesFieldGet(n, foo).neverMatches()); + // // this + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.Client)"); + // assertTrue("matches Client", ex.matchesFieldGet(x, foo).alwaysMatches()); + // assertTrue("does not match A", ex.matchesFieldGet(n, a).neverMatches()); + // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("maybe matches A", ex.matchesFieldGet(x, a).maybeMatches()); + // assertFalse("maybe matches A", ex.matchesFieldGet(x, a).alwaysMatches()); + // // target + // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertTrue("matches B", ex.matchesFieldGet(y, foo).alwaysMatches()); + // assertTrue("maybe matches A", ex.matchesFieldGet(x, foo).maybeMatches()); + // assertFalse("maybe matches A", ex.matchesFieldGet(x, foo).alwaysMatches()); + // // args - no args at get join point + // ex = p.parsePointcutExpression("args(int)"); + // assertTrue("matches x", ex.matchesFieldGet(x, a).neverMatches()); + // // within + // ex = p.parsePointcutExpression("within(*..A)"); + // assertTrue("Matches in class A", ex.matchesFieldGet(x, a).alwaysMatches()); + // assertTrue("Does not match in class B", ex.matchesFieldGet(x, b).neverMatches()); + // // withincode + // ex = p.parsePointcutExpression("withincode(* a*(..))"); + // assertTrue("Should match", ex.matchesFieldGet(x, aa).alwaysMatches()); + // assertTrue("Should not match", ex.matchesFieldGet(x, b).neverMatches()); + // } + // + // public void testArgsMatching() { + // // too few args + // PointcutExpression ex = p.parsePointcutExpression("args(*,*,*,*)"); + // assertTrue("Too few args", ex.matchesMethodExecution(foo).neverMatches()); + // assertTrue("Matching #args", ex.matchesMethodExecution(bar).alwaysMatches()); + // // one too few + ellipsis + // ex = p.parsePointcutExpression("args(*,*,*,..)"); + // assertTrue("Matches with ellipsis", ex.matchesMethodExecution(foo).alwaysMatches()); + // // exact number + ellipsis + // assertTrue("Matches with ellipsis", ex.matchesMethodExecution(bar).alwaysMatches()); + // assertTrue("Does not match with ellipsis", ex.matchesMethodExecution(a).neverMatches()); + // // too many + ellipsis + // ex = p.parsePointcutExpression("args(*,..,*)"); + // assertTrue("Matches with ellipsis", ex.matchesMethodExecution(bar).alwaysMatches()); + // assertTrue("Does not match with ellipsis", ex.matchesMethodExecution(a).neverMatches()); + // assertTrue("Matches with ellipsis", ex.matchesMethodExecution(aaa).alwaysMatches()); + // // exact match + // ex = p.parsePointcutExpression("args(String,int,Number)"); + // assertTrue("Matches exactly", ex.matchesMethodExecution(foo).alwaysMatches()); + // // maybe match + // ex = p.parsePointcutExpression("args(String,int,Double)"); + // assertTrue("Matches maybe", ex.matchesMethodExecution(foo).maybeMatches()); + // assertFalse("Matches maybe", ex.matchesMethodExecution(foo).alwaysMatches()); + // // never match + // ex = p.parsePointcutExpression("args(String,Integer,Number)"); + // if (LangUtil.is15VMOrGreater()) { + // assertTrue("matches", ex.matchesMethodExecution(foo).alwaysMatches()); + // } else { + // assertTrue("Does not match", ex.matchesMethodExecution(foo).neverMatches()); + // } + // } + // + // // public void testMatchesDynamically() { + // // // everything other than this,target,args should just return true + // // PointcutExpression ex = p.parsePointcutExpression("call(* *.*(..)) && execution(* *.*(..)) &&" + + // // "get(* *) && set(* *) && initialization(new(..)) && preinitialization(new(..)) &&" + + // // "staticinitialization(X) && adviceexecution() && within(Y) && withincode(* *.*(..)))"); + // // assertTrue("Matches dynamically",ex.matchesDynamically(a,b,new Object[0])); + // // // this + // // ex = p.parsePointcutExpression("this(String)"); + // // assertTrue("String matches",ex.matchesDynamically("",this,new Object[0])); + // // assertFalse("Object doesn't match",ex.matchesDynamically(new Object(),this,new Object[0])); + // // ex = p.parsePointcutExpression("this(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); + // // assertTrue("A matches",ex.matchesDynamically(new A(""),this,new Object[0])); + // // assertTrue("B matches",ex.matchesDynamically(new B(""),this,new Object[0])); + // // // target + // // ex = p.parsePointcutExpression("target(String)"); + // // assertTrue("String matches",ex.matchesDynamically(this,"",new Object[0])); + // // assertFalse("Object doesn't match",ex.matchesDynamically(this,new Object(),new Object[0])); + // // ex = p.parsePointcutExpression("target(org.aspectj.weaver.tools.PointcutExpressionTest.A)"); + // // assertTrue("A matches",ex.matchesDynamically(this,new A(""),new Object[0])); + // // assertTrue("B matches",ex.matchesDynamically(this,new B(""),new Object[0])); + // // // args + // // ex = p.parsePointcutExpression("args(*,*,*,*)"); + // // assertFalse("Too few args",ex.matchesDynamically(null,null,new Object[]{a,b})); + // // assertTrue("Matching #args",ex.matchesDynamically(null,null,new Object[]{a,b,aa,aaa})); + // // // one too few + ellipsis + // // ex = p.parsePointcutExpression("args(*,*,*,..)"); + // // assertTrue("Matches with ellipsis",ex.matchesDynamically(null,null,new Object[]{a,b,aa,aaa})); + // // // exact number + ellipsis + // // assertTrue("Matches with ellipsis",ex.matchesDynamically(null,null,new Object[]{a,b,aa})); + // // assertFalse("Does not match with ellipsis",ex.matchesDynamically(null,null,new Object[]{a,b})); + // // // too many + ellipsis + // // ex = p.parsePointcutExpression("args(*,..,*)"); + // // assertTrue("Matches with ellipsis",ex.matchesDynamically(null,null,new Object[]{a,b,aa,aaa})); + // // assertFalse("Does not match with ellipsis",ex.matchesDynamically(null,null,new Object[]{a})); + // // assertTrue("Matches with ellipsis",ex.matchesDynamically(null,null,new Object[]{a,b})); + // // // exact match + // // ex = p.parsePointcutExpression("args(String,int,Number)"); + // // assertTrue("Matches exactly",ex.matchesDynamically(null,null,new Object[]{"",new Integer(5),new Double(5.0)})); + // // ex = p.parsePointcutExpression("args(String,Integer,Number)"); + // // assertTrue("Matches exactly",ex.matchesDynamically(null,null,new Object[]{"",new Integer(5),new Double(5.0)})); + // // // never match + // // ex = p.parsePointcutExpression("args(String,Integer,Number)"); + // // assertFalse("Does not match",ex.matchesDynamically(null,null,new Object[]{a,b,aa})); + // // } + // + // public void testGetPointcutExpression() { + // PointcutExpression ex = p.parsePointcutExpression("staticinitialization(*..A+)"); + // assertEquals("staticinitialization(*..A+)", ex.getPointcutExpression()); + // } + // + // public void testCouldMatchJoinPointsInType() { + // PointcutExpression ex = p.parsePointcutExpression("execution(* org.aspectj.weaver.tools.PointcutExpressionTest.B.*(..))"); + // assertTrue("Could maybe match String (as best we know at this point)", ex.couldMatchJoinPointsInType(String.class)); + // assertTrue("Will always match B", ex.couldMatchJoinPointsInType(B.class)); + // ex = p.parsePointcutExpression("within(org.aspectj.weaver.tools.PointcutExpressionTest.B)"); + // assertFalse("Will never match String", ex.couldMatchJoinPointsInType(String.class)); + // assertTrue("Will always match B", ex.couldMatchJoinPointsInType(B.class)); + // } + // + // public void testMayNeedDynamicTest() { + // PointcutExpression ex = p.parsePointcutExpression("execution(* org.aspectj.weaver.tools.PointcutExpressionTest.B.*(..))"); + // assertFalse("No dynamic test needed", ex.mayNeedDynamicTest()); + // ex = p + // .parsePointcutExpression("execution(* org.aspectj.weaver.tools.PointcutExpressionTest.B.*(..)) && args(org.aspectj.weaver.tools.PointcutExpressionTest.X)"); + // assertTrue("Dynamic test needed", ex.mayNeedDynamicTest()); + // } + + // -- helpers + + private ResolvedMember getMethod(ResolvedType type, String methodName, String methodSignature) { + ResolvedMember[] methods = type.getDeclaredMethods(); + for (int i = 0; i < methods.length; i++) { + System.out.println(methods[i].getName() + methods[i].getSignature()); + if (methods[i].getName().equals(methodName) + && (methodSignature == null || methodSignature.equals(methods[i].getSignature()))) { + return methods[i]; + } + } + return null; + } + + private void checkAlwaysMatches(String pointcutExpression, String type, String methodName, String methodSignature) { + StandardPointcutExpression ex = pointcutParser.parsePointcutExpression(pointcutExpression); + assertNotNull(ex); + ResolvedType resolvedType = world.resolve(type); + ResolvedMember method = getMethod(resolvedType, methodName, methodSignature); + assertNotNull("Couldn't find a method with signature " + methodSignature, method); + boolean b = ex.matchesMethodExecution(method).alwaysMatches(); + assertTrue("Match failed", b); + } + + private void checkNeverMatches(String pointcutExpression, String type, String methodName, String methodSignature) { + StandardPointcutExpression ex = pointcutParser.parsePointcutExpression(pointcutExpression); + assertNotNull(ex); + ResolvedType resolvedType = world.resolve(type); + ResolvedMember method = getMethod(resolvedType, methodName, methodSignature); + assertNotNull(method); + boolean b = ex.matchesMethodExecution(method).neverMatches(); + assertTrue(b); + } +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/matcher/tools/ReflectionWorldPointcutExpressionTests.java b/org.aspectj.matcher/src/test/java/org/aspectj/matcher/tools/ReflectionWorldPointcutExpressionTests.java new file mode 100644 index 000000000..1a5f9be43 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/matcher/tools/ReflectionWorldPointcutExpressionTests.java @@ -0,0 +1,17 @@ +package org.aspectj.matcher.tools; + +import org.aspectj.weaver.World; +import org.aspectj.weaver.reflect.ReflectionWorld; + +/** + * Run all the pointcut parsing/matching tests against a ReflectionWorld. + * + * @author Andy Clement + */ +public class ReflectionWorldPointcutExpressionTests extends CommonPointcutExpressionTests { + + protected World getWorld() { + return new ReflectionWorld(true, getClass().getClassLoader()); + } + +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/CommonWorldTests.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/CommonWorldTests.java new file mode 100644 index 000000000..ff6c56a34 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/CommonWorldTests.java @@ -0,0 +1,264 @@ +/* ******************************************************************* + * Copyright (c) 2002-2008 Contributors + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * PARC initial implementation + * Andy Clement + * ******************************************************************/ + +package org.aspectj.weaver; + +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import junit.framework.TestCase; + +import org.aspectj.testing.util.TestUtil; + +/** + * An abstract set of tests that any World implementation should be able to pass. To run it against your World, subclass it and + * implement getWorld(). + * + * @author Andy Clement + */ +public abstract class CommonWorldTests extends TestCase { + + /** + * @return an instance of the World to be tested + */ + protected abstract World getWorld(); + + private World world; + + @Override + public void setUp() { + world = getWorld(); + } + + private final UnresolvedType[] primitiveTypes = UnresolvedType.forSignatures(new String[] { "B", "S", "C", "I", "J", "F", "D", + "V" }); + + public void testPrimitiveTypes() { + ResolvedType[] primitives = world.resolve(primitiveTypes); + for (int i = 0, len = primitives.length; i < len; i++) { + ResolvedType ty = primitives[i]; + modifiersTest(ty, Modifier.PUBLIC | Modifier.FINAL); + fieldsTest(ty, ResolvedMember.NONE); + methodsTest(ty, ResolvedMember.NONE); + interfacesTest(ty, ResolvedType.NONE); + superclassTest(ty, null); + pointcutsTest(ty, ResolvedMember.NONE); + isInterfaceTest(ty, false); + isClassTest(ty, false); + isAspectTest(ty, false); + for (int j = 0; j < len; j++) { + ResolvedType ty1 = primitives[j]; + if (ty.equals(ty1)) { + isCoerceableFromTest(ty, ty1, true); + } else if (ty.equals(UnresolvedType.BOOLEAN) || ty1.equals(UnresolvedType.BOOLEAN) + || ty.equals(UnresolvedType.VOID) || ty1.equals(UnresolvedType.VOID)) { + isCoerceableFromTest(ty, ty1, false); + } else { + isCoerceableFromTest(ty, ty1, true); + } + } + + // Result of this depends on whether autoboxing is supported + // isCoerceableFromTest(ty, UnresolvedType.OBJECT, getSupportsAutoboxing()); + + primAssignTest("B", new String[] {}); + primAssignTest("S", new String[] { "B" }); + primAssignTest("C", new String[] { "B" }); + primAssignTest("I", new String[] { "B", "S", "C" }); + primAssignTest("J", new String[] { "B", "S", "C", "I" }); + primAssignTest("F", new String[] { "B", "S", "C", "I", "J" }); + primAssignTest("D", new String[] { "B", "S", "C", "I", "J", "F" }); + primAssignTest("Z", new String[] {}); + primAssignTest("V", new String[] {}); + + } + } + + private void primAssignTest(String sig, String[] lowers) { + ResolvedType[] primitives = world.resolve(primitiveTypes); + UnresolvedType tx = UnresolvedType.forSignature(sig); + ResolvedType ty = world.resolve(tx, true); + assertTrue("Couldnt find type " + tx, !ty.isMissing()); + ResolvedType[] lowerTyArray = world.resolve(UnresolvedType.forSignatures(lowers)); + List<ResolvedType> lowerTys = new ArrayList<ResolvedType>(Arrays.asList(lowerTyArray)); + lowerTys.add(ty); + Set<ResolvedType> allLowerTys = new HashSet<ResolvedType>(lowerTys); + Set<ResolvedType> allUpperTys = new HashSet<ResolvedType>(Arrays.asList(primitives)); + allUpperTys.removeAll(allLowerTys); + + for (ResolvedType other : allLowerTys) { + isAssignableFromTest(ty, other, true); + } + for (ResolvedType other : allUpperTys) { + isAssignableFromTest(ty, other, false); + } + } + + public void testPrimitiveArrays() { + ResolvedType[] primitives = world.resolve(primitiveTypes); + for (int i = 0, len = primitives.length; i < len; i++) { + ResolvedType ty = primitives[i]; + UnresolvedType tx = UnresolvedType.forSignature("[" + ty.getSignature()); + ResolvedType aty = world.resolve(tx, true); + assertTrue("Couldnt find type " + tx, !aty.isMissing()); + modifiersTest(aty, Modifier.PUBLIC | Modifier.FINAL); + fieldsTest(aty, ResolvedMember.NONE); + methodsTest(aty, ResolvedMember.NONE); + interfaceTest( + aty, + new ResolvedType[] { world.getCoreType(UnresolvedType.CLONEABLE), + world.getCoreType(UnresolvedType.SERIALIZABLE) }); + superclassTest(aty, UnresolvedType.OBJECT); + + pointcutsTest(aty, ResolvedMember.NONE); + isInterfaceTest(aty, false); + isClassTest(aty, false); + isAspectTest(aty, false); + for (int j = 0; j < len; j++) { + ResolvedType ty1 = primitives[j]; + isCoerceableFromTest(aty, ty1, false); + tx = UnresolvedType.forSignature("[" + ty1.getSignature()); + ResolvedType aty1 = getWorld().resolve(tx, true); + assertTrue("Couldnt find type " + tx, !aty1.isMissing()); + if (ty.equals(ty1)) { + isCoerceableFromTest(aty, aty1, true); + isAssignableFromTest(aty, aty1, true); + } else { + isCoerceableFromTest(aty, aty1, false); + isAssignableFromTest(aty, aty1, false); + } + } + } + // double dimension arrays + for (int i = 0, len = primitives.length; i < len; i++) { + ResolvedType ty = primitives[i]; + UnresolvedType tx = UnresolvedType.forSignature("[[" + ty.getSignature()); + ResolvedType aty = world.resolve(tx, true); + assertTrue("Couldnt find type " + tx, !aty.isMissing()); + modifiersTest(aty, Modifier.PUBLIC | Modifier.FINAL); + fieldsTest(aty, ResolvedMember.NONE); + methodsTest(aty, ResolvedMember.NONE); + interfaceTest( + aty, + new ResolvedType[] { world.getCoreType(UnresolvedType.CLONEABLE), + world.getCoreType(UnresolvedType.SERIALIZABLE) }); + superclassTest(aty, UnresolvedType.OBJECT); + + pointcutsTest(aty, ResolvedMember.NONE); + isInterfaceTest(aty, false); + isClassTest(aty, false); + isAspectTest(aty, false); + for (int j = 0; j < len; j++) { + ResolvedType ty1 = primitives[j]; + isCoerceableFromTest(aty, ty1, false); + tx = UnresolvedType.forSignature("[[" + ty1.getSignature()); + ResolvedType aty1 = getWorld().resolve(tx, true); + assertTrue("Couldnt find type " + tx, !aty1.isMissing()); + if (ty.equals(ty1)) { + isCoerceableFromTest(aty, aty1, true); + isAssignableFromTest(aty, aty1, true); + } else { + isCoerceableFromTest(aty, aty1, false); + isAssignableFromTest(aty, aty1, false); + } + } + } + } + + // ---- tests for parts of ResolvedType objects + + protected void modifiersTest(ResolvedType ty, int mods) { + assertEquals(ty + " modifiers:", Modifier.toString(mods), Modifier.toString(ty.getModifiers())); + } + + protected void fieldsTest(ResolvedType ty, Member[] x) { + TestUtil.assertSetEquals(ty + " fields:", x, ty.getDeclaredJavaFields()); + } + + protected void methodsTest(ResolvedType ty, Member[] x) { + TestUtil.assertSetEquals(ty + " methods:", x, ty.getDeclaredJavaMethods()); + } + + protected void mungersTest(ResolvedType ty, ShadowMunger[] x) { + List<ShadowMunger> l = ty.getDeclaredShadowMungers(); + ShadowMunger[] array = (ShadowMunger[]) l.toArray(new ShadowMunger[l.size()]); + TestUtil.assertSetEquals(ty + " mungers:", x, array); + } + + protected void interfaceTest(ResolvedType type, ResolvedType[] expectedInterfaces) { + ResolvedType[] interfaces = type.getDeclaredInterfaces(); + for (int i = 0; i < expectedInterfaces.length; i++) { + boolean wasMissing = true; + for (int j = 0; j < interfaces.length; j++) { + if (interfaces[j].getSignature().equals(expectedInterfaces[i].getSignature())) { + wasMissing = false; + } + } + if (wasMissing) { + fail("Expected declared interface " + expectedInterfaces[i] + " but it wasn't found in " + + Arrays.asList(interfaces)); + } + } + } + + protected void interfacesTest(ResolvedType ty, ResolvedType[] x) { + TestUtil.assertArrayEquals(ty + " interfaces:", x, ty.getDeclaredInterfaces()); + } + + protected void superclassTest(ResolvedType ty, UnresolvedType x) { + assertEquals(ty + " superclass:", x, ty.getSuperclass()); + } + + protected void pointcutsTest(ResolvedType ty, Member[] x) { + TestUtil.assertSetEquals(ty + " pointcuts:", x, ty.getDeclaredPointcuts()); + } + + protected void isInterfaceTest(ResolvedType ty, boolean x) { + assertEquals(ty + " is interface:", x, ty.isInterface()); + } + + protected void isAspectTest(ResolvedType ty, boolean x) { + assertEquals(ty + " is aspect:", x, ty.isAspect()); + } + + protected void isClassTest(ResolvedType ty, boolean x) { + assertEquals(ty + " is class:", x, ty.isClass()); + } + + protected void isCoerceableFromTest(UnresolvedType ty0, UnresolvedType ty1, boolean x) { + assertEquals(ty0 + " is coerceable from " + ty1, ty0.resolve(world).isCoerceableFrom(ty1.resolve(world)), x); + assertEquals(ty1 + " is coerceable from " + ty0, ty1.resolve(world).isCoerceableFrom(ty0.resolve(world)), x); + } + + protected void isAssignableFromTest(UnresolvedType ty0, UnresolvedType ty1, boolean x) { + ResolvedType rty0 = ty0.resolve(world); + ResolvedType rty1 = ty1.resolve(world); + boolean result = rty0.isAssignableFrom(rty1); + assertEquals(ty0 + " is assignable from " + ty1, result, x); + } + + // ---- tests for parts of ResolvedMethod objects + + protected void modifiersTest(ResolvedMember m, int mods) { + assertEquals(m + " modifiers:", Modifier.toString(mods), Modifier.toString(m.getModifiers())); + } + + protected void exceptionsTest(ResolvedMember m, UnresolvedType[] exns) { + TestUtil.assertSetEquals(m + " exceptions:", exns, m.getExceptions()); + } + +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/MatcherModuleTests.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/MatcherModuleTests.java new file mode 100644 index 000000000..234e387de --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/MatcherModuleTests.java @@ -0,0 +1,40 @@ +/* ******************************************************************* + * Copyright (c) 2002-2008 Contributors + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * PARC initial implementation + * ******************************************************************/ + +// default package +package org.aspectj.weaver; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.aspectj.matcher.tools.ReflectionWorldPointcutExpressionTests; +import org.aspectj.weaver.patterns.PatternsTests; +import org.aspectj.weaver.reflect.ReflectionWorldBasicTest; +import org.aspectj.weaver.reflect.ReflectionWorldSpecificTest; + +public class MatcherModuleTests extends TestCase { + + public MatcherModuleTests(String name) { + super(name); + } + + public static Test suite() { + TestSuite suite = new TestSuite(MatcherModuleTests.class.getName()); + suite.addTestSuite(ReflectionWorldSpecificTest.class); + suite.addTestSuite(ReflectionWorldBasicTest.class); + suite.addTestSuite(ReflectionWorldPointcutExpressionTests.class); + suite.addTestSuite(TypeFactoryTests.class); + suite.addTest(PatternsTests.suite()); + return suite; + } +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/TestShadow.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/TestShadow.java new file mode 100644 index 000000000..0a5249245 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/TestShadow.java @@ -0,0 +1,131 @@ +/* ******************************************************************* + * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * PARC initial implementation + * ******************************************************************/ + +package org.aspectj.weaver; + +import org.aspectj.bridge.ISourceLocation; +import org.aspectj.weaver.ast.Var; + +public class TestShadow extends Shadow { + + private final World world; + private final UnresolvedType thisType; + + public TestShadow(Kind kind, Member signature, UnresolvedType thisType, World world) { + super(kind, signature, null); + this.world = world; + this.thisType = thisType; + } + + public World getIWorld() { + return world; + } + + /** this is subtly wrong. ha ha */ + public UnresolvedType getEnclosingType() { + return thisType; + } + + public Var getThisVar() { + // we should thorw if we don't have a this + return new Var(getThisType().resolve(world)); + } + + public Var getTargetVar() { + if (!hasTarget()) + throw new RuntimeException("bad"); + return new Var(getTargetType().resolve(world)); + } + + public Var getArgVar(int i) { + return new Var(getArgType(i).resolve(world)); + } + + public Var getThisEnclosingJoinPointStaticPartVar() { + throw new RuntimeException("unimplemented"); + } + + public Var getThisAspectInstanceVar(ResolvedType aspectType) { + throw new RuntimeException("unimplemented"); + } + + public Var getThisJoinPointStaticPartVar() { + throw new RuntimeException("unimplemented"); + } + + public Var getThisJoinPointVar() { + throw new RuntimeException("unimplemented"); + } + + public ISourceLocation getSourceLocation() { + throw new RuntimeException("unimplemented"); + } + + public Member getEnclosingCodeSignature() { + throw new RuntimeException("unimplemented"); + } + + /* + * (non-Javadoc) + * + * @see org.aspectj.weaver.Shadow#getKindedAnnotationVar() + */ + public Var getKindedAnnotationVar(UnresolvedType annotationType) { + throw new RuntimeException("unimplemented"); + } + + /* + * (non-Javadoc) + * + * @see org.aspectj.weaver.Shadow#getWithinAnnotationVar() + */ + public Var getWithinAnnotationVar(UnresolvedType annotationType) { + throw new RuntimeException("unimplemented"); + } + + /* + * (non-Javadoc) + * + * @see org.aspectj.weaver.Shadow#getWithinCodeAnnotationVar() + */ + public Var getWithinCodeAnnotationVar(UnresolvedType annotationType) { + throw new RuntimeException("unimplemented"); + } + + /* + * (non-Javadoc) + * + * @see org.aspectj.weaver.Shadow#getThisAnnotationVar() + */ + public Var getThisAnnotationVar(UnresolvedType annotationType) { + throw new RuntimeException("unimplemented"); + } + + /* + * (non-Javadoc) + * + * @see org.aspectj.weaver.Shadow#getTargetAnnotationVar() + */ + public Var getTargetAnnotationVar(UnresolvedType annotationType) { + throw new RuntimeException("unimplemented"); + } + + /* + * (non-Javadoc) + * + * @see org.aspectj.weaver.Shadow#getArgAnnotationVar(int) + */ + public Var getArgAnnotationVar(int i, UnresolvedType annotationType) { + throw new RuntimeException("unimplemented"); + } + +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/TestUtils.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/TestUtils.java new file mode 100644 index 000000000..ac4c46cb7 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/TestUtils.java @@ -0,0 +1,304 @@ +/* ******************************************************************* + * Copyright (c) 2008 Contributors + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Andy Clement initial implementation + * ******************************************************************/ +package org.aspectj.weaver; + +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; + +public class TestUtils { + private static final String[] ZERO_STRINGS = new String[0]; + + // For stringifying a delegate - extracted from AbstractReferenceTypeDelegate, not fixed up + // /** + // * Create the string representation for a delegate, allowing us to + // * more easily compare delegate implementations. + // */ + // public String stringifyDelegate() { + // + // StringBuffer result = new StringBuffer(); + // result.append("=== Delegate for "+getResolvedTypeX().getName()+"\n"); + // + // result.append("isAspect?"+isAspect()+"\n"); + // result.append("isAnnotationStyleAspect?"+isAnnotationStyleAspect()+"\n"); + // result.append("isInterface?"+isInterface()+"\n"); + // result.append("isEnum?"+isEnum()+"\n"); + // result.append("isClass?"+isClass()+"\n"); + // result.append("-\n"); + // result.append("isAnnotation?"+isAnnotation()+"\n"); + // result.append("retentionPolicy="+getRetentionPolicy()+"\n"); + // result.append("canAnnotationTargetType?"+canAnnotationTargetType()+"\n"); + // AnnotationTargetKind[] kinds = getAnnotationTargetKinds(); + // if (kinds!=null && kinds.length>0) { + // result.append("annotationTargetKinds:["); + // for (int i = 0; i < kinds.length; i++) { + // AnnotationTargetKind kind = kinds[i]; + // result.append(kind); + // if ((i+1)<kinds.length) result.append(" "); + // } + // result.append("]\n"); + // } + // result.append("isAnnotationWithRuntimeRetention?"+isAnnotationWithRuntimeRetention()+"\n"); + // result.append("-\n"); + // + // result.append("isAnonymous?"+isAnonymous()+"\n"); + // result.append("isNested?"+isNested()+"\n"); + // result.append("-\n"); + // + // result.append("isGeneric?"+isGeneric()+"\n"); + // result.append("declaredGenericSignature="+getDeclaredGenericSignature()+"\n"); + // result.append("-\n"); + // + // AnnotationX[] axs = getAnnotations(); + // if (axs!=null && axs.length>0) { + // result.append("getAnnotations() returns: "+axs.length+" annotations\n"); + // for (int i = 0; i < axs.length; i++) { + // AnnotationX annotationX = axs[i]; + // result.append(" #"+i+") "+annotationX+"\n"); + // } + // } else { + // result.append("getAnnotations() returns nothing\n"); + // } + // ResolvedType[] axtypes = getAnnotationTypes(); + // if (axtypes!=null && axtypes.length>0) { + // result.append("getAnnotationTypes() returns: "+axtypes.length+" annotations\n"); + // for (int i = 0; i < axtypes.length; i++) { + // ResolvedType annotation = axtypes[i]; + // result.append(" #"+i+") "+annotation+":"+annotation.getClass()+"\n"); + // } + // } else { + // result.append("getAnnotationTypes() returns nothing\n"); + // } + // + // result.append("isExposedToWeaver?"+isExposedToWeaver()+"\n"); + // result.append("getSuperclass?"+getSuperclass()+"\n"); + // result.append("getResolvedTypeX?"+getResolvedTypeX()+"\n"); + // result.append("--\n"); + // + // ResolvedMember[] fields = getDeclaredFields(); + // if (fields!=null && fields.length>0) { + // result.append("The fields: "+fields.length+"\n"); + // for (int i = 0; i < fields.length; i++) { + // ResolvedMember member = fields[i]; + // result.append("f"+i+") "+member.toDebugString()+"\n"); + // } + // } + // ResolvedMember[] methods = getDeclaredMethods(); + // if (methods!=null && methods.length>0) { + // result.append("The methods: "+methods.length+"\n"); + // for (int i = 0; i < methods.length; i++) { + // ResolvedMember member = methods[i]; + // result.append("m"+i+") "+member.toDebugString()+"\n"); + // } + // } + // ResolvedType[] interfaces = getDeclaredInterfaces(); + // if (interfaces!=null && interfaces.length>0) { + // result.append("The interfaces: "+interfaces.length+"\n"); + // for (int i = 0; i < interfaces.length; i++) { + // ResolvedType member = interfaces[i]; + // result.append("i"+i+") "+member+"\n"); + // } + // } + // + // result.append("getModifiers?"+getModifiers()+"\n"); + // + // result.append("perclause="+getPerClause()+"\n"); + // + // result.append("aj:weaverstate="+getWeaverState()+"\n"); + // + // ResolvedMember[] pointcuts = getDeclaredPointcuts(); + // if (pointcuts!=null && pointcuts.length>0) { + // result.append("The pointcuts: "+pointcuts.length+"\n"); + // + // // Sort the damn things + // List sortedSetOfPointcuts = new ArrayList(); + // for (int i = 0; i < pointcuts.length; i++) {sortedSetOfPointcuts.add(pointcuts[i]);} + // Collections.sort(sortedSetOfPointcuts); + // + // int i =0; + // for (Iterator iter = sortedSetOfPointcuts.iterator(); iter.hasNext();) { + // ResolvedMember member = (ResolvedMember) iter.next(); + // result.append("p"+i+") "+member.toDebugString()+"\n"); + // i++; + // } + // } + // + // Collection declares = getDeclares(); + // if (declares.size()>0) { + // result.append("The declares: "+declares.size()+"\n"); + // + // // // Sort the damn things + // // List sortedSetOfPointcuts = new ArrayList(); + // // for (int i = 0; i < pointcuts.length; i++) {sortedSetOfPointcuts.add(pointcuts[i]);} + // // Collections.sort(sortedSetOfPointcuts); + // + // int i=0; + // for (Iterator iter = declares.iterator(); iter.hasNext();) { + // Declare dec = (Declare) iter.next(); + // result.append("d"+i+") "+dec.toString()+"\n"); + // i++; + // } + // } + // + // TypeVariable[] tv = getTypeVariables(); + // if (tv!=null && tv.length>0) { + // result.append("The type variables: "+tv.length+"\n"); + // for (int i = 0; i < tv.length; i++) { + // result.append("tv"+i+") "+tv[i]+"\n"); + // } + // } + // + // Collection tmungers = getTypeMungers(); + // if (tmungers.size()>0) { + // List sorted = new ArrayList(); + // sorted.addAll(tmungers); + // Collections.sort(sorted,new Comparator() { + // public int compare(Object arg0, Object arg1) { + // return arg0.toString().compareTo(arg1.toString()); + // } + // }); + // result.append("The type mungers: "+tmungers.size()+"\n"); + // int i=0; + // for (Iterator iter = sorted.iterator(); iter.hasNext();) { + // ConcreteTypeMunger mun = (ConcreteTypeMunger) iter.next(); + // result.append("tm"+i+") "+mun.toString()+"\n"); + // i++; + // } + // } + // + // result.append("doesNotExposeShadowMungers?"+doesNotExposeShadowMungers()+"\n"); + // + // Collection pas = getPrivilegedAccesses(); + // if (pas!=null && pas.size()>0) { + // // List sorted = new ArrayList(); + // // sorted.addAll(tmungers); + // // Collections.sort(sorted,new Comparator() { + // // public int compare(Object arg0, Object arg1) { + // // return arg0.toString().compareTo(arg1.toString()); + // // } + // // }); + // result.append("The privileged accesses: "+pas.size()+"\n"); + // int i=0; + // for (Iterator iter = pas.iterator(); iter.hasNext();) { + // ResolvedMember mun = (ResolvedMember) iter.next(); + // result.append("tm"+i+") "+mun.toDebugString()+"\n"); + // i++; + // } + // } + // + // // public Collection getPrivilegedAccesses(); + // // public boolean hasAnnotation(UnresolvedType ofType); + // result.append("==="); + // return result.toString(); + // } + + /** + * Build a member from a string representation: <blockquote> + * + * <pre> + * static? TypeName TypeName.Id + * </pre> + * + * </blockquote> + */ + public static MemberImpl fieldFromString(String str) { + str = str.trim(); + final int len = str.length(); + int i = 0; + int mods = 0; + if (str.startsWith("static", i)) { + mods = Modifier.STATIC; + i += 6; + while (Character.isWhitespace(str.charAt(i))) + i++; + } + int start = i; + while (!Character.isWhitespace(str.charAt(i))) + i++; + UnresolvedType retTy = UnresolvedType.forName(str.substring(start, i)); + + start = i; + i = str.lastIndexOf('.'); + UnresolvedType declaringTy = UnresolvedType.forName(str.substring(start, i).trim()); + start = ++i; + String name = str.substring(start, len).trim(); + return new MemberImpl(Member.FIELD, declaringTy, mods, retTy, name, UnresolvedType.NONE); + } + + /** + * Build a member from a string representation: <blockquote> + * + * <pre> + * (static|interface|private)? TypeName TypeName . Id ( TypeName , ...) + * </pre> + * + * </blockquote> + */ + + public static Member methodFromString(String str) { + str = str.trim(); + // final int len = str.length(); + int i = 0; + + int mods = 0; + if (str.startsWith("static", i)) { + mods = Modifier.STATIC; + i += 6; + } else if (str.startsWith("interface", i)) { + mods = Modifier.INTERFACE; + i += 9; + } else if (str.startsWith("private", i)) { + mods = Modifier.PRIVATE; + i += 7; + } + while (Character.isWhitespace(str.charAt(i))) + i++; + + int start = i; + while (!Character.isWhitespace(str.charAt(i))) + i++; + UnresolvedType returnTy = UnresolvedType.forName(str.substring(start, i)); + + start = i; + i = str.indexOf('(', i); + i = str.lastIndexOf('.', i); + UnresolvedType declaringTy = UnresolvedType.forName(str.substring(start, i).trim()); + + start = ++i; + i = str.indexOf('(', i); + String name = str.substring(start, i).trim(); + start = ++i; + i = str.indexOf(')', i); + + String[] paramTypeNames = parseIds(str.substring(start, i).trim()); + + return MemberImpl.method(declaringTy, mods, returnTy, name, UnresolvedType.forNames(paramTypeNames)); + } + + public static String[] parseIds(String str) { + if (str.length() == 0) + return ZERO_STRINGS; + List<String> l = new ArrayList<String>(); + int start = 0; + while (true) { + int i = str.indexOf(',', start); + if (i == -1) { + l.add(str.substring(start).trim()); + break; + } + l.add(str.substring(start, i).trim()); + start = i + 1; + } + return (String[]) l.toArray(new String[l.size()]); + } + +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/TypeFactoryTests.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/TypeFactoryTests.java new file mode 100644 index 000000000..40fed411a --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/TypeFactoryTests.java @@ -0,0 +1,76 @@ +/* ******************************************************************* + * Copyright (c) 2010 Contributors. + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://eclipse.org/legal/epl-v10.html + * ******************************************************************/ +package org.aspectj.weaver; + +import junit.framework.TestCase; + +/** + * Check signature to type mapping. + * + * @author Andy Clement + */ +public class TypeFactoryTests extends TestCase { + + public void testParameterizedSig() { + UnresolvedType t = null; + t = UnresolvedType.forSignature("Pjava/util/List<Ljava/lang/String;>;"); + assertEquals("Ljava/util/List;", t.getErasureSignature()); + assertEquals("Ljava/lang/String;", t.getTypeParameters()[0].signature); + assertEquals("Ljava/lang/String;", t.getTypeParameters()[0].signatureErasure); + assertEquals("Pjava/util/List<Ljava/lang/String;>;", t.getSignature()); + + t = TypeFactory.createTypeFromSignature("Ljava/util/List<Ljava/lang/String;>;"); + assertEquals("Ljava/util/List;", t.getErasureSignature()); + assertEquals("Ljava/lang/String;", t.getTypeParameters()[0].signature); + assertEquals("Ljava/lang/String;", t.getTypeParameters()[0].signatureErasure); + assertEquals("Pjava/util/List<Ljava/lang/String;>;", t.getSignature()); + + t = UnresolvedType.forName("java.util.List<java.lang.String>"); + assertEquals("Ljava/util/List;", t.getErasureSignature()); + assertEquals("Ljava/lang/String;", t.getTypeParameters()[0].signature); + assertEquals("Ljava/lang/String;", t.getTypeParameters()[0].signatureErasure); + assertEquals("Pjava/util/List<Ljava/lang/String;>;", t.getSignature()); + + t = UnresolvedType.forSignature("Pjava/util/Map<TS;Pjava/util/List<Ljava/lang/String;>;>;"); + assertEquals("Ljava/util/Map;", t.getErasureSignature()); + assertEquals("TS;", t.getTypeParameters()[0].signature); + assertEquals("Ljava/lang/Object;", t.getTypeParameters()[0].signatureErasure); + assertEquals("S", ((UnresolvedTypeVariableReferenceType) t.getTypeParameters()[0]).getTypeVariable().getName()); + assertEquals("Pjava/util/Map<TS;Pjava/util/List<Ljava/lang/String;>;>;", t.getSignature()); + assertEquals("Pjava/util/List<Ljava/lang/String;>;", t.getTypeParameters()[1].signature); + assertEquals("Ljava/util/List;", t.getTypeParameters()[1].signatureErasure); + + t = UnresolvedType.forSignature("Pjava/util/List<+Pnl/ZoekFoo<TS;Pnl/ZoekCopy<TS;>;>;>;"); + assertEquals("Ljava/util/List;", t.getErasureSignature()); + WildcardedUnresolvedType wut = (WildcardedUnresolvedType) t.getTypeParameters()[0]; + assertEquals("+Pnl/ZoekFoo<TS;Pnl/ZoekCopy<TS;>;>;", wut.signature); + assertEquals("Lnl/ZoekFoo;", wut.signatureErasure); + assertTrue(wut.isExtends()); + assertEquals("Pnl/ZoekFoo<TS;Pnl/ZoekCopy<TS;>;>;", wut.getUpperBound().signature); + assertEquals("Lnl/ZoekFoo;", wut.getUpperBound().signatureErasure); + UnresolvedTypeVariableReferenceType tvar = (UnresolvedTypeVariableReferenceType) wut.getUpperBound().getTypeParameters()[0]; + assertEquals("Pnl/ZoekFoo<TS;Pnl/ZoekCopy<TS;>;>;", wut.getUpperBound().signature); + assertEquals("Lnl/ZoekFoo;", wut.getUpperBound().signatureErasure); + assertEquals("S", tvar.getTypeVariable().getName()); + UnresolvedType t2 = wut.getUpperBound().getTypeParameters()[1]; + assertEquals("Pnl/ZoekCopy<TS;>;", t2.getSignature()); + assertEquals("Lnl/ZoekCopy;", t2.getErasureSignature()); + + // // t = UnresolvedType.forSignature("Ljava/util/List<+Lnl/ZoekFoo<TS;Lnl/ZoekCopy<TS;>;>;>;"); + // t = TypeFactory.createTypeFromSignature("Ljava/util/List<+Lnl/ZoekFoo<TS;Lnl/ZoekCopy<TS;>;>;>;"); + // System.out.println(t.getSignature()); + // + // t = TypeFactory.createTypeFromSignature("Ljava/util/List<Lnl/ZoekFoo<Ljava/lang/String;>;>;"); + // System.out.println(t.getSignature()); // Pjava/util/List<Lnl/ZoekFoo<Ljava/lang/String;>;>; + + // TODO should be able to cope with nested parameterizations + // Foo<String>.Bar<List<Map<String,Integer>>> + // both components Foo and Bar of that are parameterized + } +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/AndOrNotTestCase.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/AndOrNotTestCase.java new file mode 100644 index 000000000..909db8e6a --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/AndOrNotTestCase.java @@ -0,0 +1,96 @@ +/* ******************************************************************* + * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * PARC initial implementation + * ******************************************************************/ + +package org.aspectj.weaver.patterns; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import org.aspectj.weaver.CompressingDataOutputStream; +import org.aspectj.weaver.VersionedDataInputStream; +import org.aspectj.weaver.World; +import org.aspectj.weaver.reflect.ReflectionWorld; + +/** + * @author hugunin + * + */ +public class AndOrNotTestCase extends PatternsTestCase { + + public World getWorld() { + return new ReflectionWorld(this.getClass().getClassLoader()); + } + + public void testMatchBooleanOperatorPointcutMatching() throws IOException { + + Pointcut foo = makePointcut("this(Foo)"); + Pointcut bar = makePointcut("this(Bar)"); + Pointcut c = makePointcut("this(C)"); + + checkEquals("this(Foo) && this(Bar)", new AndPointcut(foo, bar)); + checkEquals("this(Foo) && this(Bar) && this(C)", new AndPointcut(foo, new AndPointcut(bar, c))); + + checkEquals("this(Foo) || this(Bar)", new OrPointcut(foo, bar)); + checkEquals("this(Foo) || this(Bar) || this(C)", new OrPointcut(foo, new OrPointcut(bar, c))); + + checkEquals("this(Foo) && this(Bar) || this(C)", new OrPointcut(new AndPointcut(foo, bar), c)); + checkEquals("this(Foo) || this(Bar) && this(C)", new OrPointcut(foo, new AndPointcut(bar, c))); + checkEquals("(this(Foo) || this(Bar)) && this(C)", new AndPointcut(new OrPointcut(foo, bar), c)); + checkEquals("this(Foo) || (this(Bar) && this(C))", new OrPointcut(foo, new AndPointcut(bar, c))); + + checkEquals("!this(Foo)", new NotPointcut(foo)); + checkEquals("!this(Foo) && this(Bar)", new AndPointcut(new NotPointcut(foo), bar)); + checkEquals("!(this(Foo) && this(Bar)) || this(C)", new OrPointcut(new NotPointcut(new AndPointcut(foo, bar)), c)); + checkEquals("!!this(Foo)", new NotPointcut(new NotPointcut(foo))); + } + + private static class Foo { + } + + private static class Bar { + } + + private static class C { + } + + static { + new Foo(); + new Bar(); + new C(); // just to touch them and so eclipse thinks they are used + } + + private Pointcut makePointcut(String pattern) { + return new PatternParser(pattern).parsePointcut(); + } + + private void checkEquals(String pattern, Pointcut p) throws IOException { + assertEquals(pattern, p, makePointcut(pattern)); + checkSerialization(pattern); + } + + private void checkSerialization(String string) throws IOException { + Pointcut p = makePointcut(string); + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + ConstantPoolSimulator cps = new ConstantPoolSimulator(); + CompressingDataOutputStream out = new CompressingDataOutputStream(bo, cps); + p.write(out); + out.close(); + + ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); + VersionedDataInputStream in = new VersionedDataInputStream(bi, cps); + Pointcut newP = Pointcut.read(in, null); + + assertEquals("write/read", p, newP); + } + +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/ArgsTestCase.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/ArgsTestCase.java new file mode 100644 index 000000000..705674cb3 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/ArgsTestCase.java @@ -0,0 +1,201 @@ +/******************************************************************************* + * Copyright (c) 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.aspectj.weaver.patterns; + +import java.lang.reflect.Method; + +import junit.framework.TestCase; + +import org.aspectj.util.LangUtil; +import org.aspectj.weaver.tools.JoinPointMatch; +import org.aspectj.weaver.tools.PointcutExpression; +import org.aspectj.weaver.tools.PointcutParameter; +import org.aspectj.weaver.tools.PointcutParser; +import org.aspectj.weaver.tools.ShadowMatch; + +/** + * @author colyer + * + */ +public class ArgsTestCase extends TestCase { + + PointcutExpression wildcardArgs; + PointcutExpression oneA; + PointcutExpression oneAandaC; + PointcutExpression BthenAnything; + PointcutExpression singleArg; + + public void testMatchJP() throws Exception { + if (needToSkip) + return; + + Method oneAArg = B.class.getMethod("x", new Class[] { A.class }); + Method oneBArg = B.class.getMethod("y", new Class[] { B.class }); + Method acArgs = C.class.getMethod("z", new Class[] { A.class, C.class }); + Method baArgs = C.class.getMethod("t", new Class[] { B.class, A.class }); + + checkMatches(wildcardArgs.matchesMethodExecution(oneAArg), new B(), new B(), new Object[] { new A() }); + checkMatches(wildcardArgs.matchesMethodExecution(oneBArg), new B(), new B(), new Object[] { new B() }); + checkMatches(wildcardArgs.matchesMethodExecution(acArgs), new C(), new C(), new Object[] { new B(), new C() }); + checkMatches(wildcardArgs.matchesMethodExecution(baArgs), new C(), new C(), new Object[] { new B(), new B() }); + + checkMatches(oneA.matchesMethodExecution(oneAArg), new B(), new B(), new Object[] { new A() }); + checkMatches(oneA.matchesMethodExecution(oneBArg), new B(), new B(), new Object[] { new B() }); + checkNoMatch(oneA.matchesMethodExecution(acArgs), new C(), new C(), new Object[] { new B(), new C() }); + checkNoMatch(oneA.matchesMethodExecution(baArgs), new C(), new C(), new Object[] { new B(), new B() }); + + checkNoMatch(oneAandaC.matchesMethodExecution(oneAArg), new B(), new B(), new Object[] { new A() }); + checkNoMatch(oneAandaC.matchesMethodExecution(oneBArg), new B(), new B(), new Object[] { new B() }); + checkMatches(oneAandaC.matchesMethodExecution(acArgs), new C(), new C(), new Object[] { new B(), new C() }); + checkNoMatch(oneAandaC.matchesMethodExecution(baArgs), new C(), new C(), new Object[] { new B(), new B() }); + + checkNoMatch(BthenAnything.matchesMethodExecution(oneAArg), new B(), new B(), new Object[] { new A() }); + checkMatches(BthenAnything.matchesMethodExecution(oneBArg), new B(), new B(), new Object[] { new B() }); + checkNoMatch(BthenAnything.matchesMethodExecution(acArgs), new C(), new C(), new Object[] { new A(), new C() }); + checkMatches(BthenAnything.matchesMethodExecution(baArgs), new C(), new C(), new Object[] { new B(), new B() }); + + checkMatches(singleArg.matchesMethodExecution(oneAArg), new B(), new B(), new Object[] { new A() }); + checkMatches(singleArg.matchesMethodExecution(oneBArg), new B(), new B(), new Object[] { new B() }); + checkNoMatch(singleArg.matchesMethodExecution(acArgs), new C(), new C(), new Object[] { new B(), new C() }); + checkNoMatch(singleArg.matchesMethodExecution(baArgs), new C(), new C(), new Object[] { new B(), new B() }); + + } + + public void testBinding() throws Exception { + if (needToSkip) + return; + + PointcutParser parser = PointcutParser + .getPointcutParserSupportingAllPrimitivesAndUsingSpecifiedClassloaderForResolution(A.class.getClassLoader()); + PointcutParameter a = parser.createPointcutParameter("a", A.class); + A theParameter = new A(); + PointcutExpression bindA = parser.parsePointcutExpression("args(a,*)", A.class, new PointcutParameter[] { a }); + + Method acArgs = C.class.getMethod("z", new Class[] { A.class, C.class }); + ShadowMatch sMatch = bindA.matchesMethodExecution(acArgs); + JoinPointMatch jpMatch = sMatch.matchesJoinPoint(new A(), new A(), new Object[] { theParameter }); + assertTrue("should match", jpMatch.matches()); + PointcutParameter[] bindings = jpMatch.getParameterBindings(); + assertTrue("one parameter", bindings.length == 1); + assertEquals("should be bound to the arg value", theParameter, bindings[0].getBinding()); + + PointcutParameter c = parser.createPointcutParameter("c", C.class); + C cParameter = new C(); + PointcutExpression bindAandC = parser.parsePointcutExpression("args(a,c)", A.class, new PointcutParameter[] { a, c }); + sMatch = bindAandC.matchesMethodExecution(acArgs); + jpMatch = sMatch.matchesJoinPoint(new A(), new A(), new Object[] { theParameter, cParameter }); + assertTrue("should match", jpMatch.matches()); + bindings = jpMatch.getParameterBindings(); + assertTrue("two parameters", bindings.length == 2); + assertEquals("should be bound to the a arg value", theParameter, bindings[0].getBinding()); + assertEquals("should be bound to the c arg value", cParameter, bindings[1].getBinding()); + assertEquals("a", bindings[0].getName()); + assertEquals("c", bindings[1].getName()); + } + + public void testMatchJPWithPrimitiveTypes() throws Exception { + if (needToSkip) + return; + + try { + + PointcutParser parser = PointcutParser + .getPointcutParserSupportingAllPrimitivesAndUsingSpecifiedClassloaderForResolution(A.class.getClassLoader()); + PointcutExpression oneInt = parser.parsePointcutExpression("args(int)"); + PointcutExpression oneInteger = parser.parsePointcutExpression("args(Integer)"); + + Method oneIntM = A.class.getMethod("anInt", new Class[] { int.class }); + Method oneIntegerM = A.class.getMethod("anInteger", new Class[] { Integer.class }); + + if (LangUtil.is15VMOrGreater()) { + checkMatches(oneInt.matchesMethodExecution(oneIntM), new A(), new A(), new Object[] { new Integer(5) }); + checkMatches(oneInt.matchesMethodExecution(oneIntegerM), new A(), new A(), new Object[] { new Integer(5) }); + checkMatches(oneInteger.matchesMethodExecution(oneIntM), new A(), new A(), new Object[] { new Integer(5) }); + checkMatches(oneInteger.matchesMethodExecution(oneIntegerM), new A(), new A(), new Object[] { new Integer(5) }); + } else { + checkMatches(oneInt.matchesMethodExecution(oneIntM), new A(), new A(), new Object[] { new Integer(5) }); + checkNoMatch(oneInt.matchesMethodExecution(oneIntegerM), new A(), new A(), new Object[] { new Integer(5) }); + checkNoMatch(oneInteger.matchesMethodExecution(oneIntM), new A(), new A(), new Object[] { new Integer(5) }); + checkMatches(oneInteger.matchesMethodExecution(oneIntegerM), new A(), new A(), new Object[] { new Integer(5) }); + } + + } catch (Exception ex) { + fail("Unexpected exception " + ex); + } + + } + + private void checkMatches(ShadowMatch sMatch, Object thisOjb, Object targetObj, Object[] args) { + assertTrue("match expected", sMatch.matchesJoinPoint(thisOjb, targetObj, args).matches()); + } + + private void checkNoMatch(ShadowMatch sMatch, Object thisOjb, Object targetObj, Object[] args) { + assertFalse("no match expected", sMatch.matchesJoinPoint(thisOjb, targetObj, args).matches()); + } + + @SuppressWarnings("unused") + private static class A { + public void anInt(int i) { + } + + public void anInteger(Integer i) { + } + + } + + @SuppressWarnings("unused") + private static class B extends A { + public void x(A a) { + } + + public void y(B b) { + } + } + + @SuppressWarnings("unused") + private static class C { + public void z(A a, C c) { + } + + public void t(B b, A a) { + } + } + + private boolean needToSkip = false; + + /** this condition can occur on the build machine only, and is way too complex to fix right now... */ + private boolean needToSkipPointcutParserTests() { + if (!LangUtil.is15VMOrGreater()) + return false; + try { + Class.forName("org.aspectj.weaver.reflect.Java15ReflectionBasedReferenceTypeDelegate", false, this.getClass() + .getClassLoader());// ReflectionBasedReferenceTypeDelegate.class.getClassLoader()); + } catch (ClassNotFoundException cnfEx) { + return true; + } + return false; + } + + protected void setUp() throws Exception { + super.setUp(); + needToSkip = needToSkipPointcutParserTests(); + if (needToSkip) + return; + PointcutParser parser = PointcutParser + .getPointcutParserSupportingAllPrimitivesAndUsingSpecifiedClassloaderForResolution(A.class.getClassLoader()); + wildcardArgs = parser.parsePointcutExpression("args(..)"); + oneA = parser.parsePointcutExpression("args(org.aspectj.weaver.patterns.ArgsTestCase.A)"); + oneAandaC = parser + .parsePointcutExpression("args(org.aspectj.weaver.patterns.ArgsTestCase.A,org.aspectj.weaver.patterns.ArgsTestCase.C)"); + BthenAnything = parser.parsePointcutExpression("args(org.aspectj.weaver.patterns.ArgsTestCase.B,..)"); + singleArg = parser.parsePointcutExpression("args(*)"); + } +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/BindingTestCase.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/BindingTestCase.java new file mode 100644 index 000000000..7303191dd --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/BindingTestCase.java @@ -0,0 +1,132 @@ +/* ******************************************************************* + * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * PARC initial implementation + * ******************************************************************/ + +package org.aspectj.weaver.patterns; + +import org.aspectj.bridge.AbortException; +import org.aspectj.weaver.World; +import org.aspectj.weaver.patterns.BindingTypePattern; +import org.aspectj.weaver.patterns.Bindings; +import org.aspectj.weaver.patterns.PatternParser; +import org.aspectj.weaver.patterns.Pointcut; +import org.aspectj.weaver.patterns.TestScope; +import org.aspectj.weaver.reflect.ReflectionWorld; + +public class BindingTestCase extends PatternsTestCase { + + public World getWorld() { + return new ReflectionWorld(true, this.getClass().getClassLoader()); + } + + public void testResolveBindings() { + BindingTypePattern at = new BindingTypePattern(world.resolve("java.lang.Object"), 0, false); + BindingTypePattern bt = new BindingTypePattern(world.resolve("java.lang.Object"), 1, false); + + BindingTypePattern[] all = new BindingTypePattern[] { at, bt }; + BindingTypePattern[] none = new BindingTypePattern[] { null, null }; + BindingTypePattern[] a = new BindingTypePattern[] { at, null }; + BindingTypePattern[] b = new BindingTypePattern[] { null, bt }; + + checkBindings("this(b)", b); + checkBindings("this(java.lang.String)", none); + checkBindings("this(*)", none); + checkBindings("this(a)", a); + + try { + checkBindings("args(.., a,..,b)", all); + // checkBindings("args(a,..,b, ..)", all); + fail("shouldn't be implemented yet"); + } catch (Throwable ae) { + // // diff world implementations may exit by different means + // } catch (Exception e) { + // // diff world implementations may exit by different means + } + + checkBindings("args(a,..,b)", all); + checkBindings("args(b)", b); + + checkBindings("args()", none); + + checkBindings("this(a) && this(b)", all); + + checkBindingFailure("this(a) && this(a)", "multiple"); + // checkBindingFailure("this(a) && this(b)"); + + checkBindingFailure("this(a) || this(b)", "inconsistent"); + checkBindingFailure("this(java.lang.String) || this(b)", "inconsistent"); + checkBindingFailure("this(a) || this(java.lang.String)", "inconsistent"); + checkBindings("this(a) || this(a)", a); + + checkBindings("!this(java.lang.String)", none); + checkBindings("!this(java.lang.String) && this(a)", a); + checkBindingFailure("!this(a)", "negation"); + // checkBindingFailure("this(a)"); + + checkBindings("cflow(this(a))", a); + checkBindings("cflow(this(a)) && this(b)", all); + + checkBindingFailure("cflow(this(a)) || this(b)", "inconsistent"); + checkBindingFailure("cflow(this(a)) && this(a)", "multiple"); + + checkBindingFailure("!cflow(this(a))", "negation"); + + // todo + // this should fail since a isn't visible to if + // checkBindingFailure("cflow(if(a != null)) && this(a)"); + // checkBinding("cflow(if(a != null) && this(a))", a); + + } + + /** + * Method checkBindingFailure. (assumes an env where "a" and "b" are formals). + * + * @param string + */ + private void checkBindingFailure(String pattern, String prefix) { + PatternParser parser = new PatternParser(pattern); + Pointcut p = parser.parsePointcut(); + Bindings actualBindings = new Bindings(2); + try { + p.resolveBindings(makeSimpleScope(), actualBindings); + } catch (AbortException re) { + assertEquals(prefix, re.getIMessage().getMessage().substring(0, prefix.length())); + // System.out.println("expected exception: " + re); + return; + } catch (Throwable t) { + assertTrue(prefix, t.getMessage().indexOf(prefix) != -1); + return; + } + assertTrue("should have failed", false); + } + + /** + * Method checkBindings. + * + * @param string + * @param i + */ + private void checkBindings(String pattern, BindingTypePattern[] expectedBindings) { + PatternParser parser = new PatternParser(pattern); + Pointcut p = parser.parsePointcut(); + Bindings actualBindings = new Bindings(expectedBindings.length); + + TestScope simpleScope = makeSimpleScope(); + p.resolveBindings(simpleScope, actualBindings); + // System.out.println(actualBindings); + + new Bindings(expectedBindings).checkEquals(actualBindings, simpleScope); + } + + public TestScope makeSimpleScope() { + return new TestScope(new String[] { "int", "java.lang.String" }, new String[] { "a", "b" }, world); + } +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/ConstantPoolSimulator.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/ConstantPoolSimulator.java new file mode 100644 index 000000000..57f971665 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/ConstantPoolSimulator.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * Copyright (c) 2010 Contributors + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Andy Clement (SpringSource) - initial implementation + *******************************************************************************/ +package org.aspectj.weaver.patterns; + +import java.util.ArrayList; +import java.util.List; + +import org.aspectj.weaver.ConstantPoolReader; +import org.aspectj.weaver.ConstantPoolWriter; + +public class ConstantPoolSimulator implements ConstantPoolWriter, ConstantPoolReader { + List<String> list = new ArrayList<String>(); + + public int writeUtf8(String string) { + int i = list.indexOf(string); + if (i != -1) { + return i; + } + list.add(string); + return list.indexOf(string); + } + + public String readUtf8(int constantPoolIndex) { + return list.get(constantPoolIndex); + } + +}
\ No newline at end of file diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/DeclareErrorOrWarningTestCase.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/DeclareErrorOrWarningTestCase.java new file mode 100644 index 000000000..ab5f6e6f2 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/DeclareErrorOrWarningTestCase.java @@ -0,0 +1,64 @@ +/* ******************************************************************* + * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * PARC initial implementation + * ******************************************************************/ + +package org.aspectj.weaver.patterns; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import junit.framework.TestCase; + +import org.aspectj.weaver.CompressingDataOutputStream; +import org.aspectj.weaver.VersionedDataInputStream; + +public class DeclareErrorOrWarningTestCase extends TestCase { + + public void testParse() throws IOException { + DeclareErrorOrWarning d = parse("declare error: call(void foo()): \"that is bad\";"); + assertTrue(d.isError()); + assertEquals(d.getPointcut(), new PatternParser("call(void foo())").parsePointcut()); + assertEquals("that is bad", d.getMessage()); + checkSerialization(d); + + d = parse("declare warning: bar() && baz(): \"boo!\";"); + assertTrue(!d.isError()); + assertEquals(d.getPointcut(), new PatternParser("bar() && baz()").parsePointcut()); + assertEquals("boo!", d.getMessage()); + checkSerialization(d); + + } + + public void testStartAndEndPositionSet() throws IOException { + DeclareErrorOrWarning d = parse("declare error: call(void foo()): \"that is bad\";"); + assertEquals("start position should be 0", 0, d.getStart()); + assertEquals("end position should be 46", 46, d.getEnd()); + } + + private DeclareErrorOrWarning parse(String string) { + return (DeclareErrorOrWarning) new PatternParser(string).parseDeclare(); + } + + private void checkSerialization(Declare declare) throws IOException { + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + ConstantPoolSimulator cps = new ConstantPoolSimulator(); + CompressingDataOutputStream out = new CompressingDataOutputStream(bo, cps); + declare.write(out); + out.close(); + + ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); + VersionedDataInputStream in = new VersionedDataInputStream(bi, cps); + Declare newDeclare = Declare.read(in, null); + + assertEquals("write/read", declare, newDeclare); + } +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/DumpPointcutVisitor.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/DumpPointcutVisitor.java new file mode 100644 index 000000000..665f4bdda --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/DumpPointcutVisitor.java @@ -0,0 +1,557 @@ +/* ******************************************************************* + * Copyright (c) 2007-2008 Contributors + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Alexandre Vasseur + * ******************************************************************/ +package org.aspectj.weaver.patterns; + +import org.aspectj.weaver.Member; + +/** + * A sample toString like visitor that helps understanding the AST tree structure organization + * + * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> + */ +public class DumpPointcutVisitor implements PatternNodeVisitor { + + private StringBuffer sb = new StringBuffer(); + + public String get() { + return sb.toString(); + } + + private void append(Object o) { + sb.append(o.toString()); + } + + private void append(char c) { + sb.append(c); + } + + /** + * This method helps maintaining the API and raises warning when PatternNode subclasses do not implement the visitor pattern + * + * @param node + * @param data + * @return + */ + public Object visit(PatternNode node, Object data) { + System.err.println("Should implement: " + node.getClass()); + return null; + } + + public Object visit(AnyTypePattern node, Object data) { + append('*'); + return null; + } + + public Object visit(NoTypePattern node, Object data) { + append(node.toString());// TODO no idea when this one is used + return null; + } + + public Object visit(EllipsisTypePattern node, Object data) { + append(node.toString()); + return null; + } + + public Object visit(AnyWithAnnotationTypePattern node, Object data) { + if (node.getAnnotationPattern() != AnnotationTypePattern.ANY) { + append('('); + } + node.annotationPattern.accept(this, data); + append(" *"); + if (node.getAnnotationPattern() != AnnotationTypePattern.ANY) { + append(')'); + } + return null; + } + + public Object visit(AnyAnnotationTypePattern node, Object data) { + // @ANY : ignore + append('*'); + return null; + } + + public Object visit(EllipsisAnnotationTypePattern node, Object data) { + append(".."); + return null; + } + + public Object visit(AndAnnotationTypePattern node, Object data) { + node.getLeft().accept(this, data); + append(' '); + node.getRight().accept(this, data); + return null; + } + + public Object visit(AndPointcut node, Object data) { + append('('); + node.getLeft().accept(this, data); + append(" && "); + node.getRight().accept(this, data); + append(')'); + return null; + } + + public Object visit(AndTypePattern node, Object data) { + append('('); + node.getLeft().accept(this, data); + append(" && "); + node.getRight().accept(this, data); + append(')'); + return null; + } + + public Object visit(AnnotationPatternList node, Object data) { + AnnotationTypePattern[] annotations = node.getAnnotationPatterns(); + for (int i = 0; i < annotations.length; i++) { + if (i > 0) { + append(", ");// Note: list is ",", and is " " separated for annotations + } + annotations[i].accept(this, data); + } + return null; + } + + public Object visit(AnnotationPointcut node, Object data) { + append("@annotation("); + node.getAnnotationTypePattern().accept(this, data); + append(')'); + return null; + } + + public Object visit(ArgsAnnotationPointcut node, Object data) { + append("@args("); + node.getArguments().accept(this, data); + append(')'); + return null; + } + + public Object visit(ArgsPointcut node, Object data) { + append("args("); + node.getArguments().accept(this, data); + append(')'); + return null; + } + + public Object visit(BindingAnnotationTypePattern node, Object data) { + append(node); + return null; + } + + public Object visit(BindingTypePattern node, Object data) { + append(node); + return null; + } + + public Object visit(CflowPointcut node, Object data) { + append(node.isCflowBelow() ? "cflowbelow(" : "cflow("); + node.getEntry().accept(this, data); + append(')'); + return null; + } + + public Object visit(ExactAnnotationTypePattern node, Object data) { + // append('@'); // since @annotation(@someAnno) cannot be parsed anymore + append(node.getAnnotationType().getName()); + return null; + } + + public Object visit(ExactTypePattern node, Object data) { + if (node.getAnnotationPattern() != AnnotationTypePattern.ANY) { + append('('); + node.getAnnotationPattern().accept(this, data); + append(' '); + } + + String typeString = node.getType().toString(); + if (node.isVarArgs()) { + typeString = typeString.substring(0, typeString.lastIndexOf('['));// TODO AV - ugly + } + append(typeString); + if (node.isIncludeSubtypes()) { + append('+'); + } + if (node.isVarArgs()) { + append("..."); + } + if (node.getAnnotationPattern() != AnnotationTypePattern.ANY) { + append(')'); + } + return null; + } + + public Object visit(KindedPointcut node, Object data) { + append(node.getKind().getSimpleName()); + append('('); + node.getSignature().accept(this, data); + append(')'); + return null; + } + + public Object visit(ModifiersPattern node, Object data) { + append(node.toString());// note: node takes care of forbidden mods + return null; + } + + public Object visit(NamePattern node, Object data) { + append(node.toString()); + return null; + } + + public Object visit(NotAnnotationTypePattern node, Object data) { + append("!"); + node.getNegatedPattern().accept(this, data); + return null; + } + + public Object visit(NotPointcut node, Object data) { + append("!("); + node.getNegatedPointcut().accept(this, data); + append(')'); + return null; + } + + public Object visit(NotTypePattern node, Object data) { + append("!("); + node.getNegatedPattern().accept(this, data); + append(')'); + return null; + } + + public Object visit(OrAnnotationTypePattern node, Object data) { + append('('); + node.getLeft().accept(this, data); + append(" || "); + node.getRight().accept(this, data); + append(')'); + return null; + } + + public Object visit(OrPointcut node, Object data) { + append('('); + node.getLeft().accept(this, data); + append(" || "); + node.getRight().accept(this, data); + append(')'); + return null; + } + + public Object visit(OrTypePattern node, Object data) { + append('('); + node.getLeft().accept(this, data); + append(" || "); + node.getRight().accept(this, data); + append(')'); + return null; + } + + public Object visit(ReferencePointcut node, Object data) { + append(node.toString()); + return null; + } + + public Object visit(SignaturePattern node, Object data) { + if (node.getAnnotationPattern() != AnnotationTypePattern.ANY) { + node.getAnnotationPattern().accept(this, data); + append(' '); + } + + if (node.getModifiers() != ModifiersPattern.ANY) { + node.getModifiers().accept(this, data); + append(' '); + } + + if (node.getKind() == Member.STATIC_INITIALIZATION) { + node.getDeclaringType().accept(this, data); + } else if (node.getKind() == Member.HANDLER) { + append("handler("); + node.getParameterTypes().get(0).accept(this, data);// Note: we know we have 1 child + append(')'); + } else { + if (!(node.getKind() == Member.CONSTRUCTOR)) { + node.getReturnType().accept(this, data); + append(' '); + } + if (node.getDeclaringType() != TypePattern.ANY) { + node.getDeclaringType().accept(this, data); + append('.'); + } + if (node.getKind() == Member.CONSTRUCTOR) { + append("new"); + } else { + node.getName().accept(this, data); + } + if (node.getKind() == Member.METHOD || node.getKind() == Member.CONSTRUCTOR) { + append('('); + node.getParameterTypes().accept(this, data); + append(')'); + } + if (node.getThrowsPattern() != null) { + append(' '); + node.getThrowsPattern().accept(this, data); + } + } + return null; + } + + public Object visit(ThisOrTargetAnnotationPointcut node, Object data) { + append(node.isThis() ? "@this(" : "@target("); + node.getAnnotationTypePattern().accept(this, data); + append(')'); + return null; + } + + public Object visit(ThisOrTargetPointcut node, Object data) { + append(node.isThis() ? "this(" : "target("); + node.getType().accept(this, data); + append(')'); + return null; + } + + // Note: a visitor instance is not thread safe so should not be shared + private boolean inThrowsForbidden = false; + + public Object visit(ThrowsPattern node, Object data) { + if (node == ThrowsPattern.ANY) { + return null; + } + + append("throws "); + node.getRequired().accept(this, data); + if (node.getForbidden().size() > 0) { + // a hack since throws !(A, B) cannot be parsed + try { + inThrowsForbidden = true; + node.getForbidden().accept(this, data); + } finally { + inThrowsForbidden = false; + } + } + return null; + } + + public Object visit(TypePatternList node, Object data) { + if (node.getTypePatterns().length == 0) { + return null; + } + + TypePattern[] typePatterns = node.getTypePatterns(); + for (int i = 0; i < typePatterns.length; i++) { + TypePattern typePattern = typePatterns[i]; + if (i > 0) { + append(", "); + } + if (inThrowsForbidden) { + append('!'); + } + typePattern.accept(this, data); + } + return null; + } + + public Object visit(WildAnnotationTypePattern node, Object data) { + append("@("); + node.getTypePattern().accept(this, data); + append(')'); + return null; + } + + public Object visit(WildTypePattern node, Object data) { + if (node.getAnnotationPattern() != AnnotationTypePattern.ANY) { + append('('); + node.getAnnotationPattern().accept(this, data); + append(' '); + } + NamePattern[] namePatterns = node.getNamePatterns(); + for (int i = 0; i < namePatterns.length; i++) { + if (namePatterns[i] == null) { + append('.');// FIXME mh, error prone, can't we have a nullNamePattern ? + } else { + if (i > 0) { + append('.'); + } + namePatterns[i].accept(this, data); + } + } + if (node.isIncludeSubtypes()) { + append('+'); + } + if (node.isVarArgs()) { + append("..."); + } + if (node.getAnnotationPattern() != AnnotationTypePattern.ANY) { + append(')'); + } + return null; + } + + public Object visit(WithinAnnotationPointcut node, Object data) { + append("@within("); + node.getAnnotationTypePattern().accept(this, data); + append(')'); + return null; + } + + public Object visit(WithinCodeAnnotationPointcut node, Object data) { + append("@withincode("); + node.getAnnotationTypePattern().accept(this, data); + append(')'); + return null; + } + + public Object visit(WithinPointcut node, Object data) { + append("within("); + node.getTypePattern().accept(this, data); + append(')'); + return null; + } + + public Object visit(WithincodePointcut node, Object data) { + append("withincode("); + node.getSignature().accept(this, data); + append(')'); + return null; + } + + public Object visit(Pointcut.MatchesNothingPointcut node, Object data) { + append("");// TODO shouldn't that be a "false" ? + return null; + } + + // -------------- perX + + public Object visit(PerCflow node, Object data) { + append(node); + return null; + } + + public Object visit(PerFromSuper node, Object data) { + append(node); + return null; + } + + public Object visit(PerObject node, Object data) { + append(node); + return null; + } + + public Object visit(PerSingleton node, Object data) { + append(node); + return null; + } + + public Object visit(PerTypeWithin node, Object data) { + append(node); + return null; + } + + // ------------- declare X + + public Object visit(DeclareAnnotation node, Object data) { + append(node); + return null; + } + + public Object visit(DeclareErrorOrWarning node, Object data) { + append(node); + return null; + } + + public Object visit(DeclareParents node, Object data) { + append(node); + return null; + } + + public Object visit(DeclarePrecedence node, Object data) { + append(node); + return null; + } + + public Object visit(DeclareSoft node, Object data) { + append(node); + return null; + } + + // ----------- misc + + public Object visit(ConcreteCflowPointcut node, Object data) { + append(node); + return null; + } + + public Object visit(HandlerPointcut node, Object data) { + append(node); + return null; + } + + public Object visit(IfPointcut node, Object data) { + append(node); + return null; + } + + public Object visit(TypeVariablePattern node, Object data) { + append(node); + return null; + } + + public Object visit(TypeVariablePatternList node, Object data) { + append(node); + return null; + } + + public Object visit(HasMemberTypePattern node, Object data) { + append(node); + return null; + } + + public Object visit(TypeCategoryTypePattern node, Object data) { + append(node); + return null; + } + + public static void check(String s) { + check(Pointcut.fromString(s), false); + } + + public static void check(PatternNode pc, boolean isTypePattern) { + DumpPointcutVisitor v1 = new DumpPointcutVisitor(); + pc.accept(v1, null); + + DumpPointcutVisitor v2 = new DumpPointcutVisitor(); + final PatternNode pc2; + if (isTypePattern) { + pc2 = new PatternParser(v1.get()).parseTypePattern(); + } else { + pc2 = Pointcut.fromString(v1.get()); + } + pc2.accept(v2, null); + + // at second parsing, the String form stay stable when parsed and parsed again + if (!v1.get().equals(v2.get())) { + throw new ParserException("Unstable back parsing for '" + pc + "', got '" + v1.get() + "' and '" + v2.get() + "'", null); + } + } + + public static void main(String args[]) throws Throwable { + String[] s = new String[] { + // "@args(Foo, Goo, *, .., Moo)", + // "execution(* *())", + // "call(* *(int, Integer...))", + // "staticinitialization(@(Foo) @(Boo) @(Goo) Moo)", + "(if(true) && set(int BaseApp.i))" + + }; + for (int i = 0; i < s.length; i++) { + check(s[i]); + } + } + +}
\ No newline at end of file diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/ModifiersPatternTestCase.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/ModifiersPatternTestCase.java new file mode 100644 index 000000000..265ee4b0a --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/ModifiersPatternTestCase.java @@ -0,0 +1,110 @@ +/* ******************************************************************* + * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * PARC initial implementation + * ******************************************************************/ + +package org.aspectj.weaver.patterns; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.lang.reflect.Modifier; + +import org.aspectj.weaver.CompressingDataOutputStream; +import org.aspectj.weaver.VersionedDataInputStream; +import org.aspectj.weaver.World; +import org.aspectj.weaver.reflect.ReflectionWorld; + +public class ModifiersPatternTestCase extends PatternsTestCase { + + public void testMatch() { + int[] publicMatches = new int[] { Modifier.PUBLIC, Modifier.PUBLIC | Modifier.STATIC, + Modifier.PUBLIC | Modifier.STATIC | Modifier.STRICT | Modifier.FINAL, }; + + int[] publicFailures = new int[] { Modifier.PRIVATE, 0, Modifier.STATIC | Modifier.STRICT | Modifier.FINAL, }; + + int[] publicStaticMatches = new int[] { Modifier.PUBLIC | Modifier.STATIC, + Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL | Modifier.STRICT, }; + + int[] publicStaticFailures = new int[] { 0, Modifier.PUBLIC, Modifier.STATIC, }; + + int[] trickMatches = new int[] { Modifier.PRIVATE, Modifier.PRIVATE | Modifier.ABSTRACT, Modifier.PRIVATE | Modifier.FINAL, }; + + int[] trickFailures = new int[] { Modifier.PUBLIC, Modifier.PRIVATE | Modifier.STATIC, Modifier.PRIVATE | Modifier.STRICT, }; + + int[] none = new int[0]; + + checkMatch("", publicMatches, none); + checkMatch("", publicFailures, none); + checkMatch("!public", publicFailures, publicMatches); + checkMatch("public", publicMatches, publicFailures); + checkMatch("public static", none, publicFailures); + checkMatch("public static", publicStaticMatches, publicStaticFailures); + + checkMatch("private !static !strictfp", trickMatches, trickFailures); + checkMatch("private !static !strictfp", none, publicMatches); + checkMatch("private !static !strictfp", none, publicStaticMatches); + } + + private ModifiersPattern makeModifiersPattern(String pattern) { + return new PatternParser(pattern).parseModifiersPattern(); + } + + private void checkMatch(String pattern, int[] shouldMatch, int[] shouldFail) { + ModifiersPattern p = makeModifiersPattern(pattern); + checkMatch(p, shouldMatch, true); + checkMatch(p, shouldFail, false); + } + + private void checkMatch(ModifiersPattern p, int[] matches, boolean shouldMatch) { + for (int i = 0; i < matches.length; i++) { + boolean result = p.matches(matches[i]); + String msg = "matches " + p + " to " + Modifier.toString(matches[i]) + " expected "; + if (shouldMatch) { + assertTrue(msg + shouldMatch, result); + } else { + assertTrue(msg + shouldMatch, !result); + } + } + } + + public void testSerialization() throws IOException { + String[] patterns = new String[] { "", "!public", "public", "public static", "private !static !strictfp", }; + + for (int i = 0, len = patterns.length; i < len; i++) { + checkSerialization(patterns[i]); + } + } + + /** + * Method checkSerialization. + * + * @param string + */ + private void checkSerialization(String string) throws IOException { + ModifiersPattern p = makeModifiersPattern(string); + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + ConstantPoolSimulator cps = new ConstantPoolSimulator(); + CompressingDataOutputStream out = new CompressingDataOutputStream(bo, cps); + p.write(out); + out.close(); + + ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); + VersionedDataInputStream in = new VersionedDataInputStream(bi, cps); + ModifiersPattern newP = ModifiersPattern.read(in); + + assertEquals("write/read", p, newP); + } + + public World getWorld() { + return new ReflectionWorld(true, this.getClass().getClassLoader()); + } + +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/NamePatternParserTestCase.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/NamePatternParserTestCase.java new file mode 100644 index 000000000..fe3b0f2d4 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/NamePatternParserTestCase.java @@ -0,0 +1,72 @@ +/* ******************************************************************* + * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * PARC initial implementation + * ******************************************************************/ + +package org.aspectj.weaver.patterns; + +import junit.framework.TestCase; + +/** + * @author hugunin + * + * To change this generated comment edit the template variable + * "typecomment": Window>Preferences>Java>Templates. To enable and + * disable the creation of type comments go to + * Window>Preferences>Java>Code Generation. + */ +public class NamePatternParserTestCase extends TestCase { + /** + * Constructor for PatternTestCase. + * + * @param name + */ + public NamePatternParserTestCase(String name) { + super(name); + } + + public void testMatch() { + checkMatch(NamePatternTestCase.matchAll); + checkMatch(NamePatternTestCase.match1); + checkMatch(NamePatternTestCase.match2); + + NamePattern p = new PatternParser("abc *").parseNamePattern(); + assertEquals(new NamePattern("abc"), p); + } + + public void testTypePattern() { + TypePattern tp = null; + tp = new PatternParser(" @Ann * ").parseTypePattern(); + assertEquals(1, tp.start); + assertEquals(6, tp.end); + tp = new PatternParser(" (@Ann *) ").parseTypePattern(); + assertEquals(2, tp.start); + assertEquals(9, tp.end); + } + + /** + * Method checkMatch. + * + * @param string + * @param matchAll + * @param b + */ + private void checkMatch(String[] patterns) { + for (int i = 0, len = patterns.length; i < len; i++) { + String pattern = patterns[i]; + ITokenSource tokenSource = BasicTokenSource.makeTokenSource( + pattern, null); + NamePattern p1 = new PatternParser(tokenSource).parseNamePattern(); + NamePattern p2 = new NamePattern(pattern); + assertEquals("pattern: " + pattern, p2, p1); + assertEquals("eof", IToken.EOF, tokenSource.next()); + } + } +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/NamePatternTestCase.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/NamePatternTestCase.java new file mode 100644 index 000000000..e1876cc3b --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/NamePatternTestCase.java @@ -0,0 +1,105 @@ +/* ******************************************************************* + * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * PARC initial implementation + * ******************************************************************/ + +package org.aspectj.weaver.patterns; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import junit.framework.TestCase; + +import org.aspectj.weaver.CompressingDataOutputStream; +import org.aspectj.weaver.VersionedDataInputStream; + +/** + * @author hugunin + * + * To change this generated comment edit the template variable "typecomment": Window>Preferences>Java>Templates. To enable + * and disable the creation of type comments go to Window>Preferences>Java>Code Generation. + */ +public class NamePatternTestCase extends TestCase { + static String[] matchAll = new String[] { "*****", "*" }; + + static String[] match1 = new String[] { "abcde", "abc*", "abcd*", "abcde*", "*e", "*cde", "*abcde", "a*e", "ab*e", "abc*de", + "*a*b*c*d*e*", "a*c*e", "a***bcde", "*d*", }; + + static String[] match2 = new String[] { "abababab", "aba*", "abab*", "abababab*", "*b", "*ab", "*ababab", "*abababab", "a*b", + "ab*b", "abab*abab", "*a*b*a*b*a*b*a*b*", "a*****b", "a**b", "ab*b*b", }; + + /** + * Constructor for PatternTestCase. + * + * @param name + */ + public NamePatternTestCase(String name) { + super(name); + } + + public void testMatch() { + checkMatch("abcde", matchAll, true); + checkMatch("abcde", match1, true); + checkMatch("abcde", match2, false); + + checkMatch("abababab", matchAll, true); + checkMatch("abababab", match1, false); + checkMatch("abababab", match2, true); + + } + + /** + * Method checkMatch. + * + * @param string + * @param matchAll + * @param b + */ + private void checkMatch(String string, String[] patterns, boolean shouldMatch) { + for (int i = 0, len = patterns.length; i < len; i++) { + NamePattern p = new NamePattern(patterns[i]); + checkMatch(string, p, shouldMatch); + } + } + + private void checkMatch(String string, NamePattern p, boolean shouldMatch) { + String msg = "matching " + string + " to " + p; + assertEquals(msg, shouldMatch, p.matches(string)); + } + + public void testSerialization() throws IOException { + checkSerialization(matchAll); + checkSerialization(match1); + checkSerialization(match2); + } + + private void checkSerialization(String[] patterns) throws IOException { + for (int i = 0, len = patterns.length; i < len; i++) { + NamePattern p = new NamePattern(patterns[i]); + checkSerialization(p); + } + } + + private void checkSerialization(NamePattern p) throws IOException { + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + ConstantPoolSimulator cps = new ConstantPoolSimulator(); + CompressingDataOutputStream out = new CompressingDataOutputStream(bo, cps); + p.write(out); + out.close(); + + ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); + VersionedDataInputStream in = new VersionedDataInputStream(bi, cps); + NamePattern newP = NamePattern.read(in); + + assertEquals("write/read", p, newP); + } + +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/ParserTestCase.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/ParserTestCase.java new file mode 100644 index 000000000..7ffad81d5 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/ParserTestCase.java @@ -0,0 +1,788 @@ +/* ******************************************************************* + * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * PARC initial implementation + * ******************************************************************/ + +package org.aspectj.weaver.patterns; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.aspectj.weaver.Shadow; +import org.aspectj.weaver.UnresolvedType; +import org.aspectj.weaver.World; +import org.aspectj.weaver.reflect.ReflectionWorld; + +/** + * @author hugunin + * + * To change this generated comment edit the template variable "typecomment": Window>Preferences>Java>Templates. To enable + * and disable the creation of type comments go to Window>Preferences>Java>Code Generation. + */ +public class ParserTestCase extends PatternsTestCase { + + public World getWorld() { + return new ReflectionWorld(true, getClassLoaderForFile(getTestDataJar())); + } + + public void testNamePatterns() { + + // checkNoMatch("abc *", "abcd"); + // checkNoMatch("* d", "abcd"); + } + + public void testParse() { + PatternParser parser = new PatternParser("execution(void Hello.*(..))"); + KindedPointcut p = (KindedPointcut) parser.parsePointcut(); + // System.out.println(p); + assertEquals(p.kind, Shadow.MethodExecution); + assertTrue(p.getSignature().getName().matches("foobar")); + + try { + new PatternParser("initialization(void foo())").parsePointcut(); + fail("should have been a parse error"); + } catch (ParserException pe) { + // good + } + } + + // public void testParseExecutionWithAnnotation() { + // PatternParser parser = new PatternParser("execution(@SimpleAnnotation void Hello.*(..))"); + // KindedPointcut p = (KindedPointcut) parser.parsePointcut(); + // // XXX - needs finishing... + // p.resolveBindings(makeSimpleScope(), new Bindings(3)); + // assertEquals("execution(@p.SimpleAnnotation void Hello.*(..))", p.toString()); + // assertEquals(p.kind, Shadow.MethodExecution); + // assertTrue(p.getSignature().getName().matches("foobar")); + // } + + // note... toString on a pointcut is a very quick and easy way to test a successful parse + public void testParseExecutionWithMultipleAnnotations() { + PatternParser parser = new PatternParser("execution(@SimpleAnnotation (@Foo Integer) (@Goo Hello).*(..))"); + KindedPointcut p = (KindedPointcut) parser.parsePointcut(); + assertEquals("execution(@(SimpleAnnotation) (@(Foo) Integer) (@(Goo) Hello).*(..))", p.toString()); + } + + public void testParseCallWithMultipleAnnotations() { + PatternParser parser = new PatternParser("call(@SimpleAnnotation (@Foo Integer) (@Goo Hello).*(..))"); + KindedPointcut p = (KindedPointcut) parser.parsePointcut(); + assertEquals("call(@(SimpleAnnotation) (@(Foo) Integer) (@(Goo) Hello).*(..))", p.toString()); + } + + public void testParseGetWithAnnotations() { + PatternParser parser = new PatternParser("get(@Foo (@SimpleAnnotation ReturnType) (@Foo @Goo Hello).*)"); + KindedPointcut p = (KindedPointcut) parser.parsePointcut(); + assertEquals("get(@(Foo) (@(SimpleAnnotation) ReturnType) (@(Foo) @(Goo) Hello).*)", p.toString()); + } + + public void testParseBadGetWithAnnotations() { + PatternParser parser = new PatternParser("get(@Foo (@Foo @Goo Hello).*)"); + try { + // KindedPointcut p = (KindedPointcut) + parser.parsePointcut(); + fail("Expected parser exception"); + } catch (ParserException pEx) { + assertEquals("name pattern", pEx.getMessage()); + } + } + + public void testParseGetWithAndAggregationAnnotations() { + PatternParser parser = new PatternParser("get(@Foo @SimpleAnnotation ReturnType (@Foo @Goo Hello).*)"); + KindedPointcut p = (KindedPointcut) parser.parsePointcut(); + assertEquals("get(@(Foo) @(SimpleAnnotation) ReturnType (@(Foo) @(Goo) Hello).*)", p.toString()); + } + + public void testParseSetWithAnnotations() { + PatternParser parser = new PatternParser("set(@Foo (@SimpleAnnotation ReturnType) (@Foo @Goo Hello).*)"); + KindedPointcut p = (KindedPointcut) parser.parsePointcut(); + assertEquals("set(@(Foo) (@(SimpleAnnotation) ReturnType) (@(Foo) @(Goo) Hello).*)", p.toString()); + } + + public void testParseHandlerWithAnnotations() { + PatternParser parser = new PatternParser("handler(@Critical Exception+)"); + Pointcut p = parser.parsePointcut(); + assertEquals("handler((@(Critical) Exception+))", p.toString()); + } + + public void testParseInitializationWithAnnotations() { + PatternParser parser = new PatternParser("initialization(@Foo (@Goo Hello).new(@Foo Integer))"); + Pointcut p = parser.parsePointcut(); + assertEquals("initialization(@(Foo) (@(Goo) Hello).new((@(Foo) Integer)))", p.toString()); + + } + + public void testParsePreInitializationWithAnnotations() { + PatternParser parser = new PatternParser("preinitialization(@Foo (@Goo Hello).new(@Foo Integer))"); + Pointcut p = parser.parsePointcut(); + assertEquals("preinitialization(@(Foo) (@(Goo) Hello).new((@(Foo) Integer)))", p.toString()); + } + + public void testStaticInitializationWithAnnotations() { + PatternParser parser = new PatternParser("staticinitialization(@Foo @Boo @Goo Moo)"); + Pointcut p = parser.parsePointcut(); + assertEquals("staticinitialization((@(Foo) @(Boo) @(Goo) Moo).<clinit>())", p.toString()); + } + + public void testWithinWithAnnotations() { + PatternParser parser = new PatternParser("within(@Foo *)"); + Pointcut p = parser.parsePointcut(); + assertEquals("within((@(Foo) *))", p.toString()); + } + + public void testWithinCodeWithAnnotations() { + PatternParser parser = new PatternParser("withincode(@Foo * *.*(..))"); + Pointcut p = parser.parsePointcut(); + assertEquals("withincode(@(Foo) * *.*(..))", p.toString()); + } + + public void testAtAnnotation() { + PatternParser parser = new PatternParser("@annotation(Foo)"); + AnnotationPointcut p = (AnnotationPointcut) parser.parsePointcut(); + assertEquals("@annotation(Foo)", p.toString()); + } + + public void testBadAtAnnotation() { + PatternParser parser = new PatternParser("@annotation(!Foo)"); + try { + // Pointcut p = + parser.parsePointcut(); + fail("Expected parser exception"); + } catch (ParserException pEx) { + assertEquals("identifier", pEx.getMessage()); + } + } + + public void testAtAnnotationWithBinding() { + PatternParser parser = new PatternParser("@annotation(foo)"); + AnnotationPointcut p = (AnnotationPointcut) parser.parsePointcut(); + assertEquals("@annotation(foo)", p.toString()); + } + + public void testDoubleAtAnnotation() { + PatternParser parser = new PatternParser("@annotation(Foo Goo)"); + try { + // Pointcut p = + parser.parsePointcut(); + fail("Expected parser exception"); + } catch (ParserException pEx) { + assertEquals(")", pEx.getMessage()); + } + } + + public void testAtWithin() { + PatternParser parser = new PatternParser("@within(foo)"); + WithinAnnotationPointcut p = (WithinAnnotationPointcut) parser.parsePointcut(); + assertEquals("@within(foo)", p.toString()); + parser = new PatternParser("@within(Foo))"); + p = (WithinAnnotationPointcut) parser.parsePointcut(); + assertEquals("@within(Foo)", p.toString()); + } + + public void testAtWithinCode() { + PatternParser parser = new PatternParser("@withincode(foo)"); + WithinCodeAnnotationPointcut p = (WithinCodeAnnotationPointcut) parser.parsePointcut(); + assertEquals("@withincode(foo)", p.toString()); + parser = new PatternParser("@withincode(Foo))"); + p = (WithinCodeAnnotationPointcut) parser.parsePointcut(); + assertEquals("@withincode(Foo)", p.toString()); + } + + public void testAtThis() { + PatternParser parser = new PatternParser("@this(foo)"); + ThisOrTargetAnnotationPointcut p = (ThisOrTargetAnnotationPointcut) parser.parsePointcut(); + assertEquals("@this(foo)", p.toString()); + assertTrue("isThis", p.isThis()); + parser = new PatternParser("@this(Foo))"); + p = (ThisOrTargetAnnotationPointcut) parser.parsePointcut(); + assertTrue("isThis", p.isThis()); + assertEquals("@this(Foo)", p.toString()); + } + + public void testAtTarget() { + PatternParser parser = new PatternParser("@target(foo)"); + ThisOrTargetAnnotationPointcut p = (ThisOrTargetAnnotationPointcut) parser.parsePointcut(); + assertEquals("@target(foo)", p.toString()); + assertTrue("isTarget", !p.isThis()); + parser = new PatternParser("@target(Foo))"); + p = (ThisOrTargetAnnotationPointcut) parser.parsePointcut(); + assertTrue("isTarget", !p.isThis()); + assertEquals("@target(Foo)", p.toString()); + } + + public void testAtArgs() { + PatternParser parser = new PatternParser("@args(Foo,Goo,*,..,Moo)"); + Pointcut p = parser.parsePointcut(); + assertEquals("@args(Foo, Goo, ANY, .., Moo)", p.toString()); + } + + public void testParseSimpleTypeVariable() { + PatternParser parser = new PatternParser("T"); + TypeVariablePattern tv = parser.parseTypeVariable(); + TypeVariablePattern expected = new TypeVariablePattern("T"); + assertEquals("Expected simple type variable T", expected, tv); + } + + public void testParseExtendingTypeVariable() { + PatternParser parser = new PatternParser("T extends Number"); + TypeVariablePattern tv = parser.parseTypeVariable(); + TypeVariablePattern expected = new TypeVariablePattern("T", new PatternParser("Number").parseTypePattern()); + assertEquals("Expected type variable T extends Number", expected, tv); + } + + public void testParseExtendingTypeVariableWithPattern() { + PatternParser parser = new PatternParser("T extends Number+"); + TypeVariablePattern tv = parser.parseTypeVariable(); + TypeVariablePattern expected = new TypeVariablePattern("T", new PatternParser("Number+").parseTypePattern()); + assertEquals("Expected type variable T extends Number+", expected, tv); + } + + public void testParseExtendingTypeVariableWithInterface() { + PatternParser parser = new PatternParser("T extends Number & Comparable"); + TypeVariablePattern tv = parser.parseTypeVariable(); + TypeVariablePattern expected = new TypeVariablePattern("T", new PatternParser("Number").parseTypePattern(), + new TypePattern[] { new PatternParser("Comparable").parseTypePattern() }, null); + assertEquals("Expected type variable T extends Number", expected, tv); + } + + public void testParseExtendingTypeVariableWithInterfaceList() { + PatternParser parser = new PatternParser("T extends Number & Comparable & Cloneable"); + TypeVariablePattern tv = parser.parseTypeVariable(); + TypeVariablePattern expected = new TypeVariablePattern("T", new PatternParser("Number").parseTypePattern(), + new TypePattern[] { new PatternParser("Comparable").parseTypePattern(), + new PatternParser("Cloneable").parseTypePattern() }, null); + assertEquals("Expected type variable T extends Number", expected, tv); + } + + public void testParseTypeParameterList() { + PatternParser parser = new PatternParser("<T>"); + TypeVariablePatternList list = parser.maybeParseTypeVariableList(); + TypeVariablePattern[] patterns = list.getTypeVariablePatterns(); + TypeVariablePattern expected = new TypeVariablePattern("T"); + assertEquals("Expected simple type variable T", expected, patterns[0]); + assertEquals("One pattern in list", 1, patterns.length); + } + + public void testParseTypeParameterListWithSeveralTypeParameters() { + PatternParser parser = new PatternParser("<T,S extends Number, R>"); + TypeVariablePatternList list = parser.maybeParseTypeVariableList(); + TypeVariablePattern[] patterns = list.getTypeVariablePatterns(); + TypeVariablePattern expected0 = new TypeVariablePattern("T"); + assertEquals("Expected simple type variable T", expected0, patterns[0]); + TypeVariablePattern expected1 = new TypeVariablePattern("S", new PatternParser("Number").parseTypePattern()); + assertEquals("Expected type variable S extends Number", expected1, patterns[1]); + TypeVariablePattern expected2 = new TypeVariablePattern("R"); + assertEquals("Expected simple type variable R", expected2, patterns[2]); + + assertEquals("3 patterns in list", 3, patterns.length); + } + + public void testParseAllowedSuperInTypeVariable() { + PatternParser parser = new PatternParser("T super Number+"); + TypeVariablePattern tv = parser.parseTypeVariable(); + TypeVariablePattern expected = new TypeVariablePattern("T", new ExactTypePattern(UnresolvedType.OBJECT, false, false), + null, new PatternParser("Number+").parseTypePattern()); + assertEquals("Expected type variable T super Number+", expected, tv); + } + + public void testParseAnythingTypeVariable() { + PatternParser parser = new PatternParser("?"); + WildTypePattern tp = (WildTypePattern) parser.parseTypePattern(true, false); + assertEquals("Expected type variable ?", "?", tp.maybeGetSimpleName()); + } + + public void testParseAnythingExtendsTypeVariable() { + PatternParser parser = new PatternParser("? extends Number"); + WildTypePattern tp = (WildTypePattern) parser.parseTypePattern(true, false); + assertEquals("Expected type variable ?", "?", tp.maybeGetSimpleName()); + assertEquals("upper Bound of Number", new PatternParser("Number").parseTypePattern(), tp.getUpperBound()); + } + + public void testParseAnythingSuperTypeVariable() { + PatternParser parser = new PatternParser("? super Number+"); + WildTypePattern tp = (WildTypePattern) parser.parseTypePattern(true, false); + assertEquals("Expected type variable ?", "?", tp.maybeGetSimpleName()); + assertEquals("lower Bound of Number+", new PatternParser("Number+").parseTypePattern(), tp.getLowerBound()); + } + + public void testParseDeclareParentsWithTypeParameterList() { + try { + PatternParser parser = new PatternParser("declare parents<T> : Foo<T> implements IveGoneMad"); + // DeclareParents decp = (DeclareParents) + parser.parseDeclare(); + // String[] tvp = decp.getTypeParameterNames(); + // assertEquals("one type parameter",1,tvp.length); + // assertEquals("expecting T","T",tvp[0]); + fail("Expecting parse exception"); + } catch (ParserException pEx) { + assertEquals(":", pEx.getMessage()); + } + } + + public void testParameterizedTypePatternsAny() { + try { + PatternParser parser = new PatternParser("*<T,S extends Number>"); + // WildTypePattern wtp = (WildTypePattern) + parser.parseTypePattern(false, false); + // TypePatternList tvs = wtp.getTypeParameters(); + // assertEquals("2 type parameters",2,tvs.getTypePatterns().length); + // assertEquals("T",new PatternParser("T").parseTypePattern(),tvs.getTypePatterns()[0]); + // assertEquals("S extends Number",new + // PatternParser("S extends Number").parseTypePattern(false),tvs.getTypePatterns()[1]); + fail("Expecting parse exception"); + } catch (ParserException pEx) { + assertEquals(">", pEx.getMessage()); + } + } + + public void testParameterizedTypePatternsSimple() { + PatternParser parser = new PatternParser("List<String>"); + WildTypePattern wtp = (WildTypePattern) parser.parseTypePattern(); + TypePatternList tvs = wtp.getTypeParameters(); + assertEquals("1 type parameter", 1, tvs.getTypePatterns().length); + assertEquals("String", new PatternParser("String").parseTypePattern(), tvs.getTypePatterns()[0]); + assertEquals("List", wtp.getNamePatterns()[0].toString()); + } + + public void testNestedParameterizedTypePatterns() { + PatternParser parser = new PatternParser("List<List<List<String>>>"); + WildTypePattern wtp = (WildTypePattern) parser.parseTypePattern(); + TypePatternList typeParameters = wtp.getTypeParameters(); + WildTypePattern expected = (WildTypePattern) typeParameters.getTypePatterns()[0]; + assertEquals("expecting a List", "List", expected.maybeGetSimpleName()); + typeParameters = expected.getTypeParameters(); + expected = (WildTypePattern) typeParameters.getTypePatterns()[0]; + assertEquals("expecting a List", "List", expected.maybeGetSimpleName()); + typeParameters = expected.getTypeParameters(); + expected = (WildTypePattern) typeParameters.getTypePatterns()[0]; + assertEquals("expecting a String", "String", expected.maybeGetSimpleName()); + } + + public void testSimpleTypeVariableList() { + PatternParser parser = new PatternParser("<T,S,V>"); + String[] tl = parser.maybeParseSimpleTypeVariableList(); + assertEquals("3 patterns", 3, tl.length); + assertEquals("T", tl[0]); + assertEquals("S", tl[1]); + assertEquals("V", tl[2]); + } + + public void testSimpleTypeVariableListError() { + PatternParser parser = new PatternParser("<T extends Number>"); + try { + // String[] tl = + parser.maybeParseSimpleTypeVariableList(); + fail(); + } catch (ParserException ex) { + assertEquals("Expecting ',' or '>'", "',' or '>'", ex.getMessage()); + } + } + + // test cases for pointcuts involving type variable specification. + public void testParseCallPCDWithTypeVariables() { + PatternParser parser = new PatternParser("call<T>(* Foo<T>.*(T))"); + try { + parser.parsePointcut(); + // String[] tvps = pc.getTypeVariablesInScope(); + // assertEquals("1 type variable",1,tvps.length); + // assertEquals("T",tvps[0]); + fail("should have been a parse error"); + } catch (ParserException pEx) { + assertEquals("(", pEx.getMessage()); + } + } + + public void testParseCallPCDWithIllegalBounds() { + PatternParser parser = new PatternParser("call<T extends Number>(* Foo<T>.*(T))"); + try { + parser.parsePointcut(); + fail("Expecting parse exception"); + } catch (ParserException pEx) { + assertEquals("(", pEx.getMessage()); + } + } + + public void testNoTypeVarsForHandler() { + PatternParser parser = new PatternParser("handler<T>(Exception<T>)"); + try { + parser.parsePointcut(); + fail("Expecting parse exception"); + } catch (ParserException pEx) { + assertEquals("(", pEx.getMessage()); + } + } + + public void testNoTypeVarsForThis() { + PatternParser parser = new PatternParser("this<T>(Exception<T>)"); + try { + parser.parsePointcut(); + fail("Expecting parse exception"); + } catch (ParserException pEx) { + assertEquals("(", pEx.getMessage()); + } + } + + public void testNoTypeVarsForTarget() { + PatternParser parser = new PatternParser("target<T>(Exception<T>)"); + try { + parser.parsePointcut(); + fail("Expecting parse exception"); + } catch (ParserException pEx) { + assertEquals("(", pEx.getMessage()); + } + } + + public void testNoTypeVarsForArgs() { + PatternParser parser = new PatternParser("args<T>(Exception<T>)"); + try { + parser.parsePointcut(); + fail("Expecting parse exception"); + } catch (ParserException pEx) { + assertEquals("(", pEx.getMessage()); + } + } + + public void testNoTypeVarsForIf() { + PatternParser parser = new PatternParser("if<T>(true)"); + try { + parser.parsePointcut(); + fail("Expecting parse exception"); + } catch (ParserException pEx) { + assertEquals("(", pEx.getMessage()); + } + } + + public void testNoTypeVarsForCflow() { + PatternParser parser = new PatternParser("cflow<T>(call(* *(..)))"); + try { + parser.parsePointcut(); + fail("Expecting parse exception"); + } catch (ParserException pEx) { + assertEquals("(", pEx.getMessage()); + } + } + + public void testNoTypeVarsForCflowbelow() { + PatternParser parser = new PatternParser("cflowbelow<T>(call(* *(..)))"); + try { + parser.parsePointcut(); + fail("Expecting parse exception"); + } catch (ParserException pEx) { + assertEquals("(", pEx.getMessage()); + } + } + + public void testNoTypeVarsForAtWithin() { + PatternParser parser = new PatternParser("@within<T>(Foo<T>)"); + try { + parser.parsePointcut(); + fail("Expecting parse exception"); + } catch (ParserException pEx) { + assertEquals("(", pEx.getMessage()); + } + } + + public void testNoTypeVarsForAtAnnotation() { + PatternParser parser = new PatternParser("@annotation<T>(Foo<T>)"); + try { + parser.parsePointcut(); + fail("Expecting parse exception"); + } catch (ParserException pEx) { + assertEquals("(", pEx.getMessage()); + } + } + + public void testNoTypeVarsForAtWithinCode() { + PatternParser parser = new PatternParser("@withincode<T>(* Foo<T>.*(..))"); + try { + parser.parsePointcut(); + fail("Expecting parse exception"); + } catch (ParserException pEx) { + assertEquals("(", pEx.getMessage()); + } + } + + public void testNoTypeVarsForAtThis() { + PatternParser parser = new PatternParser("@this<T>(Exception<T>)"); + try { + parser.parsePointcut(); + fail("Expecting parse exception"); + } catch (ParserException pEx) { + assertEquals("(", pEx.getMessage()); + } + } + + public void testNoTypeVarsForAtTarget() { + PatternParser parser = new PatternParser("@target<T>(Exception<T>)"); + try { + parser.parsePointcut(); + fail("Expecting parse exception"); + } catch (ParserException pEx) { + assertEquals("(", pEx.getMessage()); + } + } + + public void testNoTypeVarsForAtArgs() { + PatternParser parser = new PatternParser("@args<T>(Exception<T>)"); + try { + parser.parsePointcut(); + fail("Expecting parse exception"); + } catch (ParserException pEx) { + assertEquals("(", pEx.getMessage()); + } + } + + public void testExecutionWithTypeVariables() { + PatternParser parser = new PatternParser("execution<T>(T Bar<T>.doSomething())"); + try { + // Pointcut pc = + parser.parsePointcut(); + // String[] tvs = pc.getTypeVariablesInScope(); + // assertEquals("1 type pattern",1,tvs.length); + // assertEquals("T",tvs[0]); + fail("should have been a parse error"); + } catch (ParserException pEx) { + assertEquals("(", pEx.getMessage()); + } + } + + public void testInitializationWithTypeVariables() { + PatternParser parser = new PatternParser("initialization<T>(Bar<T>.new())"); + try { + // Pointcut pc = + parser.parsePointcut(); + // String[] tvs = pc.getTypeVariablesInScope(); + // assertEquals("1 type pattern",1,tvs.length); + // assertEquals("T",tvs[0]); + fail("should have been a parse error"); + } catch (ParserException pEx) { + assertEquals("(", pEx.getMessage()); + } + } + + public void testPreInitializationWithTypeVariables() { + PatternParser parser = new PatternParser("preinitialization<T>(Bar<T>.new())"); + try { + // Pointcut pc = + parser.parsePointcut(); + // String[] tvs = pc.getTypeVariablesInScope(); + // assertEquals("1 type pattern",1,tvs.length); + // assertEquals("T",tvs[0]); + fail("should have been a parse error"); + } catch (ParserException pEx) { + assertEquals("(", pEx.getMessage()); + } + } + + public void testStaticInitializationWithTypeVariables() { + PatternParser parser = new PatternParser("staticinitialization<T>(Bar<T>)"); + try { + parser.parsePointcut(); + // String[] tvs = pc.getTypeVariablesInScope(); + // assertEquals("1 type pattern",1,tvs.length); + // assertEquals("T",tvs[0]); + fail("should have been a parse error"); + } catch (ParserException pEx) { + assertEquals("(", pEx.getMessage()); + } + } + + public void testWithinWithTypeVariables() { + PatternParser parser = new PatternParser("within<T>(Bar<T>)"); + try { + parser.parsePointcut(); + // String[] tvs = pc.getTypeVariablesInScope(); + // assertEquals("1 type pattern",1,tvs.length); + // assertEquals("T",tvs[0]); + fail("should have been a parse error"); + } catch (ParserException pEx) { + assertEquals("(", pEx.getMessage()); + } + } + + public void testTypeParamList() { + PatternParser parser = new PatternParser("Bar<T,S extends T, R extends S>"); + try { + parser.parseTypePattern(false, false); + // TypePattern[] tps = tp.getTypeParameters().getTypePatterns(); + // assertEquals("3 type patterns",3,tps.length); + // assertEquals("T",tps[0].toString()); + // assertEquals("S",tps[1].toString()); + // assertEquals("R",tps[2].toString()); + fail("should have been a parse error"); + } catch (ParserException pEx) { + assertEquals(">", pEx.getMessage()); + } + } + + public void testWithinCodeWithTypeVariables() { + PatternParser parser = new PatternParser("withincode<T,S,R>(Bar<T,S extends T, R extends S>.new())"); + try { + parser.parsePointcut(); + // String[] tvs = pc.getTypeVariablesInScope(); + // assertEquals("3 type patterns",3,tvs.length); + // assertEquals("T",tvs[0]); + // assertEquals("S",tvs[1]); + // assertEquals("R",tvs[2]); + fail("should have been a parse error"); + } catch (ParserException pEx) { + assertEquals("(", pEx.getMessage()); + } + } + + public void testCallWithTypeVariables() { + PatternParser parser = new PatternParser("call<T>(* Bar<T>.*(..))"); + try { + // Pointcut pc = + parser.parsePointcut(); + // String[] tvs = pc.getTypeVariablesInScope(); + // assertEquals("1 type pattern",1,tvs.length); + // assertEquals("T",tvs[0]); + fail("should have been a parse error"); + } catch (ParserException pEx) { + assertEquals("(", pEx.getMessage()); + } + } + + public void testGetWithTypeVariables() { + PatternParser parser = new PatternParser("get<T>(* Bar<T>.*)"); + try { + // Pointcut pc = + parser.parsePointcut(); + // String[] tvs = pc.getTypeVariablesInScope(); + // assertEquals("1 type pattern",1,tvs.length); + // assertEquals("T",tvs[0]); + fail("should have been a parse error"); + } catch (ParserException pEx) { + assertEquals("(", pEx.getMessage()); + } + } + + public void testSetWithTypeVariables() { + PatternParser parser = new PatternParser("set<T>(* Bar<T>.*)"); + try { + // Pointcut pc = + parser.parsePointcut(); + // String[] tvs = pc.getTypeVariablesInScope(); + // assertEquals("1 type pattern",1,tvs.length); + // assertEquals("T",tvs[0]); + fail("should have been a parse error"); + } catch (ParserException pEx) { + assertEquals("(", pEx.getMessage()); + } + } + + public void testIntAnnotationVal() { + PatternParser parser = new PatternParser("execution(@ComplexAnnotation(ival=5) * *(..))"); + Pointcut pc = parser.parsePointcut(); + assertEquals("Expected annotation value not found", "ival=5", getValueString(pc)); + } + + private String getValueString(Pointcut pc) { + if (!(pc instanceof KindedPointcut)) { + fail("Expected KindedPointcut but was " + pc.getClass()); + } + KindedPointcut kpc = (KindedPointcut) pc; + AnnotationTypePattern atp = kpc.getSignature().getAnnotationPattern(); + if (!(atp instanceof WildAnnotationTypePattern)) { + fail("Expected WildAnnotationTypePattern but was " + atp.getClass()); + } + WildAnnotationTypePattern watp = (WildAnnotationTypePattern) atp; + Map<String,String> m = watp.annotationValues; + Set<String> keys = m.keySet(); + List<String> orderedKeys = new ArrayList<String>(); + orderedKeys.addAll(keys); + Collections.sort(orderedKeys); + StringBuffer sb = new StringBuffer(); + for (Iterator<String> iterator = orderedKeys.iterator(); iterator.hasNext();) { + String object = (String) iterator.next(); + sb.append(object).append("=").append(m.get(object)); + if (iterator.hasNext()) { + sb.append(","); + } + } + return sb.toString(); + } + + public void testByteAnnotationVal() { + PatternParser parser = new PatternParser("execution(@ComplexAnnotation(bval=5) * *(..))"); + Pointcut pc = parser.parsePointcut(); + assertEquals("Expected annotation value not found", "bval=5", getValueString(pc)); + } + + public void testCharAnnotationVal() { + PatternParser parser = new PatternParser("execution(@ComplexAnnotation(cval='5') * *(..))"); + Pointcut pc = parser.parsePointcut(); + assertEquals("Expected annotation value not found", "cval='5'", getValueString(pc)); + } + + public void testLongAnnotationVal() { + PatternParser parser = new PatternParser("execution(@ComplexAnnotation(jval=123123) * *(..))"); + Pointcut pc = parser.parsePointcut(); + assertEquals("Expected annotation value not found", "jval=123123", getValueString(pc)); + } + + public void testDoubleAnnotationVal() { + PatternParser parser = new PatternParser("execution(@ComplexAnnotation(dval=123.3) * *(..))"); + Pointcut pc = parser.parsePointcut(); + assertEquals("Expected annotation value not found", "dval=123.3", getValueString(pc)); + } + + public void testBooleanAnnotationVal() { + PatternParser parser = new PatternParser("execution(@ComplexAnnotation(zval=true) * *(..))"); + Pointcut pc = parser.parsePointcut(); + assertEquals("Expected annotation value not found", "zval=true", getValueString(pc)); + } + + public void testShortAnnotationVal() { + PatternParser parser = new PatternParser("execution(@ComplexAnnotation(sval=43) * *(..))"); + Pointcut pc = parser.parsePointcut(); + assertEquals("Expected annotation value not found", "sval=43", getValueString(pc)); + } + + public void testEnumAnnotationVal() { + PatternParser parser = new PatternParser("execution(@ComplexAnnotation(enumval=Color.GREEN) * *(..))"); + Pointcut pc = parser.parsePointcut(); + assertEquals("Expected annotation value not found", "enumval=Color.GREEN", getValueString(pc)); + } + + public void testStringAnnotationVal() { + PatternParser parser = new PatternParser("execution(@ComplexAnnotation(strval=\"abc\") * *(..))"); + Pointcut pc = parser.parsePointcut(); + // notice quotes stripped... + assertEquals("Expected annotation value not found", "strval=abc", getValueString(pc)); + } + + public void testClassAnnotationVal() { + PatternParser parser = new PatternParser("execution(@ComplexAnnotation(classval=String.class) * *(..))"); + Pointcut pc = parser.parsePointcut(); + assertEquals("Expected annotation value not found", "classval=String.class", getValueString(pc)); + } + + // failing as {1 is treated as a single token and so we don't realise the , is within the curlies + // public void testArrayAnnotationVal() { + // PatternParser parser = new PatternParser("execution(@ComplexAnnotation(arrayval={1,2,3}) * *(..))"); + // Pointcut pc = parser.parsePointcut(); + // assertEquals("Expected annotation value not found","arrayval={1,2,3}",getValueString(pc)); + // } + + // --- + + public TestScope makeSimpleScope() { + world.setBehaveInJava5Way(true); + TestScope s = new TestScope(new String[] { "int", "java.lang.String" }, new String[] { "a", "b" }, world); + s.setImportedPrefixes(new String[] { "p." }); + return s; + } + +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/PatternsTestCase.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/PatternsTestCase.java new file mode 100644 index 000000000..62a3c0566 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/PatternsTestCase.java @@ -0,0 +1,35 @@ +package org.aspectj.weaver.patterns; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; + +import junit.framework.TestCase; + +import org.aspectj.weaver.World; + +public abstract class PatternsTestCase extends TestCase { + + protected World world; + + public void setUp() throws Exception { + super.setUp(); + world = getWorld(); + } + + protected File getTestDataJar() { + return new File("../weaver/testdata/testcode.jar"); + } + + public URLClassLoader getClassLoaderForFile(File f) { + try { + URLClassLoader ucl = new URLClassLoader(new URL[] { f.toURL() }, this.getClass().getClassLoader()); + return ucl; + } catch (MalformedURLException mue) { + throw new RuntimeException(mue); + } + } + + public abstract World getWorld(); +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/PatternsTests.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/PatternsTests.java new file mode 100644 index 000000000..afd75eab3 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/PatternsTests.java @@ -0,0 +1,50 @@ +/* ******************************************************************* + * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * PARC initial implementation + * ******************************************************************/ + +package org.aspectj.weaver.patterns; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +public class PatternsTests extends TestCase { + + public static Test suite() { + TestSuite suite = new TestSuite(PatternsTests.class.getName()); + // $JUnit-BEGIN$ + suite.addTestSuite(AndOrNotTestCase.class); + suite.addTestSuite(BindingTestCase.class); + suite.addTestSuite(DeclareErrorOrWarningTestCase.class); + suite.addTestSuite(ModifiersPatternTestCase.class); + suite.addTestSuite(NamePatternParserTestCase.class); + suite.addTestSuite(NamePatternTestCase.class); + suite.addTestSuite(ParserTestCase.class); + suite.addTestSuite(SignaturePatternTestCase.class); + suite.addTestSuite(ThisOrTargetTestCase.class); + suite.addTestSuite(TypePatternListTestCase.class); + suite.addTestSuite(TypePatternTestCase.class); + suite.addTestSuite(SimpleScopeTests.class); + suite.addTestSuite(WithinTestCase.class); + suite.addTestSuite(ArgsTestCase.class); + // suite.addTestSuite(AnnotationPatternTestCase.class); + // suite.addTestSuite(AnnotationPatternMatchingTestCase.class); + suite.addTestSuite(PointcutRewriterTest.class); + suite.addTestSuite(VisitorTestCase.class); + // $JUnit-END$ + return suite; + } + + public PatternsTests(String name) { + super(name); + } + +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/PointcutRewriterTest.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/PointcutRewriterTest.java new file mode 100644 index 000000000..d2a8fd245 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/PointcutRewriterTest.java @@ -0,0 +1,478 @@ +/* ******************************************************************* + * Copyright (c) 2004 IBM Corporation. + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * ******************************************************************/ +package org.aspectj.weaver.patterns; + +import java.util.Iterator; +import java.util.Set; +import java.util.StringTokenizer; + +import junit.framework.TestCase; + +import org.aspectj.weaver.Shadow; + +/** + * Testing the pointcut rewriter. + * + * @author Adrian Colyer + * @author Andy Clement + */ +public class PointcutRewriterTest extends TestCase { + + private PointcutRewriter prw; + + public void testComplexRewrite1() { + Pointcut p = getPointcut("(persingleton(org.eclipse.ajdt.internal.ui.ras.UIFFDC) && ((handler(java.lang.Throwable+) && args(arg1)) && ((within(org.eclipse.ajdt..*) && (!within(org.eclipse.ajdt.internal.ui.lazystart..*) && (!within(org.eclipse.ajdt.internal.ui.dialogs.OpenTypeSelectionDialog2) && !(within(org.eclipse.ajdt.internal.ui.editor.AspectJBreakpointRulerAction) && handler(org.eclipse.jface.text.BadLocationException))))) && (!(within(org.eclipse.ajdt.core.ras.FFDC+) || handler(org.eclipse.core.runtime.OperationCanceledException)) && !this(java.lang.Object)))))"); + checkMultipleRewrite(p); + p = getPointcut("((((((((((!within(org.eclipse.ajdt.internal.ui.lazystart..*) && !within(org.eclipse.ajdt.internal.ui.dialogs.OpenTypeSelectionDialog2)) && !within(org.eclipse.ajdt.core.ras.FFDC+)) && within(org.eclipse.ajdt..*)) && !within(org.eclipse.ajdt.internal.ui.editor.AspectJBreakpointRulerAction)) && handler(java.lang.Throwable+)) && !handler(org.eclipse.core.runtime.OperationCanceledException)) && !this(java.lang.Object)) && args(arg1)) && persingleton(org.eclipse.ajdt.internal.ui.ras.UIFFDC)) || (((((((((!within(org.eclipse.ajdt.internal.ui.lazystart..*) && !within(org.eclipse.ajdt.internal.ui.dialogs.OpenTypeSelectionDialog2)) && !within(org.eclipse.ajdt.core.ras.FFDC+)) && within(org.eclipse.ajdt..*)) && !handler(org.eclipse.jface.text.BadLocationException)) && handler(java.lang.Throwable+)) && !handler(org.eclipse.core.runtime.OperationCanceledException)) && !this(java.lang.Object)) && args(arg1)) && persingleton(org.eclipse.ajdt.internal.ui.ras.UIFFDC)))"); + checkMultipleRewrite(p); + p = getPointcut("(persingleton(Oranges) && ((handler(Apples+) && args(arg1)) && ((within(foo..*) && (!within(org.eclipse.ajdt.internal.ui.lazystart..*) && (!within(org.eclipse.ajdt.internal.ui.dialogs.OpenTypeSelectionDialog2) && !(within(org.eclipse.ajdt.internal.ui.editor.AspectJBreakpointRulerAction) && handler(org.eclipse.jface.text.BadLocationException))))) && (!(within(org.eclipse.ajdt.core.ras.FFDC+) || handler(org.eclipse.core.runtime.OperationCanceledException)) && !this(java.lang.Object)))))"); + checkMultipleRewrite(p); + p = getPointcut("(((handler(Apples+)) && ((within(foo..*) && (!within(org.eclipse.ajdt.internal.ui.lazystart..*) && (!within(org.eclipse.ajdt.internal.ui.dialogs.OpenTypeSelectionDialog2) && !(within(org.eclipse.ajdt.internal.ui.editor.AspectJBreakpointRulerAction) && handler(org.eclipse.jface.text.BadLocationException))))) && (!(within(org.eclipse.ajdt.core.ras.FFDC+) || handler(org.eclipse.core.runtime.OperationCanceledException)) && !this(java.lang.Object)))))"); + checkMultipleRewrite(p); + p = getPointcut("within(xxx..*) && within(XXY) && within(org.eclipse.AspectJBreakpoint)"); + checkMultipleRewrite(p); + } + + /** + * Rewrites a pointcut twice and checks the format is stable + */ + private void checkMultipleRewrite(Pointcut p) { + Pointcut rewrittenPointcut = prw.rewrite(p, false); + String rewrite = rewrittenPointcut.toString(); + Pointcut rewriteOfRewrittenPointcut = prw.rewrite(rewrittenPointcut, false); + String rewriteOfRewritten = rewriteOfRewrittenPointcut.toString(); + assertEquals(rewrite, rewriteOfRewritten); + } + + public void testDistributeNot() { + Pointcut plain = getPointcut("this(Foo)"); + assertEquals("Unchanged", plain, prw.rewrite(plain)); + Pointcut not = getPointcut("!this(Foo)"); + assertEquals("Unchanged", not, prw.rewrite(not)); + Pointcut notNot = getPointcut("!!this(Foo)"); + assertEquals("this(Foo)", prw.rewrite(notNot).toString()); + Pointcut notNotNOT = getPointcut("!!!this(Foo)"); + assertEquals("!this(Foo)", prw.rewrite(notNotNOT).toString()); + Pointcut and = getPointcut("!(this(Foo) && this(Goo))"); + assertEquals("(!this(Foo) || !this(Goo))", prw.rewrite(and, true).toString()); + Pointcut or = getPointcut("!(this(Foo) || this(Goo))"); + assertEquals("(!this(Foo) && !this(Goo))", prw.rewrite(or, true).toString()); + Pointcut nestedNot = getPointcut("!(this(Foo) && !this(Goo))"); + assertEquals("(!this(Foo) || this(Goo))", prw.rewrite(nestedNot, true).toString()); + } + + public void testPullUpDisjunctions() { + Pointcut aAndb = getPointcut("this(Foo) && this(Goo)"); + assertEquals("Unchanged", aAndb, prw.rewrite(aAndb)); + Pointcut aOrb = getPointcut("this(Foo) || this(Moo)"); + assertEquals("Unchanged", aOrb, prw.rewrite(aOrb)); + + Pointcut leftOr = getPointcut("this(Foo) || (this(Goo) && this(Boo))"); + assertEquals("or%anyorder%this(Foo)%and%anyorder%this(Boo)%this(Goo)", prw.rewrite(leftOr)); + // assertEquals("(this(Foo) || (this(Boo) && this(Goo)))",prw.rewrite(leftOr).toString()); + + Pointcut rightOr = getPointcut("(this(Goo) && this(Boo)) || this(Foo)"); + // assertEquals("(this(Foo) || (this(Boo) && this(Goo)))",prw.rewrite(rightOr).toString()); + assertEquals("or%anyorder%this(Foo)%and%anyorder%this(Goo)%this(Boo)", prw.rewrite(rightOr)); + + Pointcut leftAnd = getPointcut("this(Foo) && (this(Goo) || this(Boo))"); + // assertEquals("((this(Boo) && this(Foo)) || (this(Foo) && this(Goo)))",prw.rewrite(leftAnd).toString()); + assertEquals("or%anyorder%and%anyorder%this(Boo)%this(Foo)%and%anyorder%this(Foo)%this(Goo)", prw.rewrite(leftAnd)); + + Pointcut rightAnd = getPointcut("(this(Goo) || this(Boo)) && this(Foo)"); + // assertEquals("((this(Boo) && this(Foo)) || (this(Foo) && this(Goo)))",prw.rewrite(rightAnd).toString()); + assertEquals("or%anyorder%and%anyorder%this(Boo)%this(Foo)%and%anyorder%this(Foo)%this(Goo)", prw.rewrite(rightAnd)); + + Pointcut nestedOrs = getPointcut("this(Foo) || this(Goo) || this(Boo)"); + // assertEquals("((this(Boo) || this(Foo)) || this(Goo))",prw.rewrite(nestedOrs).toString()); + assertEquals("or%anyorder%this(Goo)%or%anyorder%this(Boo)%this(Foo)", prw.rewrite(nestedOrs)); + + Pointcut nestedAnds = getPointcut("(this(Foo) && (this(Boo) && (this(Goo) || this(Moo))))"); + // t(F) && (t(B) && (t(G) || t(M))) + // ==> t(F) && ((t(B) && t(G)) || (t(B) && t(M))) + // ==> (t(F) && (t(B) && t(G))) || (t(F) && (t(B) && t(M))) + // assertEquals("(((this(Boo) && this(Foo)) && this(Goo)) || ((this(Boo) && this(Foo)) && this(Moo)))", + // prw.rewrite(nestedAnds).toString()); + assertEquals( + "or%anyorder%and%anyorder%and%anyorder%this(Boo)%this(Foo)%this(Goo)%and%anyorder%and%anyorder%this(Boo)%this(Foo)%this(Moo)", + prw.rewrite(nestedAnds)); + } + + /** + * spec is reverse polish notation with operators and, or , not, anyorder, delimiter is "%" (not whitespace). + * + * @param spec + * @param pc + */ + private void assertEquals(String spec, Pointcut pc) { + StringTokenizer strTok = new StringTokenizer(spec, "%"); + String[] tokens = new String[strTok.countTokens()]; + for (int i = 0; i < tokens.length; i++) { + tokens[i] = strTok.nextToken(); + } + tokenIndex = 0; + assertTrue(spec, equals(pc, tokens)); + } + + private int tokenIndex = 0; + + private boolean equals(Pointcut pc, String[] tokens) { + if (tokens[tokenIndex].equals("and")) { + tokenIndex++; + if (!(pc instanceof AndPointcut)) { + return false; + } + AndPointcut apc = (AndPointcut) pc; + Pointcut left = apc.getLeft(); + Pointcut right = apc.getRight(); + if (tokens[tokenIndex].equals("anyorder")) { + tokenIndex++; + int restorePoint = tokenIndex; + boolean leftMatchFirst = equals(left, tokens) && equals(right, tokens); + if (leftMatchFirst) { + return true; + } + tokenIndex = restorePoint; + boolean rightMatchFirst = equals(right, tokens) && equals(left, tokens); + return rightMatchFirst; + } else { + return equals(left, tokens) && equals(right, tokens); + } + } else if (tokens[tokenIndex].equals("or")) { + tokenIndex++; + if (!(pc instanceof OrPointcut)) { + return false; + } + OrPointcut opc = (OrPointcut) pc; + Pointcut left = opc.getLeft(); + Pointcut right = opc.getRight(); + if (tokens[tokenIndex].equals("anyorder")) { + tokenIndex++; + int restorePoint = tokenIndex; + boolean leftMatchFirst = equals(left, tokens) && equals(right, tokens); + if (leftMatchFirst) { + return true; + } + tokenIndex = restorePoint; + boolean rightMatchFirst = equals(right, tokens) && equals(left, tokens); + return rightMatchFirst; + } else { + return equals(left, tokens) && equals(right, tokens); + } + + } else if (tokens[tokenIndex].equals("not")) { + if (!(pc instanceof NotPointcut)) { + return false; + } + tokenIndex++; + NotPointcut np = (NotPointcut) pc; + return equals(np.getNegatedPointcut(), tokens); + } else { + return tokens[tokenIndex++].equals(pc.toString()); + } + } + + // public void testSplitOutWithins() { + // Pointcut simpleExecution = getPointcut("execution(* *.*(..))"); + // assertEquals("Unchanged",simpleExecution,prw.rewrite(simpleExecution)); + // Pointcut simpleWithinCode = getPointcut("withincode(* *.*(..))"); + // assertEquals("Unchanged",simpleWithinCode,prw.rewrite(simpleWithinCode)); + // Pointcut execution = getPointcut("execution(@Foo Foo (@Goo org.xyz..*).m*(Foo,Boo))"); + // assertEquals("(within((@(Goo) org.xyz..*)) && execution(@(Foo) Foo m*(Foo, Boo)))", + // prw.rewrite(execution).toString()); + // Pointcut withincode = getPointcut("withincode(@Foo Foo (@Goo org.xyz..*).m*(Foo,Boo))"); + // assertEquals("(within((@(Goo) org.xyz..*)) && withincode(@(Foo) Foo m*(Foo, Boo)))", + // prw.rewrite(withincode).toString()); + // Pointcut notExecution = getPointcut("!execution(Foo BankAccount+.*(..))"); + // assertEquals("(!within(BankAccount+) || !execution(Foo *(..)))", + // prw.rewrite(notExecution).toString()); + // Pointcut andWithincode = getPointcut("withincode(Foo.new(..)) && this(Foo)"); + // assertEquals("((within(Foo) && withincode(new(..))) && this(Foo))", + // prw.rewrite(andWithincode).toString()); + // Pointcut orExecution = getPointcut("this(Foo) || execution(Goo Foo.moo(Baa))"); + // assertEquals("((within(Foo) && execution(Goo moo(Baa))) || this(Foo))", + // prw.rewrite(orExecution).toString()); + // } + + public void testRemoveDuplicatesInAnd() { + Pointcut dupAnd = getPointcut("this(Foo) && this(Foo)"); + assertEquals("this(Foo)", prw.rewrite(dupAnd).toString()); + Pointcut splitdupAnd = getPointcut("(this(Foo) && target(Boo)) && this(Foo)"); + assertEquals("(target(Boo) && this(Foo))", prw.rewrite(splitdupAnd).toString()); + } + + public void testNotRemoveNearlyDuplicatesInAnd() { + Pointcut toAndto = getPointcut("this(Object+) && this(Object)"); + // Pointcut rewritten = + prw.rewrite(toAndto); + } + + public void testAAndNotAinAnd() { + Pointcut aAndNota = getPointcut("this(Foo)&& !this(Foo)"); + assertEquals("Matches nothing", "", prw.rewrite(aAndNota).toString()); + Pointcut aAndBAndNota = getPointcut("this(Foo) && execution(* *.*(..)) && !this(Foo)"); + assertEquals("Matches nothing", "", prw.rewrite(aAndBAndNota).toString()); + } + + public void testIfFalseInAnd() { + Pointcut ifFalse = IfPointcut.makeIfFalsePointcut(Pointcut.CONCRETE); + Pointcut p = getPointcut("this(A)"); + assertEquals("Matches nothing", "", prw.rewrite(new AndPointcut(ifFalse, p)).toString()); + } + + public void testMatchesNothinginAnd() { + Pointcut nothing = Pointcut.makeMatchesNothing(Pointcut.CONCRETE); + Pointcut p = getPointcut("this(A)"); + assertEquals("Matches nothing", "", prw.rewrite(new AndPointcut(nothing, p)).toString()); + } + + public void testMixedKindsInAnd() { + Pointcut mixedKinds = getPointcut("call(* *(..)) && execution(* *(..))"); + assertEquals("Matches nothing", "", prw.rewrite(mixedKinds).toString()); + Pointcut ok = getPointcut("this(Foo) && call(* *(..))"); + assertEquals(ok, prw.rewrite(ok)); + } + + public void testDetermineKindSetOfAnd() { + Pointcut oneKind = getPointcut("execution(* foo(..)) && this(Boo)"); + AndPointcut rewritten = (AndPointcut) prw.rewrite(oneKind); + assertEquals("Only one kind", 1, Shadow.howMany(rewritten.couldMatchKinds())); + assertTrue("It's Shadow.MethodExecution", Shadow.MethodExecution.isSet(rewritten.couldMatchKinds())); + } + + public void testKindSetOfExecution() { + Pointcut p = getPointcut("execution(* foo(..))"); + assertEquals("Only one kind", 1, Shadow.howMany(p.couldMatchKinds())); + assertTrue("It's Shadow.MethodExecution", Shadow.MethodExecution.isSet(p.couldMatchKinds())); + p = getPointcut("execution(new(..))"); + assertEquals("Only one kind", 1, Shadow.howMany(p.couldMatchKinds())); + assertTrue("It's Shadow.ConstructorExecution", Shadow.ConstructorExecution.isSet(p.couldMatchKinds())); + } + + public void testKindSetOfCall() { + Pointcut p = getPointcut("call(* foo(..))"); + assertEquals("Only one kind", 1, Shadow.howMany(p.couldMatchKinds())); + assertTrue("It's Shadow.MethodCall", Shadow.MethodCall.isSet(p.couldMatchKinds())); + p = getPointcut("call(new(..))"); + assertEquals("Only one kind", 1, Shadow.howMany(p.couldMatchKinds())); + assertTrue("It's Shadow.ConstructorCall", Shadow.ConstructorCall.isSet(p.couldMatchKinds())); + } + + public void testKindSetOfAdviceExecution() { + Pointcut p = getPointcut("adviceexecution()"); + assertEquals("Only one kind", 1, Shadow.howMany(p.couldMatchKinds())); + assertTrue("It's Shadow.AdviceExecution", Shadow.AdviceExecution.isSet(p.couldMatchKinds())); + } + + public void testKindSetOfGet() { + Pointcut p = getPointcut("get(* *)"); + assertEquals("Only one kind", 1, Shadow.howMany(p.couldMatchKinds())); + assertTrue("It's Shadow.FieldGet", Shadow.FieldGet.isSet(p.couldMatchKinds())); + } + + public void testKindSetOfSet() { + Pointcut p = getPointcut("set(* *)"); + assertEquals("Only one kind", 1, Shadow.howMany(p.couldMatchKinds())); + assertTrue("It's Shadow.FieldSet", Shadow.FieldSet.isSet(p.couldMatchKinds())); + } + + public void testKindSetOfHandler() { + Pointcut p = getPointcut("handler(*)"); + assertEquals("Only one kind", 1, Shadow.howMany(p.couldMatchKinds())); + assertTrue("It's Shadow.ExceptionHandler", Shadow.ExceptionHandler.isSet(p.couldMatchKinds())); + } + + public void testKindSetOfInitialization() { + Pointcut p = getPointcut("initialization(new (..))"); + assertEquals("Only one kind", 1, Shadow.howMany(p.couldMatchKinds())); + assertTrue("It's Shadow.Initialization", Shadow.Initialization.isSet(p.couldMatchKinds())); + } + + public void testKindSetOfPreInitialization() { + Pointcut p = getPointcut("preinitialization(new (..))"); + assertEquals("Only one kind", 1, Shadow.howMany(p.couldMatchKinds())); + assertTrue("It's Shadow.PreInitialization", Shadow.PreInitialization.isSet(p.couldMatchKinds())); + } + + public void testKindSetOfStaticInitialization() { + Pointcut p = getPointcut("staticinitialization(*)"); + assertEquals("Only one kind", 1, Shadow.howMany(p.couldMatchKinds())); + assertTrue("It's Shadow.StaticInitialization", Shadow.StaticInitialization.isSet(p.couldMatchKinds())); + } + + public void testKindSetOfThis() { + Pointcut p = getPointcut("this(Foo)"); + Set matches = Shadow.toSet(p.couldMatchKinds()); + for (Iterator iter = matches.iterator(); iter.hasNext();) { + Shadow.Kind kind = (Shadow.Kind) iter.next(); + assertFalse("No kinds that don't have a this", kind.neverHasThis()); + } + for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { + if (!Shadow.SHADOW_KINDS[i].neverHasThis()) { + assertTrue("All kinds that do have this", matches.contains(Shadow.SHADOW_KINDS[i])); + } + } + // + @ + p = getPointcut("@this(Foo)"); + matches = Shadow.toSet(p.couldMatchKinds()); + for (Iterator iter = matches.iterator(); iter.hasNext();) { + Shadow.Kind kind = (Shadow.Kind) iter.next(); + assertFalse("No kinds that don't have a this", kind.neverHasThis()); + } + for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { + if (!Shadow.SHADOW_KINDS[i].neverHasThis()) { + assertTrue("All kinds that do have this", matches.contains(Shadow.SHADOW_KINDS[i])); + } + } + } + + public void testKindSetOfTarget() { + Pointcut p = getPointcut("target(Foo)"); + Set matches = Shadow.toSet(p.couldMatchKinds()); + for (Iterator iter = matches.iterator(); iter.hasNext();) { + Shadow.Kind kind = (Shadow.Kind) iter.next(); + assertFalse("No kinds that don't have a target", kind.neverHasTarget()); + } + for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { + if (!Shadow.SHADOW_KINDS[i].neverHasTarget()) { + assertTrue("All kinds that do have target", matches.contains(Shadow.SHADOW_KINDS[i])); + } + } + // + @ + p = getPointcut("@target(Foo)"); + matches = Shadow.toSet(p.couldMatchKinds()); + for (Iterator iter = matches.iterator(); iter.hasNext();) { + Shadow.Kind kind = (Shadow.Kind) iter.next(); + assertFalse("No kinds that don't have a target", kind.neverHasTarget()); + } + for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { + if (!Shadow.SHADOW_KINDS[i].neverHasTarget()) { + assertTrue("All kinds that do have target", matches.contains(Shadow.SHADOW_KINDS[i])); + } + } + } + + public void testKindSetOfArgs() { + Pointcut p = getPointcut("args(..)"); + assertTrue("All kinds", p.couldMatchKinds() == Shadow.ALL_SHADOW_KINDS_BITS); + // + @ + p = getPointcut("@args(..)"); + assertTrue("All kinds", p.couldMatchKinds() == Shadow.ALL_SHADOW_KINDS_BITS); + } + + public void testKindSetOfAnnotation() { + Pointcut p = getPointcut("@annotation(Foo)"); + assertTrue("All kinds", p.couldMatchKinds() == Shadow.ALL_SHADOW_KINDS_BITS); + } + + public void testKindSetOfWithin() { + Pointcut p = getPointcut("within(*)"); + assertTrue("All kinds", p.couldMatchKinds() == Shadow.ALL_SHADOW_KINDS_BITS); + // + @ + p = getPointcut("@within(Foo)"); + assertTrue("All kinds", p.couldMatchKinds() == Shadow.ALL_SHADOW_KINDS_BITS); + } + + public void testKindSetOfWithinCode() { + Pointcut p = getPointcut("withincode(* foo(..))"); + Set matches = Shadow.toSet(p.couldMatchKinds()); + for (Iterator iter = matches.iterator(); iter.hasNext();) { + Shadow.Kind kind = (Shadow.Kind) iter.next(); + assertFalse("No kinds that are themselves enclosing", + (kind.isEnclosingKind() && kind != Shadow.ConstructorExecution && kind != Shadow.Initialization)); + } + for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { + if (!Shadow.SHADOW_KINDS[i].isEnclosingKind()) { + assertTrue("All kinds that are not enclosing", matches.contains(Shadow.SHADOW_KINDS[i])); + } + } + assertTrue("Need cons-exe for inlined field inits", matches.contains(Shadow.ConstructorExecution)); + assertTrue("Need init for inlined field inits", matches.contains(Shadow.Initialization)); + // + @ + p = getPointcut("@withincode(Foo)"); + matches = Shadow.toSet(p.couldMatchKinds()); + for (Iterator iter = matches.iterator(); iter.hasNext();) { + Shadow.Kind kind = (Shadow.Kind) iter.next(); + assertFalse("No kinds that are themselves enclosing", kind.isEnclosingKind()); + } + for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { + if (!Shadow.SHADOW_KINDS[i].isEnclosingKind()) { + assertTrue("All kinds that are not enclosing", matches.contains(Shadow.SHADOW_KINDS[i])); + } + } + } + + public void testKindSetOfIf() { + Pointcut p = new IfPointcut(null, 0); + assertTrue("All kinds", p.couldMatchKinds() == Shadow.ALL_SHADOW_KINDS_BITS); + p = IfPointcut.makeIfTruePointcut(Pointcut.CONCRETE); + assertTrue("All kinds", p.couldMatchKinds() == Shadow.ALL_SHADOW_KINDS_BITS); + p = IfPointcut.makeIfFalsePointcut(Pointcut.CONCRETE); + assertTrue("Nothing", p.couldMatchKinds() == Shadow.NO_SHADOW_KINDS_BITS); + } + + public void testKindSetOfCflow() { + Pointcut p = getPointcut("cflow(this(Foo))"); + assertTrue("All kinds", p.couldMatchKinds() == Shadow.ALL_SHADOW_KINDS_BITS); + // [below] + p = getPointcut("cflowbelow(this(Foo))"); + assertTrue("All kinds", p.couldMatchKinds() == Shadow.ALL_SHADOW_KINDS_BITS); + } + + public void testKindSetInNegation() { + Pointcut p = getPointcut("!execution(new(..))"); + assertTrue("All kinds", p.couldMatchKinds() == Shadow.ALL_SHADOW_KINDS_BITS); + } + + public void testKindSetOfOr() { + Pointcut p = getPointcut("execution(new(..)) || get(* *)"); + Set matches = Shadow.toSet(p.couldMatchKinds()); + assertEquals("2 kinds", 2, matches.size()); + assertTrue("ConstructorExecution", matches.contains(Shadow.ConstructorExecution)); + assertTrue("FieldGet", matches.contains(Shadow.FieldGet)); + } + + public void testOrderingInAnd() { + Pointcut bigLongPC = getPointcut("cflow(this(Foo)) && @args(X) && args(X) && @this(Foo) && @target(Boo) && this(Moo) && target(Boo) && @annotation(Moo) && @withincode(Boo) && withincode(new(..)) && set(* *)&& @within(Foo) && within(Foo)"); + checkMultipleRewrite(bigLongPC); + Pointcut rewritten = prw.rewrite(bigLongPC); + assertEquals( + "((((((((((((within(Foo) && @within(Foo)) && set(* *)) && withincode(new(..))) && @withincode(Boo)) && target(Boo)) && this(Moo)) && @annotation(Moo)) && @this(Foo)) && @target(Boo)) && args(X)) && @args(X)) && cflow(this(Foo)))", + rewritten.toString()); + } + + public void testOrderingInSimpleOr() { + OrPointcut opc = (OrPointcut) getPointcut("execution(new(..)) || get(* *)"); + assertEquals("reordered", "(get(* *) || execution(new(..)))", prw.rewrite(opc).toString()); + } + + public void testOrderingInNestedOrs() { + OrPointcut opc = (OrPointcut) getPointcut("(execution(new(..)) || get(* *)) || within(abc)"); + assertEquals("reordered", "((within(abc) || get(* *)) || execution(new(..)))", prw.rewrite(opc).toString()); + } + + public void testOrderingInOrsWithNestedAnds() { + OrPointcut opc = (OrPointcut) getPointcut("get(* *) || (execution(new(..)) && within(abc))"); + assertEquals("reordered", "((within(abc) && execution(new(..))) || get(* *))", prw.rewrite(opc).toString()); + } + + private Pointcut getPointcut(String s) { + return new PatternParser(s).parsePointcut(); + } + + /* + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + prw = new PointcutRewriter(); + } + +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/SignaturePatternMatchSpeedTestCase.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/SignaturePatternMatchSpeedTestCase.java new file mode 100644 index 000000000..52f82bfd7 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/SignaturePatternMatchSpeedTestCase.java @@ -0,0 +1,167 @@ +/* ******************************************************************* + * Copyright (c) 2009 Contributors + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Andy Clement initial implementation + * ******************************************************************/ + +package org.aspectj.weaver.patterns; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import org.aspectj.weaver.CompressingDataOutputStream; +import org.aspectj.weaver.Member; +import org.aspectj.weaver.TestUtils; +import org.aspectj.weaver.VersionedDataInputStream; +import org.aspectj.weaver.World; +import org.aspectj.weaver.reflect.ReflectionWorld; + +public class SignaturePatternMatchSpeedTestCase extends PatternsTestCase { + + Member stringReplaceFirstMethod; + + @Override + public World getWorld() { + return new ReflectionWorld(true, this.getClass().getClassLoader()); + } + + public void testPatternEllipsis() throws IOException { + String pattern = "* *(..))"; + SignaturePattern signaturePattern = toPattern(pattern); + warmup(signaturePattern, stringReplaceFirstMethod, world); + long time = measure(signaturePattern, stringReplaceFirstMethod, world); + System.out.println("Signature pattern [" + pattern + "] took " + time + "ms for 1,000,000"); + } + + public void testPatternOneArg() throws IOException { + String pattern = "* *(*))"; + SignaturePattern signaturePattern = toPattern(pattern); + warmup(signaturePattern, stringReplaceFirstMethod, world); + long time = measure(signaturePattern, stringReplaceFirstMethod, world); + System.out.println("Signature pattern [" + pattern + "] took " + time + "ms for 1,000,000"); + } + + public void testPatternNoArgs() throws IOException { + String pattern = "* *())"; + SignaturePattern signaturePattern = toPattern(pattern); + warmup(signaturePattern, stringReplaceFirstMethod, world); + long time = measure(signaturePattern, stringReplaceFirstMethod, world); + System.out.println("Signature pattern [" + pattern + "] took " + time + "ms for 1,000,000"); + } + + public void testPatternNotVoidReturn() throws IOException { + String pattern = "!void *(..))"; + SignaturePattern signaturePattern = toPattern(pattern); + warmup(signaturePattern, stringReplaceFirstMethod, world); + long time = measure(signaturePattern, stringReplaceFirstMethod, world); + System.out.println("Signature pattern [" + pattern + "] took " + time + "ms for 1,000,000"); + } + + public void testPatternVoidReturn() throws IOException { + String pattern = "void *(..))"; + SignaturePattern signaturePattern = toPattern(pattern); + warmup(signaturePattern, stringReplaceFirstMethod, world); + long time = measure(signaturePattern, stringReplaceFirstMethod, world); + System.out.println("Signature pattern [" + pattern + "] took " + time + "ms for 1,000,000"); + } + + public void testPatternWildcardedName() throws IOException { + String pattern = "* *a*b*()"; + SignaturePattern signaturePattern = toPattern(pattern); + warmup(signaturePattern, stringReplaceFirstMethod, world); + long time = measure(signaturePattern, stringReplaceFirstMethod, world); + System.out.println("Signature pattern [" + pattern + "] took " + time + "ms for 1,000,000"); + } + + public void testPatternWildcardedName2() throws IOException { + String pattern = "* *a*b*(..)"; + SignaturePattern signaturePattern = toPattern(pattern); + warmup(signaturePattern, stringReplaceFirstMethod, world); + long time = measure(signaturePattern, stringReplaceFirstMethod, world); + System.out.println("Signature pattern [" + pattern + "] took " + time + "ms for 1,000,000"); + } + + // --- + + public void checkMatch(SignaturePattern p, Member[] yes, Member[] no) throws IOException { + p = p.resolveBindings(new TestScope(world, new FormalBinding[0]), new Bindings(0)); + + for (int i = 0; i < yes.length; i++) { + checkMatch(p, yes[i], true); + } + + for (int i = 0; i < no.length; i++) { + checkMatch(p, no[i], false); + } + + checkSerialization(p); + } + + @Override + public void setUp() throws Exception { + super.setUp(); + stringReplaceFirstMethod = TestUtils.methodFromString( + "java.lang.String java.lang.String.replaceFirst(java.lang.String,java.lang.String)").resolve(world); + } + + /** + * Run match 1000 times to warmup + */ + private void warmup(SignaturePattern signaturePattern, Member method, World world) { + for (int i = 0; i < 1000; i++) { + signaturePattern.matches(method, world, false); + } + } + + /** + * Run match 1000000 and return time taken in ms + */ + private long measure(SignaturePattern signaturePattern, Member method, World world) { + long stime = System.currentTimeMillis(); + for (int i = 0; i < 1000000; i++) { + signaturePattern.matches(method, world, false); + } + return (System.currentTimeMillis() - stime); + } + + private SignaturePattern toPattern(String pattern) { + SignaturePattern signaturePattern = makeMethodPat(pattern); + signaturePattern = signaturePattern.resolveBindings(new TestScope(world, new FormalBinding[0]), new Bindings(0)); + return signaturePattern; + } + + private void checkMatch(SignaturePattern p, Member member, boolean b) { + boolean matches = p.matches(member, world, false); + assertEquals(p.toString() + " matches " + member.toString(), b, matches); + } + + private SignaturePattern makeMethodPat(String pattern) { + return new PatternParser(pattern).parseMethodOrConstructorSignaturePattern(); + } + + private SignaturePattern makeFieldPat(String pattern) { + return new PatternParser(pattern).parseFieldSignaturePattern(); + } + + private void checkSerialization(SignaturePattern p) throws IOException { + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + ConstantPoolSimulator cps = new ConstantPoolSimulator(); + CompressingDataOutputStream out = new CompressingDataOutputStream(bo, cps); + p.write(out); + out.close(); + + ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); + VersionedDataInputStream in = new VersionedDataInputStream(bi, cps); + SignaturePattern newP = SignaturePattern.read(in, null); + + assertEquals("write/read", p, newP); + } + +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/SignaturePatternTestCase.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/SignaturePatternTestCase.java new file mode 100644 index 000000000..6c6f1f985 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/SignaturePatternTestCase.java @@ -0,0 +1,185 @@ +/* ******************************************************************* + * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). + * 2005 Contributors + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * PARC initial implementation + * ******************************************************************/ + +package org.aspectj.weaver.patterns; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import org.aspectj.weaver.CompressingDataOutputStream; +import org.aspectj.weaver.Member; +import org.aspectj.weaver.TestUtils; +import org.aspectj.weaver.VersionedDataInputStream; +import org.aspectj.weaver.World; +import org.aspectj.weaver.reflect.ReflectionWorld; + +public class SignaturePatternTestCase extends PatternsTestCase { + + @Override + public World getWorld() { + return new ReflectionWorld(true, this.getClass().getClassLoader()); + } + + public void testThrowsMatch() throws IOException { + Member onlyDerivedOnDerived = TestUtils.methodFromString("static void org.aspectj.weaver.testcode.Derived.onlyDerived()"); + Member mOnBase = TestUtils.methodFromString("void org.aspectj.weaver.testcode.Base.m()"); + Member mOnDerived = TestUtils.methodFromString("void org.aspectj.weaver.testcode.Derived.m()"); + + checkMatch(makeMethodPat("* org.aspectj.weaver.testcode.Base.*(..) throws java.lang.CloneNotSupportedException"), + new Member[] { mOnBase }, new Member[] { mOnDerived }); + + checkMatch(makeMethodPat("* org.aspectj.weaver.testcode.Derived.*(..) throws java.lang.CloneNotSupportedException"), + new Member[] {}, new Member[] { mOnBase, mOnDerived }); + + // XXX need pattern checks + Member[] NONE = new Member[] {}; + Member[] M = new Member[] { onlyDerivedOnDerived }; + Member[] NO_EXCEPTIONS = new Member[] { mOnDerived }; + Member[] BOTH = new Member[] { mOnDerived, onlyDerivedOnDerived }; + + checkMatch(makeMethodPat("* *(..)"), M, NONE); + checkMatch(makeMethodPat("* *(..) throws !*"), NO_EXCEPTIONS, M); + checkMatch(makeMethodPat("* *(..) throws *"), M, NO_EXCEPTIONS); + checkMatch(makeMethodPat("* *(..) throws *, !*"), NONE, BOTH); + + checkMatch(makeMethodPat("* *(..) throws (!*)"), NONE, BOTH); + checkMatch(makeMethodPat("* *(..) throws !(!*)"), BOTH, NONE); + + checkMatch(makeMethodPat("* *(..) throws *..IOException"), M, NO_EXCEPTIONS); + checkMatch(makeMethodPat("* *(..) throws *..IOException, *..Clone*"), M, NO_EXCEPTIONS); + checkMatch(makeMethodPat("* *(..) throws *..IOException, !*..Clone*"), NONE, BOTH); + checkMatch(makeMethodPat("* *(..) throws !*..IOException"), NO_EXCEPTIONS, M); + } + + /* + * public void testInstanceMethodMatchSpeed() throws IOException { // Member objectToString = + * TestUtils.methodFromString("java.lang.String java.lang.Object.toString()"); Member objectToString = + * TestUtils.methodFromString( + * "java.lang.String java.lang.String.replaceFirst(java.lang.String,java.lang.String)").resolve(world); SignaturePattern + * signaturePattern = makeMethodPat("* *(..))"); signaturePattern = signaturePattern.resolveBindings(new TestScope(world, new + * FormalBinding[0]), new Bindings(0)); for (int i = 0; i < 1000; i++) { boolean matches = + * signaturePattern.matches(objectToString, world, false); } long stime = System.currentTimeMillis(); for (int i = 0; i < + * 2000000; i++) { boolean matches = signaturePattern.matches(objectToString, world, false); } long etime = + * System.currentTimeMillis(); System.out.println("Took " + (etime - stime) + "ms for 2,000,000");// 4081 + * + * signaturePattern = makeMethodPat("* *())"); signaturePattern = signaturePattern.resolveBindings(new TestScope(world, new + * FormalBinding[0]), new Bindings(0)); for (int i = 0; i < 1000; i++) { boolean matches = + * signaturePattern.matches(objectToString, world, false); } stime = System.currentTimeMillis(); for (int i = 0; i < 2000000; + * i++) { boolean matches = signaturePattern.matches(objectToString, world, false); } etime = System.currentTimeMillis(); + * System.out.println("Took " + (etime - stime) + "ms for 2,000,000");// 4081 } + * + * public void testInstanceMethodMatchSpeed2() throws IOException { // Member objectToString = + * TestUtils.methodFromString("java.lang.String java.lang.Object.toString()"); Member objectToString = + * TestUtils.methodFromString( + * "java.lang.String java.lang.String.replaceFirst(java.lang.String,java.lang.String)").resolve(world); SignaturePattern + * signaturePattern = makeMethodPat("!void *(..))"); signaturePattern = signaturePattern.resolveBindings(new TestScope(world, + * new FormalBinding[0]), new Bindings(0)); for (int i = 0; i < 1000; i++) { boolean matches = + * signaturePattern.matches(objectToString, world, false); } long stime = System.currentTimeMillis(); for (int i = 0; i < + * 2000000; i++) { boolean matches = signaturePattern.matches(objectToString, world, false); } long etime = + * System.currentTimeMillis(); System.out.println("Took " + (etime - stime) + "ms for 2,000,000");// 4081 } + */ + public void testInstanceMethodMatch() throws IOException { + Member objectToString = TestUtils.methodFromString("java.lang.String java.lang.Object.toString()"); + Member integerToString = TestUtils.methodFromString("java.lang.String java.lang.Integer.toString()"); + Member integerIntValue = TestUtils.methodFromString("int java.lang.Integer.intValue()"); + // Member objectToString = Member.methodFromString("java.lang.String java.lang.Object.toString()"); + + checkMatch(makeMethodPat("* java.lang.Object.*(..)"), new Member[] { objectToString, integerToString }, + new Member[] { integerIntValue }); + + checkMatch(makeMethodPat("* java.lang.Integer.*(..)"), new Member[] { integerIntValue, integerToString }, + new Member[] { objectToString }); + } + + public void testStaticMethodMatch() throws IOException { + Member onlyBaseOnBase = TestUtils.methodFromString("static void org.aspectj.weaver.testcode.Base.onlyBase()"); + Member onlyBaseOnDerived = TestUtils.methodFromString("static void org.aspectj.weaver.testcode.Derived.onlyBase()"); + Member onlyDerivedOnDerived = TestUtils.methodFromString("static void org.aspectj.weaver.testcode.Derived.onlyDerived()"); + Member bothOnBase = TestUtils.methodFromString("static void org.aspectj.weaver.testcode.Base.both()"); + Member bothOnDerived = TestUtils.methodFromString("static void org.aspectj.weaver.testcode.Derived.both()"); + + checkMatch(makeMethodPat("* org.aspectj.weaver.testcode.Base.*(..)"), new Member[] { onlyBaseOnBase, onlyBaseOnDerived, + bothOnBase }, new Member[] { onlyDerivedOnDerived, bothOnDerived }); + + checkMatch(makeMethodPat("* org.aspectj.weaver.testcode.Derived.*(..)"), new Member[] { onlyBaseOnDerived, bothOnDerived, + onlyDerivedOnDerived }, new Member[] { onlyBaseOnBase, bothOnBase }); + } + + public void testFieldMatch() throws IOException { + Member onlyBaseOnBase = TestUtils.fieldFromString("int org.aspectj.weaver.testcode.Base.onlyBase"); + Member onlyBaseOnDerived = TestUtils.fieldFromString("int org.aspectj.weaver.testcode.Derived.onlyBase"); + Member onlyDerivedOnDerived = TestUtils.fieldFromString("int org.aspectj.weaver.testcode.Derived.onlyDerived"); + Member bothOnBase = TestUtils.fieldFromString("int org.aspectj.weaver.testcode.Base.both"); + Member bothOnDerived = TestUtils.fieldFromString("int org.aspectj.weaver.testcode.Derived.both"); + + checkMatch(makeFieldPat("* org.aspectj.weaver.testcode.Base.*"), new Member[] { onlyBaseOnBase, onlyBaseOnDerived, + bothOnBase }, new Member[] { onlyDerivedOnDerived, bothOnDerived }); + + checkMatch(makeFieldPat("* org.aspectj.weaver.testcode.Derived.*"), new Member[] { onlyBaseOnDerived, bothOnDerived, + onlyDerivedOnDerived }, new Member[] { onlyBaseOnBase, bothOnBase }); + } + + public void testConstructorMatch() throws IOException { + Member onBase = TestUtils.methodFromString("void org.aspectj.weaver.testcode.Base.<init>()"); + Member onDerived = TestUtils.methodFromString("void org.aspectj.weaver.testcode.Derived.<init>()"); + Member onBaseWithInt = TestUtils.methodFromString("void org.aspectj.weaver.testcode.Base.<init>(int)"); + + checkMatch(makeMethodPat("org.aspectj.weaver.testcode.Base.new(..)"), new Member[] { onBase, onBaseWithInt }, + new Member[] { onDerived }); + + checkMatch(makeMethodPat("org.aspectj.weaver.testcode.Derived.new(..)"), new Member[] { onDerived }, new Member[] { onBase, + onBaseWithInt }); + } + + public void checkMatch(SignaturePattern p, Member[] yes, Member[] no) throws IOException { + p = p.resolveBindings(new TestScope(world, new FormalBinding[0]), new Bindings(0)); + + for (int i = 0; i < yes.length; i++) { + checkMatch(p, yes[i], true); + } + + for (int i = 0; i < no.length; i++) { + checkMatch(p, no[i], false); + } + + checkSerialization(p); + } + + private void checkMatch(SignaturePattern p, Member member, boolean b) { + boolean matches = p.matches(member, world, false); + assertEquals(p.toString() + " matches " + member.toString(), b, matches); + } + + private SignaturePattern makeMethodPat(String pattern) { + return new PatternParser(pattern).parseMethodOrConstructorSignaturePattern(); + } + + private SignaturePattern makeFieldPat(String pattern) { + return new PatternParser(pattern).parseFieldSignaturePattern(); + } + + private void checkSerialization(SignaturePattern p) throws IOException { + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + ConstantPoolSimulator cps = new ConstantPoolSimulator(); + CompressingDataOutputStream out = new CompressingDataOutputStream(bo, cps); + p.write(out); + out.close(); + + ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); + VersionedDataInputStream in = new VersionedDataInputStream(bi, cps); + SignaturePattern newP = SignaturePattern.read(in, null); + + assertEquals("write/read", p, newP); + } + +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/SimpleScopeTests.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/SimpleScopeTests.java new file mode 100644 index 000000000..8df97e2f3 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/SimpleScopeTests.java @@ -0,0 +1,278 @@ +/* ******************************************************************* + * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * PARC initial implementation + * ******************************************************************/ + +package org.aspectj.weaver.patterns; + +import org.aspectj.weaver.UnresolvedType; +import org.aspectj.weaver.World; +import org.aspectj.weaver.reflect.ReflectionWorld; + +public class SimpleScopeTests extends PatternsTestCase { + + public World getWorld() { + return new ReflectionWorld(true, this.getClass().getClassLoader()); + } + + public void testTestScope() { + SimpleScope scope = makeTestScope(); + + FormalBinding formalBinding = scope.lookupFormal("i"); + assertEquals("i", formalBinding.getName()); + assertEquals("I", formalBinding.getType().getSignature()); + + formalBinding = scope.lookupFormal("string"); + assertEquals("string", formalBinding.getName()); + assertEquals("Ljava/lang/String;", formalBinding.getType().getSignature()); + } + + public void test1() { + SimpleScope scope = makeTestScope(); + UnresolvedType unresolvedType = scope.lookupType("void", null); + System.out.println(unresolvedType); + } + + public static final String[] ZERO_STRINGS = new String[0]; + + private TestScope makeTestScope() { + // i = int + // string = String + return new TestScope(new String[] { "int", "java.lang.String" }, new String[] { "i", "string" }, world); + } + // + // public void testStaticMatch() { + // checkMatch("java.lang.Object", "java.lang.Object", true); + // checkMatch("java.lang.Object+", "java.lang.Object", true); + // checkMatch("java.lang.Object+", "java.lang.String", true); + // checkMatch("java.lang.String+", "java.lang.Object", false); + // checkMatch("java.lang.Integer", "java.lang.String", false); + // + // checkMatch("java.lang.Integer", "int", false); + // + // checkMatch("java.lang.Number+", "java.lang.Integer", true); + // + // checkMatch("java..*", "java.lang.Integer", true); + // checkMatch("java..*", "java.lang.reflect.Modifier", true); + // checkMatch("java..*", "int", false); + // checkMatch("java..*", "javax.swing.Action", false); + // checkMatch("java..*+", "javax.swing.Action", true); + // + // checkMatch("*.*.Object", "java.lang.Object", true); + // checkMatch("*.Object", "java.lang.Object", false); + // checkMatch("*..*", "java.lang.Object", true); + // checkMatch("*..*", "int", false); + // checkMatch("java..Modifier", "java.lang.reflect.Modifier", true); + // checkMatch("java.lang.reflect.Mod..ifier", "java.lang.reflect.Modifier", false); + // + // checkMatch("java..reflect..Modifier", "java.lang.reflect.Modifier", true); + // checkMatch("java..lang..Modifier", "java.lang.reflect.Modifier", true); + // checkMatch("java..*..Modifier", "java.lang.reflect.Modifier", true); + // checkMatch("java..*..*..Modifier", "java.lang.reflect.Modifier", true); + // checkMatch("java..*..*..*..Modifier", "java.lang.reflect.Modifier", false); + // // checkMatch("java..reflect..Modifier", "java.lang.reflect.Modxifier", false); + // checkMatch("ja*va..Modifier", "java.lang.reflect.Modifier", true); + // checkMatch("java..*..Mod*ifier", "java.lang.reflect.Modifier", true); + // + // } + // + // // three levels: + // // 0. defined in current compilation unit, or imported by name + // // 1. defined in current package/type/whatever + // // 2. defined in package imported by * + // /** + // * We've decided not to test this here, but rather in any compilers + // */ + // public void testImportResolve() { + // // checkIllegalImportResolution("List", new String[] { "java.util", "java.awt", }, + // // ZERO_STRINGS); + // + // } + // + // // Assumption for bcweaver: Already resolved type patterns with no *s or ..'s into exact type + // // patterns. Exact type patterns don't have import lists. non-exact-type pattens don't + // // care about precedence, so the current package can be included with all the other packages, + // // and we don't care about compilation units, and we don't care about ordering. + // + // // only giving this wild-type patterns + // public void testImportMatch() { + // + // checkImportMatch("*List", new String[] { "java.awt.", }, ZERO_STRINGS, "java.awt.List", true); + // checkImportMatch("*List", new String[] { "java.awt.", }, ZERO_STRINGS, "java.awt.List", true); + // checkImportMatch("*List", new String[] { "java.awt.", }, ZERO_STRINGS, "java.util.List", false); + // checkImportMatch("*List", new String[] { "java.util.", }, ZERO_STRINGS, "java.awt.List", false); + // checkImportMatch("*List", new String[] { "java.util.", }, ZERO_STRINGS, "java.util.List", true); + // + // checkImportMatch("*List", ZERO_STRINGS, new String[] { "java.awt.List", }, "java.awt.List", true); + // + // checkImportMatch("awt.*List", ZERO_STRINGS, new String[] { "java.awt.List", }, "java.awt.List", false); + // checkImportMatch("*Foo", ZERO_STRINGS, new String[] { "java.awt.List", }, "java.awt.List", false); + // + // checkImportMatch("*List", new String[] { "java.util.", "java.awt.", }, ZERO_STRINGS, "java.util.List", true); + // checkImportMatch("*List", new String[] { "java.util.", "java.awt.", }, ZERO_STRINGS, "java.awt.List", true); + // + // checkImportMatch("*..List", new String[] { "java.util." }, ZERO_STRINGS, "java.util.List", true); + // checkImportMatch("*..List", new String[] { "java.util." }, ZERO_STRINGS, "java.awt.List", true); + // + // } + // + // public void testImportMatchWithInners() { + // // checkImportMatch("*Entry", new String[] { "java.util.", "java.util.Map$" }, ZERO_STRINGS, "java.util.Map$Entry", true); + // // + // // checkImportMatch("java.util.Map.*Entry", ZERO_STRINGS, ZERO_STRINGS, "java.util.Map$Entry", true); + // // + // // checkImportMatch("*Entry", new String[] { "java.util.", }, ZERO_STRINGS, "java.util.Map$Entry", false); + // // + // // checkImportMatch("*.Entry", new String[] { "java.util.", }, ZERO_STRINGS, "java.util.Map$Entry", true); + // // + // // checkImportMatch("Map.*", new String[] { "java.util.", }, ZERO_STRINGS, "java.util.Map$Entry", true); + // + // checkImportMatch("Map.*", ZERO_STRINGS, new String[] { "java.util.Map" }, "java.util.Map$Entry", true); + // } + // + // private void checkImportMatch(String wildPattern, String[] importedPackages, String[] importedNames, String matchName, + // boolean shouldMatch) { + // WildTypePattern p = makeResolvedWildTypePattern(wildPattern, importedPackages, importedNames); + // checkPatternMatch(p, matchName, shouldMatch); + // } + // + // private WildTypePattern makeResolvedWildTypePattern(String wildPattern, String[] importedPackages, String[] importedNames) { + // WildTypePattern unresolved = (WildTypePattern) new PatternParser(wildPattern).parseTypePattern(); + // + // WildTypePattern resolved = resolve(unresolved, importedPackages, importedNames); + // return resolved; + // + // } + // + // private WildTypePattern resolve(WildTypePattern unresolved, String[] importedPrefixes, String[] importedNames) { + // + // TestScope scope = makeTestScope(); + // scope.setImportedPrefixes(importedPrefixes); + // scope.setImportedNames(importedNames); + // return (WildTypePattern) unresolved.resolveBindings(scope, Bindings.NONE, false, false); + // } + // + + // + // public void testInstanceofMatch() { + // + // checkInstanceofMatch("java.lang.Object", "java.lang.Object", FuzzyBoolean.YES); + // + // checkIllegalInstanceofMatch("java.lang.Object+", "java.lang.Object"); + // checkIllegalInstanceofMatch("java.lang.Object+", "java.lang.String"); + // checkIllegalInstanceofMatch("java.lang.String+", "java.lang.Object"); + // checkIllegalInstanceofMatch("java.lang.*", "java.lang.Object"); + // checkInstanceofMatch("java.lang.Integer", "java.lang.String", FuzzyBoolean.NO); + // + // checkInstanceofMatch("java.lang.Number", "java.lang.Integer", FuzzyBoolean.YES); + // checkInstanceofMatch("java.lang.Integer", "java.lang.Number", FuzzyBoolean.MAYBE); + // + // checkIllegalInstanceofMatch("java..Integer", "java.lang.Integer"); + // + // checkInstanceofMatch("*", "java.lang.Integer", FuzzyBoolean.YES); + // + // } + // + // public void testArrayMatch() { + // checkMatch("*[][]", "java.lang.Object", false); + // checkMatch("*[]", "java.lang.Object[]", true); + // checkMatch("*[][]", "java.lang.Object[][]", true); + // checkMatch("java.lang.Object+", "java.lang.Object[]", true); + // checkMatch("java.lang.Object[]", "java.lang.Object", false); + // checkMatch("java.lang.Object[]", "java.lang.Object[]", true); + // checkMatch("java.lang.Object[][]", "java.lang.Object[][]", true); + // checkMatch("java.lang.String[]", "java.lang.Object", false); + // checkMatch("java.lang.String[]", "java.lang.Object[]", false); + // checkMatch("java.lang.String[][]", "java.lang.Object[][]", false); + // checkMatch("java.lang.Object+[]", "java.lang.String[][]", true); + // checkMatch("java.lang.Object+[]", "java.lang.String[]", true); + // checkMatch("java.lang.Object+[]", "int[][]", true); + // checkMatch("java.lang.Object+[]", "int[]", false); + // } + // + // private void checkIllegalInstanceofMatch(String pattern, String name) { + // try { + // TypePattern p = makeTypePattern(pattern); + // ResolvedType type = world.resolve(name); + // p.matchesInstanceof(type); + // } catch (Throwable e) { + // return; + // } + // assertTrue("matching " + pattern + " with " + name + " should fail", false); + // } + // + // private void checkInstanceofMatch(String pattern, String name, FuzzyBoolean shouldMatch) { + // TypePattern p = makeTypePattern(pattern); + // ResolvedType type = world.resolve(name); + // + // p = p.resolveBindings(makeTestScope(), null, false, false); + // + // // System.out.println("type: " + p); + // FuzzyBoolean result = p.matchesInstanceof(type); + // String msg = "matches " + pattern + " to " + type; + // assertEquals(msg, shouldMatch, result); + // } + // + // + // private TypePattern makeTypePattern(String pattern) { + // PatternParser pp = new PatternParser(pattern); + // TypePattern tp = pp.parseSingleTypePattern(); + // pp.checkEof(); + // return tp; + // } + // + // private void checkMatch(String pattern, String name, boolean shouldMatch) { + // TypePattern p = makeTypePattern(pattern); + // p = p.resolveBindings(makeTestScope(), null, false, false); + // checkPatternMatch(p, name, shouldMatch); + // } + // + // private void checkPatternMatch(TypePattern p, String name, boolean shouldMatch) { + // ResolvedType type = world.resolve(name); + // // System.out.println("type: " + type); + // boolean result = p.matchesStatically(type); + // String msg = "matches " + p + " to " + type + " expected "; + // if (shouldMatch) { + // assertTrue(msg + shouldMatch, result); + // } else { + // assertTrue(msg + shouldMatch, !result); + // } + // } + // + // public void testSerialization() throws IOException { + // String[] patterns = new String[] { "java.lang.Object", "java.lang.Object+", "java.lang.Integer", "int", "java..*", + // "java..util..*", "*.*.Object", "*", }; + // + // for (int i = 0, len = patterns.length; i < len; i++) { + // checkSerialization(patterns[i]); + // } + // } + // + // /** + // * Method checkSerialization. + // * + // * @param string + // */ + // private void checkSerialization(String string) throws IOException { + // TypePattern p = makeTypePattern(string); + // ByteArrayOutputStream bo = new ByteArrayOutputStream(); + // ConstantPoolSimulator cps = new ConstantPoolSimulator(); + // CompressingDataOutputStream out = new CompressingDataOutputStream(bo, cps); + // p.write(out); + // out.close(); + // + // ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); + // VersionedDataInputStream in = new VersionedDataInputStream(bi, cps); + // TypePattern newP = TypePattern.read(in, null); + // + // assertEquals("write/read", p, newP); + // } + +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/TestScope.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/TestScope.java new file mode 100644 index 000000000..e65bf2797 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/TestScope.java @@ -0,0 +1,32 @@ +/* ******************************************************************* + * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * PARC initial implementation + * ******************************************************************/ + + +package org.aspectj.weaver.patterns; + +import org.aspectj.weaver.*; +import org.aspectj.weaver.patterns.FormalBinding; +import org.aspectj.weaver.patterns.SimpleScope; + +public class TestScope extends SimpleScope { + + public TestScope( + World world, + FormalBinding[] bindings) + { + super(world, bindings); + } + + public TestScope(String[] formalTypes, String[] formalNames, World world) { + super(world, SimpleScope.makeFormalBindings(UnresolvedType.forNames(formalTypes), formalNames)); + } +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/ThisOrTargetTestCase.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/ThisOrTargetTestCase.java new file mode 100644 index 000000000..6c8d70be8 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/ThisOrTargetTestCase.java @@ -0,0 +1,163 @@ +/* ******************************************************************* + * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). + * 2005 Contributors + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * PARC initial implementation + * Adrian Colyer, runtime reflection extensions + * ******************************************************************/ + +package org.aspectj.weaver.patterns; + +import java.io.IOException; +import java.lang.reflect.Method; + +import junit.framework.TestCase; + +import org.aspectj.util.LangUtil; +import org.aspectj.weaver.tools.JoinPointMatch; +import org.aspectj.weaver.tools.PointcutExpression; +import org.aspectj.weaver.tools.PointcutParameter; +import org.aspectj.weaver.tools.PointcutParser; +import org.aspectj.weaver.tools.ShadowMatch; + +/** + * @author hugunin + * + * To change this generated comment edit the template variable "typecomment": Window>Preferences>Java>Templates. To enable + * and disable the creation of type comments go to Window>Preferences>Java>Code Generation. + */ +public class ThisOrTargetTestCase extends TestCase { + + private boolean needToSkip = false; + + /** this condition can occur on the build machine only, and is way too complex to fix right now... */ + private boolean needToSkipPointcutParserTests() { + if (!LangUtil.is15VMOrGreater()) { + return false; + } + try { + Class.forName("org.aspectj.weaver.reflect.Java15ReflectionBasedReferenceTypeDelegate", false, this.getClass() + .getClassLoader());// ReflectionBasedReferenceTypeDelegate.class.getClassLoader()); + } catch (ClassNotFoundException cnfEx) { + return true; + } + return false; + } + + protected void setUp() throws Exception { + super.setUp(); + needToSkip = needToSkipPointcutParserTests(); + } + + /** + * Constructor for PatternTestCase. + * + * @param name + */ + public ThisOrTargetTestCase(String name) { + super(name); + } + + public void testMatchJP() throws Exception { + if (needToSkip) { + return; + } + + PointcutParser parser = PointcutParser + .getPointcutParserSupportingAllPrimitivesAndUsingSpecifiedClassloaderForResolution(this.getClass().getClassLoader()); + PointcutExpression thisEx = parser.parsePointcutExpression("this(Exception)"); + PointcutExpression thisIOEx = parser.parsePointcutExpression("this(java.io.IOException)"); + + PointcutExpression targetEx = parser.parsePointcutExpression("target(Exception)"); + PointcutExpression targetIOEx = parser.parsePointcutExpression("target(java.io.IOException)"); + + Method toString = Object.class.getMethod("toString", new Class[0]); + + checkMatches(thisEx.matchesMethodCall(toString, toString), new Exception(), null, null); + checkNoMatch(thisIOEx.matchesMethodCall(toString, toString), new Exception(), null, null); + checkNoMatch(targetEx.matchesMethodCall(toString, toString), new Exception(), new Object(), null); + checkNoMatch(targetIOEx.matchesMethodCall(toString, toString), new Exception(), new Exception(), null); + + checkMatches(thisEx.matchesMethodCall(toString, toString), new IOException(), null, null); + checkMatches(thisIOEx.matchesMethodCall(toString, toString), new IOException(), null, null); + + checkNoMatch(thisEx.matchesMethodCall(toString, toString), new Object(), null, null); + checkNoMatch(thisIOEx.matchesMethodCall(toString, toString), new Exception(), null, null); + checkMatches(targetEx.matchesMethodCall(toString, toString), new Exception(), new Exception(), null); + checkNoMatch(targetIOEx.matchesMethodCall(toString, toString), new Exception(), new Exception(), null); + + checkMatches(targetIOEx.matchesMethodCall(toString, toString), new Exception(), new IOException(), null); + } + + public void testBinding() throws Exception { + if (needToSkip) { + return; + } + PointcutParser parser = PointcutParser + .getPointcutParserSupportingAllPrimitivesAndUsingSpecifiedClassloaderForResolution(this.getClass().getClassLoader()); + PointcutParameter ex = parser.createPointcutParameter("ex", Exception.class); + PointcutParameter ioEx = parser.createPointcutParameter("ioEx", IOException.class); + + PointcutExpression thisEx = parser.parsePointcutExpression("this(ex)", Exception.class, new PointcutParameter[] { ex }); + + PointcutExpression targetIOEx = parser.parsePointcutExpression("target(ioEx)", Exception.class, + new PointcutParameter[] { ioEx }); + + Method toString = Object.class.getMethod("toString", new Class[0]); + + ShadowMatch sMatch = thisEx.matchesMethodCall(toString, toString); + Exception exceptionParameter = new Exception(); + IOException ioExceptionParameter = new IOException(); + JoinPointMatch jpMatch = null; + jpMatch = sMatch.matchesJoinPoint(null, null, null);// 318899 + assertFalse(jpMatch.matches()); + jpMatch = sMatch.matchesJoinPoint(exceptionParameter, null, null); + assertTrue("should match", jpMatch.matches()); + PointcutParameter[] bindings = jpMatch.getParameterBindings(); + assertEquals("one binding", 1, bindings.length); + assertEquals("should be exceptionParameter", exceptionParameter, bindings[0].getBinding()); + assertEquals("ex", bindings[0].getName()); + + sMatch = targetIOEx.matchesMethodCall(toString, toString); + jpMatch = sMatch.matchesJoinPoint(exceptionParameter, ioExceptionParameter, null); + assertTrue("should match", jpMatch.matches()); + bindings = jpMatch.getParameterBindings(); + assertEquals("one binding", 1, bindings.length); + assertEquals("should be ioExceptionParameter", ioExceptionParameter, bindings[0].getBinding()); + assertEquals("ioEx", bindings[0].getName()); + + } + + private void checkMatches(ShadowMatch sMatch, Object thisObj, Object targetObj, Object[] args) { + assertTrue("match expected", sMatch.matchesJoinPoint(thisObj, targetObj, args).matches()); + } + + private void checkNoMatch(ShadowMatch sMatch, Object thisObj, Object targetObj, Object[] args) { + assertFalse("no match expected", sMatch.matchesJoinPoint(thisObj, targetObj, args).matches()); + } + + /** + * Method checkSerialization. + * + * @param string + */ + // private void checkSerialization(String string) throws IOException { + // Pointcut p = makePointcut(string); + // ByteArrayOutputStream bo = new ByteArrayOutputStream(); + // DataOutputStream out = new DataOutputStream(bo); + // p.write(out); + // out.close(); + // + // ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); + // DataInputStream in = new DataInputStream(bi); + // Pointcut newP = Pointcut.read(in, null); + // + // assertEquals("write/read", p, newP); + // } +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/TypePatternListTestCase.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/TypePatternListTestCase.java new file mode 100644 index 000000000..a141e2b0c --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/TypePatternListTestCase.java @@ -0,0 +1,171 @@ +/* ******************************************************************* + * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * PARC initial implementation + * ******************************************************************/ + +package org.aspectj.weaver.patterns; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Arrays; + +import org.aspectj.util.FuzzyBoolean; +import org.aspectj.weaver.CompressingDataOutputStream; +import org.aspectj.weaver.ResolvedType; +import org.aspectj.weaver.VersionedDataInputStream; +import org.aspectj.weaver.World; +import org.aspectj.weaver.reflect.ReflectionWorld; + +/** + * @author hugunin + * + * To change this generated comment edit the template variable "typecomment": Window>Preferences>Java>Templates. To enable + * and disable the creation of type comments go to Window>Preferences>Java>Code Generation. + */ +public class TypePatternListTestCase extends PatternsTestCase { + public World getWorld() { + return new ReflectionWorld(true, this.getClass().getClassLoader()); + } + + // XXX when instanceof matching works add tests for that here + + public void testMatch() { + + checkStaticMatch("()", new String[] {}, FuzzyBoolean.YES); + checkStaticMatch("()", new String[] { "java.lang.Object" }, FuzzyBoolean.NO); + + checkStaticMatch("(java.lang.Object)", new String[] { "java.lang.Object" }, FuzzyBoolean.YES); + + checkStaticMatch("(java.lang.String)", new String[] { "java.lang.Object" }, FuzzyBoolean.NO); + + checkStaticMatch("(java.lang.Object)", new String[] { "java.lang.String" }, FuzzyBoolean.NO); + + checkStaticMatch("()", new String[] { "java.lang.Object" }, FuzzyBoolean.NO); + + checkStaticMatch("(..)", new String[] {}, FuzzyBoolean.YES); + checkStaticMatch("(..)", new String[] { "int", "char" }, FuzzyBoolean.YES); + + checkStaticMatch("(int,..,int)", new String[] { "int", "int" }, FuzzyBoolean.YES); + + checkStaticMatch("(int,..)", new String[] {}, FuzzyBoolean.NO); + checkStaticMatch("(int,..)", new String[] { "int" }, FuzzyBoolean.YES); + + checkStaticMatch("(..,int,..)", new String[] { "int" }, FuzzyBoolean.YES); + + // these checks are taken from new/ExpandedDotPattern.java + stupidCheck("( .., .., ..)", new boolean[] { true, true, true, true, true }); + stupidCheck("( .., .., int)", new boolean[] { false, true, true, true, true }); + stupidCheck("( .., int, ..)", new boolean[] { false, true, true, true, true }); + stupidCheck("( .., int, int)", new boolean[] { false, false, true, true, true }); + stupidCheck("(int, .., ..)", new boolean[] { false, true, true, true, true }); + stupidCheck("(int, .., int)", new boolean[] { false, false, true, true, true }); + stupidCheck("(int, int, ..)", new boolean[] { false, false, true, true, true }); + stupidCheck("(int, int, int)", new boolean[] { false, false, false, true, false }); + + stupidCheck("( .., .., .., ..)", new boolean[] { true, true, true, true, true }); + stupidCheck("( .., .., .., int)", new boolean[] { false, true, true, true, true }); + stupidCheck("( .., .., int, ..)", new boolean[] { false, true, true, true, true }); + stupidCheck("( .., .., int, int)", new boolean[] { false, false, true, true, true }); + stupidCheck("( .., int, .., ..)", new boolean[] { false, true, true, true, true }); + stupidCheck("( .., int, .., int)", new boolean[] { false, false, true, true, true }); + stupidCheck("( .., int, int, ..)", new boolean[] { false, false, true, true, true }); + stupidCheck("( .., int, int, int)", new boolean[] { false, false, false, true, true }); + + stupidCheck("(int, .., .., ..)", new boolean[] { false, true, true, true, true }); + stupidCheck("(int, .., .., int)", new boolean[] { false, false, true, true, true }); + stupidCheck("(int, .., int, ..)", new boolean[] { false, false, true, true, true }); + stupidCheck("(int, .., int, int)", new boolean[] { false, false, false, true, true }); + stupidCheck("(int, int, .., ..)", new boolean[] { false, false, true, true, true }); + stupidCheck("(int, int, .., int)", new boolean[] { false, false, false, true, true }); + stupidCheck("(int, int, int, ..)", new boolean[] { false, false, false, true, true }); + stupidCheck("(int, int, int, int)", new boolean[] { false, false, false, false, true }); + } + + private TypePatternList makeArgumentsPattern(String pattern) { + return new PatternParser(pattern).parseArgumentsPattern(false); + } + + private void checkStaticMatch(String pattern, String[] names, FuzzyBoolean shouldMatchStatically) { + // We're only doing TypePattern.STATIC matching here because my intent was + // to test the wildcarding, and we don't do DYNAMIC matching on wildcarded things. + + TypePatternList p = makeArgumentsPattern(pattern); + ResolvedType[] types = new ResolvedType[names.length]; + for (int i = 0; i < names.length; i++) { + types[i] = world.resolve(names[i]); + } + + p.resolveBindings(makeTestScope(), Bindings.NONE, false, false); + // System.out.println("type: " + type); + FuzzyBoolean result = p.matches(types, TypePattern.STATIC); + String msg = "matches statically " + pattern + " to " + Arrays.asList(types); + assertEquals(msg, shouldMatchStatically, result); + } + + public static final String[] NO_STRINGS = new String[0]; + + private TestScope makeTestScope() { + TestScope scope = new TestScope(NO_STRINGS, NO_STRINGS, world); + return scope; + } + + public void stupidCheck(String pattern, boolean[] matches) { + TypePatternList p = makeArgumentsPattern(pattern); + p.resolveBindings(makeTestScope(), Bindings.NONE, false, false); + + int len = matches.length; + + for (int j = 0; j < len; j++) { + + ResolvedType[] types = new ResolvedType[j]; + for (int i = 0; i < j; i++) { + types[i] = world.resolve("int"); + } + + FuzzyBoolean result = p.matches(types, TypePattern.STATIC); + String msg = "matches statically " + pattern + " to " + Arrays.asList(types); + assertEquals(msg, FuzzyBoolean.fromBoolean(matches[j]), result); + } + } + + public void testSerialization() throws IOException { + String[] patterns = new String[] { "( .., .., .., int)", "( .., .., int, ..)", "( .., .., int, int)", + "( .., int, .., ..)", "( .., int, .., int)", "( .., int, int, ..)", "( .., int, int, int)", + + "(int, .., .., ..)", "(int, .., .., int)", "(int, .., int, ..)", "(int, .., int, int)", + "(int, int, .., ..)", "(int, int, .., int)", "(int, int, int, ..)", "(int, int, int, int)" }; + + for (int i = 0, len = patterns.length; i < len; i++) { + checkSerialization(patterns[i]); + } + } + + /** + * Method checkSerialization. + * + * @param string + */ + private void checkSerialization(String string) throws IOException { + TypePatternList p = makeArgumentsPattern(string); + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + ConstantPoolSimulator cps = new ConstantPoolSimulator(); + CompressingDataOutputStream out = new CompressingDataOutputStream(bo, cps); + p.write(out); + out.close(); + + ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); + VersionedDataInputStream in = new VersionedDataInputStream(bi, cps); + TypePatternList newP = TypePatternList.read(in, null); + + assertEquals("write/read", p, newP); + } + +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/TypePatternTestCase.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/TypePatternTestCase.java new file mode 100644 index 000000000..058bd2450 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/TypePatternTestCase.java @@ -0,0 +1,263 @@ +/* ******************************************************************* + * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * PARC initial implementation + * ******************************************************************/ + +package org.aspectj.weaver.patterns; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import org.aspectj.util.FuzzyBoolean; +import org.aspectj.weaver.CompressingDataOutputStream; +import org.aspectj.weaver.ResolvedType; +import org.aspectj.weaver.VersionedDataInputStream; +import org.aspectj.weaver.World; +import org.aspectj.weaver.reflect.ReflectionWorld; + +public class TypePatternTestCase extends PatternsTestCase { + + public World getWorld() { + return new ReflectionWorld(true, this.getClass().getClassLoader()); + } + + public void testStaticMatch() { + checkMatch("java.lang.Object", "java.lang.Object", true); + checkMatch("java.lang.Object+", "java.lang.Object", true); + checkMatch("java.lang.Object+", "java.lang.String", true); + checkMatch("java.lang.String+", "java.lang.Object", false); + checkMatch("java.lang.Integer", "java.lang.String", false); + + checkMatch("java.lang.Integer", "int", false); + + checkMatch("java.lang.Number+", "java.lang.Integer", true); + + checkMatch("java..*", "java.lang.Integer", true); + checkMatch("java..*", "java.lang.reflect.Modifier", true); + checkMatch("java..*", "int", false); + checkMatch("java..*", "javax.swing.Action", false); + checkMatch("java..*+", "javax.swing.Action", true); + + checkMatch("*.*.Object", "java.lang.Object", true); + checkMatch("*.Object", "java.lang.Object", false); + checkMatch("*..*", "java.lang.Object", true); + checkMatch("*..*", "int", false); + checkMatch("java..Modifier", "java.lang.reflect.Modifier", true); + checkMatch("java.lang.reflect.Mod..ifier", "java.lang.reflect.Modifier", false); + + checkMatch("java..reflect..Modifier", "java.lang.reflect.Modifier", true); + checkMatch("java..lang..Modifier", "java.lang.reflect.Modifier", true); + checkMatch("java..*..Modifier", "java.lang.reflect.Modifier", true); + checkMatch("java..*..*..Modifier", "java.lang.reflect.Modifier", true); + checkMatch("java..*..*..*..Modifier", "java.lang.reflect.Modifier", false); + // checkMatch("java..reflect..Modifier", "java.lang.reflect.Modxifier", false); + checkMatch("ja*va..Modifier", "java.lang.reflect.Modifier", true); + checkMatch("java..*..Mod*ifier", "java.lang.reflect.Modifier", true); + + } + + // three levels: + // 0. defined in current compilation unit, or imported by name + // 1. defined in current package/type/whatever + // 2. defined in package imported by * + /** + * We've decided not to test this here, but rather in any compilers + */ + public void testImportResolve() { + // checkIllegalImportResolution("List", new String[] { "java.util", "java.awt", }, + // ZERO_STRINGS); + + } + + // Assumption for bcweaver: Already resolved type patterns with no *s or ..'s into exact type + // patterns. Exact type patterns don't have import lists. non-exact-type pattens don't + // care about precedence, so the current package can be included with all the other packages, + // and we don't care about compilation units, and we don't care about ordering. + + // only giving this wild-type patterns + public void testImportMatch() { + + checkImportMatch("*List", new String[] { "java.awt.", }, ZERO_STRINGS, "java.awt.List", true); + checkImportMatch("*List", new String[] { "java.awt.", }, ZERO_STRINGS, "java.awt.List", true); + checkImportMatch("*List", new String[] { "java.awt.", }, ZERO_STRINGS, "java.util.List", false); + checkImportMatch("*List", new String[] { "java.util.", }, ZERO_STRINGS, "java.awt.List", false); + checkImportMatch("*List", new String[] { "java.util.", }, ZERO_STRINGS, "java.util.List", true); + + checkImportMatch("*List", ZERO_STRINGS, new String[] { "java.awt.List", }, "java.awt.List", true); + + checkImportMatch("awt.*List", ZERO_STRINGS, new String[] { "java.awt.List", }, "java.awt.List", false); + checkImportMatch("*Foo", ZERO_STRINGS, new String[] { "java.awt.List", }, "java.awt.List", false); + + checkImportMatch("*List", new String[] { "java.util.", "java.awt.", }, ZERO_STRINGS, "java.util.List", true); + checkImportMatch("*List", new String[] { "java.util.", "java.awt.", }, ZERO_STRINGS, "java.awt.List", true); + + checkImportMatch("*..List", new String[] { "java.util." }, ZERO_STRINGS, "java.util.List", true); + checkImportMatch("*..List", new String[] { "java.util." }, ZERO_STRINGS, "java.awt.List", true); + + } + + public void testImportMatchWithInners() { + // checkImportMatch("*Entry", new String[] { "java.util.", "java.util.Map$" }, ZERO_STRINGS, "java.util.Map$Entry", true); + // + // checkImportMatch("java.util.Map.*Entry", ZERO_STRINGS, ZERO_STRINGS, "java.util.Map$Entry", true); + // + // checkImportMatch("*Entry", new String[] { "java.util.", }, ZERO_STRINGS, "java.util.Map$Entry", false); + // + // checkImportMatch("*.Entry", new String[] { "java.util.", }, ZERO_STRINGS, "java.util.Map$Entry", true); + // + // checkImportMatch("Map.*", new String[] { "java.util.", }, ZERO_STRINGS, "java.util.Map$Entry", true); + + checkImportMatch("Map.*", ZERO_STRINGS, new String[] { "java.util.Map" }, "java.util.Map$Entry", true); + } + + private void checkImportMatch(String wildPattern, String[] importedPackages, String[] importedNames, String matchName, + boolean shouldMatch) { + WildTypePattern p = makeResolvedWildTypePattern(wildPattern, importedPackages, importedNames); + checkPatternMatch(p, matchName, shouldMatch); + } + + private WildTypePattern makeResolvedWildTypePattern(String wildPattern, String[] importedPackages, String[] importedNames) { + WildTypePattern unresolved = (WildTypePattern) new PatternParser(wildPattern).parseTypePattern(); + + WildTypePattern resolved = resolve(unresolved, importedPackages, importedNames); + return resolved; + + } + + private WildTypePattern resolve(WildTypePattern unresolved, String[] importedPrefixes, String[] importedNames) { + + TestScope scope = makeTestScope(); + scope.setImportedPrefixes(importedPrefixes); + scope.setImportedNames(importedNames); + return (WildTypePattern) unresolved.resolveBindings(scope, Bindings.NONE, false, false); + } + + public static final String[] ZERO_STRINGS = new String[0]; + + public void testInstanceofMatch() { + + checkInstanceofMatch("java.lang.Object", "java.lang.Object", FuzzyBoolean.YES); + + checkIllegalInstanceofMatch("java.lang.Object+", "java.lang.Object"); + checkIllegalInstanceofMatch("java.lang.Object+", "java.lang.String"); + checkIllegalInstanceofMatch("java.lang.String+", "java.lang.Object"); + checkIllegalInstanceofMatch("java.lang.*", "java.lang.Object"); + checkInstanceofMatch("java.lang.Integer", "java.lang.String", FuzzyBoolean.NO); + + checkInstanceofMatch("java.lang.Number", "java.lang.Integer", FuzzyBoolean.YES); + checkInstanceofMatch("java.lang.Integer", "java.lang.Number", FuzzyBoolean.MAYBE); + + checkIllegalInstanceofMatch("java..Integer", "java.lang.Integer"); + + checkInstanceofMatch("*", "java.lang.Integer", FuzzyBoolean.YES); + + } + + public void testArrayMatch() { + checkMatch("*[][]", "java.lang.Object", false); + checkMatch("*[]", "java.lang.Object[]", true); + checkMatch("*[][]", "java.lang.Object[][]", true); + checkMatch("java.lang.Object+", "java.lang.Object[]", true); + checkMatch("java.lang.Object[]", "java.lang.Object", false); + checkMatch("java.lang.Object[]", "java.lang.Object[]", true); + checkMatch("java.lang.Object[][]", "java.lang.Object[][]", true); + checkMatch("java.lang.String[]", "java.lang.Object", false); + checkMatch("java.lang.String[]", "java.lang.Object[]", false); + checkMatch("java.lang.String[][]", "java.lang.Object[][]", false); + checkMatch("java.lang.Object+[]", "java.lang.String[][]", true); + checkMatch("java.lang.Object+[]", "java.lang.String[]", true); + checkMatch("java.lang.Object+[]", "int[][]", true); + checkMatch("java.lang.Object+[]", "int[]", false); + } + + private void checkIllegalInstanceofMatch(String pattern, String name) { + try { + TypePattern p = makeTypePattern(pattern); + ResolvedType type = world.resolve(name); + p.matchesInstanceof(type); + } catch (Throwable e) { + return; + } + assertTrue("matching " + pattern + " with " + name + " should fail", false); + } + + private void checkInstanceofMatch(String pattern, String name, FuzzyBoolean shouldMatch) { + TypePattern p = makeTypePattern(pattern); + ResolvedType type = world.resolve(name); + + p = p.resolveBindings(makeTestScope(), null, false, false); + + // System.out.println("type: " + p); + FuzzyBoolean result = p.matchesInstanceof(type); + String msg = "matches " + pattern + " to " + type; + assertEquals(msg, shouldMatch, result); + } + + private TestScope makeTestScope() { + TestScope scope = new TestScope(ZERO_STRINGS, ZERO_STRINGS, world); + return scope; + } + + private TypePattern makeTypePattern(String pattern) { + PatternParser pp = new PatternParser(pattern); + TypePattern tp = pp.parseSingleTypePattern(); + pp.checkEof(); + return tp; + } + + private void checkMatch(String pattern, String name, boolean shouldMatch) { + TypePattern p = makeTypePattern(pattern); + p = p.resolveBindings(makeTestScope(), null, false, false); + checkPatternMatch(p, name, shouldMatch); + } + + private void checkPatternMatch(TypePattern p, String name, boolean shouldMatch) { + ResolvedType type = world.resolve(name); + // System.out.println("type: " + type); + boolean result = p.matchesStatically(type); + String msg = "matches " + p + " to " + type + " expected "; + if (shouldMatch) { + assertTrue(msg + shouldMatch, result); + } else { + assertTrue(msg + shouldMatch, !result); + } + } + + public void testSerialization() throws IOException { + String[] patterns = new String[] { "java.lang.Object", "java.lang.Object+", "java.lang.Integer", "int", "java..*", + "java..util..*", "*.*.Object", "*", }; + + for (int i = 0, len = patterns.length; i < len; i++) { + checkSerialization(patterns[i]); + } + } + + /** + * Method checkSerialization. + * + * @param string + */ + private void checkSerialization(String string) throws IOException { + TypePattern p = makeTypePattern(string); + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + ConstantPoolSimulator cps = new ConstantPoolSimulator(); + CompressingDataOutputStream out = new CompressingDataOutputStream(bo, cps); + p.write(out); + out.close(); + + ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); + VersionedDataInputStream in = new VersionedDataInputStream(bi, cps); + TypePattern newP = TypePattern.read(in, null); + + assertEquals("write/read", p, newP); + } + +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/VisitorTestCase.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/VisitorTestCase.java new file mode 100644 index 000000000..7fd131528 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/VisitorTestCase.java @@ -0,0 +1,76 @@ +/******************************************************************************* + * Copyright (c) 2005 Contributors. + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://eclipse.org/legal/epl-v10.html + * + * Contributors: + * Alexandre Vasseur initial implementation + *******************************************************************************/ +package org.aspectj.weaver.patterns; + +import junit.framework.TestCase; + +import java.util.HashSet; +import java.util.Set; +import java.io.LineNumberReader; +import java.io.FileReader; + +import org.aspectj.weaver.patterns.DumpPointcutVisitor; +import org.aspectj.weaver.patterns.PatternParser; +import org.aspectj.weaver.patterns.TypePattern; + +/** + * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> + */ +public class VisitorTestCase extends TestCase { + + private Set<String> pointcuts = new HashSet<>(); + private Set<String> typePatterns = new HashSet<>(); + + protected void setUp() throws Exception { + super.setUp(); + LineNumberReader rp = new LineNumberReader(new FileReader("../weaver/testdata/visitor.pointcuts.txt")); + feed(rp, pointcuts); + rp.close(); + LineNumberReader rt = new LineNumberReader(new FileReader("../weaver/testdata/visitor.typepatterns.txt")); + feed(rt, typePatterns); + rt.close(); + } + + private void feed(LineNumberReader r, Set<String> set) throws Exception { + for (String line = r.readLine(); line != null; line = r.readLine()) { + set.add(line); + } + } + + public void testPointcuts() { + if (pointcuts.isEmpty()) { + fail("Empty pointcuts file!"); + } + for (String pointcut: pointcuts) { + try { + DumpPointcutVisitor.check(pointcut); + } catch (Throwable t) { + t.printStackTrace(); + fail("Failed on '"+pointcut+"': " +t.toString()); + } + } + } + + public void testTypePatterns() { + if (typePatterns.isEmpty()) { + fail("Empty typePatterns file!"); + } + for (String tp: typePatterns) { + try { + TypePattern p = new PatternParser(tp).parseTypePattern(); + DumpPointcutVisitor.check(p, true); + } catch (Throwable t) { + fail("Failed on '"+tp+"': " +t.toString()); + } + } + } +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/WithinTestCase.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/WithinTestCase.java new file mode 100644 index 000000000..b8138b067 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/WithinTestCase.java @@ -0,0 +1,121 @@ +/* ******************************************************************* + * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * PARC initial implementation + * ******************************************************************/ + +package org.aspectj.weaver.patterns; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import org.aspectj.util.FuzzyBoolean; +import org.aspectj.weaver.CompressingDataOutputStream; +import org.aspectj.weaver.IntMap; +import org.aspectj.weaver.Shadow; +import org.aspectj.weaver.TestShadow; +import org.aspectj.weaver.TestUtils; +import org.aspectj.weaver.UnresolvedType; +import org.aspectj.weaver.VersionedDataInputStream; +import org.aspectj.weaver.World; +import org.aspectj.weaver.reflect.ReflectionWorld; + +public class WithinTestCase extends PatternsTestCase { + + public World getWorld() { + return new ReflectionWorld(true, this.getClass().getClassLoader()); + } + + public void testMatch() throws IOException { + Shadow getOutFromArrayList = new TestShadow(Shadow.FieldGet, TestUtils + .fieldFromString("java.io.PrintStream java.lang.System.out"), UnresolvedType.forName("java.util.ArrayList"), world); + + checkMatch(makePointcut("within(*)"), getOutFromArrayList, FuzzyBoolean.YES); + checkMatch(makePointcut("within(java.util.*)"), getOutFromArrayList, FuzzyBoolean.YES); + checkMatch(makePointcut("within(java.lang.*)"), getOutFromArrayList, FuzzyBoolean.NO); + checkMatch(makePointcut("within(java.util.List+)"), getOutFromArrayList, FuzzyBoolean.YES); + checkMatch(makePointcut("within(java.uti*.List+)"), getOutFromArrayList, FuzzyBoolean.YES); + checkMatch(makePointcut("within(java.uti*..*)"), getOutFromArrayList, FuzzyBoolean.YES); + checkMatch(makePointcut("within(java.util.*List)"), getOutFromArrayList, FuzzyBoolean.YES); + checkMatch(makePointcut("within(java.util.List*)"), getOutFromArrayList, FuzzyBoolean.NO); + + Shadow getOutFromEntry = new TestShadow(Shadow.FieldGet, TestUtils + .fieldFromString("java.io.PrintStream java.lang.System.out"), UnresolvedType.forName("java.util.Map$Entry"), world); + + checkMatch(makePointcut("within(*)"), getOutFromEntry, FuzzyBoolean.YES); + checkMatch(makePointcut("within(java.util.*)"), getOutFromEntry, FuzzyBoolean.YES); + checkMatch(makePointcut("within(java.util.Map.*)"), getOutFromEntry, FuzzyBoolean.YES); + checkMatch(makePointcut("within(java.util..*)"), getOutFromEntry, FuzzyBoolean.YES); + checkMatch(makePointcut("within(java.util.Map..*)"), getOutFromEntry, FuzzyBoolean.YES); + checkMatch(makePointcut("within(java.lang.*)"), getOutFromEntry, FuzzyBoolean.NO); + checkMatch(makePointcut("within(java.util.List+)"), getOutFromEntry, FuzzyBoolean.NO); + checkMatch(makePointcut("within(java.util.Map+)"), getOutFromEntry, FuzzyBoolean.YES); + checkMatch(makePointcut("within(java.lang.Object+)"), getOutFromEntry, FuzzyBoolean.YES); + + // this is something we should in type patterns tests + // checkMatch(makePointcut("within(*List)"), getOut, FuzzyBoolean.NO); + + } + + // public void testMatchJP() { + // Factory f = new Factory("WithinTestCase.java",WithinTestCase.class); + // + // JoinPoint.StaticPart inString = f.makeSJP(JoinPoint.CONSTRUCTOR_EXECUTION,f.makeConstructorSig(0,String.class,new Class[] + // {String.class},new String[]{"s"},new Class[0]),1); + // JoinPoint.StaticPart inObject = f.makeSJP(JoinPoint.CONSTRUCTOR_EXECUTION,f.makeConstructorSig(0,Object.class,new Class[] + // {},new String[]{},new Class[0]),1); + // + // Pointcut withinString = new PatternParser("within(String)").parsePointcut().resolve(); + // Pointcut withinObject = new PatternParser("within(Object)").parsePointcut().resolve(); + // Pointcut withinObjectPlus = new PatternParser("within(Object+)").parsePointcut().resolve(); + // + // checkMatches(withinString,inString,FuzzyBoolean.YES); + // checkMatches(withinString,inObject,FuzzyBoolean.NO); + // checkMatches(withinObject,inString,FuzzyBoolean.NO); + // checkMatches(withinObject,inObject, FuzzyBoolean.YES); + // checkMatches(withinObjectPlus,inString,FuzzyBoolean.YES); + // checkMatches(withinObjectPlus,inObject,FuzzyBoolean.YES); + // } + // + // private void checkMatches(Pointcut p, JoinPoint.StaticPart jpsp, FuzzyBoolean expected) { + // assertEquals(expected,p.match(null,jpsp)); + // } + // + public Pointcut makePointcut(String pattern) { + Pointcut pointcut0 = Pointcut.fromString(pattern); + + Bindings bindingTable = new Bindings(0); + IScope scope = new SimpleScope(world, FormalBinding.NONE); + + pointcut0.resolveBindings(scope, bindingTable); + Pointcut pointcut1 = pointcut0; + return pointcut1.concretize1(null, null, new IntMap()); + } + + private void checkMatch(Pointcut p, Shadow s, FuzzyBoolean shouldMatch) throws IOException { + FuzzyBoolean doesMatch = p.match(s); + assertEquals(p + " matches " + s, shouldMatch, doesMatch); + checkSerialization(p); + } + + private void checkSerialization(Pointcut p) throws IOException { + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + ConstantPoolSimulator cps = new ConstantPoolSimulator(); + CompressingDataOutputStream out = new CompressingDataOutputStream(bo, cps); + p.write(out); + out.close(); + + ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); + VersionedDataInputStream in = new VersionedDataInputStream(bi, cps); + Pointcut newP = Pointcut.read(in, null); + + assertEquals("write/read", p, newP); + } + +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/reflect/ReflectionWorldBasicTest.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/reflect/ReflectionWorldBasicTest.java new file mode 100644 index 000000000..7325bcfc9 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/reflect/ReflectionWorldBasicTest.java @@ -0,0 +1,27 @@ +/* ******************************************************************* + * Copyright (c) 2002-2008 Contributors + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Andy Clement + * ******************************************************************/ +package org.aspectj.weaver.reflect; + +import org.aspectj.weaver.CommonWorldTests; +import org.aspectj.weaver.World; + +public class ReflectionWorldBasicTest extends CommonWorldTests { + + protected boolean getSupportsAutoboxing() { + return false; + } + + protected World getWorld() { + return new ReflectionWorld(true, getClass().getClassLoader()); + } + +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/reflect/ReflectionWorldSpecificTest.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/reflect/ReflectionWorldSpecificTest.java new file mode 100644 index 000000000..1d3083602 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/reflect/ReflectionWorldSpecificTest.java @@ -0,0 +1,42 @@ +/* ******************************************************************* + * Copyright (c) 2005 Contributors. + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://eclipse.org/legal/epl-v10.html + * + * Contributors: + * Adrian Colyer Initial implementation + * ******************************************************************/ +package org.aspectj.weaver.reflect; + +import junit.framework.TestCase; + +import org.aspectj.weaver.ResolvedType; +import org.aspectj.weaver.UnresolvedType; +import org.aspectj.weaver.World; + +public class ReflectionWorldSpecificTest extends TestCase { + + public void testDelegateCreation() { + World world = new ReflectionWorld(true, getClass().getClassLoader()); + ResolvedType rt = world.resolve("java.lang.Object"); + assertNotNull(rt); + assertEquals("Ljava/lang/Object;", rt.getSignature()); + } + + public void testArrayTypes() { + IReflectionWorld world = new ReflectionWorld(true, getClass().getClassLoader()); + String[] strArray = new String[1]; + ResolvedType rt = world.resolve(strArray.getClass()); + assertTrue(rt.isArray()); + } + + public void testPrimitiveTypes() { + IReflectionWorld world = new ReflectionWorld(true, getClass().getClassLoader()); + assertEquals("int", UnresolvedType.INT, world.resolve(int.class)); + assertEquals("void", UnresolvedType.VOID, world.resolve(void.class)); + } + +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/testcode/Aspect.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/testcode/Aspect.java new file mode 100644 index 000000000..95140c792 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/testcode/Aspect.java @@ -0,0 +1,21 @@ +package org.aspectj.weaver.testcode; + +public class Aspect { + + public static void ignoreMe() { + } + + public static void before_method_call() { + System.out.println("before"); + } + + public static void afterReturning_method_call() { + System.out.println("afterReturning"); + } + + public static void afterThrowing_method_execution(Throwable t) { + System.out.println("afterThrowing " + t); + t.printStackTrace(); + } + +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/testcode/Base.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/testcode/Base.java new file mode 100644 index 000000000..e580242be --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/testcode/Base.java @@ -0,0 +1,28 @@ +package org.aspectj.weaver.testcode; + +public class Base { + + public static void onlyBase() { + } + + public static void both() { + } + + public void onlyBaseNonStatic() { + } + + public void bothNonStatic() { + } + + public int onlyBase; + public int both; + + public Base() { + } + + public Base(int i) { + } + + public void m() throws CloneNotSupportedException { + } +} diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/testcode/Derived.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/testcode/Derived.java new file mode 100644 index 000000000..5d616d79d --- /dev/null +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/testcode/Derived.java @@ -0,0 +1,28 @@ +package org.aspectj.weaver.testcode; + +import java.io.IOException; + +public class Derived extends Base { + + public static void onlyDerived() throws IOException, CloneNotSupportedException { + } + + public static void both() { + } + + public void onlyDerivedNonStatic() { + } + + public void bothNonStatic() { + } + + public int onlyDerived; + public int both; + + public Derived() { + } + + public void m() { + } + +} diff --git a/org.aspectj.matcher/src/test/java/testdata/AnnotatedClass.java b/org.aspectj.matcher/src/test/java/testdata/AnnotatedClass.java new file mode 100644 index 000000000..80dbda413 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/testdata/AnnotatedClass.java @@ -0,0 +1,11 @@ +package testdata; + +@SomeAnnotation +public class AnnotatedClass { + + @MethodLevelAnnotation + public void annotatedMethod() { } + + public void nonAnnotatedMethod() { + } +} diff --git a/org.aspectj.matcher/src/test/java/testdata/MethodLevelAnnotation.java b/org.aspectj.matcher/src/test/java/testdata/MethodLevelAnnotation.java new file mode 100644 index 000000000..2f46dd8ab --- /dev/null +++ b/org.aspectj.matcher/src/test/java/testdata/MethodLevelAnnotation.java @@ -0,0 +1,5 @@ +package testdata; +import java.lang.annotation.*; + +@Retention(RetentionPolicy.RUNTIME) +@interface MethodLevelAnnotation {} diff --git a/org.aspectj.matcher/src/test/java/testdata/SomeAnnotation.java b/org.aspectj.matcher/src/test/java/testdata/SomeAnnotation.java new file mode 100644 index 000000000..25a4991d6 --- /dev/null +++ b/org.aspectj.matcher/src/test/java/testdata/SomeAnnotation.java @@ -0,0 +1,6 @@ +package testdata; + +import java.lang.annotation.*; + +@Retention(RetentionPolicy.RUNTIME) +@interface SomeAnnotation {} |