aboutsummaryrefslogtreecommitdiffstats
path: root/org.aspectj.matcher/src/org/aspectj/weaver/patterns/PointcutRewriter.java
blob: 81ff33babfc1eaef589d6abbab725b56d0a1b9a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
/* *******************************************************************
 * 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.SortedSet;
import java.util.TreeSet;

import org.aspectj.weaver.Shadow;
import org.aspectj.weaver.patterns.Pointcut.MatchesNothingPointcut;

/**
 * Performs term rewriting for pointcut expressions.
 * 
 * @author colyer
 * @author clement
 */
public class PointcutRewriter {

	private static final boolean WATCH_PROGRESS = false;

	/**
	 * Set forcerewrite if you want to override the checking for something already in DNF (useful for some testing) Repeated
	 * processing of something already in DNF is expensive (it ends up being done for every pointcut on every incremental compile) -
	 * so let's not do it if we don't have to. See pr113257
	 */
	public Pointcut rewrite(Pointcut pc, boolean forceRewrite) {
		Pointcut result = pc;// checkPC(result);
		if (forceRewrite || !isDNF(pc)) {
			if (WATCH_PROGRESS) {
				System.out.println("Initial pointcut is        ==> " + format(pc));
			}
			result = distributeNot(result);// checkPC(result);
			if (WATCH_PROGRESS) {
				System.out.println("Distributing NOT gives     ==> " + format(result));
			}
			result = pullUpDisjunctions(result);// checkPC(result);
			if (WATCH_PROGRESS) {
				System.out.println("Pull up disjunctions gives ==> " + format(result));
			}
		} else {
			if (WATCH_PROGRESS) {
				System.out.println("Not distributing NOTs or pulling up disjunctions, already DNF ==> " + format(pc));
			}
		}
		result = simplifyAnds(result); // checkPC(result);
		if (WATCH_PROGRESS) {
			System.out.println("Simplifying ANDs gives     ==> " + format(result));
		}
		result = removeNothings(result); // checkPC(result);
		if (WATCH_PROGRESS) {
			System.out.println("Removing nothings gives    ==> " + format(result));
		}
		result = sortOrs(result); // checkPC(result);
		if (WATCH_PROGRESS) {
			System.out.println("Sorting ORs gives          ==> " + format(result));
		}
		return result;
	}

	// /**
	// * Checks pointcuts - used for debugging.
	// * - this variant checks if the context has been lost, since
	// * that can indicate an NPE will happen later reporting a message (pr162657).
	// * Not finished, but helped locate the problem ;)
	// */
	// private void checkPC(Pointcut pc) {
	// if (isNot(pc)) {
	// NotPointcut npc = (NotPointcut)pc;
	// checkPC(npc.getNegatedPointcut());
	// if (npc.getSourceContext()==null) {
	// System.out.println("Lost context for "+npc);
	// throw new RuntimeException("Lost context");
	// }
	// } else if (isOr(pc)) {
	// OrPointcut opc = (OrPointcut)pc;
	// checkPC(opc.getLeft());
	// checkPC(opc.getRight());
	// if (opc.getSourceContext()==null) {
	// System.out.println("Lost context for "+opc);
	// throw new RuntimeException("Lost context");
	// }
	// } else if (isAnd(pc)) {
	// AndPointcut apc = (AndPointcut)pc;
	// checkPC(apc.getLeft());
	// checkPC(apc.getRight());
	// if (apc.getSourceContext()==null) {
	// System.out.println("Lost context for "+apc);
	// throw new RuntimeException("Lost context");
	// }
	// } else {
	// if (pc.getSourceContext()==null) {
	// System.out.println("Lost context for "+pc);
	// throw new RuntimeException("Lost context");
	// }
	// }
	// }

	public Pointcut rewrite(Pointcut pc) {
		return rewrite(pc, false);
	}

	/**
	 * Check if a pointcut is in DNF - if it is then it should be lots of 'ORs' up the top with 'ANDs' beneath them.
	 */
	private boolean isDNF(Pointcut pc) {
		return isDNFHelper(pc, true);
	}

	/**
	 * Helper function for determining DNFness. Records when we have crossed the point of allowing ORs.
	 */
	private boolean isDNFHelper(Pointcut pc, boolean canStillHaveOrs) {
		if (isAnd(pc)) {
			AndPointcut ap = (AndPointcut) pc;
			return isDNFHelper(ap.getLeft(), false) && isDNFHelper(ap.getRight(), false);
		} else if (isOr(pc)) {
			if (!canStillHaveOrs) {
				return false;
			}
			OrPointcut op = (OrPointcut) pc;
			return isDNFHelper(op.getLeft(), true) && isDNFHelper(op.getRight(), true);
		} else if (isNot(pc)) {
			return isDNFHelper(((NotPointcut) pc).getNegatedPointcut(), canStillHaveOrs);
		} else {
			return true;
		}
	}

	/**
	 * Allows formatting of the output pointcut for debugging...
	 */
	public static String format(Pointcut p) {
		String s = p.toString();
		// Regex param needs '(' and '*' changing to '.'
		// s = s.replaceAll("persingleton.pkg1.monitoring.ErrorMonitoring.","M");
		// s = s.replaceAll("args.BindingTypePattern.java.lang.Throwable, 0.","Z");
		// s = s.replaceAll("within.pkg1.monitoring.DoMonitorErrors+.","X");
		// s=s.replaceAll("within.pkg1.monitoring....","Y");
		// s=s.replaceAll("if.true.","N");
		return s;
	}

	// !!X => X
	// !(X && Y) => !X || !Y
	// !(X || Y) => !X && !Y
	private Pointcut distributeNot(Pointcut pc) {
		if (isNot(pc)) {
			NotPointcut npc = (NotPointcut) pc;
			Pointcut notBody = distributeNot(npc.getNegatedPointcut());
			if (isNot(notBody)) {
				// !!X => X
				return ((NotPointcut) notBody).getNegatedPointcut();
			} else if (isAnd(notBody)) {
				// !(X && Y) => !X || !Y
				AndPointcut apc = (AndPointcut) notBody;
				Pointcut newLeft = distributeNot(new NotPointcut(apc.getLeft(), npc.getStart()));
				Pointcut newRight = distributeNot(new NotPointcut(apc.getRight(), npc.getStart()));
				return new OrPointcut(newLeft, newRight);
			} else if (isOr(notBody)) {
				// !(X || Y) => !X && !Y
				OrPointcut opc = (OrPointcut) notBody;
				Pointcut newLeft = distributeNot(new NotPointcut(opc.getLeft(), npc.getStart()));
				Pointcut newRight = distributeNot(new NotPointcut(opc.getRight(), npc.getStart()));
				return new AndPointcut(newLeft, newRight);
			} else {
				return new NotPointcut(notBody, npc.getStart());
			}
		} else if (isAnd(pc)) {
			AndPointcut apc = (AndPointcut) pc;
			Pointcut left = distributeNot(apc.getLeft());
			Pointcut right = distributeNot(apc.getRight());
			return new AndPointcut(left, right);
		} else if (isOr(pc)) {
			OrPointcut opc = (OrPointcut) pc;
			Pointcut left = distributeNot(opc.getLeft());
			Pointcut right = distributeNot(opc.getRight());
			return new OrPointcut(left, right);
		} else {
			return pc;
		}
	}

	// A && (B || C) => (A && B) || (A && C)
	// (A || B) && C => (A && C) || (B && C)
	private Pointcut pullUpDisjunctions(Pointcut pc) {
		if (isNot(pc)) {
			NotPointcut npc = (NotPointcut) pc;
			return new NotPointcut(pullUpDisjunctions(npc.getNegatedPointcut()));
		} else if (isAnd(pc)) {
			AndPointcut apc = (AndPointcut) pc;
			// dive into left and right here...
			Pointcut left = pullUpDisjunctions(apc.getLeft());
			Pointcut right = pullUpDisjunctions(apc.getRight());
			if (isOr(left) && !isOr(right)) {
				// (A || B) && C => (A && C) || (B && C)
				Pointcut leftLeft = ((OrPointcut) left).getLeft();
				Pointcut leftRight = ((OrPointcut) left).getRight();
				return pullUpDisjunctions(new OrPointcut(new AndPointcut(leftLeft, right), new AndPointcut(leftRight, right)));
			} else if (isOr(right) && !isOr(left)) {
				// A && (B || C) => (A && B) || (A && C)
				Pointcut rightLeft = ((OrPointcut) right).getLeft();
				Pointcut rightRight = ((OrPointcut) right).getRight();
				return pullUpDisjunctions(new OrPointcut(new AndPointcut(left, rightLeft), new AndPointcut(left, rightRight)));
			} else if (isOr(right) && isOr(left)) {
				// (A || B) && (C || D) => (A && C) || (A && D) || (B && C) || (B && D)
				Pointcut A = pullUpDisjunctions(((OrPointcut) left).getLeft());
				Pointcut B = pullUpDisjunctions(((OrPointcut) left).getRight());
				Pointcut C = pullUpDisjunctions(((OrPointcut) right).getLeft());
				Pointcut D = pullUpDisjunctions(((OrPointcut) right).getRight());
				Pointcut newLeft = new OrPointcut(new AndPointcut(A, C), new AndPointcut(A, D));
				Pointcut newRight = new OrPointcut(new AndPointcut(B, C), new AndPointcut(B, D));
				return pullUpDisjunctions(new OrPointcut(newLeft, newRight));
			} else {
				return new AndPointcut(left, right);
			}
		} else if (isOr(pc)) {
			OrPointcut opc = (OrPointcut) pc;
			return new OrPointcut(pullUpDisjunctions(opc.getLeft()), pullUpDisjunctions(opc.getRight()));
		} else {
			return pc;
		}
	}

	/**
	 * Returns a NOTted form of the pointcut p - we cope with already NOTted pointcuts.
	 */
	public Pointcut not(Pointcut p) {
		if (isNot(p)) {
			return ((NotPointcut) p).getNegatedPointcut();
		}
		return new NotPointcut(p);
	}

	/**
	 * Passed an array of pointcuts, returns an AND tree with them in.
	 */
	public Pointcut createAndsFor(Pointcut[] ps) {
		if (ps.length == 1) {
			return ps[0]; // dumb case
		}
		if (ps.length == 2) { // recursion exit case
			return new AndPointcut(ps[0], ps[1]);
		}
		// otherwise ...
		Pointcut[] subset = new Pointcut[ps.length - 1];
		for (int i = 1; i < ps.length; i++) {
			subset[i - 1] = ps[i];
		}
		return new AndPointcut(ps[0], createAndsFor(subset));
	}

	// NOT: execution(* TP.*(..)) => within(TP) && execution(* *(..))
	// since this breaks when the pattern matches an interface
	// NOT: withincode(* TP.*(..)) => within(TP) && withincode(* *(..))
	// since this is not correct when an aspect makes an ITD
	// private Pointcut splitOutWithins(Pointcut pc) {
	// if (isExecution(pc)) {
	// KindedPointcut kpc = (KindedPointcut) pc;
	// SignaturePattern sp = kpc.signature;
	// TypePattern within = sp.getDeclaringType();
	// if (isAnyType(within)) return pc;
	// SignaturePattern simplified = removeDeclaringTypePattern(sp);
	// return new AndPointcut(new WithinPointcut(within),
	// new KindedPointcut(kpc.kind,simplified));
	// } else if (isNot(pc)) {
	// return new NotPointcut(splitOutWithins(((NotPointcut)pc).getNegatedPointcut()));
	// } else if (isAnd(pc)) {
	// AndPointcut apc = (AndPointcut) pc;
	// return new AndPointcut(splitOutWithins(apc.getLeft()),
	// splitOutWithins(apc.getRight()));
	// } else if (isOr(pc)) {
	// OrPointcut opc = (OrPointcut) pc;
	// return new OrPointcut(splitOutWithins(opc.getLeft()),
	// splitOutWithins(opc.getRight()));
	// } else {
	// return pc;
	// }
	// }

	// private SignaturePattern removeDeclaringTypePattern(SignaturePattern sp) {
	// return new SignaturePattern(
	// sp.getKind(),
	// sp.getModifiers(),
	// sp.getReturnType(),
	// TypePattern.ANY,
	// sp.getName(),
	// sp.getParameterTypes(),
	// sp.getThrowsPattern(),
	// sp.getAnnotationPattern()
	// );
	// }

	// this finds the root of each && tree and then aggregates all of the branches
	// into a sorted set:
	// - duplicates are removed
	// - A && !A is replaced by a matchesNothingPointcut
	// - the kind(s) matched by the set are evaluated
	// - elements are sorted by evaluation complexity
	// - the result is written out with the least expensive branch leftmost
	private Pointcut simplifyAnds(Pointcut pc) {
		if (isNot(pc)) {
			NotPointcut npc = (NotPointcut) pc;
			Pointcut notBody = npc.getNegatedPointcut();
			if (isNot(notBody)) {
				// !!X => X
				return simplifyAnds(((NotPointcut) notBody).getNegatedPointcut());
			} else {
				return new NotPointcut(simplifyAnds(npc.getNegatedPointcut()));
			}
		} else if (isOr(pc)) {
			OrPointcut opc = (OrPointcut) pc;
			return new OrPointcut(simplifyAnds(opc.getLeft()), simplifyAnds(opc.getRight()));
		} else if (isAnd(pc)) {
			return simplifyAnd((AndPointcut) pc);
		} else {
			return pc;
		}
	}

	private Pointcut simplifyAnd(AndPointcut apc) {
		SortedSet<Pointcut> nodes = new TreeSet<Pointcut>(new PointcutEvaluationExpenseComparator());
		collectAndNodes(apc, nodes);
		// look for A and !A, or IfFalse
		for (Iterator<Pointcut> iter = nodes.iterator(); iter.hasNext();) {
			Pointcut element = iter.next();
			if (element instanceof NotPointcut) {
				Pointcut body = ((NotPointcut) element).getNegatedPointcut();
				if (nodes.contains(body)) {
					return Pointcut.makeMatchesNothing(body.state);
				}
			}
			if (element instanceof IfPointcut) {
				if (((IfPointcut) element).alwaysFalse()) {
					return Pointcut.makeMatchesNothing(element.state);
				}
			}
			// If it can't match anything, the whole AND can't match anything
			if (element.couldMatchKinds() == Shadow.NO_SHADOW_KINDS_BITS) {
				return element;
			}
		}
		if (apc.couldMatchKinds() == Shadow.NO_SHADOW_KINDS_BITS) {
			return Pointcut.makeMatchesNothing(apc.state);
		}
		// write out with cheapest on left
		Iterator<Pointcut> iter = nodes.iterator();
		Pointcut result = iter.next();
		while (iter.hasNext()) {
			Pointcut right = iter.next();
			result = new AndPointcut(result, right);
		}
		return result;
	}

	private Pointcut sortOrs(Pointcut pc) {
		SortedSet<Pointcut> nodes = new TreeSet<Pointcut>(new PointcutEvaluationExpenseComparator());
		collectOrNodes(pc, nodes);
		// write out with cheapest on left
		Iterator<Pointcut> iter = nodes.iterator();
		Pointcut result = iter.next();
		while (iter.hasNext()) {
			Pointcut right = iter.next();
			result = new OrPointcut(result, right);
		}
		return result;
	}

	/**
	 * Removes MATCHES_NOTHING pointcuts
	 */
	private Pointcut removeNothings(Pointcut pc) {
		if (isAnd(pc)) {
			AndPointcut apc = (AndPointcut) pc;
			Pointcut right = removeNothings(apc.getRight());
			Pointcut left = removeNothings(apc.getLeft());
			if (left instanceof MatchesNothingPointcut || right instanceof MatchesNothingPointcut) {
				return new MatchesNothingPointcut();
			}
			return new AndPointcut(left, right);
		} else if (isOr(pc)) {
			OrPointcut opc = (OrPointcut) pc;
			Pointcut right = removeNothings(opc.getRight());
			Pointcut left = removeNothings(opc.getLeft());
			if (left instanceof MatchesNothingPointcut && !(right instanceof MatchesNothingPointcut)) {
				return right;
			} else if (right instanceof MatchesNothingPointcut && !(left instanceof MatchesNothingPointcut)) {
				return left;
			} else if (!(left instanceof MatchesNothingPointcut) && !(right instanceof MatchesNothingPointcut)) {
				return new OrPointcut(left, right);
			} else if (left instanceof MatchesNothingPointcut && right instanceof MatchesNothingPointcut) {
				return new MatchesNothingPointcut();
			}
		}
		return pc;
	}

	private void collectAndNodes(AndPointcut apc, Set<Pointcut> nodesSoFar) {
		Pointcut left = apc.getLeft();
		Pointcut right = apc.getRight();
		if (isAnd(left)) {
			collectAndNodes((AndPointcut) left, nodesSoFar);
		} else {
			nodesSoFar.add(left);
		}
		if (isAnd(right)) {
			collectAndNodes((AndPointcut) right, nodesSoFar);
		} else {
			nodesSoFar.add(right);
		}
	}

	private void collectOrNodes(Pointcut pc, Set<Pointcut> nodesSoFar) {
		if (isOr(pc)) {
			OrPointcut opc = (OrPointcut) pc;
			collectOrNodes(opc.getLeft(), nodesSoFar);
			collectOrNodes(opc.getRight(), nodesSoFar);
		} else {
			nodesSoFar.add(pc);
		}
	}

	private boolean isNot(Pointcut pc) {
		return (pc instanceof NotPointcut);
	}

	private boolean isAnd(Pointcut pc) {
		return (pc instanceof AndPointcut);
	}

	private boolean isOr(Pointcut pc) {
		return (pc instanceof OrPointcut);
	}

}